jimmy is a stunt master in a circus which is in shape of matrix m*n.
Jimmy is preparing for new
stunt where fire starts from a point (fx,fy . Jimmy starts from a point (ix,iy) and reaches point
(jx,jy). Jimmy moves 1 step in a second either horizontally or vertically. Fire spreads from the
initial point with speed of 1 step per sec along x and y axes of initial starting point Jimmy have t
combinations of start,end and fire start place but he is not sure if all places can make him reach
endpoint without touching fire. Could you help jimmy in identifying which combinations can he
chose for the stunt.
CIrcus
Constraints :
1 <= m , n <= 1000
1 <= t <= 10
def helper(fx, ix, jx):
if (ix - fx) * (jx - fx) <= 0:
return 0
ix = abs(ix - fx)
jx = abs(iy - fy)
if jx >= ix:
return jx
d = ix - jx
t = (ix + 1) / 2
if t <= d:
return t
return ix - d - d
def solution(fx, fy, ix, iy, jx, jy):
return max(helper(fx, ix, jx), helper(fy, iy, jy)) > abs(ix - jx) + abs(iy -
jy)
Spreading fire
There is a 2D plane of size NM. There is fire which is there at K different points in the 20 plane.
From each of these K points, the fire is spreading in a circular form with the radius of the fire
increasing by time. So, if at t-1, the radius of fire (represented by R) was 2, at 1-2, it becomes 4, at
t=3, it become 6 and so on. T denotes time here. Help us determine, the number of points (points
are denoted by oxy where both x and y are whole numbers, and are within the plane) which
would not be touched by the fire
Constraints
1 <= N,M <= 1000
1 <= K <= 5
def count_safe_points(N, M, K, fire_points):
T_max = max(N, M) * 2 # Maximum time steps to consider
count = 0
for x in range(1, N + 1):
for y in range(1, M + 1):
is_safe = True
for t in range(1, T_max + 1):
for circle_x, circle_y in fire_points:
if (x - circle_x) ** 2 + (y - circle_y) ** 2 <= (t * 2) ** 2:
is_safe = False
break # Point is within fire's circle, no need to check
further
if not is_safe:
break
if is_safe:
count += 1
return count
# Example usage
N = 10
M = 10
K = 2
fire_points = [(3, 4), (8, 7)]
result = count_safe_points(N, M, K, fire_points)
print("Number of safe points:", result)
Robber on Tree
Take min and Max of array
Max-min+1 - size of array is the answer
https://drive.google.com/file/d/1wDVjcoR3VLMzgk6ZcHcgAkb3Z9bdbMHj/view
#define int int64_t
int ans=INT_MIN;
bool dfs(int src,int par,int target,int t,vector<int> graph[],vector<int>&
timeTaken)
if(src==target){
timeTaken[src]=t;
return true;
for(auto c:graph[src]){
if(src!=par){
if(dfs(c,src,target,t+1,graph,timeTaken)){
timeTaken[c]=t+1;
return true;
return false;
void dfs2(int src,int par,int t,int sum,vector<int> graph[],vector<int>&
timeTaken,vector<int>& coins)
if(t<timeTaken[src]){
sum+=coins[src];
if(t==timeTaken[src]){
sum+=(coins[src]/2);
}
// cout<<src<<' ';
int child=0;
for(auto c:graph[src]){
if(par!=c){
child++;
dfs2(c,src,t+1,sum,graph,timeTaken,coins);
if(child==0){
ans=max(ans,sum);
return ;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int mod=998244353;
int n;
cin>>n;
int R;
cin>>R;
vector<int> graph[n+1];
for(int i=0;i<n-1;i++){
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(a);
vector<int> coins(n+1);
for(int i=1;i<=n;i++)cin>>coins[i];
vector<int> timeTaken(n+1,INT_MAX);
timeTaken[R]=0;
dfs(R,-1,1,0,graph,timeTaken);
dfs2(1,-1,0,0,graph,timeTaken,coins);
cout<<ans<<endl;
return 0;
FIRE something untouched
N, M, K = map(int, input().split())
fire_points = [tuple(map(int, input().split())) for _ in range(K)]
R = int(input())
T = int(input())
def distance(x1, y1, x2, y2):
return ((x1 - x2) 2 + (y1 - y2) 2) ** 0.5
untouched_count = 0
for x in range(N):
for y in range(M):
is_untouched = True
for fx, fy in fire_points:
dist = distance(x, y, fx, fy)
if dist <= R * T:
is_untouched = False
break
if is_untouched:
untouched_count += 1
print(untouched_count)
__________________________________________________________________________________
__________________________________________________________________________________
Harry potter
map<int, int> m;
for (int i = 0; i < n; i++)
m[a[i]] = b[i];
for (auto it : m)
for (auto it2 = m.begin(); it2 != m.end(); it2++)
if (it.first > it2->first and it.second > it2->second)
m.erase(it2);
cout << m.size() << endl;
CRED VERIFICATION
int solution(const vector<int> &a, const vector<int> &b, const vector<int> &c) {
const int n = a.size();
vector<int> ind(n);
for (int i = 0; i < n; ++i) {
ind[i] = i;
sort(ind.begin(), ind.end(), [&](int x, int y) {
return b[x] < b[y];
});
const int s = 1 << n;
vector<int> t(s), dp(s), trailing(s);
for (int i = 0; i < n; ++i) {
trailing[1 << i] = i;
for (int i = 1; i < s; ++i) {
const int prev = i & (i - 1), x = ind[trailing[i & (-i)]];
t[i] = t[prev] + c[x];
dp[i] = dp[prev] + a[x] - b[x] * t[i];
return *max_element(dp.begin(), dp.end());
int main() {
cout << solution({10, 10, 10}, {1, 2, 3}, {2, 2, 2}) << endl;
def solution(a, b, c):
n = len(a)
ind = list(range(n))
ind.sort(key=lambda x: b[x])
s = 1 << n
t = [0] * s
dp = [0] * s
trailing = [0] * s
for i in range(n):
trailing[1 << i] = i
for i in range(1, s):
prev = i & (i - 1)
x = ind[trailing[i & -i]]
t[i] = t[prev] + c[x]
dp[i] = dp[prev] + a[x] - b[x] * t[i]
return max(dp)
# Example usage
if __name__ == "__main__":
a = [10, 10, 10]
b = [1, 2, 3]
c = [2, 2, 2]
result = solution(a, b, c)
print(result)
Smart gardner
__________________________________________________________________________________
class Solution {
public:
int minTaps(int n, vector<int>& ranges) {
int mn = 0;
int reach = 0;
int taps = 0;
while(reach < n){
for(int i=0; i<ranges.size(); i++){
if(i-ranges[i] <= mn && i+ranges[i] > reach)
reach = i + ranges[i];
if(mn == reach) return -1;
taps++;
mn = reach;
return taps;
};
__________________________________________________________________________________
__________________________________________________________________________________
____________________________
Lost in woods
#include <iostream>
#include <string>
using namespace std;
int main()
int numElements;
cin >> numElements;
char prevChar, currentChar;
cin >> currentChar;
string result;
for (int i = 2; i <= numElements; i++)
prevChar = currentChar;
cin >> currentChar;
if (currentChar == '*')
continue;
if (currentChar == '_' || currentChar == 'D')
{
if (prevChar == '*')
result.push_back('J');
else
result.push_back('W');
if (numElements == 1)
result = 'W';
cout << result << endl;
# include <bits/stdc++.h>
using namespace std;
string solve(vector<char>& board, int n) {
string res;
int i = 1;
while(i < n-1) {
if(board[i] == '_') {
res.push_back('W');
else {
res.push_back('J');
while(i < n-1 && board[i] == '*') {
i++;
i++;
return res;
int main(){
int n;
cin >> n;
vector<char> board;
for(int i = 0; i < n; i++) {
char temp;
cin >> temp;
board.push_back(temp);
cout << solve(board, n);
return 0;
def solve(board):
res = []
n = len(board)
i = 1
while i < n - 1:
if board[i] == '_':
res.append('W')
else:
res.append('J')
while i < n - 1 and board[i] == '*':
i += 1
i += 1
return ''.join(res)
# Example usage
n = int(input())
board = list(input())
result = solve(board)
print(result)
0’s and 1’s
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
void solve(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int x,y;
cin>>x>>y;
map<int,int> mp;
mp[0]++;
int sum=0,ans=0;
for(int i=0;i<n;i++){
if(a[i]==0)
sum+=(-y);
else
sum+=x;
if(mp.count(sum))
ans+=mp[sum];
mp[sum]++;
cout<<ans<<endl;
int main() {
int t=1;
// cin>>t;
while(t--){
solve();
return 0;
__________________________________________
def solve():
n = int(input())
a = list(map(int, input().split()))
x, y = map(int, input().split())
mp = {0: 1}
sum_val = 0
ans = 0
for i in range(n):
if a[i] == 0:
sum_val += (-y)
else:
sum_val += x
if sum_val in mp:
ans += mp[sum_val]
mp[sum_val] = mp.get(sum_val, 0) + 1
print(ans)
def main():
t = 1
# t = int(input())
for _ in range(t):
solve()
if __name__ == "__main__":
main()
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
_________________________________________________________________________________
GARDEN
#include <bits/stdc++.h>
using namespace std;
int main()
int numElements;
cin >> numElements;
vector<int64_t> minCost(numElements + 2, 0x3f3f3f3f3f3f3f3f);
minCost[0] = 0;
vector<int> range(numElements + 2), elementCost(numElements + 2);
for (int i = 1; i <= numElements + 1; i++)
cin >> range[i];
for (int i = 1; i <= numElements + 1; i++)
cin >> elementCost[i];
for (int i = 1; i <= numElements + 1; i++)
if (range[i] == 0)
continue;
int nextIdx = min(i + range[i], numElements + 1);
int prevIdx = max(i - range[i] - 1, 0);
int64_t prevElementCost = elementCost[prevIdx];
for (int j = prevIdx + 1; j <= nextIdx; j++)
minCost[j] = min(minCost[j], minCost[prevIdx] + elementCost[i]);
cout << ((minCost[numElements + 1] < 0x3f3f3f3f3f3f3f3f) ? minCost[numElements
+ 1] : -1) << "\n";
}
Dhoni
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
def find_maximum(a, b):
return a if a > b else b
def find_minimum(a, b):
return a if a < b else b
def main():
num_rows, num_cols = map(int, input().split())
maximum_value = float('-inf')
result = float('-inf')
for i in range(num_rows):
for j in range(num_cols):
cell_value = int(input())
current_difference = maximum_value - cell_value
result = find_maximum(result, current_difference)
maximum_value = find_maximum(maximum_value, cell_value)
print(result)
if __name__ == "__main__":
main()
Drag Race (all passed)
def solve(a, b):
max_points = 0
n = len(a) # Assuming both lists have the same size
for i in range(n):
points = a[i] * 5 + b[i] * 2
max_points = max(max_points, points)
return max_points
def main():
a_count = int(input())
a = list(map(int, input().split()))
b_count = int(input())
b = list(map(int, input().split()))
result = solve(a, b)
print(result)
if __name__ == "__main__":
main()
Smart gardner (doubt)
class Solution {
public:
int minTaps(int n, vector<int>& ranges) {
int mn = 0;
int reach = 0;
int taps = 0;
while(reach < n){
for(int i=0; i<ranges.size(); i++){
if(i-ranges[i] <= mn && i+ranges[i] > reach)
reach = i + ranges[i];
}
if(mn == reach) return -1;
taps++;
mn = reach;
return taps;
};
class Solution:
def minTaps(self, n, ranges):
mn = 0
reach = 0
taps = 0
while reach < n:
for i in range(len(ranges)):
if i - ranges[i] <= mn and i + ranges[i] > reach:
reach = i + ranges[i]
if mn == reach:
return -1
taps += 1
mn = reach
return taps
# Example usage
if __name__ == "__main__":
s = Solution()
n = int(input("Enter n: "))
ranges = list(map(int, input("Enter ranges: ").split()))
result = s.minTaps(n, ranges)
print("Result:", result)
Lazy chef 2
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
_________________________
private static int solve(String s, char a, char b){ // Java
int aCount = (int)s.chars().filter(o -> o == a).count();
int bCount = (int)s.chars().filter(o -> o == b).count();
int must = 0, option1 = 0, option2 = 0, left = 0;
for (char ch : s.toCharArray()){
if (ch == a){
aCount--;
option1 += bCount;
left++;
}else if (ch == b){
bCount--;
option2 += aCount;
left++;
}else{
must += Math.min(aCount+bCount, left);
return must + Math.min(option1, option2);
def solve(s, a, b):
a_count = s.count(a)
b_count = s.count(b)
must, option1, option2, left = 0, 0, 0, 0
for ch in s:
if ch == a:
a_count -= 1
option1 += b_count
left += 1
elif ch == b:
b_count -= 1
option2 += a_count
left += 1
else:
must += min(a_count + b_count, left)
return must + min(option1, option2)
# Example usage
s = input("Enter the string: ")
a = input("Enter character a: ")[0]
b = input("Enter character b: ")[0]
result = solve(s, a, b)
print("Result:", result)
KINGS DREAMS
def solve(N, m):
S = list(range(1, m + 1))
return S * (N // m) + [S:N % m]
upskilling candidates
def get_skilled(required,already,Books,price):
to_gain=0
for skill in required:
to_gain|=(1<<skill)
for x in already:
if to_gain&(1<<x):
to_gain^=(1<<x)
m=len(Books)
@cache
def solve(i,mask):
if mask==0:return 0
if i==m:return float('inf')
res=solve(i+1,mask)
v=0
for skill in Books[i]:
if mask&(1<<skill):
v|=(1<<skill)
res=min(res,price[i]+solve(i+1,mask^v))
return res
b=solve(0,to_gain)
return b if b<float('inf') else -1
Lazy chef - 2
https://leetcode.com/discuss/interview-question/2492460/Intuit-India-or-OA-or-
LAZY-CHEF-II
MATCHMAKING - 1
Description
Intuit receives calls from it's customers regarding various topics and in various languages. Intuit
wants to match these customers to experts who have knowledge on exactly the same topic and
can speak in that language. Based on the predictions, Intuit had N experts ready to take the calls,
each expert knows exactly one topic and can speak exactly one language proficiently. On a
particular day, M customers end up calling for their problems. A customer is unhappy if it is not
matched to the expert who know about the topic they wish to enquire about and know the
language they talk in. Can you help the team at Intuit assign the customers to experts, such that
the minimum number of customers return unhappy
Constraints
1<= N <= 10^5
1<= M <= 10^5
Input Format
The first line contains N, the count of experts at Intuit.
Next N line contains 2 space seperated strings, the first denoting the topic the expert knows, and
the second denoting the language they know The next line contains M. the count of customers
calling Intuit.
Next M line contains 2 space seperated strings, the first denoting the topic the customer wants to
enquire about, and the second denoting the language they speak in
Output Format
Return an integer representing the number of
customer which went unhappy with Intuit
Sample Input
4
Tax English
Crypto Hindi
Tax Spanish
SF English
4 Crypto Hindi
Tax Spanish
Crypto Spanish
Tax Spanish
Sample Output
2
Explanation
Crypto Spanish - Intuit does not have a crypt o expert who can work in Spanish.
Tax Spanish - Intuit only has a single expert who can do tax and work in Spanish
Solution :
#include <bits/stdc++.h>
using namespace std;
int main()
Solution s = Solution();
int n;
cin>>n;
unordered_map<string,vector<pair<string,int>>> mp;
for(int i=0;i<n;i++){
string a,b;
cin>>a>>b;
//map of pair pushing a new pair with same key and default flag
value 0
mp[a].push_back({b,0});
int m;
cin>>m;
vector<pair<string,string>> v;
for(int i=0;i<m;i++){
string a,b;
cin>>a>>b;
//taking all the testcase inputs
v.push_back({a,b});
}
int ans=0;
//iterating over all the testcases
for(auto &c:v){
auto it =mp.find(c.first);
//if entry is found in map then we will search that language in
pair vector by iteration
if(it!=mp.end()){
int j=0;
for(;j<it->second.size();j++){
//if the desired lang is present
if(it->second[j].first==c.second and it->second[j]==0)
//mark it as visited and cannot traverse
it again
//since given in question one expert can
be occupied with only one customer
it->second[j].second=1;
break;
//if we traversed the whole map and cannot find the
matching language from testcase
//then also customer unsatisfied
if(j==it->second.size())ans++;
else
ans++;
//in this case if the lang is not present in the map then the
customer is unsatisfied
// add the ans
cout<<ans<<"/n";
return 0;
class Solution:
def __init__(self):
self.mp = {}
def main(self):
n = int(input())
for _ in range(n):
a, b = input().split()
if a not in self.mp:
self.mp[a] = []
self.mp[a].append((b, 0))
m = int(input())
v = []
for _ in range(m):
a, b = input().split()
v.append((a, b))
ans = 0
for c in v:
if c[0] in self.mp:
found = False
for i, lang in enumerate(self.mp[c[0]]):
if lang[0] == c[1] and lang[1] == 0:
self.mp[c[0]][i] = (c[1], 1)
found = True
break
if not found:
ans += 1
else:
ans += 1
print(ans)
if __name__ == "__main__":
s = Solution()
s.main()
This question was asked in Intuit OA - Oncampus
Given a binary array, find the total number of subarrays with the ratio of 0's and 1's equal to x:y.
Constraints:
n = arr.length
2<=n<=1e5
1<=x,y<=n
Example: arr = [0,1,0,1] x = 1 y = 1
Output: 4
Explanation: The four possible subarrays are as follows:
[0 1] 0 1 --> [0,1]
0 [1 0] 1 --> [1,0]
0 1 [0 1] --> [0,1]
[0 1 0 1] --> [0,1,0,1]
With the given constraints, expecting solution no worse than O(n)
int helper(int x, int y, vector<int>&arr)
int sum = 0;
map<int,int> mp;
mp[0]++;
int ans = 0;
for(int i = 0; i<arr.size(); i++){
if(arr[i] == 0)
sum += (-y);
else
sum += (x);
if(mp.count(sum))
ans += mp[sum];
mp[sum]++;
return ans;
def helper(x, y, arr):
sum_val = 0
mp = {0: 1}
ans = 0
for i in range(len(arr)):
if arr[i] == 0:
sum_val += (-y)
else:
sum_val += x
if sum_val in mp:
ans += mp[sum_val]
if sum_val not in mp:
mp[sum_val] = 1
else:
mp[sum_val] += 1
return ans
https://leetcode.ca/all/1788.html
overleaping circles
#include <bits/stdc++.h>
using namespace std;
static bool fun(vector<int>a , vector<int>b){
return a.size()<b.size();
int circles(vector<int>&v){
vector<vector<int>>m(n);
for(int i=0;i<n;i++){
m[i].push_back(i);
for(int j = 0;j<n;j++){
float d = sqrt(((v[i][0]-v[j][0])*(v[i][0]-v[j][0])) + ((v[i][1]-
v[j][1])*(v[i][1]-v[j][1])));
if(d<=(v[i][2]+v[j][2]) && i!=j){
m[i].push_back(j);
int ans = 0;
sort(m.begin(),m.end(),fun);
while(m.size()>0 && m[m.size()-1].size()!=1){
ans++;
for(int i=1;i<m[m.size()-1].size();i++){
int j = m[m.size()-1][i];
m[j].erase(find(m[j].begin(),m[j].end(),m[m.size()-1][0]));
m.pop_back();
sort(m.begin(),m.end(),fun);
return ans;
int main() {
int n;
cin>>n;
vector<vector<int>>v;
int i = n;
while(i--){
int x;
cin>>x;
int y;
cin>>y;
int r;
cin>>r;
v.push_back({x,y,r});
cout<<circles(v);
import math
def fun(a, b):
return len(a) < len(b)
def circles(v):
n = len(v)
m = [[] for _ in range(n)]
for i in range(n):
m[i].append(i)
for j in range(n):
d = math.sqrt((v[i][0] - v[j][0])**2 + (v[i][1] - v[j][1])**2)
if d <= (v[i][2] + v[j][2]) and i != j:
m[i].append(j)
ans = 0
m.sort(key=lambda x: len(x))
while len(m) > 0 and len(m[-1]) != 1:
ans += 1
for i in range(1, len(m[-1])):
j = m[-1][i]
m[j].remove(m[-1][0])
m.pop()
m.sort(key=lambda x: len(x))
return ans
def main():
n = int(input())
v = []
for _ in range(n):
x, y, r = map(int, input().split())
v.append([x, y, r])
print(circles(v))
if __name__ == "__main__":
main()
Dhoni
def maximize_reward(matrix):
n = len(matrix)
m = len(matrix[0])
max_reward = float('-inf')
max_row = [[0] * m for _ in range(n)]
min_row = [[0] * m for _ in range(n)]
max_col = [[0] * m for _ in range(n)]
min_col = [[0] * m for _ in range(n)]
# Precompute maximum and minimum values for each row from the right
for i in range(n):
max_val = matrix[i][-1]
min_val = matrix[i][-1]
for j in range(m - 1, -1, -1):
max_val = max(max_val, matrix[i][j])
min_val = min(min_val, matrix[i][j])
max_row[i][j] = max_val
min_row[i][j] = min_val
# Precompute maximum and minimum values for each column from the bottom
for j in range(m):
max_val = matrix[-1][j]
min_val = matrix[-1][j]
for i in range(n - 1, -1, -1):
max_val = max(max_val, matrix[i][j])
min_val = min(min_val, matrix[i][j])
max_col[i][j] = max_val
min_col[i][j] = min_val
# Calculate maximum reward for each cell
for i in range(n):
for j in range(m):
diff1 = max_row[i][j] - min_row[i][j]
diff2 = max_col[i][j] - min_col[i][j]
max_reward = max(max_reward, diff1, diff2)
return max_reward
# Read input
n, m = map(int, input().split())
matrix = [list(map(int, input().split())) for _ in range(n)]
# Calculate and print the maximum reward
print(maximize_reward(matrix))
There are n servers. Ith server has requests[i] requests to serve but can serve a
maximum of max_req[i] requests.
In order to balance the load, a hackers reed to redirect some requests of Ith
server to some other servers. The latency induced in redirecting the request on
the Ith server to the Jth server is |i-j| where |x| represents the absolute value
of x. The max_latency is defined as the maximum latency Induced amongst all the
redirections.
Given the arrays requests and max_req find the minimum possible max latency if the
requests are redirected optimally such that no server has to serve more than the
maximum requests it can serve. If there is no way to serve all the requests,
report -1 as the answer.
n = 4
maxreq = [2,1,5,3]
req = [1,3,2,4]
ans :1 (max(|2-1|,|3-2|)
def is_feasible(mid, n, max_req, req):
curr_req = req[:]
curr_max_req = max_req[:]
for i in range(n):
j = i
while j >= 0 and abs(i - j) <= mid:
if curr_req[i] > 0 and curr_max_req[j] > 0:
allocated = min(curr_req[i], curr_max_req[j])
curr_req[i] -= allocated
curr_max_req[j] -= allocated
j -= 1
j = i + 1
while j < n and abs(i - j) <= mid:
if curr_req[i] > 0 and curr_max_req[j] > 0:
allocated = min(curr_req[i], curr_max_req[j])
curr_req[i] -= allocated
curr_max_req[j] -= allocated
j += 1
if curr_req[i] > 0:
return False
return True
def min_max_latency(n, max_req, req):
low = 0
high = max(max_req) + n
result = -1
while low <= high:
mid = (low + high) // 2
if is_feasible(mid, n, max_req, req):
result = mid
high = mid - 1
else:
low = mid + 1
return result
n = 4
max_req = [2, 1, 5, 3]
req = [1, 3, 2, 4]
answer = min_max_latency(n, max_req, req)
print(answer) # Output should be 1
schedule training 2
n,m=map(int,input().split(" "))
taskshour=0
for i in range(n):
taskshour+=sum(list(map(int,input().split((" ")))))
p=int(input())
commit=[]
for i in range(p):
x=list(map(int,input().split((" "))))
commit.append(x)
days=int(input())
perday=taskshour//days
if(taskshour%days>0):
flag=1
else:
flag=0
reserved=[]
for i in commit:
for j in range(i[0]+1,i[1]+1):
reserved.append(j)
free=0
max=0
for i in range(1,25):
max=i
if(i not in reserved):
free+=1
if(flag==1):
if(free==perday+1):
break
else:
if(free==perday):
break
else:
print("\n\nResult",-1)
print("\n\nResult",max)
__________________________________________________________________________________
__________________________________________________________________________________
_____________________________
scheduled training
n,m=map(int,input().split(" "))
taskshour=0
for i in range(n):
taskshour+=sum(list(map(int,input().split((" ")))))
p=int(input())
commit=[]
for i in range(p):
x=list(map(int,input().split((" "))))
commit.append(x)
days=int(input())
perday=taskshour//days
if(taskshour%days>0):
flag=1
else:
flag=0
reserved=[]
for i in commit:
for j in range(i[0]+1,i[1]+1):
reserved.append(j)
free=0
max=0
for i in range(1,25):
max=i
if(i not in reserved):
free+=1
if(flag==1):
if(free==perday+1):
break
else:
if(free==perday):
break
else:
print("\n\nResult",-1)
print("\n\nResult",max)
STUBBORN FRIENDS
def rec(i, t, n, dp, v):
if i == n:
return 0
if dp[i][t] != -1:
return dp[i][t]
temp = rec(i + 1, t, n, dp, v)
for x in v[i]:
if x[0] <= t:
temp = max(temp, x[1] + rec(i + 1, t - x[0], n, dp, v))
dp[i][t] = temp
return temp
def dfs(src, par, ct, adj, vis):
vis[src] = ct
for x in adj[src]:
if x != par and vis[src] == 0:
dfs(x, src, ct, adj, vis)
def solve():
n, t = map(int, input().split())
ci = [0] + list(map(int, input().split()))
mi = [0] + list(map(int, input().split()))
m = int(input())
adj = [[] for _ in range(n + 1)]
for i in range(m):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
ct = -1
vis = [0] * (n + 1)
dp = [[-1] * (t + 1) for _ in range(n + 1)]
v = [[] for _ in range(n + 1)]
for i in range(1, n + 1):
if vis[i] != 0:
continue
ct += 1
dfs(i, 0, ct, adj, vis)
for j in range(1, n + 1):
if vis[j] == ct:
v[ct].append((ci[j], mi[j]))
n = ct + 1
ans = rec(0, t, n, dp, v)
print(ans)
t = int(input())
while t > 0:
solve()
t -= 1
#include <bits/stdc++.h>
using namespace std;
int main()
int numElements;
cin >> numElements;
vector<int64_t> minCost(numElements + 2, 0x3f3f3f3f3f3f3f3f);
minCost[0] = 0;
vector<int> range(numElements + 2), elementCost(numElements + 2);
for (int i = 1; i <= numElements + 1; i++)
cin >> range[i];
for (int i = 1; i <= numElements + 1; i++)
cin >> elementCost[i];
for (int i = 1; i <= numElements + 1; i++)
if (range[i] == 0)
continue;
int nextIdx = min(i + range[i], numElements + 1);
int prevIdx = max(i - range[i] - 1, 0);
int64_t prevElementCost = elementCost[prevIdx];
for (int j = prevIdx + 1; j <= nextIdx; j++)
minCost[j] = min(minCost[j], minCost[prevIdx] + elementCost[i]);
}
}
cout << ((minCost[numElements + 1] < 0x3f3f3f3f3f3f3f3f) ? minCost[numElements
+ 1] : -1) << "\n";
def main():
num_elements = int(input())
min_cost = [0x3f3f3f3f3f3f3f3f] * (num_elements + 2)
min_cost[0] = 0
range_vals = [0] * (num_elements + 2)
element_cost = [0] * (num_elements + 2)
for i in range(1, num_elements + 2):
range_vals[i] = int(input())
for i in range(1, num_elements + 2):
element_cost[i] = int(input())
for i in range(1, num_elements + 2):
if range_vals[i] == 0:
continue
next_idx = min(i + range_vals[i], num_elements + 1)
prev_idx = max(i - range_vals[i] - 1, 0)
prev_element_cost = element_cost[prev_idx]
for j in range(prev_idx + 1, next_idx + 1):
min_cost[j] = min(min_cost[j], min_cost[prev_idx] + element_cost[i])
print(min_cost[num_elements + 1] if min_cost[num_elements + 1] <
0x3f3f3f3f3f3f3f3f else -1)
if __name__ == "__main__":
main()
Garden
Jump kady
def can_reach_destination(m, n, X, p, q, u, v):
dp = [[float('inf')] * (n+1) for _ in range(m+1)]
dp[p][q] = 0
for i in range(p, u+1):
for j in range(q, v+1):
if i == p and j == q:
continue
for k in range(1, X+1):
if i - k >= 1:
dp[i][j] = min(dp[i][j], dp[i-k][j] + 1)
if j - k >= 1:
dp[i][j] = min(dp[i][j], dp[i][j-k] + 1)
if dp[u][v] == float('inf'):
return -1
else:
return dp[u][v]
# Read input
m, n, X = map(int, input().split())
p, q = map(int, input().split())
u, v = map(int, input().split())
# Calculate and print the result
result = can_reach_destination(m, n, X, p, q, u, v)
print(result)
229 VIEWS
There is a 2D plane of size N* M. There is fire which is there at K different points in the 2D plane.
From each of these K points, the fire is spreading in a circular form with the radius of the fire
increasing by time. So, if at t=1, the radius if fire was 2, at t=2, it becomes 4, at t=3, it become 6
and so on. "t" denotes time here.
Help us determine, the number of points (points are denoted by {x,y}, where both x and y are
whole numbers, and are within the plane) which would not be touched by the fire
Constraints
1 <= N <= 1000
1<= M <= 1000
1<=K<=5
1 <= R <= 10
1 <= T <= 100
Something like this:
Assume:
(1) You meant all xs are in [0, n - 1] and ys are in [0, m - 1].
(2) You are asking for each T = 0,1, 2...t, how many points are unaffected.
This can be preprocessed by a loop of m * n * k which calculates the earliest time a point is on
fire.
Then we do something like merge sort or we can call that 2 pointers....
int sqr(int x) {
return x * x;
vector<int> solution(int n, int m, int r, int t, const vector<vector<int>> &f) {
const int rr = sqr(r);
vector<int> v;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int temp = INT_MAX;
for (const auto& v : f) {
temp = min(temp, (int) sqrt((sqr(i - v[0]) + sqr(j - v[1]) + rr -
1) / rr + .5));
if (temp <= t) {
v.push_back(temp);
sort(v.begin(), v.end());
vector<int> ans(t + 1, n * m);
for (int i = 0, j = 0; i <= t; ++i) {
for (; j < v.size() && v[j] <= i; ++j)
ans[i] -= j;
return ans;
import math
def solution(n, m, r, t, f):
rr = r * r
v = []
for i in range(n):
for j in range(m):
temp = math.inf
for point in f:
temp = min(temp, int(math.sqrt(((i - point[0]) ** 2 + (j -
point[1]) ** 2 + rr - 1) / rr + 0.5)))
if temp <= t:
v.append(temp)
v.sort()
ans = [n * m] * (t + 1)
j = 0
for i in range(t + 1):
while j < len(v) and v[j] <= i:
j += 1
ans[i] -= j
return ans
# Example usage
if __name__ == "__main__":
n = 5
m = 5
r = 2
t = 3
f = [[1, 1], [3, 3]]
result = solution(n, m, r, t, f)
print(result)