source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
4
problem
stringlengths
488
6.07k
gold_standard_solution
stringlengths
19
30.1k
verification_info
dict
metadata
dict
problem_id
stringlengths
5
9
apps
verifiable_code
1484
Solve the following coding problem using the programming language python: Young Sheldon is given the task to teach Chemistry to his brother Georgie. After teaching him how to find total atomic weight, Sheldon gives him some formulas which consist of $x$, $y$ and $z$ atoms as an assignment. You already know that Georgie doesn't like Chemistry, so he want you to help him solve this assignment. Let the chemical formula be given by the string $S$. It consists of any combination of x, y and z with some value associated with it as well as parenthesis to encapsulate any combination. Moreover, the atomic weight of x, y and z are 2, 4 and 10 respectively. You are supposed to find the total atomic weight of the element represented by the given formula. For example, for the formula $(x_2y_2)_3z$, given string $S$ will be: $(x2y2)3z$. Hence, substituting values of x, y and z, total atomic weight will be $(2*2+4*2)*3 + 10 = 46$. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input $S$. -----Output:----- For each testcase, output in a single line, the total atomic weight. -----Constraints----- - $1 \leq T \leq 100$ - Length of string $S \leq 100$ - String contains $x, y, z, 1, 2,..., 9$ and parenthesis -----Sample Input:----- 2 (xy)2 x(x2y)3(z)2 -----Sample Output:----- 12 46 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): s = list(input().strip()) i = 0 while i < len(s) - 1: if s[i].isalpha() or s[i] == ')': if s[i + 1].isdigit(): if i + 2 >= len(s) or s[i + 2] == ')': s = s[:i+1] + ['*', s[i+1]] + s[i+2:] else: s = s[:i+1] + ['*', s[i+1], '+'] + s[i+2:] i += 1 elif s[i + 1].isalpha() or s[i + 1] == '(': s = s[:i+1] + ['+'] + s[i+1:] i += 1 s = ''.join(s) s = s.strip('+') x = 2 y = 4 z = 10 print(eval(s)) ```
{ "language": "python", "test_cases": [ { "input": "2\n(xy)2\nx(x2y)3(z)2\n", "output": "12\n46\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CORS2020/problems/PENEVAL" }
vfc_4778
apps
verifiable_code
1485
Solve the following coding problem using the programming language python: Chef has a pepperoni pizza in the shape of a $N \times N$ grid; both its rows and columns are numbered $1$ through $N$. Some cells of this grid have pepperoni on them, while some do not. Chef wants to cut the pizza vertically in half and give the two halves to two of his friends. Formally, one friend should get everything in the columns $1$ through $N/2$ and the other friend should get everything in the columns $N/2+1$ through $N$. Before doing that, if Chef wants to, he may choose one row of the grid and reverse it, i.e. swap the contents of the cells in the $i$-th and $N+1-i$-th column in this row for each $i$ ($1 \le i \le N/2$). After the pizza is cut, let's denote the number of cells containing pepperonis in one half by $p_1$ and their number in the other half by $p_2$. Chef wants to minimise their absolute difference. What is the minimum value of $|p_1-p_2|$? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains a string with length $N$ describing the $i$-th row of the grid; this string contains only characters '1' (denoting a cell with pepperonis) and '0' (denoting a cell without pepperonis). -----Output----- For each test case, print a single line containing one integer — the minimum absolute difference between the number of cells with pepperonis in the half-pizzas given to Chef's friends. -----Constraints----- - $1 \le T \le 1,000$ - $2 \le N \le 1,000$ - $N$ is even - the sum of $N \cdot N$ over all test cases does not exceed $2 \cdot 10^6$ -----Example Input----- 2 6 100000 100000 100000 100000 010010 001100 4 0011 1100 1110 0001 -----Example Output----- 2 0 -----Explanation----- Example case 1: Initially, $|p_1-p_2| = 4$, but if Chef reverses any one of the first four rows from "100000" to "000001", $|p_1-p_2|$ becomes $2$. Example case 2: Initially, $|p_1-p_2| = 0$. We cannot make that smaller by reversing any row. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n=int(input()) l1=[] l2=[] for i in range(n): s=input() a=s[ :n//2].count('1') b=s[n//2: ].count('1') if a>b: l1.append(a-b) elif a<b: l2.append(b-a) p=sum(l1) q=sum(l2) if p==q: print(0) elif p>q: diff=p-q flag=0 for i in range(diff//2, 0, -1): a=diff-i if (i in l1) or (a in l1): print(abs(a-i)) flag=1 break if flag==0: print(diff) else: diff=q-p flag=0 for i in range(diff//2, 0, -1): a=diff-i if (i in l2) or (a in l2): print(abs(a-i)) flag=1 break if flag==0: print(diff) ```
{ "language": "python", "test_cases": [ { "input": "2\n6\n100000\n100000\n100000\n100000\n010010\n001100\n4\n0011\n1100\n1110\n0001\n", "output": "2\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/PEPPERON" }
vfc_4782
apps
verifiable_code
1486
Solve the following coding problem using the programming language python: You are provided with the marks of entire class in Data structures exam out of 100. You need to calculate the number of students having backlog (passing marks is >=31) and the average of the class. But this average is not a normal average, for this average marks of students having backlog are not considered but they will be considered in number of students. Also print the index of topper’s marks and print the difference of everyone’s marks with respect to the topper. In first line print the number of students having backlog and average of the class. In second line print indices of all the toppers(in case of more than 1 topper print index of all toppers in reverse order). Next N lines print the difference of everyone’s marks with respect to topper(s). Note- if all students have backlog than average will be 0. INPUT The first line of the input contains an integer T denoting the number of test cases. Next line contains N denoting the no of students in the class. The line contains N space seprated integers A1,A2,A3….AN denoting the marks of each student in exam. OUTPUT First line contains the number of students having backlog and the special average of marks as described above. Average must have 2 decimal places. Next line contains the indices of all the toppers in given array in reverse order. Next N lines contain the difference of every student’s marks with respect to toppers. Constraints 1<= T <= 100 1<= N <= 30 0<= Ai<= 100 Example Input 1 9 56 42 94 25 74 99 27 52 83 Output 2 55.55 5 43 57 5 74 25 0 72 47 16 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for j in range(int(input())): input() a = list(map(int,input().split())) marks = 0 backlok = 0 top_marks = max(a) topper = [] for i in range(len(a)): if(a[i] >= 31): marks+=a[i] if(a[i]<31): backlok+=1 if(a[i] == top_marks): topper.append(i) print(backlok, "{:0.2f}".format(marks/len(a),2)) topper.sort(reverse=True) for i in topper: print(i," ") for i in a: print(top_marks-i) ```
{ "language": "python", "test_cases": [ { "input": "1\n9\n56 42 94 25 74 99 27 52 83\n", "output": "2 55.56\n5\n43\n57\n5\n74\n25\n0\n72\n47\n16\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/UCOD2020/problems/DSEXAM" }
vfc_4786
apps
verifiable_code
1487
Solve the following coding problem using the programming language python: Chef has $N$ boxes arranged in a line.Each box has some candies in it,say $C[i]$. Chef wants to distribute all the candies between of his friends: $A$ and $B$, in the following way: $A$ starts eating candies kept in the leftmost box(box at $1$st place) and $B$ starts eating candies kept in the rightmost box(box at $N$th place). $A$ eats candies $X$ times faster than $B$ i.e. $A$ eats $X$ candies when $B$ eats only $1$. Candies in each box can be eaten by only the person who reaches that box first. If both reach a box at the same time, then the one who has eaten from more number of BOXES till now will eat the candies in that box. If both have eaten from the same number of boxes till now ,then $A$ will eat the candies in that box. Find the number of boxes finished by both $A$ and $B$. NOTE:- We assume that it does not take any time to switch from one box to another. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains three lines of input. The first line of each test case contains $N$, the number of boxes. - The second line of each test case contains a sequence,$C_1$ ,$C_2$ ,$C_3$ . . . $C_N$ where $C_i$ denotes the number of candies in the i-th box. - The third line of each test case contains an integer $X$ . -----Output:----- For each testcase, print two space separated integers in a new line - the number of boxes eaten by $A$ and $B$ respectively. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq N \leq 200000$ - $1 \leq C_i \leq 1000000$ - $1 \leq X \leq 10$ - Sum of $N$ over all test cases does not exceed $300000$ -----Subtasks----- Subtask 1(24 points): - $1 \leq T \leq 10$ - $1 \leq N \leq 1000$ - $1 \leq C_i \leq 1000$ - $1 \leq X \leq 10$ Subtask 2(51 points): original constraints -----Sample Input:----- 1 5 2 8 8 2 9 2 -----Sample Output:----- 4 1 -----EXPLANATION:----- $A$ will start eating candies in the 1st box(leftmost box having 2 candies) . $B$ will start eating candies in the 5th box(rightmost box having 9 candies) .As $A's$ speed is 2 times as that of $B's$, $A$ will start eating candies in the 2nd box while $B$ would still be eating candies in the 5th box.$A$ will now start eating candies from the 3rd box while $B$ would still be eating candies in the 5th box.Now both $A$ and $B$ will finish candies in their respective boxes at the same time($A$ from the 3rd box and $B$ from 5th box). Since $A$ has eaten more number of boxes($A$ has eaten 3 boxes while $B$ has eaten 1 box) till now,so $A$ will be eating candies in the 4th box. Hence $A$ has eaten 4 boxes and $B$ has eaten 1 box. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys # stdin = open("testdata.txt", "r") ip = sys.stdin def solve(C, n, x): if n==1: return (1, 0) b1, b2 = 1, 1 a , b = C[0], C[-1] while b1 + b2 < n: if a < b*x: a += C[b1] b1 += 1 elif a > b*x: b2 += 1 b += C[n-b2] else: if b1 >= b2: a += C[b1] b1 += 1 else: b2 += 1 b += C[b2] return (b1, b2) t = int(ip.readline()) for _ in range(t): n = int(ip.readline()) C = list(map(int, ip.readline().split())) x = int(ip.readline()) ans = solve(C, n, x) print(*ans) ```
{ "language": "python", "test_cases": [ { "input": "1\n5\n2 8 8 2 9\n2\n", "output": "4 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/BIT2B" }
vfc_4790
apps
verifiable_code
1489
Solve the following coding problem using the programming language python: $Harshad$ $Mehta$ is planning a new scam with the stocks he is given a stock of integer price S and a number K . $harshad$ has got the power to change the number $S$ at most $K$ times In order to raise the price of stock and now cash it for his benefits Find the largest price at which $harshad$ can sell the stock in order to maximize his profit -----Input:----- - First line will contain $S$ and $K$ , the price of the stock and the number K -----Output:----- Print the largest profit he can make in a single line. -----Constraints----- - S can take value upto 10^18 NOTE: use 64 int number to fit range - K can take value from [0.. 9] -----Sample Input:----- 4483 2 -----Sample Output:----- 9983 -----EXPLANATION:----- First two digits of the number are changed to get the required number. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a,b=[int(_) for _ in input().split()] if b==0: print(a) else: l=[] a=str(a) for i in range(len(a)): l.append(a[i]) for i in range(len(l)): if b==0: break if l[i]=='9': continue else: l[i]='9' b-=1 s='' for i in l: s+=i print(s) ```
{ "language": "python", "test_cases": [ { "input": "4483 2\n", "output": "9983\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/SPRT2020/problems/STCKSCAM" }
vfc_4798
apps
verifiable_code
1490
Solve the following coding problem using the programming language python: Rahul is a serial killer. Rahul has been betrayed by his lover in the past and now he want to eliminate entire Universe.He has already Eliminated majority of the population and now only a handful number of people are left. Like other Serial killers, he has an interesting pattern of killing people. He either kill one individual at a time or if he find two individuals of different heights,he eliminates both of them simultaneously. Now Rahul wants to eliminate them as quickly as he can. So given $N$ as the number of people left and an array containing height of those $N$ people,tell the minimum number of kills Rahul require to eliminate the entire universe. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each test case constitutes of Two lines. - First line contains $N$, representing the number of people left in the universe - The second line contains an array $a[i]$ of size $N$ containing heights of those $N$ people. -----Output:----- For each testcase, you have to output a Single line Containing the minimum number of kills required by Rahul to eliminate the Universe. -----Constraints----- - $1 \leq T \leq 50000$ - $1 \leq N \leq 50000$ - $100 \leq a[i] \leq 10^5$ -----Sample Input:----- 1 10 178 184 178 177 171 173 171 183 171 175 -----Sample Output:----- 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import ceil t=int(input()) for i in range(t): p=int(input()) l=list(map(int,input().split())) maxx=1 for i in range(len(l)): maxx=max(maxx,l.count(l[i])) if(maxx*2>p): print(maxx) else: q=p-maxx*2 maxx+=ceil(q/2) print(maxx) ```
{ "language": "python", "test_cases": [ { "input": "1\n10\n178 184 178 177 171 173 171 183 171 175\n", "output": "5\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/COFY2020/problems/GKSMNRSK" }
vfc_4802
apps
verifiable_code
1491
Solve the following coding problem using the programming language python: Chef recently learned about ratios and proportions. He wrote some positive integers a, b, c, d on a paper. Chef wants to know whether he can shuffle these numbers so as to make some proportion? Formally, four numbers x, y, z, w are said to make a proportion if ratio of x : y is same as that of z : w. -----Input----- Only line of the input contains four space separated positive integers - a, b, c, d. -----Output----- Print "Possible" if it is possible to shuffle a, b, c, d to make proportion, otherwise "Impossible" (without quotes). -----Constraints----- - 1 ≤ a, b, c, d ≤ 1000 -----Example----- Input: 1 2 4 2 Output: Possible -----Explanation----- By swapping 4 and the second 2, we get 1 2 2 4. Note that 1 2 2 4 make proportion as 1 : 2 = 2 : 4. Hence answer is "Possible" The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def permutate(arr): if len(arr) == 1: yield arr for x in range(len(arr)): for perm in permutate(arr[:x] + arr[x+1:]): yield [arr[x]] + perm vals = [int(x) for x in input().split()] founded = False for val in permutate(vals): if (val[0] / float(val[1]) == val[2] / float(val[3])): print("Possible") founded = True break if not founded: print("Impossible") ```
{ "language": "python", "test_cases": [ { "input": "1 2 4 2\n", "output": "Possible\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/COOK72/problems/CHEFCBA" }
vfc_4806
apps
verifiable_code
1492
Solve the following coding problem using the programming language python: Devu is a disastrous oracle: his predictions about various events of your life are horrifying. Instead of providing good luck, he "blesses" you with bad luck. The secret behind his wickedness is a hidden omen which is a string of length m. On your visit to him, you can ask a lot of questions about your future, each of which should be a string of length m. In total you asked him n such questions, denoted by strings s1, s2, ... , sn of length m each. Each of the question strings is composed of the characters 'a' and 'b' only. Amount of bad luck this visit will bring you is equal to the length of longest common subsequence (LCS) of all the question strings and the hidden omen string. Of course, as the omen string is hidden, you are wondering what could be the least value of bad luck you can get. Can you find out what could be the least bad luck you can get? Find it fast, before Devu tells you any bad omens. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. First line of each test case contains a single integer n denoting number of strings. For each of next n lines, the ith line contains the string si. -----Output----- For each test case, output a single integer corresponding to the answer of the problem. -----Constraints----- - All the strings (including the hidden omen) contain the characters 'a' and 'b' only. Subtask #1: (40 points) - 1 ≤ T, n, m ≤ 14 Subtask #2: (60 points) - 1 ≤ T, n, m ≤ 100 -----Example----- Input:3 2 ab ba 2 aa bb 3 aabb abab baab Output:1 0 2 -----Explanation----- In the first example, the minimum value of LCS of all the strings is 1, the string by oracle can be one of these {aa, ab, ba, bb}. In the second example, whatever string oracle has does not matter, LCS will always be zero. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for j in range(0, t): n = int(input()) m = 100 for i in range(0, n): str = input() p = min(str.count("a",0,len(str)),str.count("b",0,len(str))) if (m > p): m = p print(m) t = t-1 ```
{ "language": "python", "test_cases": [ { "input": "3\n2\nab\nba\n2\naa\nbb\n3\naabb\nabab\nbaab\n", "output": "1\n0\n2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/DEC15/problems/ORACLCS" }
vfc_4810
apps
verifiable_code
1493
Solve the following coding problem using the programming language python: Devu is a class teacher of a class of n students. One day, in the morning prayer of the school, all the students of his class were standing in a line. You are given information of their arrangement by a string s. The string s consists of only letters 'B' and 'G', where 'B' represents a boy and 'G' represents a girl. Devu wants inter-gender interaction among his class should to be maximum. So he does not like seeing two or more boys/girls standing nearby (i.e. continuous) in the line. e.g. he does not like the arrangements BBG and GBB, but he likes BG, GBG etc. Now by seeing the initial arrangement s of students, Devu may get furious and now he wants to change this arrangement into a likable arrangement. For achieving that, he can swap positions of any two students (not necessary continuous). Let the cost of swapping people from position i with position j (i ≠ j) be c(i, j). You are provided an integer variable type, then the cost of the the swap will be defined by c(i, j) = |j − i|type. Please help Devu in finding minimum cost of swaps needed to convert the current arrangement into a likable one. -----Input----- The first line of input contains an integer T, denoting the number of test cases. Then T test cases are follow. The first line of each test case contains an integer type, denoting the type of the cost function. Then the next line contains string s of length n, denoting the initial arrangement s of students. Note that the integer n is not given explicitly in input. -----Output----- For each test case, print a single line containing the answer of the test case, that is, the minimum cost to convert the current arrangement into a likable one. If it is not possible to convert the current arrangement into a likable one, then print -1 instead of the minimum cost. -----Constraints and Subtasks-----Subtask 1: 25 points - 1 ≤ T ≤ 105 - 1 ≤ n ≤ 105 - type = 0 - Sum of n over all the test cases in one test file does not exceed 106. Subtask 2: 25 points - 1 ≤ T ≤ 105 - 1 ≤ n ≤ 105 - type = 1 - Sum of n over all the test cases in one test file does not exceed 106. Subtask 3: 25 points - 1 ≤ T ≤ 105 - 1 ≤ n ≤ 105 - type = 2 - Sum of n over all the test cases in one test file does not exceed 106. Subtask 4: 25 points - 1 ≤ T ≤ 102 - 1 ≤ n ≤ 103 - type can be 0, 1 or 2, that is type ∈ {0, 1, 2}. -----Example----- Input: 8 0 BB 0 BG 0 BBGG 1 BGG 1 BGGB 1 BBBGG 2 BBGG 2 BGB Output: -1 0 1 1 1 3 1 0 -----Explanation----- Note type of the first 3 test cases is 0. So c(i, j) = 1. Hence we just have to count minimum number of swaps needed. Example case 1. There is no way to make sure that both the boys does not stand nearby. So answer is -1. Example case 2. Arrangement is already valid. No swap is needed. So answer is 0. Example case 3. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is 1. Now type of the next 3 test cases is 1. So c(i, j) = |j − i|, that is, the absolute value of the difference between i and j. Example case 4. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBG which is a valid arrangement. So answer is |1 - 0| = 1. Example case 5. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBGB which is a valid arrangement. So answer is |1 - 0| = 1. Example case 6. Swap boy at position 1 with girl at position 4. After swap the arrangement will be BGBGB which is a valid arrangement. So answer is |4 - 1| = 3. Then type of the last 2 test cases is 2. So c(i, j) = (j − i)2 Example case 7. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is (2 - 1)2 = 1. Example case 8. Arrangement is already valid. No swap is needed. So answer is 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def outOfIndex(boys,girls,COST): if COST == 0: return len(boys) else: total_cost = [ abs(x-y) for x,y in zip(boys,girls)] total_cost = sum(total_cost) return total_cost for _ in range(int(input())): COST = int(input()) queue = input() B = queue.count('B') G = queue.count('G') boys=[] girls = [] if (abs(B-G)>1): print(-1) else: if B > G: for c in range(len(queue)): if c%2!=0 and queue[c]=='B': boys.append(c) if c%2==0 and queue[c] =='G': girls.append(c) print(outOfIndex(boys,girls,COST)) boys.clear() girls.clear() elif B < G: for c in range(len(queue)): if c%2!=0 and queue[c]=='G': girls.append(c) if c%2==0 and queue[c] =='B': boys.append(c) print(outOfIndex(boys,girls,COST)) boys.clear() girls.clear() else: for c in range(len(queue)): if c%2!=0 and queue[c]=='B': boys.append(c) if c%2==0 and queue[c] =='G': girls.append(c) attempt1 = outOfIndex(boys,girls,COST) boys.clear() girls.clear() for c in range(len(queue)): if c%2!=0 and queue[c]=='G': girls.append(c) if c%2==0 and queue[c] =='B': boys.append(c) attempt2 = outOfIndex(boys,girls,COST) print(min(attempt1,attempt2)) boys.clear() girls.clear() ```
{ "language": "python", "test_cases": [ { "input": "8\n0\nBB\n0\nBG\n0\nBBGG\n1\nBGG\n1\nBGGB\n1\nBBBGG\n2\nBBGG\n2\nBGB\n", "output": "-1\n0\n1\n1\n1\n3\n1\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/DEVCLASS" }
vfc_4814
apps
verifiable_code
1494
Solve the following coding problem using the programming language python: Rohit has n empty boxes lying on the ground in a line. The size of the boxes is given in the form of an array $a$. The size of the ith box is denoted by $a[i]$. Since Rohit has a tiny room, there is a shortage of space. Therefore, he has to reduce the number of boxes on the ground by putting a box into another box that is at least twice the size of the current box i.e if we have to put the ith box into the jth box then $( 2*a[i] ) <= a[j]$. Each box can contain a maximum of one box and the box which is kept in another box cannot hold any box itself. Find the minimum number of boxes that will remain on the ground after putting boxes into each other. -----Input:----- - The first line contains a single integer n. - The next n lines contain the integer a[i] - the size of the i-th box. -----Output:----- Output a single integer denoting the minimum number of boxes remaining on the ground. -----Constraints----- - $1 \leq n \leq 5*10^5$ - $1 \leq a[i] \leq 10^5$ -----Subtasks----- - 30 points : $1 \leq n \leq 10^2$ - 70 points : $1 \leq n \leq 5*10^5$ -----Sample Input:----- 5 16 1 4 8 2 -----Sample Output:----- 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n=int(input()) l=[0]*n for i in range(n): l[i]=int(input()) l.sort() s=0 i=n-1 while i>=0: x=2*l[i] if l[-1]>=x: j=i while j<len(l): if l[j]>=x: l.pop(j) l.pop(i) s+=1 break j+=1 i-=1 s+=len(l) print(s) ```
{ "language": "python", "test_cases": [ { "input": "5\n16\n1\n4\n8\n2\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/POPU2021/problems/BXRED" }
vfc_4818
apps
verifiable_code
1495
Solve the following coding problem using the programming language python: After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vacation and get back to work. But after a tiresome season, Watson is in no mood to return soon. So to keep Holmes engaged, he decided to give Holmes one math problem. And Holmes agreed to solve the problem and said as soon as he solves the problem, they should return back to work. Watson too agreed. The problem was as follows. Watson knows Holmes’ favorite numbers are 6 and 5. So he decided to give Holmes N single digit numbers. Watson asked Holmes to form a new number with the given N numbers in such a way that the newly formed number should be completely divisible by 5 and 6. Watson told Holmes that he should also form the number from these digits in such a way that the formed number is maximum. He may or may not use all the given numbers. But he is not allowed to use leading zeros. Though he is allowed to leave out some of the numbers, he is not allowed to add any extra numbers, which means the maximum count of each digit in the newly formed number, is the same as the number of times that number is present in those given N digits. -----Input----- The first line of input contains one integers T denoting the number of test cases. Each test case consists of one integer N, number of numbers. Next line contains contains N single digit integers -----Output----- For each test case output a single number, where the above said conditions are satisfied. If it is not possible to create such a number with the given constraints print -1.If there exists a solution, the maximised number should be greater than or equal to 0. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 10000 - 0 ≤ Each digit ≤ 9 -----Subtasks----- Subtask #1 : (90 points) - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 10000 Subtask 2 : (10 points) - 1 ≤ T ≤ 10 - 1 ≤ N≤ 10 -----Example----- Input: 2 12 3 1 2 3 2 0 2 2 2 0 2 3 11 3 9 9 6 4 3 6 4 9 6 0 Output: 33322222200 999666330 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for i in range(0,t): n=int(input()) lis=list(map(int,input().split())) lis2=[] for j in range(0,10): lis2.append(0) for j in range(0,len(lis)): lis2[lis[j]]+=1; s=sum(lis) while s%3!=0: if s%3==2: if lis2[2]>=1: lis2[2]-=1 s=s-2 elif lis2[5]>=1: lis2[5]-=1 s=s-5 elif lis2[8]>=1: lis2[8]-=1 s=s-8 elif lis2[1]>=2: lis2[1]-=2 s=s-2 elif lis2[1]>=1 and lis2[4]>=1: lis2[1]-=1 lis2[4]-=1 s=s-5 elif lis2[4]>=2: lis2[4]-=2 s=s-8 elif lis2[1]>=1 and lis2[7]>=1: lis2[1]-=1 lis2[7]-=1 s=s-8 elif lis2[4]>=1 and lis2[7]>=1: lis2[4]-=1 lis2[7]-=1 s=s-11 elif lis2[7]>=2: lis2[7]-=2 s=s-14 elif s%3==1: if lis2[1]>=1: lis2[1]-=1 s=s-1 elif lis2[4]>=1: lis2[4]-=1 s=s-4 elif lis2[7]>=1: lis2[7]-=1 s=s-7 elif lis2[2]>=2: lis2[2]-=2 s=s-4 elif lis2[5]>=1 and lis2[2]>=1: lis2[2]-=1 lis2[5]-=1 s=s-7 elif lis2[5]>=2: lis2[5]-=2 s=s-10 elif lis2[2]>=1 and lis2[8]>=1: lis2[2]-=1 lis2[8]-=1 s=s-10 elif lis2[8]>=1 and lis2[5]>=1: lis2[8]-=1 lis2[5]-=1 s=s-13 elif lis2[8]>=2: lis2[8]-=2 s=s-16 lis3=[] for j in range(1,10): if lis2[j]>=1: for k in range(0,lis2[j]): lis3.append(j) lis3.reverse() for k in range(0,lis2[0]): lis3.append(0) sol='' for k in range(0,len(lis3)): sol+=str(lis3[k]) print(sol) ```
{ "language": "python", "test_cases": [ { "input": "2\n12\n3 1 2 3 2 0 2 2 2 0 2 3\n11\n3 9 9 6 4 3 6 4 9 6 0\n", "output": "33322222200\n999666330\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/LOCJUL16/problems/NUMHOLMS" }
vfc_4822
apps
verifiable_code
1496
Solve the following coding problem using the programming language python: Chef has a nice complete binary tree in his garden. Complete means that each node has exactly two sons, so the tree is infinite. Yesterday he had enumerated the nodes of the tree in such a way: - Let's call the nodes' level a number of nodes that occur on the way to this node from the root, including this node. This way, only the root has the level equal to 1, while only its two sons has the level equal to 2. - Then, let's take all the nodes with the odd level and enumerate them with consecutive odd numbers, starting from the smallest levels and the leftmost nodes, going to the rightmost nodes and the highest levels. - Then, let's take all the nodes with the even level and enumerate them with consecutive even numbers, starting from the smallest levels and the leftmost nodes, going to the rightmost nodes and the highest levels. - For the better understanding there is an example: 1 / \ 2 4 / \ / \ 3 5 7 9 / \ / \ / \ / \ 6 8 10 12 14 16 18 20 Here you can see the visualization of the process. For example, in odd levels, the root was enumerated first, then, there were enumerated roots' left sons' sons and roots' right sons' sons. You are given the string of symbols, let's call it S. Each symbol is either l or r. Naturally, this sequence denotes some path from the root, where l means going to the left son and r means going to the right son. Please, help Chef to determine the number of the last node in this path. -----Input----- The first line contains single integer T number of test cases. Each of next T lines contain a string S consisting only of the symbols l and r. -----Output----- Per each line output the number of the last node in the path, described by S, modulo 109+7. -----Constraints----- - 1 ≤ |T| ≤ 5 - 1 ≤ |S| ≤ 10^5 - Remember that the tree is infinite, so each path described by appropriate S is a correct one. -----Example----- Input: 4 lrl rll r lllr Output: 10 14 4 13 -----Explanation----- See the example in the statement for better understanding the samples. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here MOD=10**9+7 for _ in range(int(input())): s=input() ind=1 level=1 for i in range(len(s)): if s[i]=='l': if level%2==1: ind=ind*2 else: ind=ind*2-1 if s[i]=='r': if level%2==1: ind=ind*2+2 else: ind=ind*2+1 level+=1 ind%=MOD print(ind) ```
{ "language": "python", "test_cases": [ { "input": "4\nlrl\nrll\nr\nlllr\n\n", "output": "10\n14\n4\n13\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/CHEFLR" }
vfc_4826
apps
verifiable_code
1497
Solve the following coding problem using the programming language python: Divya's watch of worth Rs10 cr is abducted by N thieves(1,2....i...N). The fight over the watch leads to a final decision that it should belong to the thief who wins a simple game. The rules of the game state that every thief registers a time in the format HH:MM:SS . Accordingly the average A of three clockwise angles between the hours , minutes and seconds hands is calculated . Thus the ith thief with the maximum A wins the game and gets to keep the watch. The thieves are poor in mathematics and will need your help . Given the number of thieves and their registered time resolves the conflict and help them in choosing the winner -----Input----- First line of input contains T which denotes the number of test cases. The first line of each test case consists of an integer which denotes the number of thieves thereby N line follow which give the time choosen by each thieve in the format HH:MM:SS. -----Output:----- Output single integer i which denotes the ith thief. -----Constraints:----- 1<=T<=100 1<=N<=50 01<=HH<=12 00<=MM<=60 00<=SS<=60 -----Example:----- Input: 2 3 12:28:26 07:26:04 11:23:17 2 07:43:25 06:23:34 Output: 3 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for t in range(int(input())): n = int(input()) mx = -1 for i in range(n): h, m, s = list(map(int,input().split(":"))) h %= 12 m %= 60 s %= 60 ha = h*30 + m*0.5 + s*0.5/60 ma = m*6 + s*0.1 sa = s*6 hm1 = abs(ha - ma) hm2 = 360 - hm1 hm3 = abs(hm1 - hm2) hm = min(hm1, hm2, hm3) ms1 = abs(ma - sa) ms2 = 360 - ms1 ms3 = abs(ms1 - ms2) ms = min(ms1, ms2, ms3) sh1 = abs(sa - ha) sh2 = 360 - sh1 sh3 = abs(sh1 - sh2) sh = min(sh1, sh2, sh3) avg = (hm + ms + sh) / 3 if (mx < avg): ans = i+1 mx = avg print(ans) ```
{ "language": "python", "test_cases": [ { "input": "2\n3\n12:28:26\n07:26:04\n11:23:17\n2\n07:43:25\n06:23:34\n", "output": "3\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ITRA2016/problems/ITRA06" }
vfc_4830
apps
verifiable_code
1498
Solve the following coding problem using the programming language python: Ash is on his way to becoming the Pokemon Master. His pokemon can perform the following moves: - Tackle - Deal damage worth $X$ points - Grow - Increase damage by $Y$ points i.e. $X$ = $X$ + $Y$ But, it can only perform Grow first (0 or more times) and then tackle (0 or more) times after which it cannot perform Grow again. That is, it cannot perform the Grow operation once it has performed the tackle operation. A pokemon can be caught only if it’s health is exactly 1. A wild pokemon has appeared and has health worth $H$ points. Find the minimum number of moves required to catch it or say that it is not possible. -----Input:----- - The first line of the input consists of a single integer $T$ denoting the number of test cases. - Each test case consists of 3 space-separated integers $H$, $X$ and $Y$. -----Output:----- - For each test case, print a single line containing one integer - the minimum number of moves required to catch the pokemon if it is possible to catch it else print -1. -----Constraints----- - 1 <= $T$ <= 103 - 1 <= $X$, $Y$ < $H$ <= 109 -----Subtasks----- Subtask #1 (30 points): - 1 <= $X$, $Y$ < $H$ <= 1000 Subtask #2 (70 points): - Original Constraints -----Sample Input:----- 2 101 10 10 11 3 3 -----Sample Output:----- 6 -1 -----EXPLANATION:----- - Example Case 1: Ash can make use of Grow once. So $X$ = 10 + 10 = 20 Then he can do Tackle 5 times to decrease $H$ to 1. OR Ash can make use of Grow 4 times. So $X$ = 10 + 4*10 = 50 Then he can do Tackle 2 times to decrease $H$ to 1. Hence, a total of 6 moves are required either way which is minimum. - Example Case 2: No matter how many times Ash uses Grow or Tackle, pokemon can never be caught. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def Testcase(): h,x,y = [int(x) for x in input().strip().split()] h = h-1 yt = h//y +1 # print(yt) flag=0 ans = 100000000009 for i in range(0,yt): temp = x+i*y if h%temp==0: flag = 1 cl =i+int(h/temp) # print(temp,cl) ans = min(ans,cl) # print(temp,ans,i) print(ans if flag==1 else '-1') t = int(input()) while t>0: Testcase() t-=1 ```
{ "language": "python", "test_cases": [ { "input": "2\n101 10 10\n11 3 3\n", "output": "6\n-1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/TCFL2020/problems/TCFL20D" }
vfc_4834
apps
verifiable_code
1499
Solve the following coding problem using the programming language python: Given $N *M$ matrix containing elements either $1$ or $0$ and string S of length $N+M-1$ containing characters $0$ or $1$. Your task is to make all the paths from top left corner to the bottom right corner of the matrix same as the given string .You can perform two types of operations any time .Path means you can only allow it to take right or down. Operations : - Changing the matrix elements from $1$ to $0$ or vice versa will cost P rupees per element. - Changing the character of string from $1$ to $0$ or vice versa will cost Q rupees per character. You have to minimize the cost, (possibly 0) . -----Input:----- - First line of input contains the total no. of test cases $T$. - For every test case, first line of input contains two spaced positive integers, $N$ and $M$. - Next $N$ lines contains $M$-spaced integers which can be only $0$ or $1$. - Next line of input contains a string $S$ of length $N+M-1$. - Last line of input contains two spaced integers, $P$ and $Q$. -----Output:----- - $You$ $have$ $to$ $print$ $the$ $minimum$ $cost .$ -----Constraints----- - $1 \leq T \leq 20$ - $1 \leq N, M \leq 1000$ - $|S| = N+M-1$ - $0 \leq P, Q \leq 1000$The input/output is quite large, please use fast reading and writing methods. -----Sample Input----- 2 3 3 1 0 1 0 1 1 1 1 0 10111 10 5 3 3 0 0 1 0 1 1 0 1 1 00011 2 9 -----Sample Output----- 5 4 -----Explanation----- - You can change the last element of the matrix and also can change the last element of string but the minimum cost will produce by changing string element , therefore it will cost 5 rupees. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from sys import stdin,stdout import math,bisect from collections import Counter,deque,defaultdict L=lambda:list(map(int, stdin.readline().strip().split())) M=lambda:list(map(int, stdin.readline().strip().split())) I=lambda:int(stdin.readline().strip()) S=lambda:stdin.readline().strip() C=lambda:stdin.readline().strip().split() def pr(a):return(" ".join(list(map(str,a)))) #_________________________________________________# def solve(): n, m = M() a = [] for i in range(n): a += [L()] s = S() p, q = M() ans = [[0,0] for i in range(n+m)] for i in range(n): for j in range(m): if a[i][j]==0: ans[i+j][0]+=1 else: ans[i+j][1]+=1 c = 0 for i in range(n+m-1): A,B,C,D = 0,0,0,0 if s[i]=='0': A = ans[i][1]*p B = q + ans[i][0]*p c+=min(A,B) else: C = ans[i][0]*p D = q + ans[i][1]*p c+=min(C,D) print(c) for _ in range(I()): solve() ```
{ "language": "python", "test_cases": [ { "input": "2\n3 3\n1 0 1\n0 1 1\n1 1 0\n10111\n10 5\n3 3\n0 0 1\n0 1 1\n0 1 1\n00011\n2 9\n", "output": "5\n4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/LOGI2020/problems/MATMIN1" }
vfc_4838
apps
verifiable_code
1500
Solve the following coding problem using the programming language python: A valid parentheses sequence is a non-empty string where each character is either '(' or ')', which satisfies the following constraint: You can find a way to repeat erasing adjacent pairs of parentheses '()' until it becomes empty. For example, '(())' and '()((()()))' are valid parentheses sequences, but ')()(' and '(()' are not. Mike has a valid parentheses sequence. He really likes everything about his sequence, except the fact that it is quite long. So Mike has recently decided that he will replace his parentheses sequence with a new one in the near future. But not every valid parentheses sequence will satisfy him. To help you understand his requirements we'll introduce the pseudocode of function F(S): FUNCTION F( S - a valid parentheses sequence ) BEGIN balance = 0 max_balance = 0 FOR index FROM 1 TO LENGTH(S) BEGIN if S[index] == '(' then balance = balance + 1 if S[index] == ')' then balance = balance - 1 max_balance = max( max_balance, balance ) END RETURN max_balance END In other words, F(S) is equal to the maximal balance over all prefixes of S. Let's denote A as Mike's current parentheses sequence, and B as a candidate for a new one. Mike is willing to replace A with B if F(A) is equal to F(B). He would also like to choose B with the minimal possible length amongst ones satisfying the previous condition. If there are several such strings with the minimal possible length, then Mike will choose the least one lexicographically, considering '(' to be less than ')'. Help Mike! -----Input----- The first line of the input contains one integer T denoting the number of testcases to process. The only line of each testcase contains one string A denoting Mike's parentheses sequence. It is guaranteed that A only consists of the characters '(' and ')'. It is also guaranteed that A is a valid parentheses sequence. -----Output----- The output should contain exactly T lines, one line per each testcase in the order of their appearance. The only line of each testcase should contain one string B denoting the valid parentheses sequence that should be chosen by Mike to replace A. -----Constraints----- 1 ≤ T ≤ 5; 1 ≤ |A| ≤ 100000(105). -----Example----- Input: 1 ()((()())) Output: ((())) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python try: for i in range(int(input())): s=input() balance=0 max_balance=0 for i in s: if i=='(':balance+=1 else: balance-=1 max_balance=max(max_balance,balance) print('('*max_balance,')'*max_balance,sep="") except Exception as e: print(e) ```
{ "language": "python", "test_cases": [ { "input": "1\n()((()()))\n\n\n", "output": "((()))\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/BRACKETS" }
vfc_4842
apps
verifiable_code
1501
Solve the following coding problem using the programming language python: Given a Complete Binary Tree of ‘n’ depth, you can perform 4 types of mirror operation on the tree:- Mirror on the right. The tree is mirrored to the right and rightmost node on every level is connected with the mirrored corresponding node. Mirror on the left. The tree is mirrored to the left and leftmost node on every level is connected with the mirrored corresponding node. Mirror on the top. The tree is mirrored to the top and topmost nodes are connected with corresponding nodes. Mirror on the bottom. The tree is mirrored to the bottom and bottom most nodes are connected with the corresponding nodes. See the image for details. Mirror Right: Mirror Bottom: You are given ‘q’ queries, each performing this type of operation or asking for the no of edges in the produced graph. Queries are of the form “1 x” or “2” where x is 1 for right, 2 for left, 3 for top or 4 for bottom. 1 x: Perform x operation on the result graph. 2: Print the no of edges in the graph. Since it can be very large, print it modulo 1000000007. -----Input:----- - First line will contain $n$, the depth of the initial tree and $q$, the number of queries. - Next $q$ lines contain queries of the form "1 $x$" or "2". -----Output:----- For each query of type "2", output a single line containing the no of edges in the graph modulo 1000000007. -----Constraints----- - $1 \leq n \leq 1000$ - $1 \leq q \leq 10^5$ - $1 \leq x \leq 4$ -----Sample Input:----- 2 3 1 1 1 4 2 -----Sample Output:----- 38 -----EXPLANATION:----- Initial no of edges = 6 After the operation 1 1, no of edges = 15 After the operation 1 4, no of edges = 38 At operation 2, we print the no of edges that is 38. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import os,sys from io import BytesIO, IOBase def ii(): return int(input()) def si(): return input() def mi(): return list(map(int,input().split())) def li(): return list(mi()) import math import collections def CountFrequency(arr): return collections.Counter(arr) for i in range(1): n,q=mi() p=pow(2,n+1)-2 t=1 b=pow(2,n) s=n+1 for i in range(q): a=li() if len(a)==2: if a[1]==1 or a[1]==2: p*=2 p+=s t*=2 b*=2 else: p*=2 if a[1]==3: p+=t t=b s*=2 else: p+=b b=t s*=2 else: print(p%1000000007) ```
{ "language": "python", "test_cases": [ { "input": "2 3\n1 1\n1 4\n2\n", "output": "38\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/MIRTREE" }
vfc_4846
apps
verifiable_code
1502
Solve the following coding problem using the programming language python: Your are given a string $S$ containing only lowercase letter and a array of character $arr$. Find whether the given string only contains characters from the given character array. Print $1$ if the string contains characters from the given array only else print $0$. Note: string contains characters in lower case only. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains- a string $S$ of lowercase letter a integer $n$ denoting length of character array $arr$ next line contains $n$ space separated characters. -----Output:----- For each testcase, Print $1$ if the string contains characters from the given array only else print $0$. -----Constraints----- - $1 \leq T \leq 1000$ - $0 \leq n \leq 10^5$ -----Sample Input:----- 3 abcd 4 a b c d aabbbcccdddd 4 a b c d acd 3 a b d -----Sample Output:----- 1 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for _ in range(t): S=set(input().strip()) n=int(input().strip()) a=set(input().strip().split(" ")) g=True for i in S: if(i not in a): g=False if(g): print(1) else: print(0) ```
{ "language": "python", "test_cases": [ { "input": "3\nabcd\n4\na b c d\naabbbcccdddd\n4\na b c d\nacd\n3\na b d\n", "output": "1\n1\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CDGO2021/problems/STRNCHAR" }
vfc_4850
apps
verifiable_code
1503
Solve the following coding problem using the programming language python: Santosh has a farm at Byteland. He has a very big family to look after. His life takes a sudden turn and he runs into a financial crisis. After giving all the money he has in his hand, he decides to sell his plots. The speciality of his land is that it is rectangular in nature. Santosh comes to know that he will get more money if he sells square shaped plots. So keeping this in mind, he decides to divide his land into minimum possible number of square plots, such that each plot has the same area, and the plots divide the land perfectly. He does this in order to get the maximum profit out of this. So your task is to find the minimum number of square plots with the same area, that can be formed out of the rectangular land, such that they divide it perfectly. -----Input----- - The first line of the input contains $T$, the number of test cases. Then $T$ lines follow. - The first and only line of each test case contains two space-separated integers, $N$ and $M$, the length and the breadth of the land, respectively. -----Output----- For each test case, print the minimum number of square plots with equal area, such that they divide the farm land perfectly, in a new line. -----Constraints----- $1 \le T \le 20$ $1 \le M \le 10000$ $1 \le N \le 10000$ -----Sample Input:----- 2 10 15 4 6 -----SampleOutput:----- 6 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import math N=int(input()) for i in range(N): a,b=list(map(int,input().split())) c=a//math.gcd(a,b)*b//math.gcd(a,b) print(c) ```
{ "language": "python", "test_cases": [ { "input": "2\n10 15\n4 6\n", "output": "6\n6\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/RECTSQ" }
vfc_4854
apps
verifiable_code
1504
Solve the following coding problem using the programming language python: To make Yalalovichik even more satisfied and happy, Jafar decided to invent Yalalovichik strings. A string is called a Yalalovichik string if the set of all of its distinct non-empty substrings is equal to the set of all of its distinct non-empty subsequences. You are given a string S$S$. You need to find the number of its distinct non-empty substrings which are Yalalovichik strings. Note: A string A$A$ is called a subsequence of a string B$B$ if A$A$ can be formed by erasing some characters (possibly none) from B$B$. A string A$A$ is called a substring of a string B$B$ if it can be formed by erasing some characters (possibly none) from the beginning of B$B$ and some (possibly none) from the end of B$B$. Two substrings or subsequences are considered different if they are different strings. -----Input----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer N=|S|$N = |S|$. - The second line contains the string S$S$. -----Output----- For each test case, print a single line containing one integer — the number of distinct Yalalovichik substrings of S$S$. -----Constraints----- - 1≤T≤100$1 \le T \le 100$ - 1≤N≤106$1 \le N \le 10^6$ - the sum of N$N$ over all test cases does not exceed 2⋅106$2 \cdot 10^6$ - S$S$ contains only lowercase English letters -----Example Input----- 1 3 xxx -----Example Output----- 3 -----Explanation----- Example case 1: The distinct Yalalovichik substrings are "x", "xx" and "xxx". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n,s = int(input()),input().strip() previ,num,_s,dic = s[0],0,[],{} for i in s: if previ == i: num+=1 continue _s.append((previ, num)) if previ not in dic or dic[previ]<num:dic[previ] = num previ,num = i,1 _s.append((previ, num)) if previ not in dic or dic[previ]<num:dic[previ] = num sum1 = sum(dic.values()) del dic, s l,dicc = [i for (i, j) in _s],{} congr = [(l[i], l[i+1]) for i in range(len(l)-1)] for i in range(len(congr)): if congr[i] not in dicc:dicc[congr[i]] = set() dicc[congr[i]].add( (_s[i][1], _s[i+1][1]) ) sum2,ll = 0,[] for i in dicc.keys(): sortedset,deleted = sorted(list(dicc[i])),[] for k in range(1, len(sortedset)): j = sortedset[k] if j[1]>sortedset[k-1][1]: ind = k - 1 ```
{ "language": "python", "test_cases": [ { "input": "1\n3\nxxx\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/YVSTR" }
vfc_4858
apps
verifiable_code
1506
Solve the following coding problem using the programming language python: Cherry has a binary matrix $A$ consisting of $N$ rows and $M$ columns. The rows are numbered from $1$ to $N$, columns are numbered from $1$ to $M$. Element at row $i$ ($1$ ≤ $i$ ≤ $N$) and column $j$ ($1$ ≤ $j$ ≤ $M$) is denoted as $A_{ij}$. All elements of $A$ are either $0$ or $1$. He performs $Q$ queries on matrix. Each query is provided by four integers $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ which define the rectangle, where ($x_{1}$, $y_{1}$) stands for the coordinates of the top left cell of the rectangle, while ($x_{2}$, $y_{2}$) stands for the coordinates of the bottom right cell. You need to flip all the bits i.e. ($0$ to $1$, $1$ to $0$) that are located fully inside the query rectangle. Finally, print the matrix after performing all the queries. Note: $x_{1}$ represents the row number while $y_{1}$ represents the column number. -----Input:----- - The first line of the input contains two integers $N$ and $M$ — the number of rows and the number of columns in the matrix. - Each of the next $N$ lines contains a string of length $M$, where the $j^{th}$ character of $i^{th}$ line denotes the value of $A_{i,j}$. - Next line contains an integer $Q$ — the number of queries. - Then follow $Q$ lines with queries descriptions. Each of them contains four space-seperated integers $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ — coordinates of the up left and bottom right cells of the query rectangle. -----Output:----- Print the matrix, in the form of $N$ strings, after performing all the queries. -----Constraints----- - $1 \leq N,M \leq 1000$ - $0 \leq A_{ij} \leq 1$ - $1 \leq Q \leq 10^6$ - $1 \leq x_{1} \leq x_{2} \leq N$ - $1 \leq y_{1} \leq y_{2} \leq M$ -----Sample Input:----- 2 2 00 00 3 1 1 1 1 2 2 2 2 1 1 2 2 -----Sample Output:----- 01 10 -----Explanation:----- Example case 1: After processing the 1st query 1 1 1 1, matrix becomes: [1000][1000]\begin{bmatrix} 10 \\ 00 \end{bmatrix} After processing the 2nd query 2 2 2 2, the matrix becomes: [1001][1001]\begin{bmatrix} 10 \\ 01 \end{bmatrix} After processing the 3rd query 1 1 2 2, matrix becomes: [0110][0110]\begin{bmatrix} 01 \\ 10 \end{bmatrix} We need to output the matrix after processing all queries. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys,os,io,time,copy,math,queue,bisect from collections import deque from functools import lru_cache if os.path.exists('input.txt'): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') sys.setrecursionlimit(100000000) def main(): n,m=map(int,input().split()) mat=[] for _ in range(n): s=input() a=[] for i in s: a.append(int(i)) mat.append(a) Q=int(input()) ans=[[0 for i in range(m+1)] for j in range(n+1)] for i in range(Q): x1,y1,x2,y2=map(int,input().split()) x1-=1 y1-=1 x2-=1 y2-=1 ans[x1][y1]+=1 ans[x2+1][y1]-=1 ans[x1][y2+1]-=1 ans[x2+1][y2+1]+=1 for j in range(m+1): for i in range(1,n+1): ans[i][j]=ans[i-1][j]+ans[i][j] for i in range(n+1): for j in range(1,m+1): ans[i][j]=ans[i][j-1]+ans[i][j] for i in range(n): for j in range(m): mat[i][j]=(ans[i][j]+mat[i][j])%2 for m in mat: for i in m: print(i,end="") print("") main() ```
{ "language": "python", "test_cases": [ { "input": "2 2\n00\n00\n3\n1 1 1 1\n2 2 2 2\n1 1 2 2\n", "output": "01\n10\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/CENS20A" }
vfc_4866
apps
verifiable_code
1508
Solve the following coding problem using the programming language python: The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 0 01 10 012 101 210 0123 1012 2101 3210 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): n=int(input()) if n==1: print("0") else: s=[] for i in range(n): s.append(str(i)) print(''.join(s)) p=1 for i in range(n-1): s.pop(n-1) s=[str(p)]+s print(''.join(s)) p+=1 ```
{ "language": "python", "test_cases": [ { "input": "4\n1\n2\n3\n4\n", "output": "0\n01\n10\n012\n101\n210\n0123\n1012\n2101\n3210\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PEND2020/problems/ITGUY59" }
vfc_4874
apps
verifiable_code
1509
Solve the following coding problem using the programming language python: The Siruseri amusement park has a new attraction. It consists of a rectangular array of discs. Each disc is divided into four equal sectors and the four sectors are coloured with the colours Red, Blue, Green and Yellow (in some order). The ordering may be different in different discs. Here is a possible arrangment of the discs: You start at the top left disc. Your task is to walk down to the bottom right disc. In each step, you can rotate the current disc by $90$ degrees in the clockwise direction or move to a neighbouring disc. However, you can move to a neighbouring disc only if adjacent sectors of these two discs have the same colour. For example, in the figure above, you can move from the disc at position ($1$, $1$) to either of its neighbours. However, from the disc at position ($1$, $2$) you can only move to the disc at position ($1$, $1$). If you wish to move from ($1$, $2$) to ($1$, $3$) then you would have to rotate this disc three times so that the colour (red) on the adjacent sectors are the same. For each rotate move, a penalty point is added to the score. The aim is to reach the bottom right with as few penalty points as possible. For example, in the arrangement described in the above figure, the best possible score is $2$, corresponding to the following path: Move from ($1$, $1$) to ($2$, $1$). Move from ($2$, $1$) to ($2$, $2$). Rotate. Rotate. Move from ($2$, $2$) to ($2$, $3$). Move from ($2$, $3$) to ($1$, $3$). Move from ($1$, $3$) to ($1$, $4$). Finally, move from ($1$, $4$) to ($2$, $4$). Your task is to determine the minimum number of penalty points required to go from the top left disc to the bottom right disc for the given arrangement of discs. -----Input:----- The first line contains two integers $M$ and $N$. $M$ is the number of rows and $N$ is the number of columns in the given arrangment. This is followed by $M \times N$ lines of input. Lines $2$ to $N+1$, describe the colours on the discs on the first row, Lines $N+2$ to $2 \cdot N+1$ describe the colours on discs in the second row and so on. Each of these lines contain a permutation of the set {R, G, B, Y} giving the colours in the top, right, bottom and left sectors in that order. -----Output:----- A single integer on a single line indicating the minimum number of penalty points required to go from the top left disc to the bottom right disc for the given arrangement of discs. -----Constraints:----- - In $80 \%$ of the input, $1 \leq M,N \leq 60$. - In all the inputs $1 \leq M,N \leq 1000$. -----Sample Input----- 2 4 G Y B R B G R Y G Y B R G R B Y B Y G R G B R Y B R G Y B R G Y -----Sample Output----- 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #for _ in range(int(input()): #n,m = map(int,input().split()) #x = [int(w) for w in input().split()] #n = int(input()) #x = [int(input()) for _ in range(n)] #for i in range(n): #dt = {} for i in x:dt[i] = dt.get(i,0)+1 #dt = {k:v for k,v in sorted(x.items(), key=lambda i: i[1])} m,n = map(int,input().split()) # top,right,bottom,left x = [] for i in range(m): x.append([]) for j in range(n): clr = [w for w in input().split()] x[i].append(clr) import queue as Q dp = [float('inf')]*m for i in range(m): dp[i] = [float('inf')]*n dp[m-1][n-1] = 0 pq = Q.PriorityQueue() pq.put([dp[m-1][n-1],m-1,n-1]) visited = set() xx,yy = [-1,0,1,0],[0,1,0,-1] # top,right,bottom,left while not pq.empty(): pop = pq.get() cx,cy = pop[1],pop[2] if (cx,cy) not in visited: visited.add((cx,cy)) for k in range(4): nx,ny = cx+xx[k],cy+yy[k] if 0<=nx<m and 0<=ny<n and (nx,ny) not in visited: clr = x[cx][cy][k] #print("*",nx,ny,"_",k,clr) ind = x[nx][ny].index(clr) cost = (k-(ind+2)%4)%4 #print(cost) if dp[cx][cy]+cost < dp[nx][ny]: dp[nx][ny] = dp[cx][cy]+cost pq.put([dp[nx][ny],nx,ny]) #print("#############") #print(dp) print(dp[0][0]) ```
{ "language": "python", "test_cases": [ { "input": "2 4\nG Y B R\nB G R Y\nG Y B R\nG R B Y\nB Y G R\nG B R Y\nB R G Y\nB R G Y\n", "output": "2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/IARCSJUD/problems/MINTURN" }
vfc_4878
apps
verifiable_code
1510
Solve the following coding problem using the programming language python: You are playing a game where you have been sent in a town to collect 10 types of coin and their symbol are defined with $A, B, C, D, E, F, G, H , I, J$. In that town every enemy have a coin. By killing one you will get a coin from that enemy. Each enemy have only a unique coin. The challange of the game is You have to collect all the coin and only then you will get the victory. You are a brave gamer so you took this hard challange and successfully finished it. After finishing, you are thinking of the game. You know the order off collecting coin. Now you are thinking how many enemy did you have killed? Can you solve that out? -----Input:----- First line of the input is an integer $T$.Next T line consists of a string which denotes the order of your collecting coins. The string consists of Uppercase latin latter only and from A to J. -----Output:----- Print T line, in each line an integer with the number of enemy you have killed in the operation. -----Constraints----- - $1 \leq T \leq 5000$ -----Sample Input:----- 1 ABCDEFGHIJ -----Sample Output:----- 10 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): s = input() c = 0 for i in s: if i.isalpha() and i.isupper(): c += 1 print(c) ```
{ "language": "python", "test_cases": [ { "input": "1\nABCDEFGHIJ\n", "output": "10\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/NEWB2020/problems/HNH01" }
vfc_4882
apps
verifiable_code
1511
Solve the following coding problem using the programming language python: Chef loves to play with iron (Fe) and magnets (Ma). He took a row of $N$ cells (numbered $1$ through $N$) and placed some objects in some of these cells. You are given a string $S$ with length $N$ describing them; for each valid $i$, the $i$-th character of $S$ is one of the following: - 'I' if the $i$-th cell contains a piece of iron - 'M' if the $i$-th cell contains a magnet - '_' if the $i$-th cell is empty - ':' if the $i$-th cell contains a conducting sheet - 'X' if the $i$-th cell is blocked If there is a magnet in a cell $i$ and iron in a cell $j$, the attraction power between these cells is $P_{i,j} = K+1 - |j-i| - S_{i,j}$, where $S_{i,j}$ is the number of cells containing sheets between cells $i$ and $j$. This magnet can only attract this iron if $P_{i, j} > 0$ and there are no blocked cells between the cells $i$ and $j$. Chef wants to choose some magnets (possibly none) and to each of these magnets, assign a piece of iron which this magnet should attract. Each piece of iron may only be attracted by at most one magnet and only if the attraction power between them is positive and there are no blocked cells between them. Find the maximum number of magnets Chef can choose. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $K$. - The second line contains a single string $S$ with length $N$. -----Output----- For each test case, print a single line containing one integer ― the maximum number of magnets that can attract iron. -----Constraints----- - $1 \le T \le 2,000$ - $1 \le N \le 10^5$ - $0 \le K \le 10^5$ - $S$ contains only characters 'I', 'M', '_', ':' and 'X' - the sum of $N$ over all test cases does not exceed $5 \cdot 10^6$ -----Subtasks----- Subtask #1 (30 points): there are no sheets, i.e. $S$ does not contain the character ':' Subtask #2 (70 points): original constraints -----Example Input----- 2 4 5 I::M 9 10 MIM_XII:M -----Example Output----- 1 2 -----Explanation----- Example case 1: The attraction power between the only magnet and the only piece of iron is $5+1-3-2 = 1$. Note that it decreases with distance and the number of sheets. Example case 2: The magnets in cells $1$ and $3$ can attract the piece of iron in cell $2$, since the attraction power is $10$ in both cases. They cannot attract iron in cells $6$ or $7$ because there is a wall between them. The magnet in cell $9$ can attract the pieces of iron in cells $7$ and $6$; the attraction power is $8$ and $7$ respectively. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here for _ in range(int(input())) : n,k=map(int,input().split()) #reading the string s=input() i,j=0,0 q=0 while(i<n and j<n) : if(s[i]=='M') : if(s[j]=='I') : cnt=0 if(i>j) : p=s[j:i] cnt=p.count(':') else : p=s[i:j] cnt=p.count(':') t=k+1-abs(i-j)-cnt if(t>0) : q+=1 i+=1 j+=1 else: if(i<j) : i+=1 else: j+=1 elif(s[j]=='X') : j+=1 i=j else: j+=1 elif(s[i]=='X') : i+=1 j=i else: i+=1 print(q) ```
{ "language": "python", "test_cases": [ { "input": "2\n4 5\nI::M\n9 10\nMIM_XII:M\n", "output": "1\n2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/FEMA2" }
vfc_4886
apps
verifiable_code
1512
Solve the following coding problem using the programming language python: Tuzik and Vanya are playing the following game. They have an N × M board and a chip to indicate the current game position. The chip can be placed on any one cell of the game board, each of which is uniquely identified by an ordered pair of positive integers (r, c), where 1 ≤ r ≤ N is the row number and 1 ≤ c ≤ M is the column number. Initially, the chip is placed at the cell identified as (1, 1). For his move, a player can move it either 1, 2 or 3 cells up, or 1 or 2 cells to the right. The player who can not move the chip loses. In other words, a player suffers defeat if the chip is placed in the cell (N, M) at the start of his turn. Tuzik starts the game. You have to determine who will win the game if both players play optimally. -----Input----- The first line contains an integer T denoting the number of tests. Each of the following T lines contain two integers N and M. -----Output----- For each test output "Tuzik" or "Vanya" on a separate line, indicating who will win the game. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N, M ≤ 106 -----Example----- Input: 2 4 4 2 2 Output: Tuzik Vanya -----Explanation-----Test case 1: On his first turn Tuzik moves chip 3 cells up to the cell (4, 1). On his turn Vanya can move chip only right to the cell (4, 2) or to the cell (4, 3) and after that Tuzik moves it to (4, 4) and finishes the game. Test case 2: On his first Turn Tuzik can move chip to the cell (2, 1) or (1, 2), but on his next turn Vanya moves it to (2, 2) and wins the game. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python cases = int(input()) for _ in range(cases): rows, cols = map(int, input().split()) if (cols - 1) % 3 == 0 and (rows - 1) % 4 == 0: print('Vanya') elif (cols - 1) % 3 != 0 and (rows - 1) % 4 == 0: print('Tuzik') elif (cols - 1) % 3 == 0 and (rows - 1) % 4 != 0: print('Tuzik') else: if (cols - 1) % 3 == 1 and (rows - 1) % 4 == 1: print('Vanya') elif (cols - 1) % 3 == 2 and (rows - 1) % 4 == 2: print('Vanya') else: print('Tuzik') ```
{ "language": "python", "test_cases": [ { "input": "2\n4 4\n2 2\n", "output": "Tuzik\nVanya\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/TUZGMBR" }
vfc_4890
apps
verifiable_code
1513
Solve the following coding problem using the programming language python: Ishank lives in a country in which there are N$N$ cities and N−1$N-1$ roads. All the cities are connected via these roads. Each city has been assigned a unique number from 1 to N$N$. The country can be assumed as a tree, with nodes representing the cities and edges representing the roads. The tree is rooted at 1.Every Time, when a traveler through a road, he will either gain some amount or has to pay some amount. Abhineet is a traveler and wishes to travel to various cities in this country. There's a law in the country for travelers, according to which, when a traveler moves from the city A$A$ to city B$B$, where city A$A$ and B$B$ are connected by a road then the traveler is either paid or has to pay the amount of money equal to profit or loss respectively. When he moves from A$A$ to B$B$, he hires a special kind of vehicle which can reverse its direction at most once. Reversing the direction means earlier the vehicle is going towards the root, then away from the root or vice versa. Abhineet is analyzing his trip and therefore gave Q$Q$ queries to his friend, Ishank, a great coder. In every query, he gives two cities A$A$ and B$B$. Ishank has to calculate the maximum amount he can gain (if he cannot gain, then the minimum amount he will lose) if he goes from the city A$A$ to city B$B$. -----Input:----- -The first line of the input contains a two space-separated integers N and Q. -The next N-1 line contains 3 space-separated integers Xi and Yi and Zi denoting that cities Xi and Yi are connected by a road which gives profit Zi (Negative Zi represents loss). -The next Q contains 2 space-separated integers A and B denoting two cities. -----Output:----- Print a single line corresponding to each query — the maximum amount he can gain (if he cannot gain, then the minimum amount he will lose with negative sign) if he goes from city A to city B. -----Constraints----- - 2≤N≤105$2 \leq N \leq 10^5$ - 1≤Q≤105$1 \leq Q \leq 10^5$ - 1≤Xi,Yi,A,B≤N$1 \leq Xi, Yi, A, B \leq N$ - abs(Zi)≤109$ abs(Zi) \leq 10^9$ -----Sample Input:----- 9 5 1 2 8 1 3 -9 2 4 1 2 5 -6 3 6 7 3 7 6 6 8 3 6 9 4 1 2 2 7 4 3 3 2 8 9 -----Sample Output:----- 10 5 0 -1 21 -----EXPLANATION:----- In the first query, he goes from 1 to 2, 2 to 4, takes a turn and go to 2. Therefore profit=8+1+1=10. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: X=list(map(int, input().split())) except: X=[0,0] ch=[] chnew=[] par={} par[1]=0 for i in range(X[0]+1): ch.append([]) chnew.append([]) for i in range(X[0]-1): Y=list(map(int, input().split())) #par[Y[1]]=[Y[0],Y[2]] ch[Y[0]].append([Y[1],Y[2]]) ch[Y[1]].append([Y[0],Y[2]]) tre=[1] while(len(tre)): cr=tre[-1] tre=tre[:-1] for i in ch[cr]: chnew[cr].append(i) par[i[0]]=[cr,i[1]] tre.append(i[0]) for j in ch[i[0]]: if(j[0]==cr): ch[i[0]].remove(j) break ch=chnew def goup(par,nd): if(nd==1): return 0 else: p=par[nd] ans=p[1]+goup(par,p[0]) return (max([ans,0])) def godown(ch,nd): ans=0 for i in ch[nd]: ans=max([(i[1]+godown(ch,i[0])),ans]) return(ans) for i in range(X[1]): Z=list(map(int,input().split())) r=Z[0] s=Z[1] nans=0 while(r!=s): if(r>s): nans=nans+par[r][1] r=par[r][0] else: nans=nans+par[s][1] s=par[s][0] if((r==Z[0]) or (r==Z[1])): if(Z[0]<Z[1]): nans=nans+2*max(goup(par,Z[0]),godown(ch,Z[1])) else: nans=nans+2*max(goup(par,Z[1]),godown(ch,Z[0])) else: nans=nans+2*goup(par,r) print(nans) ```
{ "language": "python", "test_cases": [ { "input": "9 5\n1 2 8\n1 3 -9\n2 4 1\n2 5 -6\n3 6 7\n3 7 6\n6 8 3\n6 9 4\n1 2\n2 7\n4 3\n3 2\n8 9\n", "output": "10\n5\n0\n-1\n21\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/CTOUR" }
vfc_4894
apps
verifiable_code
1514
Solve the following coding problem using the programming language python: Raj is a math pro and number theory expert. One day, he met his age-old friend Chef. Chef claimed to be better at number theory than Raj, so Raj gave him some fuzzy problems to solve. In one of those problems, he gave Chef a 3$3$-tuple of non-negative integers (a0,b0,c0)$(a_0, b_0, c_0)$ and told Chef to convert it to another tuple (x,y,z)$(x, y, z)$. Chef may perform the following operations any number of times (including zero) on his current tuple (a,b,c)$(a, b, c)$, in any order: - Choose one element of this tuple, i.e. a$a$, b$b$ or c$c$. Either add 1$1$ to that element or subtract 1$1$ from it. The cost of this operation is 1$1$. - Merge: Change the tuple to (a−1,b−1,c+1)$(a-1, b-1, c+1)$, (a−1,b+1,c−1)$(a-1, b+1, c-1)$ or (a+1,b−1,c−1)$(a+1, b-1, c-1)$, i.e. add 1$1$ to one element and subtract 1$1$ from the other two. The cost of this operation is 0$0$. - Split: Change the tuple to (a−1,b+1,c+1)$(a-1, b+1, c+1)$, (a+1,b−1,c+1)$(a+1, b-1, c+1)$ or (a+1,b+1,c−1)$(a+1, b+1, c-1)$, i.e. subtract 1$1$ from one element and add 1$1$ to the other two. The cost of this operation is also 0$0$. After each operation, all elements of Chef's tuple must be non-negative. It is not allowed to perform an operation that would make one or more elements of this tuple negative. Can you help Chef find the minimum cost of converting the tuple (a0,b0,c0)$(a_0, b_0, c_0)$ to the tuple (x,y,z)$(x, y, z)$? It can be easily proved that it is always possible to convert any tuple of non-negative integers to any other. -----Input----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first and only line of each test case contains six space-separated integers a0$a_0$, b0$b_0$, c0$c_0$, x$x$, y$y$ and z$z$. -----Output----- For each test case, print a single line containing one integer ― the minimum cost. -----Constraints----- - 1≤T≤105$1 \le T \le 10^5$ - 0≤a0,b0,c0,x,y,z≤1018$0 \le a_0, b_0, c_0, x, y, z \le 10^{18}$ -----Subtasks----- Subtask #1 (20 points): 0≤a0,b0,c0,x,y,z≤100$0 \le a_0, b_0, c_0, x, y, z \le 100$ Subtask #2 (80 points): original constraints -----Example Input----- 2 1 1 1 2 2 2 1 2 3 2 4 2 -----Example Output----- 0 1 -----Explanation----- Example case 1: The tuple (1,1,1)$(1, 1, 1)$ can be converted to (2,2,2)$(2, 2, 2)$ using only three Split operations, with cost 0$0$: (1,1,1)→(2,0,2)→(1,1,3)→(2,2,2)$(1, 1, 1) \rightarrow (2, 0, 2) \rightarrow (1, 1, 3) \rightarrow (2, 2, 2)$. Example case 2: We can use one addition operation and one Split operation: (1,2,3)→(1,3,3)→(2,4,2)$(1, 2, 3) \rightarrow (1, 3, 3) \rightarrow (2, 4, 2)$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): a,b,c,x,y,z = list(map(int,input().split())) if a == 0 and b == 0 and c == 0 and x == 0 and y == 0 and z == 0: print(0) continue ans = 0 if a == 0 and b == 0 and c == 0: st = set((abs(x-a)%2,abs(y-b)%2,abs(z-c)%2)) if st == {0,1}: ans = 1 else: ans = 2 else: if x == 0 and y == 0 and z == 0: st = set((abs(x-a)%2,abs(y-b)%2,abs(z-c)%2)) if st == {0,1}: ans = 1 else: ans = 2 else: st = set((abs(x-a)%2,abs(y-b)%2,abs(z-c)%2)) if st == {0,1}: ans = 1 print(ans) ```
{ "language": "python", "test_cases": [ { "input": "2\n1 1 1 2 2 2\n1 2 3 2 4 2\n", "output": "0\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/FUZZYCON" }
vfc_4898
apps
verifiable_code
1515
Solve the following coding problem using the programming language python: Chefina is always interested to play with string. But due to exam pressure she has no time to solve a string problem. She wants your help. Can you help her to solve that problem? You are given a string. You have to find out the $Wonder$ $Sum$ of the string. $Wonder$ $Sum$ of a string is defined as the sum of the value of each character of the string. The value of each character means: - If the string is started with "a" , then the value of each character of the string is like "a"=100, "b"=101, "c"="102" ………"z"=125. - If the string is started with "z" , then the value of each character of the string is like "a"=2600, "b"=2601, "c"="2602" ………"z"=2625. Since even the $Wonder$ $Sum$ can be large, output $Wonder$ $Sum$ modulo ($10^9 + 7$). -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, a string $S$ with lower case alphabet only. -----Output:----- For each testcase, output in a single line integer i.e. $Wonder$ $Sum$ modulo ($10^9 + 7$). -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq |S| \leq 10^5$ -----Sample Input:----- $2$$cab$ $sdef$ -----Sample Output:----- $903$ $7630$ -----EXPLANATION:----- i) For the first test case, since the string is started with "$c$", so output is ($302$+$300$+$301$)=$903$ ii)For the second test case, since the string is started with "$s$", so output is ($1918$+$1903$+$1904$+$1905$)=$7630$ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): string = input().rstrip() start=(ord(string[0])-96)*100 sum=0 #print(start) for i in range(len(string)): sum+=start+(ord(string[i])-97) print(sum%1000000007) ```
{ "language": "python", "test_cases": [ { "input": "2\ncab\nsdef\n", "output": "903\n7630\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/NOOB2020/problems/NBC005" }
vfc_4902
apps
verifiable_code
1516
Solve the following coding problem using the programming language python: Chef wants to make a feast. In order to do that, he needs a lot of different ingredients. Each ingredient has a certain tastiness; the tastiness of each ingredient may be any positive integer. Initially, for each tastiness between $K$ and $K+N-1$ (inclusive), Chef has an infinite supply of ingredients with this tastiness. The ingredients have a special property: any two of them can be mixed to create a new ingredient. If the original ingredients had tastiness $x$ and $y$ (possibly $x = y$), the new ingredient has tastiness $x+y$. The ingredients created this way may be used to mix other ingredients as well. Chef is free to mix ingredients in any way he chooses any number of times. Let's call a tastiness $v$ ($v > 0$) unreachable if there is no way to obtain an ingredient with tastiness $v$; otherwise, tastiness $v$ is reachable. Chef wants to make ingredients with all reachable values of tastiness and he would like to know the number of unreachable values. Help him solve this problem. Since the answer may be large, compute it modulo $1,000,000,007$ ($10^9+7$). Note that there is an infinite number of reachable values of tastiness, but it can be proven that the number of unreachable values is always finite for $N \ge 2$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $N$ and $K$. -----Output----- For each test case, print a single line containing one integer — the number of unreachable values of tastiness, modulo $1,000,000,007$. -----Constraints----- - $1 \le T \le 10^5$ - $2 \le N \le 10^{18}$ - $1 \le K \le 10^{18}$ -----Subtasks----- Subtask #1 (20 points): $N = 2$ Subtask #2 (80 points): original constraints -----Example Input----- 2 2 1 3 3 -----Example Output----- 0 2 -----Explanation----- Example case 1: It is possible to obtain ingredients with all values of tastiness. Example case 2: Ingredients with tastiness $1$ and $2$ cannot be made. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python __author__ = 'Prateek' MOD = int(10**9+7) def test(): n,k=list(map(int,input().split())) l = k d =n-1 ans = l-1 ans = ans%MOD a = k-n term = (d+a)//d ll = (a%MOD - (((term-1)%MOD)*(d%MOD))%MOD)%MOD if ll < 0: ll = (ll +MOD)%MOD m = ((term%MOD)*((a%MOD+ll%MOD)%MOD))%MOD m = (m*pow(2,MOD-2,MOD))%MOD ans += m ans = ans%MOD print(ans) if __author__ == 'Prateek': t = int(input()) for _ in range(t): test() ```
{ "language": "python", "test_cases": [ { "input": "2\n2 1\n3 3\n", "output": "0\n2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/CHFING" }
vfc_4906
apps
verifiable_code
1517
Solve the following coding problem using the programming language python: Consider a number X on which K Mag-Inc operations are to be performed. In a Mag-Inc operation, the number X undergoes an increment of A/B times of X where A and B are two integers. There is a numerator and a denominator array of size K which contain the ith values of A and B. After K Mag-Inc operations, the number X turns to M. Now your job is to find what percentage of M is to be decremented from M if it has to be converted back to X. Let this percentage be denoted by Z. Print the integral part of Z. -----Input:----- First line contains an integer T denoting the number of test cases. First line of every test case contains two space separated integers X and K. The second and third line of every test case will contain K space separated integers denoting the Numerator and Denominator array. -----Output:----- For each test case, print the required result in a single line. -----Constraints:----- 1 ≤ T ≤ 100 1 ≤ K, A, B ≤ 40000 1≤X≤10^100 -----Example:-----Input: 2 100 1 1 4 100 2 1 1 2 3Output: 20 50 -----Explanation:----- Case 2: 100 undergoes an increment of (1/2)*100. Therefore M = 100 + 50. Now M = 150. Now again, M undergoes an increment of (1/3)*150. Therefore, M = 150 + 50. Now as we want to revert back M = 200 to X i.e. 100, we need to decrement it by a value of 100 and we know that 100 is 50% of 200. Hence, we print 50. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys import math def solution(): T = int(input().strip()) for _ in range(T): x, k = list(map(float, input().strip().split(' '))) original_x = x if k == 1: a = [float(input().strip())] b = [float(input().strip())] else: a = list(map(float, input().strip().split(' '))) b = list(map(float, input().strip().split(' '))) for i in range(int(k)): x = x + (a[i]/b[i])*(x) percentage = ((x - original_x) / x)*100 print("%d"%(int(percentage))) solution() ```
{ "language": "python", "test_cases": [ { "input": "2\n100 1\n1\n4\n100 2\n1 1\n2 3\n", "output": "20\n50\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CCWR2016/problems/CCWR02" }
vfc_4910
apps
verifiable_code
1518
Solve the following coding problem using the programming language python: The chef was busy in solving algebra, he found some interesting results, that there are many numbers which can be formed by sum of some numbers which are prime. Chef wrote those numbers in dairy. Cheffina came and saw what the chef was doing. Cheffina immediately closed chef's dairy and for testing chef's memory, she starts asking numbers and chef needs to answer wheater given number N can be formed by the sum of K prime numbers if it yes then print 1 else print 0. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, two integers $N, K$. -----Output:----- For each test case, output in a single line answer as 1 or 0. -----Constraints----- - $1 \leq T \leq 10^5$ - $2 \leq N \leq 10^5$ - $1 \leq K \leq 10^5$ -----Sample Input:----- 2 12 2 11 2 -----Sample Output:----- 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import sqrt def isprime(n): if (n % 2 == 0 and n > 2) or n == 1: return 0 else: s = int(sqrt(n)) + 1 for i in range(3, s, 2): if n % i == 0: return 0 return 1 def find(N, K): if (N < 2 * K): return 0 if (K == 1): return isprime(N) if (K == 2): if (N % 2 == 0): return 1 return isprime(N - 2); return 1 for _ in range(int(input())): n, k = list(map(int, input().split())) print(find(n, k)) ```
{ "language": "python", "test_cases": [ { "input": "2\n12 2\n11 2\n", "output": "1\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PBK22020/problems/ITGUY27" }
vfc_4914
apps
verifiable_code
1519
Solve the following coding problem using the programming language python: In order to win over and get noticed by his favorite streamer Daenerys, Jon decides to donate a significant amount of money . Every donation made to Daenerys is of $at$ $least$ $1$ $beastcoin$ and is displayed on Daenerys's stream alongside any message written and is visible to every viewer. After spotting that Daenerys had set out a target for the streaming day at minimum $X$ beastcoins, all her viewers would only donate amounts less than $X$ beastcoins. Jon decided to better all of them by straight out donating more than or equal to $X$ beastcoins. Further, he decides to write a message along with his special donation to leave her in awe. His message would be : "Crossing my donation with any other donation will only increase the value of my donation". By Crossing, he means to take the $XOR$ . But even for all his intellectual brilliance, money doesn't grow on trees for Jon. After all he is an underpaid employee in his fancy big name MNC. Unlike Daenerys's daily cash cow who makes videos of how she donated carelessly to other people, Jon has a budget and in this case too, he is looking for the minimum donation he needs to make. Can you tell Jon the minimum amount he needs to donate to Daenerys so that he is able to credibly put out the above comment alongside the donation in order to HOPEFULLY win her over. -----Input Format----- - First line contain an interger $T$, which denotes number of testcases. Next $T$ lines contain single interger $X$. -----Output Format----- - For every testcase print one integer, i.e. minimum donation Jon needs to make. -----Constriants----- - $ 1 \leq T \leq 100000 $ - $ 2 \leq X \leq 10^{18} $ -----Sample Input----- 2 3 7 -----Sample Output----- 4 8 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input(''))): n=int(input('')) x=bin(n) x=len(x)-2 if n==(2**(x-1)): print(n) else: print(2**x) ```
{ "language": "python", "test_cases": [ { "input": "2\n3\n7\n", "output": "4\n8\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/INSO2020/problems/INQU2000" }
vfc_4918
apps
verifiable_code
1520
Solve the following coding problem using the programming language python: Given an array of n$n$ integers : A1,A2,...,An$ A_1, A_2,... , A_n$, find the longest size subsequence which satisfies the following property: The xor of adjacent integers in the subsequence must be non-decreasing. -----Input:----- - First line contains an integer n$n$, denoting the length of the array. - Second line will contain n$n$ space separated integers, denoting the elements of the array. -----Output:----- Output a single integer denoting the longest size of subsequence with the given property. -----Constraints----- - 1≤n≤103$1 \leq n \leq 10^3$ - 0≤Ai≤1018$0 \leq A_i \leq 10^{18}$ -----Sample Input:----- 8 1 200 3 0 400 4 1 7 -----Sample Output:----- 6 -----EXPLANATION:----- The subsequence of maximum length is {1, 3, 0, 4, 1, 7} with Xor of adjacent indexes as {2,3,4,5,6} (non-decreasing) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here n=int(input()) l=[int(i) for i in input().split()] xors=[] for i in range(n): for j in range(i+1,n): xors.append([l[i]^l[j],(i,j)]) xors.sort() #print(xors) upto=[0]*n for i in range(len(xors)): #a=xors[i][0] b,c=xors[i][1][0],xors[i][1][1] upto[c]=max(upto[c],upto[b]+1) #print(upto) print(max(upto)+1) ```
{ "language": "python", "test_cases": [ { "input": "8\n1 200 3 0 400 4 1 7\n", "output": "6\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/XOMMON" }
vfc_4922
apps
verifiable_code
1521
Solve the following coding problem using the programming language python: The Siruseri Singing Championship is going to start, and Lavanya wants to figure out the outcome before the tournament even begins! Looking at past tournaments, she realizes that the judges care only about the pitches that the singers can sing in, and so she devises a method through which she can accurately predict the outcome of a match between any two singers. She represents various pitches as integers and has assigned a lower limit and an upper limit for each singer, which corresponds to their vocal range. For any singer, the lower limit will always be less than the upper limit. If a singer has lower limit $L$ and upper limit $U$ ($L < U$), it means that this particular singer can sing in all the pitches between $L$ and $U$, that is they can sing in the pitches {$L, L+1, L+2, \ldots, U$}. The lower bounds and upper bounds of all the singers are distinct. When two singers $S_i$ and $S_j$ with bounds ($L_i$, $U_i)$ and ($L_j$, $U_j$) compete against each other, $S_i$ wins if they can sing in every pitch that $S_j$ can sing in, and some more pitches. Similarly, $S_j$ wins if they can sing in every pitch that $S_i$ can sing in, and some more pitches. If neither of those two conditions are met, the match ends up as a draw. $N$ singers are competing in the tournament. Each singer competes in $N$-1 matches, one match against each of the other singers. The winner of a match scores 2 points, and the loser gets no points. But in case of a draw, both the singers get 1 point each. You are given the lower and upper bounds of all the $N$ singers. You need to output the total scores of each of the $N$ singers at the end of the tournament. -----Input----- - The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows. - The first line of every testcase contains a single integer, $N$, which is the number of singers. - $N$ lines follow, the i-th of which contains two integers: $L_i$ and $U_i$, which correspond to the lower bound and upper bound of the i-th singer. -----Output----- For each testcase output a single line containing $N$ integers, the i-th of which should be score of the i-th singer at the end of the tournament. -----Constraints----- - $1 \le T \le 5$ - $2 \le N \le 10^5$ - $1 \le L_i < U_i \le 10^9$ - All the $2*N$ integers (lower bounds and upper bounds) are distinct. -----Subtasks----- Subtask #1 (15 points): $1 \le N \le 10^3$ Subtask #2 (25 points): - $1 \le N \le 10^5$ - It is guaranteed that no match ends in a draw. Subtask #3 (60 points): Original constraints. -----Sample Input----- 2 3 10 20 13 18 15 19 3 10 22 13 21 15 20 -----Sample Output----- 4 1 1 4 2 0 -----Explanation----- Testcase 1: There are three singers, with the lower bounds and upper bounds as (10, 20), (13, 18) and (15, 19). When the first singer and second singer compete against each other in a match, we see that the second singer can sing in the pitches {13, 14, 15, 16, 17, 18}. Whereas the first singer can sing in the pitches {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}. So, we see that the first singer can sing everything that the second singer can, and also some other pitches. Hence the first singer wins this match, and gets 2 points. The second singer gets no points from this match. When the first singer and third singer compete against each other in a match, we see that the third singer can sing in the pitches {15, 16, 17, 18, 19}. So again, we see that the first singer can sing everything that the third singer can. Hence the first singer wins this match, and gets 2 points. The third singer gets no points from this match. When the second singer and third singer compete against each other in a match, we see that the second singer can sing in the pitches {13, 14, 15, 16, 17, 18}, whereas the third singer can sing in the pitches {15, 16, 17, 18, 19}. In particular, the second singer can sing in the pitch 14, which the third singer cannot sing in. And the third singer can sing in the pitch 19, which the second singer cannot sing in. So neither of the two conditions are met, and hence this match ends in a draw. Both the second and third singer get 1 point each. Thus at the end of the tournament, the total score of first player is 2 + 2 = 4. Total score of the second player is 0 + 1 = 1. Total score of the third player is 0 + 1 = 1. Hence the output is 4 1 1 Testcase 2: There are three singers, with the lower bounds and upper bounds as (10, 22), (13, 21) and (15, 20). We see that the first singer wins against both second and third singers. And the second singer wins against the third singer. So the final total scores are (2 + 2), (0 + 2), (0 + 0), which is 4 2 0. Note that this would be a valid testcase in Subtask 2, because no match ends in a draw. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from operator import itemgetter t=int(input()) for _ in range(t): n=int(input()) start=[] end=[] for i in range(n): first, last = map (int, input().split()) start.append((first, i)) end.append((last, i)) score=[0]*n start.sort(key=itemgetter(0)) end.sort(key=itemgetter(0), reverse=True) for i in range(n-1): score[start[i][1]]+=n-i-1 score[end[i][1]]+=n-i-1 print(' '.join([str(i) for i in score])) ```
{ "language": "python", "test_cases": [ { "input": "2\n3\n10 20\n13 18\n15 19\n3\n10 22\n13 21\n15 20\n", "output": "4 1 1\n4 2 0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ZCOPRAC/problems/SINGTOUR" }
vfc_4926
apps
verifiable_code
1522
Solve the following coding problem using the programming language python: Kira likes to play with strings very much. Moreover he likes the shape of 'W' very much. He takes a string and try to make a 'W' shape out of it such that each angular point is a '#' character and each sides has same characters. He calls them W strings. For example, the W string can be formed from "aaaaa#bb#cc#dddd" such as: a a d a # d a b c d a b c d # # He also call the strings which can generate a 'W' shape (satisfying the above conditions) W strings. More formally, a string S is a W string if and only if it satisfies the following conditions (some terms and notations are explained in Note, please see it if you cannot understand): - The string S contains exactly 3 '#' characters. Let the indexes of all '#' be P1 < P2 < P3 (indexes are 0-origin). - Each substring of S[0, P1−1], S[P1+1, P2−1], S[P2+1, P3−1], S[P3+1, |S|−1] contains exactly one kind of characters, where S[a, b] denotes the non-empty substring from a+1th character to b+1th character, and |S| denotes the length of string S (See Note for details). Now, his friend Ryuk gives him a string S and asks him to find the length of the longest W string which is a subsequence of S, with only one condition that there must not be any '#' symbols between the positions of the first and the second '#' symbol he chooses, nor between the second and the third (here the "positions" we are looking at are in S), i.e. suppose the index of the '#'s he chooses to make the W string are P1, P2, P3 (in increasing order) in the original string S, then there must be no index i such that S[i] = '#' where P1 < i < P2 or P2 < i < P3. Help Kira and he won't write your name in the Death Note. Note: For a given string S, let S[k] denote the k+1th character of string S, and let the index of the character S[k] be k. Let |S| denote the length of the string S. And a substring of a string S is a string S[a, b] = S[a] S[a+1] ... S[b], where 0 ≤ a ≤ b < |S|. And a subsequence of a string S is a string S[i0] S[i1] ... S[in−1], where 0 ≤ i0 < i1 < ... < in−1 < |S|. For example, let S be the string "kira", then S[0] = 'k', S[1] = 'i', S[3] = 'a', and |S| = 4. All of S[0, 2] = "kir", S[1, 1] = "i", and S[0, 3] = "kira" are substrings of S, but "ik", "kr", and "arik" are not. All of "k", "kr", "kira", "kia" are subsequences of S, but "ik", "kk" are not. From the above definition of W string, for example, "a#b#c#d", "aaa#yyy#aaa#yy", and "o#oo#ooo#oooo" are W string, but "a#b#c#d#e", "#a#a#a", and "aa##a#a" are not. -----Input----- First line of input contains an integer T, denoting the number of test cases. Then T lines follow. Each line contains a string S. -----Output----- Output an integer, denoting the length of the longest W string as explained before. If S has no W string as its subsequence, then output 0. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ |S| ≤ 10000 (104) - S contains no characters other than lower English characters ('a' to 'z') and '#' (without quotes) -----Example----- Input: 3 aaaaa#bb#cc#dddd acb#aab#bab#accba abc#dda#bb#bb#aca Output: 16 10 11 -----Explanation----- In the first case: the whole string forms a W String. In the second case: acb#aab#bab#accba, the longest W string is acb#aab#bab#accba In the third case: abc#dda#bb#bb#aca, note that even though abc#dda#bb#bb#aca (boldened characters form the subsequence) is a W string of length 12, it violates Ryuk's condition that there should not be any #'s inbetween the 3 chosen # positions. One correct string of length 11 is abc#dda#bb#bb#aca The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def frequency(s,n): f=[[0 for i in range(26)]for j in range(n+1)] count=0 for i in range(n): if s[i]!="#": f[count][ord(s[i])-97]+=1 else: count+=1 for j in range(26): f[count][j]=f[count-1][j] return (f,count) def solve(s): n=len(s) f,count=frequency(s,n) if count<3: return 0 ans=0 index=[] for i in range(n-1,-1,-1): if s[i]=="#": index.append(i) for c in range(1,count-2+1): if index[-2]==index[-1]+1 or index[-3]==index[-2]+1: index.pop() continue left=max(f[c-1]) mid1=0 mid2=0 right=0 for j in range(26): mid1=max(mid1,f[c][j]-f[c-1][j]) mid2=max(mid2,f[c+1][j]-f[c][j]) right=max(right,f[count][j]-f[c+1][j]) if left and mid1 and mid2 and right: ans=max(ans,left+mid1+mid2+right) index.pop() return ans for _ in range(int(input())): s=input() ans=solve(s) if ans: print(ans+3) else: print(0) ```
{ "language": "python", "test_cases": [ { "input": "3\naaaaa#bb#cc#dddd\nacb#aab#bab#accba\nabc#dda#bb#bb#aca\n\n\n", "output": "16\n10\n11\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/WSTRING" }
vfc_4930
apps
verifiable_code
1523
Solve the following coding problem using the programming language python: Zonal Computing Olympiad 2014, 30 Nov 2013 In IPL 2025, the amount that each player is paid varies from match to match. The match fee depends on the quality of opposition, the venue etc. The match fees for each match in the new season have been announced in advance. Each team has to enforce a mandatory rotation policy so that no player ever plays three matches in a row during the season. Nikhil is the captain and chooses the team for each match. He wants to allocate a playing schedule for himself to maximize his earnings through match fees during the season. -----Input format----- Line 1: A single integer N, the number of games in the IPL season. Line 2: N non-negative integers, where the integer in position i represents the fee for match i. -----Output format----- The output consists of a single non-negative integer, the maximum amount of money that Nikhil can earn during this IPL season. -----Sample Input 1----- 5 10 3 5 7 3 -----Sample Output 1----- 23 (Explanation: 10+3+7+3) -----Sample Input 2----- 8 3 2 3 2 3 5 1 3 -----Sample Output 2----- 17 (Explanation: 3+3+3+5+3) -----Test data----- There is only one subtask worth 100 marks. In all inputs: • 1 ≤ N ≤ 2×105 • The fee for each match is between 0 and 104, inclusive. -----Live evaluation data----- There are 12 test inputs on the server during the exam. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here n=int(input()) l=list(map(int,input().split())) temp=[] for item in l: temp.append(item) if(n<=3): print(sum(temp)) else: for i in range(3,n): temp[i]=l[i]+min(temp[i-1],temp[i-2],temp[i-3]) res=sum(l)-min(temp[n-1],temp[n-2],temp[n-3]) print(res) ```
{ "language": "python", "test_cases": [ { "input": "5\n10 3 5 7 3\n", "output": "23\n(\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ZCOPRAC/problems/ZCO14004" }
vfc_4934
apps
verifiable_code
1524
Solve the following coding problem using the programming language python: Zombies zombies everywhere!! In a parallel world of zombies, there are N zombies. There are infinite number of unused cars, each of same model only differentiated by the their colors. The cars are of K colors. A zombie parent can give birth to any number of zombie-children (possibly zero), i.e. each zombie will have its parent except the head zombie which was born in the winters by combination of ice and fire. Now, zombies are having great difficulties to commute to their offices without cars, so they decided to use the cars available. Every zombie will need only one car. Head zombie called a meeting regarding this, in which he will allow each zombie to select a car for him. Out of all the cars, the head zombie chose one of cars for him. Now, he called his children to choose the cars for them. After that they called their children and so on till each of the zombie had a car. Head zombie knew that it won't be a good idea to allow children to have cars of same color as that of parent, as they might mistakenly use that. So, he enforced this rule during the selection of cars. Professor James Moriarty is a criminal mastermind and has trapped Watson again in the zombie world. Sherlock somehow manages to go there and met the head zombie. Head zombie told Sherlock that they will let Watson free if and only if Sherlock manages to tell him the maximum number of ways in which the cars can be selected by N Zombies among all possible hierarchies. A hierarchy represents parent-child relationships among the N zombies. Since the answer may be large, output the answer modulo 109 + 7. Sherlock can not compute big numbers, so he confides you to solve this for him. -----Input----- The first line consists of a single integer T, the number of test-cases. Each test case consists of two space-separated integers N and K, denoting number of zombies and the possible number of colors of the cars respectively. -----Output----- For each test-case, output a single line denoting the answer of the problem. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 10^9 - 1 ≤ K ≤ 10^9 -----Subtasks----- Subtask #1 : (10 points) - 1 ≤ T ≤ 20 - 1 ≤ N, K ≤ 10 Subtask 2 : (20 points) - 1 ≤ T ≤ 10 - 1 ≤ N, K ≤ 10000 Subtask 3 : (70 points) - 1 ≤ T ≤ 100 - 1 ≤ N, K ≤ 10^9 -----Example----- Input 2 2 2 3 3 Output: 2 12 -----Explanation In the first sample test case, there are 2 zombies. Let us name them Z1 and Z2. Let one hierarchy be one in which Z1 is parent of Z2. There are 2 colors, suppose red and blue. If Z1 takes red, then Z2 should take a blue. If Z1 takes blue, then Z2 should take red. Note that one other possible hierarchy could be one in which Z2 is a parent of Z1. In that hierarchy also, number of possible ways of assigning cars is 2. So there maximum number of possible ways is 2. In the second example, we have 3 Zombies say Z1, Z2, Z3 and cars of 3 colors, suppose red, blue and green. A hierarchy to maximize the number of possibilities is Z1 is the parent of Z2, Z2 is the parent of Z3. Zombie Z1 can choose one of red, blue or green cars. Z2 can choose one of the remaining two colors (as its car's color can not be same as its parent car.). Z3 can also choose his car in two colors, (one of them could be color same as Z1, and other being the color which is not same as cars of both Z1 and Z2.). This way, there can be 12 different ways of selecting the cars. ----- In the first sample test case, there are 2 zombies. Let us name them Z1 and Z2. Let one hierarchy be one in which Z1 is parent of Z2. There are 2 colors, suppose red and blue. If Z1 takes red, then Z2 should take a blue. If Z1 takes blue, then Z2 should take red. Note that one other possible hierarchy could be one in which Z2 is a parent of Z1. In that hierarchy also, number of possible ways of assigning cars is 2. So there maximum number of possible ways is 2. In the second example, we have 3 Zombies say Z1, Z2, Z3 and cars of 3 colors, suppose red, blue and green. A hierarchy to maximize the number of possibilities is Z1 is the parent of Z2, Z2 is the parent of Z3. Zombie Z1 can choose one of red, blue or green cars. Z2 can choose one of the remaining two colors (as its car's color can not be same as its parent car.). Z3 can also choose his car in two colors, (one of them could be color same as Z1, and other being the color which is not same as cars of both Z1 and Z2.). This way, there can be 12 different ways of selecting the cars. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python ways=x=0 val=10**9 remi=((10**9)+7) t=int(input()) for i in range(t): n,k=list(map(int,input().split())) if t<=100 and n>=1 and k<=val: x=(k-1)**(n-1) ways=k*x ways=ways%remi print(ways) x=ways=0 else: break ```
{ "language": "python", "test_cases": [ { "input": "2\n2 2\n3 3\n", "output": "2\n12\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/APRIL16/problems/BIPIN3" }
vfc_4938
apps
verifiable_code
1525
Solve the following coding problem using the programming language python: The Chef has a huge square napkin of size 2n X 2n. He folds the napkin n-3 times. Each time he folds its bottom side over its top side, and then its right side over its left side. After each fold, the side length of the napkin is reduced by half. The Chef continues folding until there remains a 8x8 sheet, lying flat on a table. Oh, did I forget to mention that the Chef was cooking a new brown colored curry while folding the napkin. He drops some brown colored gravy onto some cells in the folded 8x8 napkin. When he drops the gravy, it soaks through all the cells below it. Now the Chef unfolds the napkin to its original size. There are now many curry stained brown colored cells in the napkin. They form several separate regions, each of which is connected. Could you help the Chef count how many regions of brown cells are there in the napkin? Note that two cells are adjacent if they share a common edge (they are not considered adjacent if they only share a corner). Two cells are connected if we can go from one cell to the other via adjacent cells. A region is a maximal set of cells such that every two of its cells are connected. Please see the example test case for more details. -----Input----- The first line contains t, the number of test cases (about 50). Then t test cases follow. Each test case has the following form: - The first line contains N (3 ≤ N ≤ 109) - Then, 8 lines follow. Each line is a string of 8 characters, 0 or 1, where 1 denotes a stained brown cell in the folded napkin. -----Output----- For each test case, print a single number that is the number of disconnected brown regions in the unfolded napkin. Since the result may be a very large number, you only need to print its remainder when dividing by 21945. -----Example----- Input: 3 3 01000010 11000001 00000000 00011000 00011000 00010100 00001000 00000000 4 01000010 11000001 00000000 00011000 00011000 00010100 00001000 00000000 1000000000 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 Output: 6 22 1 -----Output details----- Case 1 and 2: There are 6 brown regions in the 8x8 napkin. If we unfold it once, it has 22 brown regions: 11 regions in the top half and 11 regions in the bottom half (as shown in the figure above). Case 3: All cells of the napkin are stained, so there is always one brown region, no matter how many times the Chef unfolds the napkin. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys t = int(sys.stdin.readline()) def identify(x, y): rows[x][y] = '2' r = 0 if x == 0: r |= 1 elif rows[x-1][y] == '1': r |= identify(x-1, y) if x == 7: r |= 4 elif rows[x+1][y] == '1': r |= identify(x+1, y) if y == 0: r |= 2 elif rows[x][y-1] == '1': r |= identify(x, y-1) if y == 7: r |= 8 elif rows[x][y+1] == '1': r |= identify(x, y+1) return r P = 21945 while t: t-=1 n = int(sys.stdin.readline())-3 rows = [list(sys.stdin.readline().strip()) for i in range(8)] total = 0 for i in range(8): for j in range(8): if rows[i][j] == '1': r = identify(i,j) # print '\n'.join([''.join(ro) for ro in rows]) # print r if n == 0: total += 1 # print total continue if r == 0: total += pow(2, 2*n, P) elif r == 1 or r == 2 or r == 4 or r == 8: total += pow(2, 2*n-1, P) if r == 1 or r == 2: total += pow(2, n, P) elif r == 5 or r == 10: total += pow(2, n, P) elif r == 3 or r == 6 or r == 12 or r == 9: total += pow(2, 2*n-2, P) if r == 3: total += 3 + 2*pow(2, n-1, P) - 2 elif r == 6 or r == 9: total += pow(2, n-1, P) elif r == 15: total += 1 else: total += pow(2, n-1, P) if r == 11 or r == 7: total += 1 # print total print(total % P) ```
{ "language": "python", "test_cases": [ { "input": "3\n3\n01000010\n11000001\n00000000\n00011000\n00011000\n00010100\n00001000\n00000000\n4\n01000010\n11000001\n00000000\n00011000\n00011000\n00010100\n00001000\n00000000\n1000000000\n11111111\n11111111\n11111111\n11111111\n11111111\n11111111\n11111111\n11111111\n\n\n", "output": "6\n22\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/AUG09/problems/F3" }
vfc_4942
apps
verifiable_code
1527
Solve the following coding problem using the programming language python: Today is Chef's birthday. His mom decided to surprise him with a truly fantastic gift: his favourite binary string B. But, unfortunately, all the stocks of binary string B have been sold out, and only a binary string A (A ≠ B) is available in the market. She purchases the string A and tries to convert it to string B by applying any of following three operations zero or more times. AND Operation: She will choose a pair of indices i and j such that i != j and perform following sequence of operations. - result = Ai & Aj - Ai = result & Ai - Aj = result & Aj OR Operation: She will choose a pair of indices i and j such that i != j and perform following sequence of operations. - result = Ai | Aj - Ai = result | Ai - Aj = result | Aj XOR Operation: She will choose a pair of indices i and j such that i != j and perform following sequence of operations. - result = Ai ^ Aj - Ai = result ^ Ai - Aj = result ^ Aj Chef's mom is eagerly waiting to surprise him with his favourite gift and therefore, she wants to convert string A to string B as fast as possible. Can you please help her by telling her the minimum number of operations she will require? If it is impossible to do so, then let Chef's mom know about it. -----Input----- First line of input contains a single integer T denoting the number of test cases. T test cases follow. First line of each test case, will contain binary string A. Second line of each test case, will contain binary string B. -----Output----- For each test case, Print "Lucky Chef" (without quotes) in first line and minimum number of operations required to convert string A to sting B in second line if conversion is possible. Print "Unlucky Chef" (without quotes) in a new line otherwise. -----Constraints----- - 1 ≤ T ≤ 105 - 1 ≤ |A| ≤ 106 - 1 ≤ |B| ≤ 106 - A != B - |A| = |B| - sum of |A| over all test cases does not exceed 106 - sum of |B| over all test cases does not exceed 106 -----Subtasks----- - Subtask #1 (40 points) : Sum of |A| & |B| over all test cases does not exceed 103 - Subtask #2 (60 points) : Sum of |A| & |B| over all test cases does not exceed 106 -----Example----- Input 2 101 010 1111 1010 Output Lucky Chef 2 Unlucky Chef -----Explanation----- Example case 1. - Applying XOR operation with indices i = 1 and j = 2. Resulting string will be 011. - Then, Applying AND operation with indices i = 1 and j = 3. Resulting string will be 010. Example case 2. - It is impossible to convert string A to string B. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for j in range(int(input())): a=input() b=input() c,d=0,0 a0=a.count("0") a1=a.count("1") if(a0==len(a) or a1==len(a)): print("Unlucky Chef") else: print("Lucky Chef") for i in range(len(a)): if(a[i]!=b[i]): if(a[i]=="0"): c+=1 else: d+=1 print(max(c,d)) ```
{ "language": "python", "test_cases": [ { "input": "2\n101\n010\n1111\n1010\n", "output": "Lucky Chef\n2\nUnlucky Chef\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/BINOP" }
vfc_4950
apps
verifiable_code
1528
Solve the following coding problem using the programming language python: You are Dastan, the great Prince of Persia! After searching long for the mysterious 'Sands of Time', you have finally arrived at the gates of the city that hosts the ancient temple of the gods. However, the gate is locked and it can only be opened with a secret code, which you need to obtain by solving the following puzzle: There is a table in front of you, with $N$ coins placed in a row and numbered $1$ through $N$ from left to right. For each coin, you know whether it is initially showing heads or tails. You have to perform exactly $K$ operations. In one operation, you should remove the rightmost coin present on the table, and if this coin was showing heads right before it was removed, then you should also flip all the remaining coins. (If a coin was showing heads, then after it is flipped, it is showing tails, and vice versa.) The code needed to enter the temple is the number of coins which, after these $K$ operations are performed, have not been removed and are showing heads. Can you find this number? The fate of Persia lies in your hands… -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $K$. - The second line contains $N$ space-separated characters. For each valid $i$, the $i$-th of these characters is 'H' if the $i$-th coin is initially showing heads or 'T' if it is showing tails. -----Output----- For each test case, print a single line containing one integer ― the number of coins that are showing heads after $K$ operations. -----Constraints----- - $1 \le T \le 200$ - $1 \le K < N \le 100$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 3 5 3 H T T H T 7 4 H H T T T H H 6 1 T H T H T T -----Example Output----- 1 2 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for i in range(t): n,k=[int(i) for i in input().split()] l=input().split() for i in range(k): if l.pop()=='H': for ind,j in enumerate(l): if j=='H': l[ind]='T' else: l[ind]='H' print(sum([1 for i in l if i=='H'])) ```
{ "language": "python", "test_cases": [ { "input": "3\n5 3\nH T T H T\n7 4\nH H T T T H H\n6 1\nT H T H T T\n", "output": "1\n2\n2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/POPGATES" }
vfc_4954
apps
verifiable_code
1529
Solve the following coding problem using the programming language python: During Quarantine Time Chef is at home and he was quite confused about what to cook so, he went to his son and asked about what would he prefer to have? He replied, cakes. Now, chef cook $N$ number of cake and number of layers for every cake is different. After cakes are baked, Chef arranged them in a particular order and then generates a number by putting number of layers of cakes as digit in sequence (e.g., if chef arranges cakes with layers in sequence $2$, $3$ and $5$ then generated number is $235$). Chef has to make his son powerful in mathematics, so he called his son and ask him to arrange the cakes in all the possible ways and every time when different sequence is generated he has to note down the number. At the end he has to find sum of all the generated numbers. So, help him to complete this task. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line of each test case contains a single integer $N$ denoting number of cakes. - The second line contains $N$ space-separated integers $L1$ $L2$ … $LN$ layers of the cake. -----Output:----- For each test case, print a single line containing sum of all the possible numbers which is generated by arranging cake in different sequence. -----Constraints :----- - $1 \leq T \leq 2*10^5$ - $1 \leq N, L1, L2, L3,…, LN \leq 9$ -----Sample Input:----- 1 3 2 3 5 -----Sample Output:----- 2220 -----Explanation:----- Sum of all possibilities : $235 + 532 + 253 + 352 + 523 + 325 = 2220 $ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #cook your recipe from math import factorial test_cases = int(input()) for _ in range(test_cases): n = int(input()) sum1 = 0 final_sum = 0 num = list(map(int, input().split())) rep_time = factorial(n - 1) rep_count = dict() for i in num: if i in rep_count: rep_count[i] +=1 else: rep_count[i] =1 for j in rep_count: if rep_count[j] ==1: sum1 += j * factorial(n - rep_count[j]) else: sum1 += j * factorial(n-1)/ factorial(n - rep_count[j]) for k in range(n): final_sum += sum1 * (10**k) print(int(final_sum)) ```
{ "language": "python", "test_cases": [ { "input": "1\n3\n2 3 5\n", "output": "2220\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/QFUN2020/problems/CHEFCAKE" }
vfc_4958
apps
verifiable_code
1530
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 5 1 2 3 4 5 -----Sample Output:----- 1 1 32 1 32 654 1 32 654 10987 1 32 654 10987 1514131211 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) for i in range(n): for j in range(n): if i>=j: print(int((i+1)*(i+2)/2)-j,end='') print() ```
{ "language": "python", "test_cases": [ { "input": "5\n1\n2\n3\n4\n5\n", "output": "1\n1\n32\n1\n32\n654\n1\n32\n654\n10987\n1\n32\n654\n10987\n1514131211\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PTRN2020/problems/ITGUY44" }
vfc_4962
apps
verifiable_code
1531
Solve the following coding problem using the programming language python: Bobby has decided to hunt some Parrots. There are n horizontal branch of trees aligned parallel to each other. Branches are numbered 1 to n from top to bottom. On each branch there are some parrots sitting next to each other. Supposed there are a[i]$a[i]$ parrots sitting on the i−th$ i-th$ branch. Sometimes Bobby shots one of the parrot and the parrot dies (suppose that this parrots sat at the i−th$i-th$ branch). Consequently all the parrots on the i−th$i-th$ branch to the left of the dead parrot get scared and jump up on the branch number i − 1$i - 1$, if there exists no upper branch they fly away. Also all the parrots to the right of the dead parrot jump down on branch number i + 1$i + 1$, if there exists no such branch they fly away. Bobby has shot m parrots. You're given the initial number of parrots on each branch, tell him how many parrots are sitting on each branch after the shots. -----Input:----- The first line of the input contains an integer N$N$. The next line contains a list of space-separated integers a1, a2, …, an. The third line contains an integer M$M$. Each of the next M$M$ lines contains two integers x[i]$x[i]$ and y[i]$y[i]$. The integers mean that for the i-th time Bobby shoot the y[i]-th (from left) parrot on the x[i]-th branch. It's guaranteed there will be at least y[i] parrot on the x[i]-th branch at that moment. -----Output:----- On the i−th$i-th$ line of the output print the number of parrots on the i−th$i-th$ branch. -----Constraints----- - 1≤N≤100$1 \leq N \leq 100$ - 0≤a[i]≤100$0 \leq a[i] \leq 100$ - 0≤M≤100$0 \leq M \leq 100$ - 1≤x[i]≤n$1 \leq x[i] \leq n$, 1≤y[i]$1 \leq y[i] $ -----Sample Input:----- 5 10 10 10 10 10 5 2 5 3 13 2 12 1 13 4 6 3 2 4 1 1 2 2 -----Sample Output:----- 0 12 5 0 16 3 0 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) x = [int(i) for i in input().split()] m = int(input()) for i in range(m): a,b = map(int,input().split()) a -= 1 t = b-1 t1 = x[a]-b if a-1>=0: x[a-1] += t if a+1<n: x[a+1] += t1 x[a] = 0 for i in x: print(i) ```
{ "language": "python", "test_cases": [ { "input": "5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6\n3\n2 4 1\n1\n2 2\n", "output": "0\n12\n5\n0\n16\n3\n0\n3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CFUN2020/problems/CODSTAN2" }
vfc_4966
apps
verifiable_code
1532
Solve the following coding problem using the programming language python: As you know America’s Presidential Elections are about to take place and the most popular leader of the Republican party Donald Trump is famous for throwing allegations against anyone he meets. He goes to a rally and meets n people which he wants to offend. For each person i he can choose an integer between 1 to max[i]. He wants to decide in how many ways he can offend all these persons (N) given the condition that all numbers chosen by him for each person are distinct. So he needs your help to find out the number of ways in which he can do that. If no solution is possible print 0 -----Input----- The first line of the input contains an integer T (1<=T<=100) denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the number of people Trump wants to offend. The second line contains N space-separated integers maxnumber[0], maxnumber[1], ..., maxnumber[n-1] denoting the maxnumber that trump can choose for each person. -----Output----- For each test case, output a single line containing the number of ways Trump can assign numbers to the people, modulo 1,000,000,007. If it's impossible to assign distinct integers to the people, print 0 -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 50 - 1 ≤ Maxnumber[i] ≤ 3000 -----Example----- Input: 3 1 4 2 10 5 4 2 3 1 3 Output: 4 45 0 -----Explanation----- In case 1, He can choose any number from 1 to 4 In case 2,Out of the total 50 combination he can not take (1,1) ,(2,2) , (3,3) ,(4,4) or (5,5). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for t in range(int(input())): n = int(input()) a = sorted(map(int,input().split())) ans = 1 for i in range(n): ans *= (a[i]-i) ans %= (10**9+7) if (ans == 0): break print(ans) ```
{ "language": "python", "test_cases": [ { "input": "3\n1\n4\n2\n10 5\n4\n2 3 1 3\n", "output": "4\n45\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CDGF2016/problems/CDGLF01" }
vfc_4970
apps
verifiable_code
1533
Solve the following coding problem using the programming language python: You are given a weighted graph with $N$ nodes and $M$ edges. Some of the nodes are marked as special nodes. Your task is to find the shortest pairwise distance between any two different special nodes. -----Input----- - The first line of the input contains three space-separated integers $N$, $M$ and $K$ denoting the number of nodes, the number of edges, and the number of special nodes. - The next line contains $K$ space-separated distinct integers $A_{1}$, $A_{2}$, $\ldots$, $A_{K}$, denoting the special nodes. - The next $M$ lines each contain three space-separated integers - $X$, $Y$, $Z$, denoting an edge connecting the nodes $X$ and $Y$, with weight $Z$. -----Output----- Output the shortest pairwise distance between any two different special nodes. -----Constraints----- - The given graph is connected. - The given graph doesn't contain self loops and multiple edges. - $1 \leq A_{i} \leq N$ - $1 \leq Z_{j} \leq 10^{4}$ - $1 \leq X_{j}, Y_{j} \leq N$ -----Subtasks----- Subtask #1 (20 points): - $2 \leq N \leq 300$ - $N-1 \leq M \leq \frac{N \cdot (N-1)}{2}$ - $2 \leq K \leq N$ Subtask #2 (25 points): - $2 \leq N \leq 10^5$ - $N-1 \leq M \leq 10^5$ - $2 \leq K \leq 10$ Subtask #3 (55 points): - $2 \leq N \leq 10^5$ - $N-1 \leq M \leq 3 \cdot 10^5$ - $2 \leq K \leq 10^4$ -----Example Input----- 5 5 3 1 3 5 1 2 3 2 3 4 3 4 1 4 5 8 1 5 19 -----Example Output----- 7 -----Explanation----- Nodes $1$, $3$, and $5$ are special nodes. Shortest distance between nodes $1$ and $3$ is $7$, and that between nodes $3$ and $5$ is $9$. Shortest distance between nodes $1$ and $5$ is $16$. Minimum of these distances is $7$. Hence answer is $7$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n,m,lk = list(map(int,input().split())) sp = [int(i)-1 for i in input().split()] dp = [] for i in range(n): dp += [[0]*n] for i in range(n): for j in range(n): if(i!=j): dp[i][j]=10**18 for _ in range(m): x,y,z = list(map(int,input().split())) dp[x-1][y-1]=z dp[y-1][x-1]=z for k in range(n): for i in range(n): for j in range(n): if(dp[i][j]>dp[i][k]+dp[k][j]): dp[i][j]=dp[i][k]+dp[k][j] dist = 10**18 for i in range(lk): for j in range(i+1,lk): dist = min(dist,dp[sp[i]][sp[j]]) print(dist) ```
{ "language": "python", "test_cases": [ { "input": "5 5 3\n1 3 5\n1 2 3\n2 3 4\n3 4 1\n4 5 8\n1 5 19\n", "output": "7\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/LTIME34/problems/PAIRCLST" }
vfc_4974
apps
verifiable_code
1534
Solve the following coding problem using the programming language python: Sereja has two integers — A and B — in 7-ary system. He wants to calculate the number C, such that B * C = A. It is guaranteed that B is a divisor of A. Please, help Sereja calculate the number C modulo 7L. -----Input----- First line of input contains an integer T — the number of test cases. T tests follow. For each test case, the first line contains the integer A, and the second line contains the integer B, and the third line contains the integer L. A and B are given in 7-ary system. -----Output----- Output the answer in 7-ary system. -----Constraints----- - 1 ≤ T ≤ 10 - A and B are both positive integers. - Length of A is a positive integer and doesn't exceed 106. - L and length of B are positive integers and do not exceed 10000. -----Subtasks----- - Sub task #1 (20 points): Length of A is a positive integer and doesn't exceed 20. - Sub task #2 (30 points): Length of A is a positive integer and doesn't exceed 2000. - Sub task #3 (50 points): Original constraints. -----Example----- Input:3 21 5 10 202 13 1 202 13 2 Output:3 3 13 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) while t>0 : a=int(input()) b=int(input()) l=int(input()) x=0 y=0 z=0 a1=0 b1=0 c1=0 while(a//10!=0 or a%10!=0): a1+=(a%10+((a//10)%10)*7+((a//100)%10)*49+((a//1000)%10)*343+((a//10000)%10)*2401+((a//100000)%10)*16807+((a//1000000)%10)*117649+((a//10000000)%10)*823543+((a//100000000)%10)*5764801+((a//1000000000)%10)*40353607)*(282475249**x) x+=1 a//=10000000000 while (b//10!=0 or b%10!=0): b1+=(b%10+((b//10)%10)*7+((b//100)%10)*49+((b//1000)%10)*343+((b//10000)%10)*2401+((b//100000)%10)*16807+((b//1000000)%10)*117649+((b//10000000)%10)*823543+((b//100000000)%10)*5764801+((b//1000000000)%10)*40353607)*(282475249**y) y+=1 b//=10000000000 c=(a1//b1)%(7**l) while z<l: c1+=(c%7+((c//7)%7)*10+((c//49)%7)*100+((c//343)%7)*1000+((c//2401)%7)*10000+((c//16807)%7)*100000+((c//117649)%7)*1000000+((c//823543)%7)*10000000+((c//5764801)%7)*100000000+((c//40353607)%7)*1000000000)*(10000000000**(z//10)) c//=282475249 z+=10 print(c1) t-=1 ```
{ "language": "python", "test_cases": [ { "input": "3\n21\n5\n10\n202\n13\n1\n202\n13\n2\n", "output": "3\n3\n13\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/DEC15/problems/SEADIV" }
vfc_4978
apps
verifiable_code
1535
Solve the following coding problem using the programming language python: There are $N$ villages numbered $1$ to $N$. The villages are connected through bi-directional paths in between them. The whole network is in the form of a tree. Each village has only $1$ fighter but they help each other in times of crisis by sending their fighter to the village in danger through paths along the villages. Defeating a fighter will mean conquering his village. In particular, If village $X$ is under attack, all villages having a path to $X$ will send their fighters for help. Naruto wants to conquer all the villages. But he cannot take on so many fighters at the same time so he plans to use a secret technique with which he can destroy any $1$ village (along with paths connected to it) in the blink of an eye. However, it can be used only once. He realized that if he destroys any village, say $X$, the maximum number of fighters he has to fight at once reduces to $W$. He wants $W$ to be as small as possible. Help him find the optimal $X$. In case of multiple answers, choose the smallest value of $X$. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - First Line contains $N$. - Next $N - 1$ lines contain $U, V$, denoting a path between village $U$ and $V$. -----Output:----- - For each Test case, print in a new line, optimal $X$ and corresponding value of $W$. -----Constraints----- - $1 \leq T \leq 10$ - $3 \leq N \leq 10^5$ - $1 \leq U, V \leq N$ - $U != V$ -----Sample Input:----- 2 5 1 2 1 3 2 4 3 5 3 1 2 2 3 -----Sample Output:----- 1 2 2 1 -----EXPLANATION:----- Sample 1: By destroying village $1$, The fighters Naruto will be fighting at the same time will be from villages $[2, 4]$ and $[3, 5]$. For this $W$ = $2$. No other choice can give lesser $W$. Hence $1$ is optimal choice. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def solve(edges,ans): n = len(edges) visited = set() parents = [-1]*(n+1) dp = [0]*(n+1) stack = [1] w = float('inf') x = -1 while stack: node = stack[-1] if node not in visited: count = 0 for kid in edges[node]: if parents[kid] == -1: if kid != 1: parents[kid] = node else: if kid != parents[node]: if kid in visited: count += 1 else: stack.append(kid) if node == 1: count -= 1 if count == len(edges[node])-1: stack.pop() visited.add(node) max_val = 0 for kid in edges[node]: dp[node] += dp[kid] max_val = max(max_val,dp[kid]) dp[node] += 1 max_val = max(max_val,n-dp[node]) if max_val < w: w = max_val x = node elif max_val == w: x = min(x,node) ans.append(str(x)+' '+str(w)) def main(): t = int(input()) ans = [] for i in range(t): n = int(input()) edges = {} for j in range(1,n+1): edges[j] = [] for j in range(n-1): x,y = list(map(int,input().split())) edges[x].append(y) edges[y].append(x) solve(edges,ans) print('\n'.join(ans)) main() ```
{ "language": "python", "test_cases": [ { "input": "2\n5\n1 2\n1 3\n2 4\n3 5\n3\n1 2\n2 3\n", "output": "1 2\n2 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ENAU2020/problems/ECAUG207" }
vfc_4982
apps
verifiable_code
1536
Solve the following coding problem using the programming language python: Istiak is learning about arithmetic progressions. Today, he wrote an arithmetic sequence on a piece of paper. Istiak was very happy that he managed to write an arithmetic sequence and went out for lunch. Istiak's friend Rafsan likes to irritate him by playing silly pranks on him. This time, he could have chosen one element of Istiak's sequence and changed it. When Istiak came back, he was devastated to see his sequence ruined — it became a sequence $a_1, a_2, \ldots, a_N$ (possibly identical to the original sequence, if Rafsan did not change anything, in which case Istiak is just overreacting). Help him recover the original sequence. Formally, you have to find an arithmetic sequence $b_1, b_2, \ldots, b_N$ which differs from $a$ in at most one position. $b$ is said to be an arithmetic sequence if there is a real number $d$ such that $b_i - b_{i-1} = d$ for each $i$ ($2 \le i \le N$). If there are multiple valid solutions, you may find any one. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $a_1, a_2, \ldots, a_N$. -----Output----- For each test case, print a single line containing $N$ space-separated integers $b_1, b_2, \ldots, b_N$. It is guaranteed that a valid solution exists. -----Constraints----- - $4 \le N \le 10^5$ - $|a_i| \le 10^9$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $5 \cdot 10^5$ -----Example Input----- 3 4 1 3 10 7 5 -10 -5 0 5 10 4 2 2 2 10 -----Example Output----- 1 3 5 7 -10 -5 0 5 10 2 2 2 2 -----Explanation----- Example case 1: Rafsan changed the third element from $5$ to $10$. Example case 2: No elements were changed. Example case 3: Rafsan changed the fourth element from $2$ to $10$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here test_cases = int(input()) for i in range(test_cases): no_of_elements = int(input()) sequence = list(map(int, input().split())) d1 = sequence[1] - sequence[0] d2 = sequence[2] - sequence[1] d3 = (sequence[3] - sequence[0])/3 d4 = (sequence[3] - sequence[1])/2 d5 = (sequence[2] - sequence[0])/2 if (d2 == d4): d = d2 elif(d3 == d5): d = d3 elif(d1 == d3): d = d1 elif(d1 == d5): d = d1 if (d == d1): for i in range(no_of_elements): sequence[i] = int(sequence[0] + i*d) else: for i in range(no_of_elements): sequence[i] = int(sequence[-1] - ((no_of_elements - i - 1)*d)) for i in sequence: print(i, end=" ") print('\n') ```
{ "language": "python", "test_cases": [ { "input": "3\n4\n1 3 10 7\n5\n-10 -5 0 5 10\n4\n2 2 2 10\n", "output": "1 3 5 7\n-10 -5 0 5 10\n2 2 2 2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/RECVSEQ" }
vfc_4986
apps
verifiable_code
1537
Solve the following coding problem using the programming language python: Prime numbers are arranged in a ordered list U$U$, in increasing order. Let S$S$ be a sublist of U$U$ with a unique property that for every element A$A$ belonging to list S$S$, if i$i$ denotes the index of A$A$ in list U$U$, than i$i$ also belongs to list U$U$. Given N$N$, find sum of first N$N$ elements of list S$S$, assuming 1-based indexing. As the sum can be very large, print the sum modulo 109+7$10^{9}+7$. -----Input:----- -The first line of the input contains a single integer T$T$ denoting the number of test cases. -Only line of each test case has an integer N$N$ . -----Output:----- For each test case, print a single integer denoting the sum of first N$N$ elements of set S$S$ modulo 109+7$10^{9}+7$. -----Constraints----- - 1≤T≤10000$1 \leq T \leq 10000$ - 1≤N≤1000$1 \leq N \leq 1000$ -----Subtasks----- - 20 points : - 1≤T≤10000$1 \leq T \leq 10000$ - 1≤N≤10$1 \leq N \leq 10$ - 20 points : - 1≤T≤100$1 \leq T \leq 100$ - 1≤N≤100$1 \leq N \leq 100$ - 60 points : Original Constraints -----Sample Input:----- 2 1 2 -----Sample Output:----- 3 8 -----EXPLANATION:----- Example case 1: First few elements of set S$S$ are {3,5,11…} , so sum is 3. Example case 2: Sum is 3+5=8. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math def prime(aa): f=0 for y in ar: if aa%y==0: return 0 return 1 ar=[] ar.append(2) pc=3 te=int(input()) for _ in range(te): a=int(input()) f=0 c=0 add=0 for x in ar: try: add=add+ar[x-1] except: while True: if prime(pc)==1: ar.append(pc) if x<=len(ar): break pc+=1 pc+=1 add=add+ar[x-1] c+=1 if c==a: break print(add) ```
{ "language": "python", "test_cases": [ { "input": "2\n1\n2\n", "output": "3\n8\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ALQU2018/problems/SUPPRM" }
vfc_4990
apps
verifiable_code
1538
Solve the following coding problem using the programming language python: Two integers A and B are the inputs. Write a program to find GCD and LCM of A and B. -----Input----- The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer A and B. -----Output----- Display the GCD and LCM of A and B separated by space respectively. The answer for each test case must be displayed in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A,B ≤ 1000000 -----Example----- Input 3 120 140 10213 312 10 30 Output 20 840 1 3186456 10 30 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def GCD(x, y): while y: x, y = y, x % y return x def LCM(x, y): lcm = (x*y)//GCD(x,y) return lcm t = int(input()) while t>0: x,y = list(map(int,input().split())) print(GCD(x,y),LCM(x,y)) t -=1 ```
{ "language": "python", "test_cases": [ { "input": "3\n120 140\n10213 312\n10 30\n", "output": "20 840\n1 3186456\n10 30\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/FLOW016" }
vfc_4994
apps
verifiable_code
1539
Solve the following coding problem using the programming language python: Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. She has been collecting stones since her childhood - now she has become really good with identifying which ones are fake and which ones are not. Her King requested for her help in mining precious stones, so she has told him which all stones are jewels and which are not. Given her description, your task is to count the number of jewel stones. More formally, you're given a string J composed of latin characters where each character is a jewel. You're also given a string S composed of latin characters where each character is a mined stone. You have to find out how many characters of S are in J as well. -----Input----- First line contains an integer T denoting the number of test cases. Then follow T test cases. Each test case consists of two lines, each of which contains a string composed of English lower case and upper characters. First of these is the jewel string J and the second one is stone string S. You can assume that 1 <= T <= 100, 1 <= |J|, |S| <= 100 -----Output----- Output for each test case, a single integer, the number of jewels mined. -----Example----- Input: 4 abc abcdef aA abAZ aaa a what none Output: 3 2 1 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) for i in range(n): count = 0 k = input() x = list(k) kk = input() y = list(kk) for j in y: for jj in x: if(j==jj): count = count+1 break print(count) ```
{ "language": "python", "test_cases": [ { "input": "4\nabc\nabcdef\naA\nabAZ\naaa\na\nwhat\nnone\n", "output": "3\n2\n1\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/MAY12/problems/STONES" }
vfc_4998
apps
verifiable_code
1540
Solve the following coding problem using the programming language python: There are total N friends went to Chef's Pizza shop. There they bought a pizza. Chef divided the pizza into K equal slices. Now you have to check whether these K pizza slices can be distributed equally among the friends. Also given that every person should get at least one slice. If the above conditions are possible then print "YES" otherwise print "NO". -----Input:----- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a integers N. The second line of each test case contains K. -----Output:----- For each test case, print a single line containing "YES" if the given conditions are true else "NO" if the given conditions are false. -----Constraints----- 1<=T<=10 1<=N<=10^6 1<=K<=10^6 -----Sample Input:----- 2 10 20 12 5 -----Sample Output:----- YES NO -----EXPLANATION:----- Explanation case 1: since there are 10 friends and 20 pizza slice, so each can get 2 slices, so "YES". Explanation case 2: Since there are 12 friends and only 5 pizza slice, so there is no way pizza slices can be distributed equally and each friend gets at least one pizza slice, so "NO". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n = int(input()) k = int(input()) if k%n==0: print("YES") else: print("NO") ```
{ "language": "python", "test_cases": [ { "input": "2\n10\n20\n12\n5\n", "output": "YES\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/SPTC2020/problems/CPCEJC1" }
vfc_5002
apps
verifiable_code
1541
Solve the following coding problem using the programming language python: Tennis is a popular game. Consider a simplified view of a tennis game from directly above. The game will appear to be played on a 2 dimensional rectangle, where each player has his own court, a half of the rectangle. Consider the players and the ball to be points moving on this 2D plane. The ball can be assumed to always move with fixed velocity (speed and direction) when it is hit by a player. The ball changes its velocity when hit by the other player. And so on, the game continues. Chef also enjoys playing tennis, but in n+1$n + 1$ dimensions instead of just 3. From the perspective of the previously discussed overhead view, Chef's court is an n$n$-dimensional hyperrectangle which is axis-aligned with one corner at (0,0,0,…,0)$(0, 0, 0, \dots, 0)$ and the opposite corner at (l1,l2,l3,…,ln$(l_1, l_2, l_3, \dots, l_n$). The court of his opponent is the reflection of Chef's court across the n−1$n - 1$ dimensional surface with equation x1=0$x_1 = 0$. At time t=0$t=0$, Chef notices that the ball is at position (0,b2,…,bn)$(0, b_2, \dots, b_n)$ after being hit by his opponent. The velocity components of the ball in each of the n$n$ dimensions are also immediately known to Chef, the component in the ith$i^{th}$ dimension being vi$v_i$. The ball will continue to move with fixed velocity until it leaves Chef's court. The ball is said to leave Chef's court when it reaches a position strictly outside the bounds of Chef's court. Chef is currently at position (c1,c2,…,cn)$(c_1, c_2, \dots, c_n)$. To hit the ball back, Chef must intercept the ball before it leaves his court, which means at a certain time the ball's position and Chef's position must coincide. To achieve this, Chef is free to change his speed and direction at any time starting from time t=0$t=0$. However, Chef is lazy so he does not want to put in more effort than necessary. Chef wants to minimize the maximum speed that he needs to acquire at any point in time until he hits the ball. Find this minimum value of speed smin$s_{min}$. Note: If an object moves with fixed velocity →v$\vec{v}$ and is at position →x$\vec{x}$ at time 0$0$, its position at time t$t$ is given by →x+→v⋅t$\vec{x} + \vec{v} \cdot t$. -----Input----- - The first line contains t$t$, the number of test cases. t$t$ cases follow. - The first line of each test case contains n$n$, the number of dimensions. - The next line contains n$n$ integers l1,l2,…,ln$l_1, l_2, \dots, l_n$, the bounds of Chef's court. - The next line contains n$n$ integers b1,b2,…,bn$b_1, b_2, \dots, b_n$, the position of the ball at t=0$t=0$. - The next line contains n$n$ integers v1,v2,…,vn$v_1, v_2, \dots, v_n$, the velocity components of the ball. - The next line contains n$n$ integers, c1,c2,…,cn$c_1, c_2, \dots, c_n$, Chef's position at t=0$t=0$. -----Output----- - For each test case, output a single line containing the value of smin$s_{min}$. Your answer will be considered correct if the absolute error does not exceed 10−2$10^{-2}$. -----Constraints----- - 1≤t≤1500$1 \leq t \leq 1500$ - 2≤n≤50$2 \leq n \leq 50$ - 1≤li≤50$1 \leq l_i \leq 50$ - 0≤bi≤li$0 \leq b_i \leq l_i$ and b1=0$b_1 = 0$ - −10≤vi≤10$-10 \leq v_i \leq 10$ and v1>0$v_1 > 0$ - 0≤ci≤li$0 \leq c_i \leq l_i$ - It is guaranteed that the ball stays in the court for a non-zero amount of time. -----Sample Input----- 2 2 3 4 0 2 2 -2 2 2 3 10 10 10 0 0 0 1 1 1 5 5 5 -----Sample Output----- 2.0000 0.0000 -----Explanation----- Case 1: The court is 2-dimentional. The ball's trajectory is marked in red. For Chef it is optimal to move along the blue line at a constant speed of 2 until he meets the ball at the boundary. Case 2: The court is 3-dimensional and the ball is coming straight at Chef. So it is best for Chef to not move at all, thus smin=0$s_{min} = 0$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python eps=1e-8 t=int(input()) for ii in range(t): n=int(input()) l=[int(i) for i in input().split() ] b=[int(i) for i in input().split() ] v=[int(i) for i in input().split() ] c=[int(i) for i in input().split() ] greatest_time=l[0]/v[0] for i in range(1,n): if v[i]>0: greatest_time=min(greatest_time,(l[i]-b[i])/v[i]) elif v[i]<0: greatest_time=min(greatest_time,-b[i]/v[i]) p = sum((b[i] - c[i]) ** 2 for i in range(n)) q = sum(2 * (b[i] - c[i]) * v[i] for i in range(n)) r = sum(vi ** 2 for vi in v) func = lambda t: p/t/t + q/t + r #ternary search def ternsearch(): if b==c: return(0) lo,hi=0,greatest_time while hi-lo>eps: d=(hi-lo)/3 m1=lo+d m2=m1+d if func(m1)<=func(m2): hi=m2 else: lo=m1 #print(hi,lo) #print(func(lo)**(0.5)) return max(0,func(lo))**(0.5) ans=ternsearch() print('%.12f' % (ans,)) ```
{ "language": "python", "test_cases": [ { "input": "2\n2\n3 4\n0 2\n2 -2\n2 2\n3\n10 10 10\n0 0 0\n1 1 1\n5 5 5\n", "output": "2.0000\n0.0000\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/CLTNIS" }
vfc_5006
apps
verifiable_code
1542
Solve the following coding problem using the programming language python: Every character in the string “IITMANDI” is given a certain number of points. You are given a scrabble board with only one row. The input contains the positions of score modifiers such as: Double Letter, Triple Letter, Double Word and Triple Word. You need to find the best position to place the string “IITMANDI” such that your score is maximized. Double Letter - Doubles the number of points you get for the letter placed on the double letter. Triple Letter - Triples the number of points you get for the letter placed on the triple letter. Double Word - Doubles the number of points you get for the word. Applied after applying above modifiers. Triple Word - Triples the number of points you get for the word. Applied after applying the above modifiers. The word has to be read from left to right. You can’t place it in the reverse direction. The letters have to be placed continuously on the board. If there is no modifier or a double word or triple word modifier before a tile, it's score is added to the total score. The double word and triple modifiers are applied at the end. -----Input Format----- - First line containes a single integer $T$ - the number of test cases. - First line of each test case contains a single integer $N$ - the size of the board. - Second line of each test case contains a string of size $N$ representing the board according to the following convention: '.' - No modifier 'd' - Double letter 't' - Triple letter 'D' - Double word 'T' - Triple word - Third line of each test case contains 8 integers corresponding to the points associated with each letter of the string "IITMANDI". Note that the 3 'I's in IITMANDI cannot be interchanged freely. The score of the first 'I' will be equal to the first integer, score of the second 'I' will be equal to the second integer and the score of the last 'I' will be equal to the last integer. -----Output Format----- For each test case, output a single integer in a new line, the maximum possible score. -----Constraints----- $ 1 \leq T \leq 1000 $ $ 8 \leq N \leq 100 $ $ 0 \leq $ Points for each character $ \leq 10^5 $ -----Sample Input----- 2 10 ..d.t.D..d 10 11 12 9 8 10 11 15 22 dtDtTD..ddT.TtTdDT..TD 12297 5077 28888 17998 12125 27400 31219 21536 -----Sample Output----- 270 35629632 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: T = int(input()) for i in range(T): n = int(input()) s = input() arr = [int(i) for i in input().strip().split(" ")] res = 1 result = 0 for j in range(n-7): res = 1 res1= 0 s1 = s[j:j+8] for i in range(8): if s1[i] == 'D': res = res*2 res1 += arr[i] elif s1[i] == 'T': res = res*3 res1 = res1 + arr[i] elif s1[i] == 'd': res1 = res1 + arr[i]*2 elif s1[i] == 't': res1 += arr[i]*3 else: res1 += arr[i] res = res*res1 result = max(res,result) print(result) except EOFError: pass ```
{ "language": "python", "test_cases": [ { "input": "2\n10\n..d.t.D..d\n10 11 12 9 8 10 11 15\n22\ndtDtTD..ddT.TtTdDT..TD\n12297 5077 28888 17998 12125 27400 31219 21536\n", "output": "270\n35629632\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/MAXSCRAB" }
vfc_5010
apps
verifiable_code
1543
Solve the following coding problem using the programming language python: Let X be the set of all integers between 0 and n-1. Suppose we have a collection S1, S2, ..., Sm of subsets of X. Say an atom A is a subset of X such that for each Si we have either A is a subset of Si or A and Si do not have any common elements. Your task is to find a collection A1, ..., Ak of atoms such that every item in X is in some Ai and no two Ai, Aj with i ≠ j share a common item. Surely such a collection exists as we could create a single set {x} for each x in X. A more interesting question is to minimize k, the number of atoms. -----Input----- The first line contains a single positive integer t ≤ 30 indicating the number of test cases. Each test case begins with two integers n,m where n is the size of X and m is the number of sets Si. Then m lines follow where the i'th such line begins with an integer vi between 1 and n (inclusive) indicating the size of Si. Following this are vi distinct integers between 0 and n-1 that describe the contents of Si. You are guaranteed that 1 ≤ n ≤ 100 and 1 ≤ m ≤ 30. Furthermore, each number between 0 and n-1 will appear in at least one set Si. -----Output----- For each test case you are to output a single integer indicating the minimum number of atoms that X can be partitioned into to satisfy the constraints. -----Example----- Input: 2 5 2 3 0 1 2 3 2 3 4 4 3 2 0 1 2 1 2 2 2 3 Output: 3 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here # cook your dish here for _ in range(int(input())): n,m=list(map(int,input().split())) atomlist = ['']*n for k in range(m): s=[] s.extend(input().split()[1:]) #print(s) for w in range(n): if str(w) in s: atomlist[w]+="1" else: atomlist[w]+="0" #print(atomlist) print(len(set(atomlist))) ```
{ "language": "python", "test_cases": [ { "input": "2\n5 2\n3 0 1 2\n3 2 3 4\n4 3\n2 0 1\n2 1 2\n2 2 3\n", "output": "3\n4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/ATOMS" }
vfc_5014
apps
verifiable_code
1544
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 5 1 2 3 4 5 -----Sample Output:----- * * ** * ** *** * ** * * **** * ** * * * * ***** -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def solve(): n=int(input()) i=0 while i<n-1: if i==0: print("*",end="") else: print("*",end="") for k in range(i-1): print(" ",end="") print("*",end="") print() i+=1 for i in range(n): print("*",end="") print() t=int(input()) i=0 while(i<t): solve() i+=1 ```
{ "language": "python", "test_cases": [ { "input": "5\n1\n2\n3\n4\n5\n", "output": "*\n*\n**\n*\n**\n***\n*\n**\n* *\n****\n*\n**\n* *\n* *\n*****\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PTRN2020/problems/ITGUY43" }
vfc_5018
apps
verifiable_code
1545
Solve the following coding problem using the programming language python: The Quark Codejam's number QC(n, m) represents the number of ways to partition a set of n things into m nonempty subsets. For example, there are seven ways to split a four-element set into two parts: {1, 2, 3} ∪ {4}, {1, 2, 4} ∪ {3}, {1, 3, 4} ∪ {2}, {2, 3, 4} ∪ {1}, {1, 2} ∪ {3, 4}, {1, 3} ∪ {2, 4}, {1, 4} ∪ {2, 3}. We can compute QC(n, m) using the recurrence, QC(n, m) = mQC(n − 1, m) + QC(n − 1, m − 1), for integers 1 < m < n. but your task is a somewhat different: given integers n and m, compute the parity of QC(n, m), i.e. QC(n, m) mod 2. Example : QC(4, 2) mod 2 = 1. Write a program that reads two positive integers n and m, computes QC(n, m) mod 2, and writes the result. -----Input----- The input begins with a single positive integer on a line by itself indicating the number of the cases. This line is followed by the input cases. The input consists two integers n and m separated by a space, with 1 ≤ m ≤ n ≤ 1000000000. -----Output----- For each test case, print the output. The output should be the integer S(n, m) mod 2. Sample Input 1 4 2 Sample Output 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for i in range(eval(input())): n,k=input().strip().split() n=int(n) k=int(k) print(int( ((n-k)&(int((k-1)/2)))==0)) ```
{ "language": "python", "test_cases": [ { "input": "1\n4 2\n", "output": "1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/COJA2016/problems/CODEJAM1" }
vfc_5022
apps
verifiable_code
1546
Solve the following coding problem using the programming language python: Chef loves triangles. But the chef is poor at maths. Given three random lengths Chef wants to find if the three sides form a right-angled triangle or not. Can you help Chef in this endeavour? -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, three Integers $A,B and C$ -----Output:----- For each test case, output in a single line "YES" if it is possible to form a triangle using the given numbers or "NO" if it is not possible to form a triangle. -----Constraints----- - $1 \leq T \leq 1000000$ - $0 \leq A,B,C \leq 100$ -----Sample Input:----- 2 3 4 5 1 3 4 -----Sample Output:----- YES NO -----EXPLANATION:----- 3,4,5 forms a right-angled triangle. 1, 3 and 4 does not form a right-angled triangle. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here def check(a,b,c): if (a==0) or (b==0) or (c==0): return "NO" else: i=3 while(i>0): if (a*a)==(b*b)+(c*c): return "YES" else: t=a a=b b=c c=t i-=1 return "NO" try: for _ in range(int(input())): a,b,c=map(int,input().split()) print(check(a,b,c)) except: print(e) pass ```
{ "language": "python", "test_cases": [ { "input": "2\n3 4 5\n1 3 4\n", "output": "YES\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ENFE2020/problems/ECFEB201" }
vfc_5026
apps
verifiable_code
1547
Solve the following coding problem using the programming language python: Increasing COVID cases have created panic amongst the people of Chefland, so the government is starting to push for production of a vaccine. It has to report to the media about the exact date when vaccines will be available. There are two companies which are producing vaccines for COVID. Company A starts producing vaccines on day $D_1$ and it can produce $V_1$ vaccines per day. Company B starts producing vaccines on day $D_2$ and it can produce $V_2$ vaccines per day. Currently, we are on day $1$. We need a total of $P$ vaccines. How many days are required to produce enough vaccines? Formally, find the smallest integer $d$ such that we have enough vaccines at the end of the day $d$. -----Input----- - The first and only line of the input contains five space-separated integers $D_1$, $V_1$, $D_2$, $V_2$ and $P$. -----Output----- Print a single line containing one integer ― the smallest required number of days. -----Constraints----- - $1 \le D_1, V_1, D_2, V_2 \le 100$ - $1 \le P \le 1,000$ -----Subtasks----- Subtask #1 (30 points): $D_1 = D_2$ Subtask #2 (70 points): original constraints -----Example Input 1----- 1 2 1 3 14 -----Example Output 1----- 3 -----Explanation----- Since $D_1 = D_2 = 1$, we can produce $V_1 + V_2 = 5$ vaccines per day. In $3$ days, we produce $15$ vaccines, which satisfies our requirement of $14$ vaccines. -----Example Input 2----- 5 4 2 10 100 -----Example Output 2----- 9 -----Explanation----- There are $0$ vaccines produced on the first day, $10$ vaccines produced on each of days $2$, $3$ and $4$, and $14$ vaccines produced on the fifth and each subsequent day. In $9$ days, it makes a total of $0 + 10 \cdot 3 + 14 \cdot 5 = 100$ vaccines. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: d1,v1,d2,v2,p=map(int, input().split()) total=0 while p>0: total+=1 if total>=d1: p=p-v1 if total>=d2: p=p-v2 print(total) except: pass ```
{ "language": "python", "test_cases": [ { "input": "1 2 1 3 14\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/VACCINE1" }
vfc_5030
apps
verifiable_code
1548
Solve the following coding problem using the programming language python: “Jesse, you asked me if I was in the meth business, or the money business… Neither. I’m in the empire business.” Walter’s sold his stack in Gray Matter Technologies, a company which he deserved half a credit, for peanuts. Now this company is worth a billion dollar company. Walter wants to get it's shares to have his Empire Business back and he founds an opportunity. There are $N$ persons having shares $A_1, A_2, A_3, … A_N$ in this company. Walter can buy these shares with their minimum Sold Values. Sold Values of a person's share $ i $ $(1 \leq i \leq N) $ with another person's share $ j $ $ (1 \leq j \leq N) $ is equal to $ A_j+|i-j| $. So, a person's share can have $ N $ possible sold values and Walter has to find minimum sold value among them for each person. Since Walter has to run his meth business also he asks you to find minimum sold value for each person. -----Input:----- - First line will contain $T$, number of test cases. Then the testcases follow. - The First line of each test case contains a integer $N$. - The Second line of each test case contains $N$ space integers namely $A_1,A_2,…A_N$. -----Output:----- For each test case, output in single line $N$ space integers denoting minimum sold value for each person. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 2*10^6 $ - $1 \leq A_i \leq 10^9 $ Sum of $N$ over all test cases will not exceed $2*10^6$. -----Sample Input:----- 2 5 6 5 5 5 2 5 1 2 3 4 5 -----Sample Output:----- 6 5 4 3 2 1 2 3 4 5 -----Explanation----- For first case: - Sold value for index $1$: $6,6,7,8,6$ - Sold value for index $2$: $7,5,6,7,5$ - Sold value for index $3$: $8,6,5,6,4$ - Sold value for index $4$: $9,7,6,5,3$ - Sold value for index $5$: $10,8,7,6,2$ Minimum sold value for each index will be $6,5,4,3,2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here T=int(input()) for _ in range(T): n=int(input()) arr=list(map(int,input().split())) left=[-1 for i in range(n)] right=[-1 for i in range(n)] min1=float("inf") for i in range(n): min1=min(arr[i],min1+1) left[i]=min1 min1=float("inf") for i in range(n-1,-1,-1): min1=min(arr[i],min1+1) right[i]=min1 for i in range(n): print(min(left[i],right[i]),end=" ") print("",end="\n") ```
{ "language": "python", "test_cases": [ { "input": "2\n5\n6 5 5 5 2\n5\n1 2 3 4 5\n", "output": "6 5 4 3 2\n1 2 3 4 5\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/SOLDVAL" }
vfc_5034
apps
verifiable_code
1549
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form new pattern. Help the chef to code this pattern problem. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integer $K$. -----Output:----- For each testcase, output as pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 2 2 4 -----Sample Output:----- 2 12 012 12 2 4 34 234 1234 01234 1234 234 34 4 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import copy for _ in range(int(input())): k=int(input()) c=[] d=[] start=0 while True: c=[] for i in range(start): c.append(" ") for i in range(start,k+1): c.append(str(i)) start+=1 d.append(c) if start>k: break e=copy.copy(d[1:]) d.reverse() d=d+e ##print(d) for i in range(len(d)): print(''.join(d[i])) ```
{ "language": "python", "test_cases": [ { "input": "2\n2\n4\n", "output": "2\n12\n012\n12\n2\n4\n34\n234\n1234\n01234\n1234\n234\n34\n4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PBK02020/problems/ITGUY12" }
vfc_5038
apps
verifiable_code
1550
Solve the following coding problem using the programming language python: The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2). You have developed two sequences of numbers. The first sequence that uses the bitwise XOR operation instead of the addition method is called the Xoronacci number. It is described as follows: X(n) = X(n-1) XOR X(n-2) The second sequence that uses the bitwise XNOR operation instead of the addition method is called the XNoronacci number. It is described as follows: E(n) = E(n-1) XNOR E(n-2) The first and second numbers of the sequence are as follows: X(1) = E(1) = a X(2) = E(2) = b Your task is to determine the value of max(X(n),E(n)), where n is the n th term of the Xoronacci and XNoronacci sequence. -----Input:----- The first line consists of a single integer T denoting the number of test cases. The first and the only line of each test case consists of three space separated integers a, b and n. -----Output:----- For each test case print a single integer max(X(n),E(n)). -----Constraints----- - $1 \leq T \leq 1000$ - $2 \leq a,b,n \leq 1000000000000$ -----Sample Input:----- 1 3 4 2 -----Sample Output:----- 4 -----EXPLANATION:----- Xoronacci Sequence : 3 4 7 ……. XNoronacci Sequence : 3 4 0 ……. Here n = 2. Hence max(X(2),E(2)) = 4 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Python3 program to find XNOR # of two numbers import math def swap(a, b): temp = a a = b b = temp # log(n) solution def xnor(a, b): # Make sure a is larger if (a < b): swap(a, b) if (a == 0 and b == 0): return 1; # for last bit of a a_rem = 0 # for last bit of b b_rem = 0 # counter for count bit and # set bit in xnor num count = 0 # for make new xnor number xnornum = 0 # for set bits in new xnor # number while (a != 0): # get last bit of a a_rem = a & 1 # get last bit of b b_rem = b & 1 # Check if current two # bits are same if (a_rem == b_rem): xnornum |= (1 << count) # counter for count bit count = count + 1 a = a >> 1 b = b >> 1 return xnornum; t= int(input()) for o in range(t): a,b,n=map(int,input().split()) c=a^b x=bin(c) x=x.split("b") x=x[1] x=len(x) d=xnor(a,b) p=[a,b,c];r=[a,b,d] k=n%3-1 if p[k]>r[k]: print(p[k]) else : print(r[k]) ```
{ "language": "python", "test_cases": [ { "input": "1\n3 4 2\n", "output": "4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CEFT2020/problems/SERIESTO" }
vfc_5042
apps
verifiable_code
1551
Solve the following coding problem using the programming language python: "I don't have any fancy quotes." - vijju123 Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy. You are given some quotes. For each quote, you need to tell Chef if it is Real Fancy or just regularly fancy. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains a single string $S$ denoting a quote. -----Output----- For each test case, print a single line containing the string "Real Fancy" or "regularly fancy" (without quotes). -----Constraints----- - $1 \le T \le 50$ - $1 \le |S| \le 100$ - each character of $S$ is either a lowercase English letter or a space -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 2 i do not have any fancy quotes when nothing goes right go left -----Example Output----- Real Fancy regularly fancy -----Explanation----- Example case 1: "i do not have any fancy quotes" Example case 2: The word "not" does not appear in the given quote. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import re t=int(input()) while(t>0): s=list(input().split(' ')) if("not" in s): print("Real Fancy") else: print("regularly fancy") t=t-1 ```
{ "language": "python", "test_cases": [ { "input": "2\ni do not have any fancy quotes\nwhen nothing goes right go left\n", "output": "Real Fancy\nregularly fancy\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/FANCY" }
vfc_5046
apps
verifiable_code
1552
Solve the following coding problem using the programming language python: Chef has two piles of stones with him, one has n1 stones and the other has n2 stones. Fired up by boredom, he invented a game with the two piles. Before the start of the game Chef chooses an integer m. In the j-th move: - He chooses a number xj such that 1 ≤ xj ≤ m, and removes xj stones from both the piles (this is only possible when both the piles have ≥ xj stones). - The number chosen must be unique over all the moves in the game. That is, for all k < j, xj ≠ xk. The game stops when Chef is unable to make any more moves. Chef wants to make the moves in such a way that the sum of the number of stones remaining in the two piles is minimized. Please help Chef find this. -----Input----- - The first line of input contains an integer T denoting the number of test cases. - Each test case consists of 1 line with three integers — n1, n2 and m — separated by single spaces. -----Output----- For each test case, output a single line containing the minimum sum of the number of stones of two piles. -----Constraints----- Subtask 1 : (5 pts) - 1 ≤ T ≤ 100 - 0 ≤ m ≤ 18 - 0 ≤ n1, n2 ≤ 100 Subtask 2 : (25 pts) - 1 ≤ T ≤ 1000 - 0 ≤ m ≤ 10000 - 0 ≤ n1, n2 ≤ 10000 Subtask 3 : (70 pts) - 1 ≤ T ≤ 105 - 0 ≤ m ≤ 109 - 0 ≤ n1, n2 ≤ 1018 -----Example----- Input:3 1 1 1 1 2 1 4 5 2 Output:0 1 3 -----Explanation----- Example case 1. : Remove 1 stone from each of the piles. Now 0 stones are remaining, so chef cannot remove any more stones from the piles. Hence, answer is 0+0 = 0 Example case 2. : Again, remove 1 stone from both the piles to get (0,1) stones. Now chef cannot remove any more stones from pile 1, so he stops. Hence, answer is 0+1 = 1. Example case 3. : First remove 1 stone from both the piles to get (3,4) stones. Now, remove 2 stones from both the piles so that (1,2) stones are remaining. Now chef cannot remove any more stones owing to the condition that he cannot remove the same number of stones twice. So, the answer is 1+2 = 3. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys n = int(sys.stdin.readline()) for _ in range(n): p1, p2, m = list(map(int, sys.stdin.readline().split())) l = min(p1, p2) #while(m > 0 and l > 0): # k = min(l, m) # l -= k # m -= 1 q = min(p1, p2) d = min((m * (m + 1)) / 2, q) print(p1 - d + p2 - d) ```
{ "language": "python", "test_cases": [ { "input": "3\n1 1 1\n1 2 1\n4 5 2\n", "output": "0\n1\n3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/DEC15/problems/CHEFST" }
vfc_5050
apps
verifiable_code
1553
Solve the following coding problem using the programming language python: The GoC Timber Mafia is notorious for its deforestation activities in the forests near Siruseri. These activities have increased multifold after the death of the bandit who used to lord over these jungles. Having lost the battle to prevent the Mafia from illegally felling the teak trees in this forest, the government of Siruseri came up with a novel idea. Why not legalise the deforestation activity and at least make some money in the process? So the Government decided to lease out parts of the forest to the Timber Mafia. Most of the teak trees in the forests of Siruseri were planted during the colonial times, after the native trees had been cut. Like everything European, the forest is very regular and orderly. It is rectangular in shape and the trees are arranged in uniformly spaced rows and coloumns. Since the trees differ in height and girth, the timber value differs from tree to tree. The forest department has collected data on each tree and knows the volume of wood (in cubic feet) available in each tree in the forest. The forest department maintains this information in the form of an $M \times N$ array of integers, where the $(i, j)$th entry is the volume, in cubic feet, of the $i^{th}$ tree on the $i^{th}$ row (or, equivalently, the $i^{th}$ tree on the $i^{th}$ column). We assume that our rows are numbered top to bottom and the columns are numbered from left to right. For example, such an array could look like This array tells us that the volume of the tree at position $(3,4)$ is $15$ cubic feet and so on. Any rectangular piece of land with trees at each corner can be leased out. In order to fix the lease price for any rectangular plot of the forest the forest department needs to know the amount of wood available inside the plot. A rectangular plot is described by the positions of the trees in its top left corner and the bottom right corner. For example the positions $(2,2)$ and $(3,4)$ describes the following part rectangular part of the above forest. The total amount of wood available in this rectangular plot is $76$ cubic feet. Similarly $(4,2)$ and $(4,2)$ describes the rectangle with just one tree and its volume is $20$ cubic feet. Your task is to write a program that helps the forest department to compute the total volume of the trees insides any specfied rectangular plot. -----Input:----- - The first line of the input contains two integers $M$ and $N$ indicating the number of rows and columns of trees in the forest. - The following $M$ lines have $N$ integers each. The $j^{th}$ integer on line $i+1$ denotes the volume (in cubic feet) of the $j^{th}$ tree on the $i^{th}$ row. - Line $M+2$ contains a single integer $C$ indicating the number of rectangles for which the total volume is to be computed. - Each of the following $C$ lines (line $M+2+1 ... M+2+C$) contain four integers $x_1, y_1, x_2$ and $y_2$ (with $x_1 \leq x_2$ and $y_1 \leq y_2$) and describes a rectangle. The rectangle has its top left corner at the tree in position $(x_1,y_1)$ and its bottom right corner at the tree at position $(x_2,y_2)$. -----Output:----- Your output must contain $C$ lines with one integer on each line. Line $i$ must contain the total volume of wood in the rectangle described on line $M+2+i$ in the input. -----Constraints----- - In $30 \%$ of inputs, $1 \leq C \leq 100$. - In all inputs, $2 \leq N, M \leq 1000$ and $1 \leq C \leq 1000000$ - $0 \leq$ volume of wood in each tree $\leq 1000$ - $1 \leq x_1 \leq x_2 \leq M$ - $1 \leq y_1 \leq y_2 \leq N$ -----Sample Input----- 4 4 3 4 15 23 14 20 12 9 3 8 12 15 12 20 7 5 2 2 2 3 4 4 2 4 2 -----Sample Output----- 76 20 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here from sys import stdin n, m = map(int,stdin.readline().split()) forest=[] matrix=[] for _ in range(n): forest.append(list(map(int,stdin.readline().split()))) matrix.append([0]*m) matrix[0][0]=forest[0][0] for j in range(1,m): matrix[0][j]=matrix[0][j-1]+forest[0][j] for i in range(1,n): matrix[i][0]=matrix[i-1][0]+forest[i][0] for i in range(1,n): for j in range(1,m): matrix[i][j]=matrix[i-1][j]+matrix[i][j-1]-matrix[i-1][j-1]+forest[i][j] c=int(input()) for _ in range(c): x1, y1, x2, y2 = map(int,stdin.readline().split()) x1-=1 y1-=1 x2-=1 y2-=1 appo=0 if x1>0: appo+=matrix[x1-1][y2] if y1>0: appo+=matrix[x2][y1-1] if x1>0 and y1>0: appo-=matrix[x1-1][y1-1] print(matrix[x2][y2]-appo) ```
{ "language": "python", "test_cases": [ { "input": "4 4\n3 4 15 23\n14 20 12 9\n3 8 12 15\n12 20 7 5\n2\n2 2 3 4\n4 2 4 2\n", "output": "76\n20\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/IARCSJUD/problems/TIMBER" }
vfc_5054
apps
verifiable_code
1554
Solve the following coding problem using the programming language python: Meliodas and Ban are fighting over chocolates. Meliodas has $X$ chocolates, while Ban has $Y$. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or atleast one of them is left with no chocolates. Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war? -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, which contains two integers $X, Y$, the no of chocolates Meliodas and Ban have, respectively. -----Output:----- For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting. -----Constraints----- - $1 \leq T \leq 100000$ - $0 \leq X,Y \leq 10^9$ -----Sample Input:----- 3 5 3 10 10 4 8 -----Sample Output:----- 2 20 8 -----EXPLANATION:----- Denoting Meliodas as $M$, Ban as $B$. Testcase 1: $M$=5, $B$=3 Ban eates 3 chocolates of Meliodas. $M$=2, $B$=3 Meliodas eats 2 chocolates of Ban. $M$=2, $B$=1 Ban eates 1 chocolate of Meliodas. $M$=1, $B$=1 Since they have the same no of candies, they stop quarreling. Total candies left: 2 Testcase 2: $M$=10, $B$=10 Since both of them had the same candies to begin with, there was no point in fighting. Total candies left: 20 Testcase 3: $M$=4, $B$=8 Meliodas eats 4 chocolates of Ban. $M$=4, $B$=4 Since they have the same no of candies, they stop quarreling. Total candies left: 8 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from math import * t=int(input()) for i in range(t): m,b=input().split() m=int(m) b=int(b) print(2*gcd(m,b)) ```
{ "language": "python", "test_cases": [ { "input": "3\n5 3\n10 10\n4 8\n", "output": "2\n20\n8\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/SINS" }
vfc_5058
apps
verifiable_code
1555
Solve the following coding problem using the programming language python: Chef is interested to solve series problems. Chef wants to solve a series problem but he can't solve it till now.Can you help Chef to solve the series problem? - In series problem, the series goes as follows 1,9,31,73,141 . . . . . . . . Your task is to find the Nth term of series. For larger value of $N$ answer becomes very large, So your output should be performed $N$th term modulo 1000000007 ($10^9+7$ ). -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single integer $N$. -----Output:----- For each testcase, output in a single line answer i.e. The $N$th term of series modulo 1000000007. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 10^9$ -----Sample Input:----- 2 8 10 -----Sample Output:----- 561 1081 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: for t in range(int(input())): n=int(input()) ans=n*n*n+((n-1)**2) if ans<=10**9+7: print(ans) else: print(ans)%(10**9+7) except: pass ```
{ "language": "python", "test_cases": [ { "input": "2\n8\n10\n", "output": "561\n1081\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/NOOB2020/problems/NBC004" }
vfc_5062
apps
verifiable_code
1556
Solve the following coding problem using the programming language python: The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 1 10 10 101 101 101 1010 1010 1010 1010 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n = int(input()) num = "" val = 1 for i in range(n): num += str(val) if val == 1: val = 0 else: val = 1 for i in range(n): print(num) ```
{ "language": "python", "test_cases": [ { "input": "4\n1\n2\n3\n4\n", "output": "1\n10\n10\n101\n101\n101\n1010\n1010\n1010\n1010\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PTRN2021/problems/ITGUY55" }
vfc_5066
apps
verifiable_code
1557
Solve the following coding problem using the programming language python: Chef usually likes to play cricket, but now, he is bored of playing it too much, so he is trying new games with strings. Chef's friend Dustin gave him binary strings $S$ and $R$, each with length $N$, and told him to make them identical. However, unlike Dustin, Chef does not have any superpower and Dustin lets Chef perform only operations of one type: choose any pair of integers $(i, j)$ such that $1 \le i, j \le N$ and swap the $i$-th and $j$-th character of $S$. He may perform any number of operations (including zero). For Chef, this is much harder than cricket and he is asking for your help. Tell him whether it is possible to change the string $S$ to the target string $R$ only using operations of the given type. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains a binary string $S$. - The third line contains a binary string $R$. -----Output----- For each test case, print a single line containing the string "YES" if it is possible to change $S$ to $R$ or "NO" if it is impossible (without quotes). -----Constraints----- - $1 \le T \le 400$ - $1 \le N \le 100$ - $|S| = |R| = N$ - $S$ and $R$ will consist of only '1' and '0' -----Example Input----- 2 5 11000 01001 3 110 001 -----Example Output----- YES NO -----Explanation----- Example case 1: Chef can perform one operation with $(i, j) = (1, 5)$. Then, $S$ will be "01001", which is equal to $R$. Example case 2: There is no sequence of operations which would make $S$ equal to $R$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): length = int(input()) S = input() R = input() if S.count("1") == R.count("1"): print("YES") else: print("NO") ```
{ "language": "python", "test_cases": [ { "input": "2\n5\n11000\n01001\n3\n110\n001\n", "output": "YES\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/PLAYSTR" }
vfc_5070
apps
verifiable_code
1558
Solve the following coding problem using the programming language python: Anas is playing an amazing game on a grid with $N$ rows and $M$ columns. The rows are numbered $1$ through $N$ from top to bottom and the columns are numbered $1$ through $M$ from left to right. Anas wants to destroy this grid. To do that, he wants to send two heroes from the top left cell to the bottom right cell: - The first hero visits cells in row-major order: $(1,1) \rightarrow (1,2) \rightarrow \ldots \rightarrow (1,M) \rightarrow (2,1) \rightarrow (2,2) \rightarrow \ldots \rightarrow (2,M) \rightarrow \ldots \rightarrow (N,M)$. - The second hero visits cells in column-major order: $(1,1) \rightarrow (2,1) \rightarrow \ldots \rightarrow (N,1) \rightarrow (1,2) \rightarrow (2,2) \rightarrow \ldots \rightarrow (N,2) \rightarrow \ldots \rightarrow (N,M)$. We know that each hero destroys the first cell he visits, rests in the next $K$ cells he visits without destroying them, then destroys the next cell he visits, rests in the next $K$ cells, destroys the next cell, and so on until he reaches (and rests in or destroys) the last cell he visits. Anas does not know the value of $K$. Therefore, for each value of $K$ between $0$ and $N \cdot M - 1$ inclusive, he wants to calculate the number of cells that will be destroyed by at least one hero. Can you help him? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains two space-separated integers $N$ and $M$. -----Output----- For each test case, print a single line containing $N \cdot M$ space-separated integers as described above. -----Constraints----- - $1 \le T \le 100$ - $2 \le N, M \le 1,000$ - the sum of $N \cdot M$ over all test cases does not exceed $2 \cdot 10^6$ -----Subtasks----- Subtask #1 (30 points): - $2 \le N, M \le 50$ - the sum of $N \cdot M$ over all test cases does not exceed $5,000$ Subtask #2 (70 points): original constraints -----Example Input----- 1 2 3 -----Example Output----- 6 4 3 3 2 1 -----Explanation----- Example case 1: - $K = 0$: All cells will be destroyed by the heroes. - $K = 1$: The first hero will destroy the cells $[(1,1), (1,3), (2,2)]$, while the second one will destroy the cells $[(1,1), (1,2), (1,3)]$. - $K = 2$: The first hero will destroy the cells $[(1,1), (2,1)]$, while the second one will destroy the cells $[(1,1), (2,2)]$. - $K = 3$: The first hero will destroy the cells $[(1,1), (2,2)]$, while the second one will destroy the cells $[(1,1), (1,3)]$. - $K = 4$: The first hero will destroy the cells $[(1,1), (2,3)]$ and the second one will also destroy the cells $[(1,1), (2,3)]$. - $K = 5$ : The first hero will destroy the cell $(1,1)$ and the second one will also destroy the cell $(1,1)$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Code chef problem DESTCELL, Destroy Cells """ def find_destroyed_cells(cell_advance, n, m, k): row = 1 col = 1 destroyed_cells = {(1, 1)} while True: row, col = cell_advance(row, col, n, m, k) if row <= n and col <= m: destroyed_cells.add((row, col)) else: break return destroyed_cells def cell_advance_hero1(row, col, n, m, k): return row + (col + k) // m, (col + k) % m + 1 def cell_advance_hero2(row, col, n, m, k): return (row + k) % n + 1, col + (row + k)//n def main(): t = int(input()) for _ in range(t): n, m = [int(s) for s in input().split(' ')] counts = [] for k in range(n*m): cells_h1 = find_destroyed_cells(cell_advance_hero1, n, m, k) cells_h2 = find_destroyed_cells(cell_advance_hero2, n, m, k) destroyed = len(cells_h1) + len(cells_h2) - len(cells_h1 & cells_h2) counts.append(destroyed) print(' '.join([str(c) for c in counts])) main() ```
{ "language": "python", "test_cases": [ { "input": "1\n2 3\n", "output": "6 4 3 3 2 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/DESTCELL" }
vfc_5074
apps
verifiable_code
1559
Solve the following coding problem using the programming language python: Scheme? - Too loudly said. Just a new idea. Now Chef is expanding his business. He wants to make some new restaurants in the big city of Lviv. To make his business competitive he should interest customers. Now he knows how. But don't tell anyone - it is a secret plan. Chef knows four national Ukrainian dishes - salo, borsch, varenyky and galushky. It is too few, of course, but enough for the beginning. Every day in his restaurant will be a dish of the day among these four ones. And dishes of the consecutive days must be different. To make the scheme more refined the dish of the first day and the dish of the last day must be different too. Now he wants his assistant to make schedule for some period. Chef suspects that there is more than one possible schedule. Hence he wants his assistant to prepare all possible plans so that he can choose the best one among them. He asks you for help. At first tell him how many such schedules exist. Since the answer can be large output it modulo 109 + 7, that is, you need to output the remainder of division of the actual answer by 109 + 7. -----Input----- The first line of the input contains an integer T, the number of test cases. Each of the following T lines contains a single integer N denoting the number of days for which the schedule should be made. -----Output----- For each test case output a single integer in a separate line, the answer for the corresponding test case. -----Constraints-----1 ≤ T ≤ 100 2 ≤ N ≤ 109 -----Example----- Input: 3 2 3 5 Output: 12 24 240 -----Explanation----- Case 1. For N = 2 days we have the following 12 schedules: First day Second day salo borsch salo varenyky salo galushky borsch salo borsch varenyky borsch galushky varenyky salo varenyky borsch varenyky galushky galushky salo galushky borsch galushky varenyky Case 2. For N = 3 we have the following 24 schedules: First daySecond dayThird day salo borsch varenyky salo borsch galushky salo varenyky borsch salo varenyky galushky salo galushky borsch salo galushky varenyky borsch salo varenyky borsch salo galushky borsch varenyky salo borsch varenyky galushky borsch galushky salo borsch galushky varenyky varenyky salo borsch varenyky salo galushky varenyky borsch salo varenyky borsch galushky varenyky galushky salo varenyky galushky borsch galushky salo borsch galushky salo varenyky galushky borsch salo galushky borsch varenyky galushky varenyky salo galushky varenyky borsch Case 3. Don't be afraid. This time we will not provide you with a table of 240 schedules. The only thing we want to mention here is that apart from the previous two cases schedules for other values of N can have equal dishes (and even must have for N > 4). For example the schedule (salo, borsch, salo, borsch) is a correct schedule for N = 4 while the schedule (varenyky, salo, galushky, verynky, salo) is a correct schedule for N = 5. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python r = 1000000007 t = int(input()) for i in range(t): n = int(input()) print(pow(3,n,r) + pow(-1,n)*3) ```
{ "language": "python", "test_cases": [ { "input": "3\n2\n3\n5\n", "output": "12\n24\n240\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/OCT12/problems/NEWSCH" }
vfc_5078
apps
verifiable_code
1560
Solve the following coding problem using the programming language python: Chef has an array A consisting of N integers. He also has an intger K. Chef wants you to find out number of different arrays he can obtain from array A by applying the following operation exactly K times. - Pick some element in the array and multiply it by -1 As answer could be quite large, print it modulo 109 + 7. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains two space separated integers N, K as defined above. - The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. -----Output----- - For each test case, output a single line containing an integer corresponding to the number of different arrays Chef can get modulo 109 + 7. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N, K ≤ 105 - -106 ≤ Ai ≤ 106 -----Subtasks----- - Subtask #1 (10 points) : N, K ≤ 10 - Subtask #2 (30 points) : N, K ≤ 100 - Subtask #3 (60 points) : N, K ≤ 105 -----Example----- Input: 3 1 3 100 3 1 1 2 1 3 2 1 2 1 Output: 1 3 4 -----Explanation----- Example case 1. Chef has only one element and must apply the operation 3 times to it. After applying the operations, he will end up with -100. That is the only array he will get. Example case 2. Chef can apply operation to one of three elements. So, he can obtain three different arrays. Example case 3. Note that other than applying operation to positions (1, 2), (1, 3), (2, 3), Chef can also apply the operation twice on some element and get the original. In summary, Chef can get following four arrays. [1, 2, 1] [-1, -2, 1] [-1, 2, -1] [1, -2, -1] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python fact = [] fact.append(1) for i in range(1,100001): fact.append((i*fact[i-1])%1000000007) def power(a,b,p): x=1 y=a while(b>0): if(b%2 == 1): x=(x*y) if(x>p): x=x%p y=(y*y) if(y>p): y=y%p b=b/2 return x def inverse(N,p): return power(N,p-2,p) def combination(N,R,p): return (fact[N]*((inverse(fact[R],p)*inverse(fact[N-R],p))%p))%p T = int(input()) for i in range(T): N,K = [int(y) for y in input().split()] A = [int(arr) for arr in input().split()] numZ = 0; answer = 0; p = 1000000007 for j in range(len(A)): if(A[j] == 0): numZ = numZ + 1 N = N - numZ if(numZ > 0): if(N > K): temp = K; while(temp >= 0): answer = answer + combination(N,temp,p) temp = temp - 1 else: temp = N while(temp >= 0): answer = answer + combination(N,temp,p) temp = temp - 1 else: if(N > K): temp = K; while(temp >= 0): answer = answer + combination(N,temp,p) temp = temp - 2 else: temp = N while(temp >= 0): answer = answer + combination(N,temp,p) temp = temp - 2 print(answer%1000000007) ```
{ "language": "python", "test_cases": [ { "input": "3\n1 3\n100\n3 1\n1 2 1\n3 2\n1 2 1\n", "output": "1\n3\n4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/JUNE16/problems/CHEFARK" }
vfc_5082
apps
verifiable_code
1561
Solve the following coding problem using the programming language python: Chef Tobby asked Bhuvan to brush up his knowledge of statistics for a test. While studying some distributions, Bhuvan learns the fact that for symmetric distributions, the mean and the median are always the same. Chef Tobby asks Bhuvan out for a game and tells him that it will utilize his new found knowledge. He lays out a total of 109 small tiles in front of Bhuvan. Each tile has a distinct number written on it from 1 to 109. Chef Tobby gives Bhuvan an integer N and asks him to choose N distinct tiles and arrange them in a line such that the mean of median of all subarrays lies between [N-1, N+1], both inclusive. The median of subarray of even length is the mean of the two numbers in the middle after the subarray is sorted Bhuvan realizes that his book didn’t teach him how to solve this and asks for your help. Can you solve the problem for him? In case, no solution exists, print -1. -----Input section----- First line contains, T, denoting the number of test cases. Each of the next T lines, contain a single integer N. -----Output section----- If no solution, exists print -1. If the solution exists, output N space separated integers denoting the elements of the array A such that above conditions are satisfied. In case, multiple answers exist, you can output any one them. -----Input constraints----- 1 ≤ T ≤ 20 1 ≤ N ≤ 100 -----Sample Input----- 3 1 2 3 -----Sample Output----- 1 1 2 1 2 3 -----Explanation----- For test case 3, the subarrays and their median are as follows: - {1}, median = 1 - {2}, median = 2 - {3}, median = 3 - {1, 2}, median = 1.5 - {2, 3}, median = 2.5 - {1, 2, 3}, median = 2 The mean of the medians is 2 which lies in the range [2, 4] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python x=int(input()) for a in range(x): n=int(input()) L=[str(n)] c=1 while(len(L)!=n): L.append(str(n+c)) if len(L)==n: break L.append(str(n-c)) c+=1 a=" ".join(L) print(a) ```
{ "language": "python", "test_cases": [ { "input": "3\n1\n2\n3\n", "output": "1\n1 2\n1 2 3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/COOK86/problems/LIKECS02" }
vfc_5086
apps
verifiable_code
1562
Solve the following coding problem using the programming language python: "I'm a fan of anything that tries to replace actual human contact." - Sheldon. After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact. He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m$m$ such that ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$ = ∑ki=1$\sum_{i=1}^k$mi$m_i$, he would finish the real human contact. Since Sheldon is busy choosing between PS-4 and XBOX-ONE, he want you to help him to calculate the minimum value of m$m$. -----Input:----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains a single integer k$k$. - Next line contains k space separated integers n1,n2...nk$n_1,n_2...n_k$ . -----Output:----- For each test case output the minimum value of m for which ∑ki=1$\sum_{i=1}^k$n$n$i$i$C$C$m$m$i$i$ is even, where m$m$=m1$m_1$+m2$m_2$+. . . mk$m_k$ and 0$0$ <= mi$m_i$<= ni$n_i$ . If no such answer exists print -1. -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤k≤1000$1 \leq k \leq 1000$ - 1≤ni≤10$1 \leq n_i \leq 10$18$18$ -----Sample Input:----- 1 1 5 -----Sample Output:----- 2 -----EXPLANATION:----- 5$5$C$C$2$2$ = 10 which is even and m is minimum. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) def conv(n): k = bin(n) k = k[2:] z = len(k) c = '1'*z if c == k: return False def find(n): x = bin(n)[2:] str = '' for i in x[::-1]: if i == '0': str+='1' break else: str+='0' return int(str[::-1],2) for i in range(t): n = int(input()) ```
{ "language": "python", "test_cases": [ { "input": "1\n1\n5\n", "output": "2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/SUMNCR" }
vfc_5090
apps
verifiable_code
1563
Solve the following coding problem using the programming language python: A reversed arabic no is one whose digits have been written in the reversed order. However in this any trailing zeroes are omitted. The task at hand here is a simple one. You need to add two numbers which have been written in reversed arabic and return the output back in reversed arabic form, assuming no zeroes were lost while reversing. -----Input----- The input consists of N cases. The first line of the input contains only a positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers seperated by space. These are the reversednumbers you are to add. -----Output----- For each case, print exactly one line containing only one integer- the reversed sum of two reversed numbers. Omit any leading zeroes in the output. -----Example----- Input: 1 24 1 Output: 34 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = int(input()) for index in range(0, n): a, b = list(map(str, input().split())) a = int(a[::-1]) b = int(b[::-1]) a = str(a + b) a = int(a[::-1]) print(a) ```
{ "language": "python", "test_cases": [ { "input": "1\n24 1\n", "output": "34\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/ADR2012/problems/A112" }
vfc_5094
apps
verifiable_code
1564
Solve the following coding problem using the programming language python: Sergey recently learned about country codes - two letter strings, denoting countries. For example, BY stands for Belarus and IN stands for India. Mesmerized by this new discovery, Sergey now looks for country codes everywhere! Sergey has recently found a string S consisting of uppercase Latin letters. He wants to find the number of different country codes that appear in S as contiguous substrings. For the purpose of this problem, consider that every 2-letter uppercase string is a valid country code. -----Input----- The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first and only line of each test case contains a string S, consisting of uppercase Latin letters. -----Output----- For each test case, output a single line containing the number of different country codes appearing in the given string. -----Constraints----- - 1 ≤ T ≤ 100 - Subtask 1 (35 points): 2 ≤ |S| ≤ 3 - Subtask 2 (65 points): 2 ≤ |S| ≤ 104 -----Example----- Input:2 INBY BYBY Output:3 2 -----Explanation----- Example case 1. The codes are IN, NB and BY. Example case 2. The codes are BY and YB. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #import set t = eval(input()) while(t): s = input() set1 = set() j = 0 for i in s[:-1]: a = s[j:j+2] set1.add(a) j = j + 1 print(str(len(set1)) + '\n') t= t-1 ```
{ "language": "python", "test_cases": [ { "input": "2\nINBY\nBYBY\n", "output": "3\n2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/LTIME31/problems/DISTCODE" }
vfc_5098
apps
verifiable_code
1565
Solve the following coding problem using the programming language python: Suppose there is a X x Y x Z 3D matrix A of numbers having coordinates (i, j, k) where 0 ≤ i < X, 0 ≤ j < Y, 0 ≤ k < Z. Now another X x Y x Z matrix B is defined from A such that the (i, j, k) element of B is the sum of all the the numbers in A in the cuboid defined by the (0, 0, 0) and (i, j, k) elements as the diagonally opposite vertices. In other word (i, j, k) in B is the sum of numbers of A having coordinates (a, b, c) such that 0 ≤ a ≤ i, 0 ≤ b ≤ j, 0 ≤ c ≤ k. The problem is that given B, you have to find out A. -----Input----- The first line of input will contain the number of test cases ( ≤ 10). That many test cases will follow in subsequent lines. The first line of each test case will contain the numbers X Y Z (0 ≤ X, Y, Z ≤ 100). After that there will be X x Y lines each containing Z numbers of B. The first line contains the numbers (0, 0, 0), (0, 0, 1)..., (0, 0, Z-1). The second line has the numbers (0, 1, 0), (0, 1, 1)..., (0, 1, Z-1) and so on. The (Y+1)th line will have the numbers (1, 0, 0), (1, 0, 1)..., (1, 0, Z-1) and so on. -----Output----- For each test case print the numbers of A in exactly the same fashion as the input. -----Example----- Input: 2 3 1 1 1 8 22 1 2 3 0 9 13 18 45 51 Output: 1 7 14 0 9 4 18 18 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Problem: http://www.codechef.com/JULY09/submit/CUBESUM/ # Author: Susam Pal def computeA(): X, Y, Z = [int(x) for x in input().split()] B = [] for x in range(X): B.append([]) for y in range(Y): B[-1].append([int(t) for t in input().split()]) for z in range(Z): result = B[x][y][z] if x: result -= B[x - 1][y][z] if y: result += B[x - 1][y - 1][z] if z: result -= B[x - 1][y - 1][z - 1] if y: result -= B[x][y - 1][z] if z: result += B[x][y - 1][z - 1] if z: result -= B[x][y][z - 1] if x: result += B[x - 1][y][z - 1] print(result, end=' ') print() test_cases = int(input()) for i in range(test_cases): computeA() ```
{ "language": "python", "test_cases": [ { "input": "2\n3 1 1\n1\n8\n22\n1 2 3\n0 9 13\n18 45 51\n", "output": "1\n7\n14\n0 9 4\n18 18 2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/JULY09/problems/CUBESUM" }
vfc_5102
apps
verifiable_code
1566
Solve the following coding problem using the programming language python: A matrix B (consisting of integers) of dimension N × N is said to be good if there exists an array A (consisting of integers) such that B[i][j] = |A[i] - A[j]|, where |x| denotes absolute value of integer x. You are given a partially filled matrix B of dimension N × N. Q of the entries of this matrix are filled by either 0 or 1. You have to identify whether it is possible to fill the remaining entries of matrix B (the entries can be filled by any integer, not necessarily by 0 or 1) such that the resulting fully filled matrix B is good. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The first line of each test case contains two space separated integers N, Q. Each of the next Q lines contain three space separated integers i, j, val, which means that B[i][j] is filled with value val. -----Output----- For each test case, output "yes" or "no" (without quotes) in a single line corresponding to the answer of the problem. -----Constraints----- - 1 ≤ T ≤ 106 - 2 ≤ N ≤ 105 - 1 ≤ Q ≤ 106 - 1 ≤ i, j ≤ N - 0 ≤ val ≤ 1 - Sum of each of N, Q over all test cases doesn't exceed 106 -----Subtasks----- - Subtask #1 (40 points) 2 ≤ N ≤ 103, 1 ≤ Q ≤ 103, Sum of each of N, Q over all test cases doesn't exceed 104 - Subtask #2 (60 points) Original Constraints -----Example----- Input 4 2 2 1 1 0 1 2 1 2 3 1 1 0 1 2 1 2 1 0 3 2 2 2 0 2 3 1 3 3 1 2 1 2 3 1 1 3 1 Output yes no yes no -----Explanation----- Example 1. You can fill the entries of matrix B as follows. 0 1 1 0 This matrix corresponds to the array A = [1, 2]. Example 2. It is impossible to fill the remaining entries of matrix B such that the resulting matrix is good, as B[1][2] = 1 and B[2][1] = 0, which is impossible. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys sys.setrecursionlimit(1000000) mod = 10**9 + 7 ts = int(input()) while ts > 0: n,q = list(map(int,input().split())) ncc = n-1 par = [i for i in range(n)] rank = [1]*n xor = [0]*n flag = 1 def find(a): if par[a] == a: return a else: temp = find(par[a]) xor[a]^=xor[par[a]] par[a] = temp return temp def union(a,b): a,b = find(a),find(b) if a ==b: return if rank[a] > rank[b]: par[b] = a rank[a]+=rank[b] elif rank[a] < rank[b]: par[a] = b rank[b]+=rank[a] else: par[b] = a rank[a]+=rank[b] par[b] =a for _ in range(q): a,b,x = list(map(int,input().split())) a-=1 b-=1 if flag == -1: continue para = find(a) parb = find(b) if para == parb and xor[a] ^ xor[b] != x: flag = -1 continue # print("no") if para != parb: if rank[para] < rank[parb]: xor[para] = xor[a] ^ xor[b] ^ x par[para] = parb rank[parb]+=rank[para] else: xor[parb] = xor[a] ^ xor[b] ^ x par[parb] = para rank[para]+=rank[parb] ncc-=1 if flag != -1: print("yes") else: print("no") ts-=1 ```
{ "language": "python", "test_cases": [ { "input": "4\n2 2\n1 1 0\n1 2 1\n2 3\n1 1 0\n1 2 1\n2 1 0\n3 2\n2 2 0\n2 3 1\n3 3\n1 2 1\n2 3 1\n1 3 1\n", "output": "yes\nno\nyes\nno\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/FILLMTR" }
vfc_5106
apps
verifiable_code
1567
Solve the following coding problem using the programming language python: Ashley likes playing with strings. She gives Mojo a fun problem to solve. In her imaginary string world, a string of even length is called as "Doublindrome" if both halves of the string are palindromes (both halves have length equal to half of original string). She gives Mojo a string and asks him if he can form a "Doublindrome" by rearranging the characters of the given string or keeping the string as it is. As Mojo is busy playing with cats, solve the problem for him. Print "YES" (without quotes) if given string can be rearranged to form a "Doublindrome" else print "NO" (without quotes). -----Input:----- - First line will contain a single integer $T$, the number of testcases. - Each testcase consists of two lines, first line consists of an integer $N$ (length of the string) and second line consists of the string $S$. -----Output:----- For each testcase, print "YES"(without quotes) or "NO"(without quotes) on a new line. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 100$ - $N$ is always even. - String $S$ consists only of lowercase English alphabets. -----Sample Input:----- 1 8 abbacddc -----Sample Output:----- YES -----EXPLANATION:----- The given string is a Doublindrome as its 2 halves "abba" and "cddc" are palindromes. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n=int(input()) s=input() d={} for j in s: if j not in d: d[j]=1 else: d[j]+=1 f=0 for j in d: if(d[j]%2==1): f=f+1 if((n//2)%2==0 and f==0): print("YES") continue if((n//2)%2==1 and f<=2 and f%2==0): print("YES") continue print("NO") ```
{ "language": "python", "test_cases": [ { "input": "1\n8\nabbacddc\n", "output": "YES\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/NCC2020/problems/NCC002" }
vfc_5110
apps
verifiable_code
1568
Solve the following coding problem using the programming language python: Dhote and Shweta went on a tour by plane for the first time.Dhote was surprised by the conveyor belt at the airport.As Shweta was getting bored Dhote had an idea of playing a game with her.He asked Shweta to count the number of bags whose individual weight is greater than or equal to the half of the total number of bags on the conveyor belt.Shweta got stuck in the puzzle! Help Shweta. -----Input:----- - First line will contain T$T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integers N$N$. - next line conatins N$N$ integers that represents weight of bag -----Output:----- For each testcase, print required answer in new line . -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 1≤N≤105$1 \leq N \leq 10^5$ - 1≤weightofbag≤105$ 1\leq weight of bag \leq 10^5$ -----Sample Input:----- 1 4 1 2 3 4 -----Sample Output:----- 3 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t=int(input()) for _ in range(t): size=int(input()) li=list(map(int,input().split())) c = 0 for i in li: if(i >=len(li)/2): c += 1 print(c) ```
{ "language": "python", "test_cases": [ { "input": "1\n4\n1 2 3 4\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/INEK2019/problems/IF10" }
vfc_5114
apps
verifiable_code
1569
Solve the following coding problem using the programming language python: Dio Brando has set a goal for himself of becoming the richest and the most powerful being on earth.To achieve his goals he will do anything using either manipulation,seduction or plain violence. Only one guy stands between his goal of conquering earth ,named Jotaro Kujo aka JoJo .Now Dio has a stand (visual manifestation of life energy i.e, special power ) “Za Warudo” ,which can stop time itself but needs to chant few words to activate the time stopping ability of the stand.There is a code hidden inside the words and if you can decipher the code then Dio loses his power. In order to stop Dio ,Jotaro asks your help to decipher the code since he can’t do so while fighting Dio at the same time. You will be given a string as input and you have to find the shortest substring which contains all the characters of itself and then make a number based on the alphabetical ordering of the characters. For example : “bbbacdaddb” shortest substring will be “bacd” and based on the alphabetical ordering the answer is 2134 -----NOTE:----- A substring is a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from position l to position r is S[l;r]=SlSl+1…Sr. -----Input :----- The first line contains $T$,number of test cases. The second line contains a string $S$. -----Output:----- For each test cases ,output the number you can get from the shortest string -----Constraints:----- $1 \leq t \leq 100$ $1 \leq |S| \leq 10^6$ -----Test Cases:----- -----Sample Input:----- 6 abcdfgh urdrdrav jojojojoj bbbbaaa cddfsccs tttttttttttt -----Sample Output:----- 1234678 2118418418122 1015 21 46193 20 -----Explanation:----- Test case 1: abcdfgh is the shortest substring containing all char of itself and the number is 1234678 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import sys import math from collections import Counter from collections import OrderedDict def inputt(): return sys.stdin.readline().strip() def printt(n): sys.stdout.write(str(n)+'\n') def listt(): return [int(i) for i in inputt().split()] def gcd(a,b): return math.gcd(a,b) def lcm(a,b): return (a*b) / gcd(a,b) from collections import defaultdict def find_sub_string(str): str_len = len(str) # Count all distinct characters. dist_count_char = len(set([x for x in str])) ctr, start_pos, start_pos_index, min_len = 0, 0, -1, 9999999999 curr_count = defaultdict(lambda: 0) for i in range(str_len): curr_count[str[i]] += 1 if curr_count[str[i]] == 1: ctr += 1 if ctr == dist_count_char: while curr_count[str[start_pos]] > 1: if curr_count[str[start_pos]] > 1: curr_count[str[start_pos]] -= 1 start_pos += 1 len_window = i - start_pos + 1 if min_len > len_window: min_len = len_window start_pos_index = start_pos return str[start_pos_index: start_pos_index + min_len] t= int(inputt()) for _ in range(t): j=[] str1 =inputt() s=find_sub_string(str1) for i in s: j.append(abs(97-ord(i))+1) st = [str(i) for i in j] print(''.join(st)) ```
{ "language": "python", "test_cases": [ { "input": "6\nabcdfgh\nurdrdrav\njojojojoj\nbbbbaaa\ncddfsccs\ntttttttttttt\n", "output": "1234678\n2118418418122\n1015\n21\n46193\n20\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/CSEP2020/problems/JOJOA" }
vfc_5118
apps
verifiable_code
1570
Solve the following coding problem using the programming language python: The chef is placing the laddus on the large square plat. The plat has the side of length N. Each laddu takes unit sq.unit area. Cheffina comes and asks the chef one puzzle to the chef as, how many squares can be formed in this pattern with all sides of new square are parallel to the original edges of the plate. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $N$. -----Output:----- For each test case, output in a single line answer as maximum squares on plate satisfying the condition. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^5$ -----Sample Input:----- 2 1 2 -----Sample Output:----- 1 5 -----EXPLANATION:----- For 1) Only 1 Square For 2) 4 squares with area 1 sq.unit 1 square with area 4 sq.unit The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t = int(input()) while t: m = int(input()) print(int(m * (m + 1) * (2 * m + 1) / 6)) t -= 1 ```
{ "language": "python", "test_cases": [ { "input": "2\n1\n2\n", "output": "1\n5\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PBK12020/problems/ITGUY18" }
vfc_5122
apps
verifiable_code
1571
Solve the following coding problem using the programming language python: Chef is making polygon cakes in his kitchen today! Since the judge panel is very strict, Chef's cakes must be beautiful and have sharp and precise $internal$ angles in arithmetic progression. Given the number of sides, $N$, of the cake Chef is baking today and also the measure of its first angle(smallest angle), $A$, find the measure of the $K^{th}$ angle. -----Input:----- - The first line contains a single integer $T$, the number of test cases. - The next $T$ lines contain three space separated integers $N$, $A$ and $K$, the number of sides of polygon, the first angle and the $K^{th}$ angle respectively. -----Output:----- For each test case, print two space separated integers $X$ and $Y$, such that the $K^{th}$ angle can be written in the form of $X/Y$ and $gcd(X, Y) = 1$ -----Constraints----- - $1 \leq T \leq 50$ - $3 \leq N \leq 1000$ - $1 \leq A \leq 1000000000$ - $1 \leq K \leq N$ - It is guaranteed the answer is always valid. -----Sample Input:----- 1 3 30 2 -----Sample Output:----- 60 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here import math T = int(input()) for _ in range(T): N, A, K = map(int, input().split(" ")) total = (N-2) * 180 diffT = total - N*A diffN = sum(range(1,N)) r = (A*diffN+(K-1)*diffT) d = math.gcd(r, diffN) while d > 1: r//=d diffN//=d d = math.gcd(r, diffN) print(r, diffN) ```
{ "language": "python", "test_cases": [ { "input": "1\n3 30 2\n", "output": "60 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/PCJ18C" }
vfc_5126
apps
verifiable_code
1572
Solve the following coding problem using the programming language python: Indian National Olympiad in Informatics 2016 Boing Inc, has N employees, numbered 1 ... N. Every employee other than Mr. Hojo (the head of the company) has a manager (P[i] denotes the manager of employee i). Thus an employee may manage any number of other employees but he reports only to one manager, so that the organization forms a tree with Mr. Hojo at the root. We say that employee B is a subordinate of employee A if B appears in the subtree rooted at A. Mr. Hojo, has hired Nikhil to analyze data about the employees to suggest how to identify faults in Boing Inc. Nikhil, who is just a clueless consultant, has decided to examine wealth disparity in the company. He has with him the net wealth of every employee (denoted A[i] for employee i). Note that this can be negative if the employee is in debt. He has already decided that he will present evidence that wealth falls rapidly as one goes down the organizational tree. He plans to identify a pair of employees i and j, j a subordinate of i, such A[i] - A[j] is maximum. Your task is to help him do this. Suppose, Boing Inc has 4 employees and the parent (P[i]) and wealth information (A[i]) for each employee are as follows: i 1 2 3 4 A[i] 5 10 6 12 P[i] 2 -1 4 2 P[2] = -1 indicates that employee 2 has no manager, so employee 2 is Mr. Hojo. In this case, the possible choices to consider are (2,1) with a difference in wealth of 5, (2,3) with 4, (2,4) with -2 and (4,3) with 6. So the answer is 6. -----Input format----- There will be one line which contains (2*N + 1) space-separate integers. The first integer is N, giving the number of employees in the company. The next N integers A[1], .., A[N] give the wealth of the N employees. The last N integers are P[1], P[2], .., P[N], where P[i] identifies the manager of employee i. If Mr. Hojo is employee i then, P[i] = -1, indicating that he has no manager. -----Output format----- One integer, which is the needed answer. -----Test data----- -108 ≤ A[i] ≤ 108, for all i. Subtask 1 (30 Marks) 1 ≤ N ≤ 500. Subtask 2 (70 Marks) 1 ≤ N ≤ 105. -----Sample Input----- 4 5 10 6 12 2 -1 4 2 -----Sample Output----- 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys from collections import defaultdict input = sys.stdin.readline sys.setrecursionlimit(1000000) arr=[int(x) for x in input().split()] if arr[0]==1: print(0) return p=[None] for i in range(1,arr[0]+1): p.append(arr[i]) a=[None] for i in range(arr[0]+1,2*arr[0]+1): a.append(arr[i]) graph=defaultdict(list) n=len(a)-1 for i in range(1,n+1): if a[i]==-1: source=i continue graph[a[i]].append((i,(p[a[i]]-p[i]))) def func(node): nonlocal res if len(graph[node])==0: return -10**9 curr=-10**9 for child in graph[node]: x=max(child[1],(func(child[0])+child[1])) curr=max(curr,x) res=max(curr,res) return curr res=-10**9 curr=func(source) print(res) ```
{ "language": "python", "test_cases": [ { "input": "4 5 10 6 12 2 -1 4 2\n", "output": "6\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/INOIPRAC/problems/INOI1601" }
vfc_5130
apps
verifiable_code
1573
Solve the following coding problem using the programming language python: A tennis tournament is about to take place with $N$ players participating in it. Every player plays with every other player exactly once and there are no ties. That is, every match has a winner and a loser. With Naman's birthday approaching, he wants to make sure that each player wins the same number of matches so that nobody gets disheartened. Your task is to determine if such a scenario can take place and if yes find one such scenario. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single integer $N$ denoting number of players. -----Output:----- - If it's impossible for everyone to win the same number of matches, print "NO" (without quotes). - Otherwise print "YES" (without quotes) and then print $N$ lines , each line should consist of a string containing only 0s and 1s and should be of size $N$. - If the jth character in the ith line is 1 then it means in the match between $i$ and $j$ , $i$ wins. - You will get a WA if the output does not correspond to a valid tournament, or if the constraints are not satisfied. - You will get also WA verdict if any 2 lines have contradicting results or if a player beats himself. -----Constraints----- - $1 \leq T \leq 100$ - $2 \leq N \leq 100$ -----Subtasks----- - 10 points : $2 \leq N \leq 6$ - 90 points : Original Constraints. -----Sample Input:----- 2 3 2 -----Sample Output:----- YES 010 001 100 NO -----Explanation:----- One such scenario for $N$ = $3$ is when player $1$ beats player $2$, player $2$ to beats player $3$ and player $3$ beats player $1$. Here all players win exactly $1$ match. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here a = int(input()) for i in range(a): n = int(input()) if n%2==0: print('NO') else: print('YES') for i1 in range(n): li = [0]*n b = str() for i2 in range((n-1)//2): li[(i1+i2+1)%n]+=1 for i3 in range(len(li)): b+=str(li[i3]) print(b) ```
{ "language": "python", "test_cases": [ { "input": "2\n3\n2\n", "output": "YES\n010\n001\n100\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/EXUNB" }
vfc_5134
apps
verifiable_code
1574
Solve the following coding problem using the programming language python: You like tracking airplane flights a lot. Specifically, you maintain history of an airplane’s flight at several instants and record them in your notebook. Today, you have recorded N such records h1, h2, ..., hN, denoting the heights of some airplane at several instants. These records mean that airplane was first flying on height h1, then started changing its height to h2, then from h2 to h3 and so on. The airplanes are usually on cruise control while descending or ascending, so you can assume that plane will smoothly increase/decrease its height from hi to hi + 1 with a constant speed. You can see that during this period, the airplane will cover all possible heights in the range [min(hi, hi+1), max(hi, hi+1)] (both inclusive). It is easy to see that the plane will be at all possible heights in the range exactly a single instant of time during this ascend/descend. You are interested in finding the maximum integer K such that the plane was at some height exactly K times during the flight. -----Input----- There is a single test case. First line of the input contains an integer N denoting the number of records of heights of the plane. Second line contains N space separated integers denoting h1, h2, ..., hN. -----Output----- Output a single maximum integer K in one line, such that the plane was at some height exactly K times during the flight. -----Constraints----- - hi ≠ hi+1 -----Subtasks----- Subtask #1: (30 points) - 1 ≤ N ≤ 1000 - 1 ≤ hi ≤ 1000 Subtask #2: (70 points) - 1 ≤ N ≤ 105 - 1 ≤ hi ≤ 109 -----Example----- Input: 5 1 2 3 2 3 Output: 3 -----Explanation----- The flight can be draw as: 3 /\/ 2 / 1 There are infinitely many heights at which the plane was 3 times during the flight, for example 2.5, 2.1. Notice that the plane was only 2 times at height 2. Moreover, there are no height at which the plane was more than 3 times, so the answer is 3. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def f(n): s = list(map(int, input().split())) low = [] high = [] for i in range(n - 1): low.append(min(s[i], s[i+1])) high.append(max(s[i], s[i+1])) low.sort() high.sort() curr = mx = 0 i = j = 0 n -= 1 while i < n and j < n: if low[i] < high[j]: i += 1 curr += 1 else: j += 1 curr -= 1 mx = max(mx, curr) return mx n = int(input()) print(f(n)) ```
{ "language": "python", "test_cases": [ { "input": "5\n1 2 3 2 3\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/FLYMODE" }
vfc_5138
apps
verifiable_code
1575
Solve the following coding problem using the programming language python: You must have tried to solve the Rubik’s cube. You might even have succeeded at it. Rubik’s cube is a 3x3x3 cube which has 6 different color for each face.The Rubik’s cube is made from 26 smaller pieces which are called cubies. There are 6 cubies at the centre of each face and these comprise of a single color. There are 8 cubies at the 8 corners which comprise of exactly 3 colors. The 12 reamaining cubies comprise of exactly 2 colors. Apple has come up with a variation of the Rubik’s Cube, it’s the Rubik’s cuboid which has different colors on its 6 faces. The Rubik’s Cuboid comes in various sizes represented by M x N x O (M,N,O are natural numbers). Apple is giving away 100 Rubik’s cuboid for free to people who can answer a simple questions. Apple wants to know, in a Rubik’s cuboid with arbitrary dimensions, how many cubies would be there, which comprise of exactly 2 color. -----Input----- The input contains several test cases.The first line of the input contains an integer T denoting the number of test cases. Each test case comprises of 3 natural numbers, M,N & O, which denote the dimensions of the Rubiks Cuboid. -----Output----- For each test case you are required to output the number of cubies which comprise of 2 squares, each of which is of a different color. -----Constraints----- - 1 ≤ T ≤ <1000 - 1 ≤ M ≤ <100000 - 1 ≤ N ≤ <100000 - 1 ≤ O ≤ <100000 -----Example----- Input: 1 3 3 3 Output: 12 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): m=int(input()) n=int(input()) o=int(input()) ans=4*(m+n+o)-24 if(ans <= 0): print('0') else: print(ans) ```
{ "language": "python", "test_cases": [ { "input": "1\n3\n3\n3\n", "output": "12\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/INLO2016/problems/INLO22" }
vfc_5142
apps
verifiable_code
1576
Solve the following coding problem using the programming language python: The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 3 2 3 4 -----Sample Output:----- 12 21 123 231 312 1234 2341 3412 4123 -----EXPLANATION:----- No need, else pattern can be decode easily. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for a0 in range(int(input())): n = int(input()) l = [] for i in range(1,n+1): l.append(i) for j in range(n): s = "" for k in l: s+=str(k) print(s) x = l[0] l.pop(0) l.append(x) ```
{ "language": "python", "test_cases": [ { "input": "3\n2\n3\n4\n", "output": "12\n21\n123\n231\n312\n1234\n2341\n3412\n4123\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/PTRN2020/problems/ITGUY39" }
vfc_5146
apps
verifiable_code
1577
Solve the following coding problem using the programming language python: You are given $N$ gears numbered $1$ through $N$. For each valid $i$, gear $i$ has $A_i$ teeth. In the beginning, no gear is connected to any other. Your task is to process $M$ queries and simulate the gears' mechanism. There are three types of queries: - Type 1: Change the number of teeth of gear $X$ to $C$. - Type 2: Connect two gears $X$ and $Y$. - Type 3: Find the speed of rotation of gear $Y$ if gear $X$ rotates with speed $V$. It is known that if gear $i$ is directly connected to gear $j$ and gear $i$ rotates with speed $V$, then gear $j$ will rotate with speed $-V A_i / A_j$, where the sign of rotation speed denotes the direction of rotation (so minus here denotes rotation in the opposite direction). You may also notice that gears can be blocked in some cases. This happens when some gear would have to rotate in different directions. If a gear is connected to any blocked gear, it is also blocked. For example, if three gears are connected to each other, this configuration can not rotate at all, and if we connect a fourth gear to these three, it will also be blocked and not rotate. -----Input----- - The first line of the input contains two space-separated integers $N$ and $M$. - The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$. - The following $M$ lines describe queries. Each of these lines begins with an integer $T$ denoting the type of the current query. - If $T = 1$, it is followed by a space and two space-separated integers $X$ and $C$. - If $T = 2$, it is followed by a space and two space-separated integers $X$ and $Y$. - If $T = 3$, it is followed by a space and three space-separated integers $X$, $Y$ and $V$. -----Output----- For each query of type 3, print a single line containing two integers separated by a slash '/' — the numerator and denominator of the rotation speed of the given gear expressed as an irreducible fraction (even if this speed is an integer), or $0$ if the gear does not rotate at all. -----Constraints----- - $1 \le N \le 10^5$ - $1 \le M \le 2\cdot 10^5$ - $6 \le A_i \le 10^6$ for each valid $i$ - $1 \le X, Y \le N$ - $1 \le C, V \le 10^6$ -----Subtasks----- Subtask #1 (30 points): - $N \le 2,000$ - $M \le 5,000$ Subtask #2 (70 points): original constraints -----Example Input----- 4 10 6 8 10 13 3 1 2 2 2 1 2 3 1 2 3 2 2 3 1 1 7 3 1 3 10 2 3 1 3 1 3 2 2 1 4 3 1 4 6 -----Example Output----- 0 -9/4 7/1 0 0 -----Explanation----- For the first query of type 3, there are no connections between gears, so the answer is $0$. For the second query of type 3, we can calculate the rotation speed using the formula $-3\cdot\frac{6}{8} = \frac{-9}{4}$. For the third query of type 3, we can use the formula twice, so the speed of the second gear is $-10\cdot\frac{7}{8} = -\frac{35}{4}$, and the speed of the third gear is $-(-\frac{35}{4})\frac{8}{10} = \frac{7}{1}$. For the last query of type 3, all gears are blocked. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class Dsu: def __init__(self, v, s): self.par = s self.v = v self.dr = [1] * v self.zero = [False] * v self.speed = [] for i in range(v): self.speed.append([]) self.speed[i].append(i) def find(self, i): # if parent[i] == -1: # return i # else: return self.find_parent(parent, parent[i]) if i != self.par[i][0]: org = self.par[i][0] self.par[i][0] = self.find(self.par[i][0]) if self.zero[i] or self.zero[self.par[i][0]] or self.zero[org]: self.zero[i] = self.zero[self.par[i][0]] = self.zero[org] = True if org != self.par[i][0]: self.speed[self.par[i][0]].append(i) return self.par[i][0] def union(self, x, y): # def union(self, parent, x, y): # x_set = self.find_parent(parent, x) # y_set = self.find_parent(parent, y) # parent[x_set] = y_set self.rx = self.find(x) self.ry = self.find(y) self.sign = -self.dr[x] * self.dr[y] if self.rx != self.ry: if (self.par[self.rx][1]<self.par[self.ry][1]): mx=self.ry mn=self.rx if (self.par[self.rx][1]>self.par[self.ry][1]): mx=self.rx mn=self.ry if self.par[self.rx][1] != self.par[self.ry][1]: self.par[mn][0] = mx if self.zero[mn] or self.zero[mx] or self.zero[x] or self.zero[y]: self.zero[mn] = self.zero[mx] = self.zero[x] = self.zero[y] = True else: for i in range(len(self.speed[mn])): self.dr[self.speed[mn][i]] *= self.sign org = self.par[self.speed[mn][i]][0] if org != mx: self.par[self.speed[mn][i]][0] = mx self.speed[mx].append(self.speed[mn][i]) self.speed[mx].append(mn) else: self.par[self.ry][0] = self.rx self.par[self.rx][1] += 1 if self.zero[self.rx] or self.zero[self.ry] or self.zero[x] or self.zero[y]: self.zero[self.rx] = self.zero[self.ry] = self.zero[x] = self.zero[y] = True else: for i in range(len(self.speed[self.ry])): self.dr[self.speed[self.ry][i]] *= self.sign org = self.par[self.speed[self.ry][i]][0] if org != self.rx: self.par[self.speed[self.ry][i]][0] = self.rx self.speed[self.rx].append(self.speed[self.ry][i]) self.speed[self.rx].append(self.ry) else: return def optwo(x, y, D): if (D.find(x) == D.find(y) and D.dr[x] == D.dr[y]): D.zero[x] = D.zero[y] = True D.union(x, y) def gcd(a, b): if a == 0: return b else: return gcd(b % a, a) def opthree(x, y, v, D): if (D.find(x) != D.find(y)) or (D.zero[D.par[y][0]]): print(0) else: g = gcd(v * speed[x], speed[y]) flag=(D.dr[x] * D.dr[y])//abs(D.dr[x] * D.dr[y]) print(str(flag * v * speed[x] // g) + "/" + str(speed[y] // g)) n, M = map(int, input().split()) speed = list(map(int, input().split())) s = [] for i in range(n): s.append([i, 0]) D = Dsu(n, s) for i in range(M): T = list(map(int, input().split())) if (T[0] == 1): speed[T[1] - 1] = T[2] elif (T[0] == 2): optwo(T[1] - 1, T[2] - 1, D) elif (T[0] == 3): opthree(T[1] - 1, T[2] - 1, T[3], D) ```
{ "language": "python", "test_cases": [ { "input": "4 10\n6 8 10 13\n3 1 2 2\n2 1 2\n3 1 2 3\n2 2 3\n1 1 7\n3 1 3 10\n2 3 1\n3 1 3 2\n2 1 4\n3 1 4 6\n\n", "output": "0\n-9/4\n7/1\n0\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/GEARS" }
vfc_5150
apps
verifiable_code
1578
Solve the following coding problem using the programming language python: Given an alphanumeric string made up of digits and lower case Latin characters only, find the sum of all the digit characters in the string. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow. - Each test case is described with a single line containing a string S, the alphanumeric string. -----Output----- - For each test case, output a single line containing the sum of all the digit characters in that string. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ |S| ≤ 1000, where |S| is the length of the string S. -----Example----- Input: 1 ab1231da Output: 7 -----Explanation----- The digits in this string are 1, 2, 3 and 1. Hence, the sum of all of them is 7. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(eval(input())): s = input() ans = 0 for i in s: if i.isdigit(): ans += int(i) print(ans) ```
{ "language": "python", "test_cases": [ { "input": "1\nab1231da\n", "output": "7\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/TSTIND16/problems/KOL15A" }
vfc_5154
apps
verifiable_code
1579
Solve the following coding problem using the programming language python: You are given an integer sequence $A_1, A_2, \ldots, A_N$. For any pair of integers $(l, r)$ such that $1 \le l \le r \le N$, let's define $\mathrm{OR}(l, r)$ as $A_l \lor A_{l+1} \lor \ldots \lor A_r$. Here, $\lor$ is the bitwise OR operator. In total, there are $\frac{N(N+1)}{2}$ possible pairs $(l, r)$, i.e. $\frac{N(N+1)}{2}$ possible values of $\mathrm{OR}(l, r)$. Determine if all these values are pairwise distinct. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing the string "YES" if all values of $\mathrm{OR}(l, r)$ are pairwise distinct or "NO" otherwise (without quotes). -----Constraints----- - $1 \le T \le 300$ - $1 \le N \le 10^5$ - $0 \le A_i \le 10^{18}$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $3 \cdot 10^5$ -----Example Input----- 4 3 1 2 7 2 1 2 3 6 5 8 5 12 32 45 23 47 -----Example Output----- NO YES YES NO -----Explanation----- Example case 1: The values of $\mathrm{OR}(l, r)$ are $1, 2, 7, 3, 7, 7$ (corresponding to the contiguous subsequences $[1], [2], [7], [1,2], [2,7], [1,2,7]$ respectively). We can see that these values are not pairwise distinct. Example case 2: The values of $\mathrm{OR}(l, r)$ are $1, 2, 3$ (corresponding to the contiguous subsequences $[1], [2], [1, 2]$ respectively) and they are pairwise distinct. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) if n<=62: st = set() for i in range(n): curr = 0 for j in range(i,n): curr = curr|arr[j] st.add(curr) if len(st)==n*(n+1)//2: print("YES") else: print("NO") else: print("NO") ```
{ "language": "python", "test_cases": [ { "input": "4\n3\n1 2 7\n2\n1 2\n3\n6 5 8\n5\n12 32 45 23 47\n", "output": "NO\nYES\nYES\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/ORTHODOX" }
vfc_5158
apps
verifiable_code
1580
Solve the following coding problem using the programming language python: In this problem the input will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), :(colon) and white space characters (blank, newline). Your task is print the words in the text in lexicographic order (that is, dictionary order). Each word should appear exactly once in your list. You can ignore the case (for instance, "The" and "the" are to be treated as the same word). There should be no uppercase letters in the output. For example, consider the following candidate for the input text: This is a sample piece of text to illustrate this problem. The corresponding output would read as: a illustrate is of piece problem sample text this to -----Input format----- - The first line of input contains a single integer $N$, indicating the number of lines in the input. - This is followed by $N$ lines of input text. -----Output format----- - The first line of output contains a single integer $M$ indicating the number of distinct words in the given text. - The next $M$ lines list out these words in lexicographic order. -----Constraints----- - $1 \leq N \leq 10000$ - There are at most 80 characters in each line. - There are at the most 1000 distinct words in the given text. -----Sample Input----- 2 This is a sample piece of text to illustrate this problem. -----Sample Output----- 10 a illustrate is of piece problem sample text this to The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys t=int(input()) x=sys.stdin.readlines() l=[] for s in x: s=s.replace(".","") s=s.replace("'","") s=s.replace(",","") s=s.replace(":","") s=s.replace(";","") lst=[str(i) for i in s.split()] for j in lst: l.append(j) m=[] for y in l: z=y.lower() m.append(z) n=[] for k in m: if(k in n): continue else: n.append(k) print(len(n)) h=sorted(n) for j in h: print(j) ```
{ "language": "python", "test_cases": [ { "input": "2\nThis is a sample piece of text to illustrate this\nproblem.\n", "output": "10\na\nillustrate\nis\nof\npiece\nproblem\nsample\ntext\nthis\nto\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/IARCSJUD/problems/WORDLIST" }
vfc_5162
apps
verifiable_code
1581
Solve the following coding problem using the programming language python: Kajaria has an empty bag and 2 types of tiles - tiles of type $1$ have the number $X$ written and those of type $2$ have the number $Y$ written on them. He has an infinite supply of both type of tiles. In one move, Kajaria adds exactly $1$ tile to the bag. He adds a tile of type $1$ with probability $p$ and a tile of type $2$ with probability $(1 - p)$. If $2$ tiles in the bag have the same number written on them (say $Z$), they are merged into a single tile of twice that number ($2Z$). Find the expected number of moves to reach the first tile with number $S$ written on it. Notes on merging: - Consider that the bag contains tiles $(5, 10, 20, 40)$ and if the new tile added is $5$, then it would merge with the existing $5$ and the bag would now contain $(10, 10, 20, 40)$. The tiles $10$ (already present) and $10$ (newly formed) would then merge in the same move to form $(20, 20, 40)$, and that will form $(40, 40)$, which will form $(80)$. Kajaria guarantees that: - $X$ and $Y$ are not divisible by each other. - A tile with number $S$ can be formed. -----Input----- - First line contains a single integer $T$ - the total no. of testcases - Each testcase is described by $2$ lines: - $X, Y, S$ - $3$ space-separated natural numbers - $u, v$ - $2$ space-separated natural numbers describing the probability $p$ The value of $p$ is provided as a fraction in its lowest form $u/v$ ($u$ and $v$ are co-prime) -----Output----- - For each testcase, if the expected number of moves can be expressed as a fraction $p/q$ in its lowest form, print $(p * q^{-1})$ modulo $10^9 + 7$, where $q^{-1}$ denotes the modular inverse of $q$ wrt $10^9 + 7$. -----Constraints----- - $1 \leq T \leq 10^5$ - $2 \leq X, Y \leq 5 * 10^{17}$ - $1 \leq S \leq 10^{18}$ - $1 \leq u < v \leq 10^{9}$ -----Sample Input----- 1 5 3 96 1 3 -----Sample Output----- 48 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here t=int(input()) MOD=1000000007 def mod(n, m=MOD): n%=m while n<0: n+=m return n def power(n, p): res=1 while p: if p%2: res=mod(res*n) p//=2 n=mod(n*n) return res while t: ma=input().split() x=int(ma[0]) y=int(ma[1]) s=int(ma[2]) ma=input().split() u=int(ma[0]) v=int(ma[1]) if s%x==0 and ((s // x) & ((s // x) - 1) == 0): inv=power(u, MOD-2) print(mod(mod(mod(s//x)*v)*inv)) else: inv=power(v-u, MOD-2) print(mod(mod(mod(s//y)*v)*inv)) t-=1 ```
{ "language": "python", "test_cases": [ { "input": "1\n5 3 96\n1 3\n", "output": "48\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/TILEBAG" }
vfc_5166
apps
verifiable_code
1582
Solve the following coding problem using the programming language python: There are n cards of different colours placed in a line, each of them can be either red, green or blue cards. Count the minimum number of cards to withdraw from the line so that no two adjacent cards have the same colour. -----Input----- - The first line of each input contains an integer n— the total number of cards. - The next line of the input contains a string s, which represents the colours of the cards. We'll consider the cards in a line numbered from 1 to n from left to right. Then the $i^t$$^h$ alphabet equals "G", if the $i^t$$^h$ card is green, "R" if the card is red, and "B", if it's blue. -----Output----- - Print a single integer — the answer to the problem. -----Constraints----- - $1 \leq n \leq 50$ -----Sample Input 1:----- 5 RGGBG -----Sample Input 2:----- 5 RRRRR -----Sample Input 3:----- 2 BB -----Sample Output 1:----- 1 -----Sample Output 2:----- 4 -----Sample Output 3:----- 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here n = int(input()) s = [i for i in input()] count = 0 for i in range(1,n): if s[i] == s[i-1]: count += 1 else: continue print(count) ```
{ "language": "python", "test_cases": [ { "input": "5\nRGGBG\nSample Input 2:\n5\nRRRRR\nSample Input 3:\n2\nBB\n", "output": "1\nSample Output 2:\n4\nSample Output 3:\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/COTH2020/problems/MINCARDS" }
vfc_5170
apps
verifiable_code
1584
Solve the following coding problem using the programming language python: -----Problem Statement----- You all must have played the game candy crush. So here is a bomb which works much the fruit bomb in candy crush. A designer, Anton, designed a very powerful bomb. The bomb, when placed on a location $(x, y)$ in a $R \times C$ grid, wipes out the row $x$ and column $y$ completely. You are given a $R\times C$ grid with $N$ targets. You have only one bomb. Your aim is to maximize the damage and hence destroy most number of targets. Given the location of targets on the grid, find out the number of targets that can destroyed. The grid system uses index starting with $0$. -----Input----- - First line contains three space separated integers, $R$, $C$ and $N$. Then, $N$ lines follow. - Each line contains space separated integers $r$ and $c$ mentioning the location of the target. -----Output----- A single integer giving the number of targets that can be destroyed. -----Constraints----- - $1 \leq R, C \leq 3 \times 10^5$ - $1 \leq N \leq min(R \times C, 3 \times 10^5)$ - $0 \leq r < R$ - $0 \leq c < C$ - Any input pair $(r, c)$ is not repeated. -----Subtasks----- The total marks will be divided into: - 20% : $R, C \leq 10^3$ - 80% : Original Constraints -----Sample Input----- 2 3 3 1 1 0 0 0 2 -----Sample Output----- 3 -----EXPLANATION----- It is possible to destroy all the targets if we place the bomb at $(0, 1)$. Hence, total number of targets destroyed is $3$, which is our answer. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python r,c,n = map(int , input().split());coordinates = [];coordinates_1,coordinates_2 = {},{} for _ in range(n): x,y = map(int , input().split()) coordinates.append([x,y]) for i in coordinates: if(i[0] in coordinates_1): coordinates_1[i[0]] += 1 else: coordinates_1[i[0]] = 1 if(i[1] in coordinates_2): coordinates_2[i[1]] += 1 else: coordinates_2[i[1]] = 1 print(max(coordinates_1.values()) + max(coordinates_2.values())) ```
{ "language": "python", "test_cases": [ { "input": "2 3 3\n1 1\n0 0\n0 2\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/SCAT2020/problems/SC_03" }
vfc_5178
apps
verifiable_code
1585
Solve the following coding problem using the programming language python: Chef is now a corporate person. He has to attend office regularly. But chef does not want to go to office, rather he wants to stay home and discover different recipes and cook them. In the office where chef works, has two guards who count how many times a person enters into the office building. Though the duty of a guard is 24 hour in a day, but sometimes they fall asleep during their duty and could not track the entry of a person in the office building. But one better thing is that they never fall asleep at the same time. At least one of them remains awake and counts who enters into the office. Now boss of Chef wants to calculate how many times Chef has entered into the building. He asked to the guard and they give him two integers A and B, count of first guard and second guard respectively. Help the boss to count the minimum and maximum number of times Chef could have entered into the office building. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of the T test cases follows. Each test case consists of a line containing two space separated integers A and B. -----Output----- For each test case, output a single line containing two space separated integers, the minimum and maximum number of times Chef could have entered into the office building. -----Constraints----- - 1 ≤ T ≤ 100 - 0 ≤ A, B ≤ 1000000 -----Example----- Input: 1 19 17 Output: 19 36 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here for _ in range(int(input())): x, y= map(int, input().split()) print(max(x,y), x+y) ```
{ "language": "python", "test_cases": [ { "input": "1\n19 17\n", "output": "19 36\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/REMISS" }
vfc_5182
apps
verifiable_code
1586
Solve the following coding problem using the programming language python: Indian National Olympiad in Informatics 2012 You are given a table with 2 rows and N columns. Each cell has an integer in it. The score of such a table is defined as follows: for each column, consider the sum of the two numbers in the column; the maximum of the N numbers so obtained is the score. For example, for the table 7162 1234 the score is max(7 + 1, 1 + 2, 6 + 3, 2 + 4) = 9. The first row of the table is fixed, and given as input. N possible ways to fill the second row are considered: 1,2,...,N 2,3,...,N,1 3,4,...,N,1,2 ··· N, 1, ... , ,N − 1 For instance, for the example above, we would consider each of the following as possibilities for the second row. 1234 2341 3412 4123 Your task is to find the score for each of the above choices of the second row. In the example above, you would evaluate the following four tables, 7162 7162 7162 7162 1234 2341 3412 4123 and compute scores 9, 10, 10 and 11, respectively. -----Input format ----- The first line of the input has a single integer, N. The second line of the input has N integers, representing the first row, from left to right. -----Output format ----- The output should consist of a single line with N integers. For 1 ² k ² N, the kth number in the output should be the score when the second row of the table is taken to be k,k+1,...,N,1,...,k−1. -----Test Data ----- The testdata is grouped into two subtasks with the following constraints on the inputs. • Subtask 1 [30 points] : 1 ≤ N ≤ 3000. • Subtask 2 [70 points] : 1 ≤ N ≤ 200000. In both the subtasks, all the integers in the first row of the table are between 1 and 100000, inclusive. -----Example ----- Here is the sample input and output corresponding to the example above. -----Sample input ----- 4 7 1 6 2 -----Sample output----- 9 10 10 11 Note: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect! The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # cook your dish here try: n=int(input()) list_n = list(range(1,n+1)) list_n_flag=[] fix_arr = list(map(int,input().split())) k=1 res_list=[] fin_list=[] list_n_flag = list_n[k:] + list_n[:k] res_list = [list_n[i] + fix_arr[i] for i in range(len(fix_arr))] maxx = max(res_list) fin_list.append(maxx) while list_n!=list_n_flag: res_list = [list_n_flag[i] + fix_arr[i] for i in range(len(fix_arr))] maxx = max(res_list) fin_list.append(maxx) list_n_flag = list_n_flag[k:] + list_n_flag[:k] print(*fin_list,sep=" ") except: pass ```
{ "language": "python", "test_cases": [ { "input": "and output corresponding to the example above.\nSample input\n4\n7 1 6 2\nSample output\n9 10 10 11\nNote: Your program should not print anything other than what is specified in the output format. Please remove all diagnostic print statements before making your final submission. A program with extraneous output will be treated as incorrect!\n", "output": "", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/INOIPRAC/problems/INOI1202" }
vfc_5186
apps
verifiable_code
1587
Solve the following coding problem using the programming language python: Chef likes problems on geometry a lot. Please help him to solve one such problem. Find all possible triangles with integer sides which has the radius of inscribed circle (also known as incircle) equal to R. Two triangles are said to be different if they have at least one different side lengths. Formally, let there be two triangles T1, T2. Let a, b, c denote the sides of triangle T1, such that a ≤ b ≤ c. Similarly, Let d, e, f denote the sides of triangle T2, such that d ≤ e ≤ f. Then T1 will said to be different from T2 if either a ≠ d, or b ≠ e or c ≠ f. -----Input----- There is a single test case per test file. The only line of input contains an integer R. -----Output----- Output in first line single number - number of triangles satisfying statement. Order the sides of triangles in non-decreasing order. Output all triangles in non-decreasing order, i.e. order first by smallest sides, otherwise by second smallest sides, if first and second sides equal, then by third. -----Constraints----- - 1 ≤ R ≤ 100 -----Subtasks----- - Subtask #1: (20 points) 1 ≤ R ≤ 3 - Subtask #2: (30 points) 1 ≤ R ≤ 20 - Subtask #3: (50 points) Original constraints -----Example----- Input:2 Output:5 5 12 13 6 8 10 6 25 29 7 15 20 9 10 17 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python r=int(input()) c=0 L=[] for i in range(2*r+1,2*r**2+2): for j in range(i,r**4+2*r**2+2): for k in range(j,r**4+3*r**2+2): if 4*(i+j+k)*r**2==(i+j-k)*(i+k-j)*(j+k-i): L.append([i,j,k]) c+=1 print(c) for i in range(c): for j in range(3): print(L[i][j], end=' ') print() ```
{ "language": "python", "test_cases": [ { "input": "2\n", "output": "5\n5 12 13\n6 8 10\n6 25 29\n7 15 20\n9 10 17\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/LTIME40/problems/LTM40CD" }
vfc_5190
apps
verifiable_code
1588
Solve the following coding problem using the programming language python: Lucy had recently learned the game, called Natural Numbers. The rules of the game are really simple. There are N players. At the same time, every player says one natural number. Let's call the number said by the i-th player Ai. The person with the smallest unique number (that is, the smallest number that was not said by anybody else) wins. Sometimes, there is a case when there are no unique numbers at all. Then the game is obviously a draw, so nobody wins it. Sometimes, it's hard to determine the winner, especially, when the number of players is enormous. So in this problem, your assignment will be: given the names of the players and the numbers every of them have said. Please, tell the name of the winner, or determine that nobody wins. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of every test case consists of a single integer N - the number of players. Then, N lines will follow. Each of these N lines will consist of the player's name and the number Ai said by her, separated by a single space. -----Output----- For each test case, output a single line containing an answer to the corresponding test case - the name of the winner, or a string "Nobody wins.", if nobody wins the game. -----Example----- Input: 2 5 Kouta 1 Yuka 1 Mayu 3 Lucy 2 Nana 5 2 Lucy 2 Nana 2 Output: Lucy Nobody wins. -----Scoring----- Subtask 1 (17 points): T = 10000, 1 <= N <= 10, 1 <= Ai <= 10 Subtask 2 (19 points): T = 10000, 1 <= N <= 10, 1 <= Ai <= 2*109 Subtask 3 (30 points): T = 100, 1 <= N <= 1000, 1<= Ai <= 2*109 Subtask 4 (34 points): T = 10, 1 <= N <= 10000, 1 <= Ai <= 2*109 You can safely assume that in all the test cases the length of any name will not exceed five letters. All the players' names are unique. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python try: t = int(input()) while t: t -= 1 n = int(input()) arr = [] obj = {} for i in range(n): x,y = input().split() y = int(y) arr.append([x, y]) if y in obj: obj[y].append(x) else: obj[y] = [x] arr.sort(key = lambda i: i[1], reverse = True) while len(arr) and len(obj[arr[-1][1]]) > 1: arr.pop() if len(arr) == 0: print('Nobody wins.') else: print(arr.pop()[0]) except: pass ```
{ "language": "python", "test_cases": [ { "input": "2\n5\nKouta 1\nYuka 1\nMayu 3\nLucy 2\nNana 5\n2\nLucy 2\nNana 2\n\n\n", "output": "Lucy\nNobody wins.\n", "type": "stdin_stdout" } ] }
{ "difficulty": "interview", "problem_url": "https://www.codechef.com/problems/NUMBERS" }
vfc_5194