source
stringclasses
4 values
task_type
stringclasses
1 value
in_source_id
stringlengths
0
138
problem
stringlengths
219
13.2k
gold_standard_solution
stringlengths
0
413k
problem_id
stringlengths
5
10
metadata
dict
verification_info
dict
apps
verifiable_code
1658
Solve the following coding problem using the programming language python: When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to d_{i}. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes. But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' — you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 10^9 + 7. -----Input----- The first line contains two space-separated integers n and x (1 ≤ n ≤ 10^5, 0 ≤ x ≤ 10^9) — the number of children of each node and the distance from the root within the range of which you need to count the nodes. The next line contains n space-separated integers d_{i} (1 ≤ d_{i} ≤ 100) — the length of the edge that connects each node with its i-th child. -----Output----- Print a single number — the number of vertexes in the tree at distance from the root equal to at most x. -----Examples----- Input 3 3 1 2 3 Output 8 -----Note----- Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 def mul_vec_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD return c def mul_vec_sparse_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(x * v[j] % MOD for j, x in a[i]) % MOD return c _, x = [int(v) for v in input().split()] a = [[0] * N for i in range(N)] a[0][0] = 1 a[N - 1][0] = 1 for i in range(1, N - 1): a[i][i + 1] = 1 for d in map(int, input().split()): a[N - 1][N - d] += 1 sa = [[] for i in range(N)] for i in range(N): for j in range(N): if a[i][j] != 0: sa[j].append((i, a[i][j])) r = [[1 if i == j else 0 for j in range(N)] for i in range(N)] while x > 0: if x & 1: r[0] = mul_vec_mat(r[0], a) r[1] = mul_vec_mat(r[1], a) aa = [[0] * N for i in range(N)] aa[0] = mul_vec_mat(a[0], a) aa[1] = mul_vec_mat(a[1], a) for i in range(2, N): aa[i] = mul_vec_sparse_mat(aa[i - 1], sa) a = aa x >>= 1 for i in range(2, N): r[i] = mul_vec_sparse_mat(r[i - 1], sa) b = [0] * N b[0] = 1 b[N - 1] = 1 print(sum(r[N - 1][i] * b[i] % MOD for i in range(N)) % MOD) ```
vfc_16386
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/514/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 3\n1 2 3\n", "output": "8\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1659
Solve the following coding problem using the programming language python: After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids. -----Input----- The first line contains two space-separated integers n and x (1 ≤ n ≤ 1000, 0 ≤ x ≤ 10^9). Each of the next n lines contains a character '+' or '-', and an integer d_{i}, separated by a space (1 ≤ d_{i} ≤ 10^9). Record "+ d_{i}" in i-th line means that a carrier with d_{i} ice cream packs occupies i-th place from the start of the queue, and record "- d_{i}" means that a child who wants to take d_{i} packs stands in i-th place. -----Output----- Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress. -----Examples----- Input 5 7 + 5 - 10 - 20 + 40 - 20 Output 22 1 Input 5 17 - 16 - 2 - 98 + 100 - 98 Output 3 2 -----Note----- Consider the first sample. Initially Kay and Gerda have 7 packs of ice cream. Carrier brings 5 more, so now they have 12 packs. A kid asks for 10 packs and receives them. There are only 2 packs remaining. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. Carrier bring 40 packs, now Kay and Gerda have 42 packs. Kid asks for 20 packs and receives them. There are 22 packs remaining. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, x = list(map(int, input().split())) r = 0 for _ in range(n): a, b = input().split() if a == "+": x += int(b) else: if int(b) <= x: x -= int(b) else: r += 1 print(x, r) ```
vfc_16390
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/686/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20\n", "output": "22 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 17\n- 16\n- 2\n- 98\n+ 100\n- 98\n", "output": "3 2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n+ 1000000000\n", "output": "7000000000 0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 12\n- 12\n+ 7\n- 6\n- 1\n+ 46\n", "output": "46 0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "11 1000\n- 100\n+ 100\n+ 100\n+ 100\n+ 100\n- 100\n- 100\n- 100\n- 100\n- 100\n- 100\n", "output": "700 0\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1660
Solve the following coding problem using the programming language python: Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. -----Input----- The first line contains two integers n, m (2 ≤ n ≤ 3·10^5; 1 ≤ m ≤ min(n·(n - 1), 3·10^5)). Then, m lines follows. The i-th line contains three space separated integers: u_{i}, v_{i}, w_{i} (1 ≤ u_{i}, v_{i} ≤ n; 1 ≤ w_{i} ≤ 10^5) which indicates that there's a directed edge with weight w_{i} from vertex u_{i} to vertex v_{i}. It's guaranteed that the graph doesn't contain self-loops and multiple edges. -----Output----- Print a single integer — the answer to the problem. -----Examples----- Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 -----Note----- In the first sample the maximum trail can be any of this trails: $1 \rightarrow 2,2 \rightarrow 3,3 \rightarrow 1$. In the second sample the maximum trail is $1 \rightarrow 2 \rightarrow 3 \rightarrow 1$. In the third sample the maximum trail is $1 \rightarrow 2 \rightarrow 5 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 6$. 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 * f = list(map(int, stdin.read().split())) n, m = f[0], f[1] d = [[] for i in range(100001)] for j in range(2, len(f), 3): x, y, w = f[j:j + 3] d[w].append((y, x)) s = [0] * (n + 1) for q in d: for y, k in [(y, s[x]) for y, x in q]: s[y] = max(s[y], k + 1) print(max(s)) ```
vfc_16394
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/459/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 3\n1 2 1\n2 3 1\n3 1 1\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 3\n1 2 1\n2 3 2\n3 1 3\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4\n", "output": "6\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 2\n1 2 1\n2 1 2\n", "output": "2\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1661
Solve the following coding problem using the programming language python: Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$. Maxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$. Games in the shop are ordered from left to right, Maxim tries to buy every game in that order. When Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop. Maxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game. For example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$. Your task is to get the number of games Maxim will buy. -----Input----- The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 1000$), where $c_i$ is the cost of the $i$-th game. The third line of the input contains $m$ integers $a_1, a_2, \dots, a_m$ ($1 \le a_j \le 1000$), where $a_j$ is the value of the $j$-th bill from the Maxim's wallet. -----Output----- Print a single integer — the number of games Maxim will buy. -----Examples----- Input 5 4 2 4 5 2 4 5 3 4 6 Output 3 Input 5 2 20 40 50 20 40 19 20 Output 0 Input 6 4 4 8 15 16 23 42 1000 1000 1000 1000 Output 4 -----Note----- The first example is described in the problem statement. In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop. In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = [int(x) for x in input().strip().split()] c = [int(x) for x in input().strip().split()] a = [int(x) for x in input().strip().split()] ans = 0 ai = 0 for ci in c: if ai < len(a) and a[ai] >= ci: ai += 1 ans += 1 print(ans) ```
vfc_16398
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1009/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 4\n2 4 5 2 4\n5 3 4 6\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 2\n20 40 50 20 40\n19 20\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 4\n4 8 15 16 23 42\n1000 1000 1000 1000\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 1\n1 1 1 1 1\n5\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1662
Solve the following coding problem using the programming language python: Sereja loves integer sequences very much. He especially likes stairs. Sequence a_1, a_2, ..., a_{|}a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a_1 < a_2 < ... < a_{i} - 1 < a_{i} > a_{i} + 1 > ... > a_{|}a| - 1 > a_{|}a|. For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't. Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table? -----Input----- The first line contains integer m (1 ≤ m ≤ 10^5) — the number of Sereja's cards. The second line contains m integers b_{i} (1 ≤ b_{i} ≤ 5000) — the numbers on the Sereja's cards. -----Output----- In the first line print the number of cards you can put on the table. In the second line print the resulting stairs. -----Examples----- Input 5 1 2 3 4 5 Output 5 5 4 3 2 1 Input 6 1 1 2 2 3 3 Output 5 1 2 3 2 1 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()) a=list(map(int,input().split())) count=[0]*(10**5+1) for i in a: count[i]+=1 ans=[] for i in range(10**5+1): if count[i]: ans.append(i) count[i]-=1 if len(ans)!=n: for i in reversed(range(10**5+1)): if count[i] and ans[-1]!=i: ans.append(i) print(len(ans)) print(*ans) ```
vfc_16402
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/381/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 2 3 4 5\n", "output": "5\n5 4 3 2 1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1663
Solve the following coding problem using the programming language python: Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price $n$, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price. For example, is Sasha names $1213121$, Vova can remove the substring $1312$, and the result is $121$. It is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be $0$. Sasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move. Help Sasha to compute this sum. Since the answer can be very large, print it modulo $10^9 + 7$. -----Input----- The first and only line contains a single integer $n$ ($1 \le n < 10^{10^5}$). -----Output----- In the only line print the required sum modulo $10^9 + 7$. -----Examples----- Input 107 Output 42 Input 100500100500 Output 428101984 -----Note----- Consider the first example. Vova can choose to remove $1$, $0$, $7$, $10$, $07$, or $107$. The results are $07$, $17$, $10$, $7$, $1$, $0$. Their sum is $42$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s=input();M=10**9+7;o=u=v=0;n=len(s) for i in range(n):c=int(s[i]);u+=v;v=(10*v+c)%M;o+=pow(10,n-i-1,M)*((i*i+i)//2*c+u) print(o%M) ```
vfc_16406
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1422/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "107\n", "output": "42\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "100500100500\n", "output": "428101984\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "22098174938\n", "output": "647942793\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1403665305\n", "output": "765601706\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1664
Solve the following coding problem using the programming language python: Let's analyze a program written on some strange programming language. The variables in this language have names consisting of $1$ to $4$ characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit. There are four types of operations in the program, each denoted by one of the characters: $, ^, # or &. Each line of the program has one of the following formats: <lvalue>=<rvalue>, where <lvalue> and <rvalue> are valid variable names; <lvalue>=<arg1><op><arg2>, where <lvalue>, <arg1> and <arg2> are valid variable names, and <op> is an operation character. The program is executed line-by-line, and the result of execution is stored in a variable having the name res. If res is never assigned in the program, then the result will be equal to the value of res before running the program. Two programs are called equivalent if no matter which operations do characters $, ^, # and & denote (but, obviously, performing the same operation on the same arguments gives the same result) and which values do variables have before execution of program, the value of res after running the first program is equal to the value of res after running the second program (the programs are executed independently). You are given a program consisting of $n$ lines. Your task is to write a program consisting of minimum possible number of lines that is equivalent to the program you are given. -----Input----- The first line contains one integer $n$ ($1 \le n \le 1000$) — the number of lines in the program. Then $n$ lines follow — the program itself. Each line corresponds to the format described in the statement and has no extra whitespaces. -----Output----- In the first line print $k$ — the minimum number of lines in the equivalent program. Then print $k$ lines without any whitespaces — an equivalent program having exactly $k$ lines, in the same format it is described in the statement. -----Examples----- Input 4 c=aa#bb d12=c res=c^d12 tmp=aa$c Output 2 aaaa=aa#bb res=aaaa^aaaa Input 2 max=aaaa$bbbb min=bbbb^aaaa Output 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from random import seed, randint import sys sys.setrecursionlimit(10000) opr = ['#', '^', '&', '$'] namespace = { "res" : (False, "res") } rules = dict() lookup = dict() cnt = -1 def get_tag(var): if var in namespace: return namespace[var][1] else: return var N = int(input()) for _ in range(N): lval, rval = input().split('=') for c in opr: if c in rval: arg1, arg2 = list(map(get_tag, rval.split(c))) rule = (arg1, arg2, c) if rule in rules: namespace[lval] = (True, rules[rule]) else: cnt += 1 namespace[lval] = (True, cnt) rules[rule] = cnt lookup[cnt] = rule break else: if rval in namespace: namespace[lval] = namespace[rval] else: namespace[lval] = (False, rval) if namespace["res"] == (False, "res"): print("0") return program = [] myvars = dict() def reserve(): return ''.join(chr(randint(0, 25) + ord('a')) for _ in range(4)) def implement(rule, final): if type(rule) == str: return rule elif rule in myvars: return myvars[rule] else: if final: name = "res" else: name = reserve() myvars[rule] = name arg1, arg2, op = lookup[rule] var1, var2 = implement(arg1, False), implement(arg2, False) program.append(name + "=" + var1 + op + var2) return name seed(123) if namespace["res"][0]: implement(namespace["res"][1], True) else: program.append("res=" + namespace["res"][1]) print(len(program)) print("\n".join(program)) #print(namespace) #print(rules) ```
vfc_16410
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1156/G", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\nc=aa#bb\nd12=c\nres=c^d12\ntmp=aa$c\n", "output": "2\naaaa=aa#bb\nres=aaaa^aaaa\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\nmax=aaaa$bbbb\nmin=bbbb^aaaa\n", "output": "0", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\nres=res\nb=a\nc=b\nd=c\nres=d\nres=res\n", "output": "1\nres=a\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\nc=a\na=b\nb=c\nres=a&b\n", "output": "1\nres=b&a\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\nres=res\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\na=b\nb=c\nc=a\nres=res&a\nres=res#b\nres=res^c\n", "output": "3\naaaa=res&b\naaab=aaaa#c\nres=aaab^b\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1666
Solve the following coding problem using the programming language python: Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw. At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories. -----Input----- The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space. -----Output----- In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers c_{i}, d_{i} — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (c_{i}, d_{i}) in the strictly increasing order. Let us remind you that the pair of numbers (p_1, q_1) is less than the pair of numbers (p_2, q_2), if p_1 < p_2, or p_1 = p_2 and also q_1 < q_2. -----Examples----- Input 3 2 1 1 Output 3 2 1 3 1 3 2 Input 2 4 2 2 Output 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys f = sys.stdin #f = open("input.txt", "r") x, y, a, b = map(int, f.readline().strip().split()) a1, a2 = [], [] if a+(x-a) <= b: print(0) else: for i in range(a, x+1): for k in range(b, y+1): if i > k: a1.append(i) a2.append(k) print(len(a1)) for i in range(len(a1)): print(a1[i], a2[i]) ```
vfc_16418
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/242/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 2 1 1\n", "output": "3\n2 1\n3 1\n3 2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 4 2 2\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1 1 1\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 5 2 3\n", "output": "1\n4 3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 6 3 4\n", "output": "15\n5 4\n6 4\n6 5\n7 4\n7 5\n7 6\n8 4\n8 5\n8 6\n9 4\n9 5\n9 6\n10 4\n10 5\n10 6\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 10 1 1\n", "output": "45\n2 1\n3 1\n3 2\n4 1\n4 2\n4 3\n5 1\n5 2\n5 3\n5 4\n6 1\n6 2\n6 3\n6 4\n6 5\n7 1\n7 2\n7 3\n7 4\n7 5\n7 6\n8 1\n8 2\n8 3\n8 4\n8 5\n8 6\n8 7\n9 1\n9 2\n9 3\n9 4\n9 5\n9 6\n9 7\n9 8\n10 1\n10 2\n10 3\n10 4\n10 5\n10 6\n10 7\n10 8\n10 9\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1667
Solve the following coding problem using the programming language python: For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations. Max is a young biologist. For $n$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $k$ that if the shark in some day traveled the distance strictly less than $k$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $k$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $k$. The shark never returned to the same location after it has moved from it. Thus, in the sequence of $n$ days we can find consecutive nonempty segments when the shark traveled the distance less than $k$ in each of the days: each such segment corresponds to one location. Max wants to choose such $k$ that the lengths of all such segments are equal. Find such integer $k$, that the number of locations is as large as possible. If there are several such $k$, print the smallest one. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of days. The second line contains $n$ distinct positive integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the distance traveled in each of the day. -----Output----- Print a single integer $k$, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, $k$ is smallest possible satisfying the first and second conditions. -----Examples----- Input 8 1 2 7 3 4 8 5 6 Output 7 Input 6 25 1 2 3 14 36 Output 2 -----Note----- In the first example the shark travels inside a location on days $1$ and $2$ (first location), then on $4$-th and $5$-th days (second location), then on $7$-th and $8$-th days (third location). There are three locations in total. In the second example the shark only moves inside a location on the $2$-nd day, so there is only one location. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import bisect; def getIntList(): return list(map(int, input().split())); def getTransIntList(n): first=getIntList(); m=len(first); result=[[0]*n for _ in range(m)]; for i in range(m): result[i][0]=first[i]; for j in range(1, n): curr=getIntList(); for i in range(m): result[i][j]=curr[i]; return result; n=int(input()); a=getIntList(); anums=[(a[i], i) for i in range(n)]; anums.sort(); location=0; length=0; k=1; pieces=[]; def upgrade(x): curr=(x, x+1) i=bisect.bisect(pieces, curr); joinLeft=False; joinRight=False; if i>0 and pieces[i-1][1]==x: joinLeft=True; if i<len(pieces) and pieces[i][0]==x+1: joinRight=True; if joinLeft: if joinRight: pieces[i-1]=(pieces[i-1][0], pieces[i][1]) pieces.pop(i); else: pieces[i-1]=(pieces[i-1][0], x+1); return pieces[i-1][1]-pieces[i-1][0]; else: if joinRight: pieces[i]=(x, pieces[i][1]) else: pieces.insert(i, curr); return pieces[i][1]-pieces[i][0]; currLength=0; currSum=0; for x in anums: currSum+=1; val, num=x; l=upgrade(num); #print(pieces); currLength=max(currLength, l); #print(currLength,"*",len(pieces),"==",currSum) if currLength*len(pieces)==currSum: currK=val+1; currLocation=len(pieces); if currLocation>location: location=currLocation; k=currK; if (location+2)*currLength-1>n: break; print(k); ```
vfc_16422
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/982/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "8\n1 2 7 3 4 8 5 6\n", "output": "7", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\n25 1 2 3 14 36\n", "output": "2", "type": "stdin_stdout" }, { "fn_name": null, "input": "20\n1 20 2 19 3 18 4 17 5 16 6 15 7 14 8 13 9 12 10 11\n", "output": "11", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n1 2 5 7 3 4 6\n", "output": "5", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n1000000000\n", "output": "1000000001", "type": "stdin_stdout" } ] }
apps
verifiable_code
1668
Solve the following coding problem using the programming language python: A PIN code is a string that consists of exactly $4$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0. Polycarp has $n$ ($2 \le n \le 10$) bank cards, the PIN code of the $i$-th card is $p_i$. Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $n$ codes would become different. Formally, in one step, Polycarp picks $i$-th card ($1 \le i \le n$), then in its PIN code $p_i$ selects one position (from $1$ to $4$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different. Polycarp quickly solved this problem. Can you solve it? -----Input----- The first line contains integer $t$ ($1 \le t \le 100$) — the number of test cases in the input. Then test cases follow. The first line of each of $t$ test sets contains a single integer $n$ ($2 \le n \le 10$) — the number of Polycarp's bank cards. The next $n$ lines contain the PIN codes $p_1, p_2, \dots, p_n$ — one per line. The length of each of them is $4$. All PIN codes consist of digits only. -----Output----- Print the answers to $t$ test sets. The answer to each set should consist of a $n + 1$ lines In the first line print $k$ — the least number of changes to make all PIN codes different. In the next $n$ lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them. -----Example----- Input 3 2 1234 0600 2 1337 1337 4 3139 3139 3139 3139 Output 0 1234 0600 1 1337 1237 3 3139 3138 3939 6139 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline t=int(input()) for testcases in range(t): n=int(input()) LIST=[input().strip() for i in range(n)] SET=set() ANS=0 CHANGE=set() for i in range(n): if LIST[i] in SET: ANS+=1 CHANGE.add(i) else: SET.add(LIST[i]) ALIST=[] for i in range(n): if i in CHANGE: flag=0 now=LIST[i] for j in range(4): for k in range(10): x=now[:j]+str(k)+now[j+1:] if x in SET: continue else: ALIST.append(x) SET.add(x) flag=1 break if flag: break else: ALIST.append(LIST[i]) print(ANS) print("\n".join(ALIST)) ```
vfc_16426
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1263/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n2\n1234\n0600\n2\n1337\n1337\n4\n3139\n3139\n3139\n3139\n", "output": "0\n1234\n0600\n1\n1337\n0337\n3\n3139\n0139\n1139\n2139\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n10\n0000\n0000\n0000\n0000\n0000\n0000\n0000\n0000\n0000\n0000\n1\n1234\n7\n1234\n4567\n8901\n2345\n6789\n0123\n4567\n", "output": "9\n0000\n1000\n2000\n3000\n4000\n5000\n6000\n7000\n8000\n9000\n0\n1234\n1\n1234\n4567\n8901\n2345\n6789\n0123\n0567\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\n4\n3139\n3138\n3138\n3137\n4\n3138\n3148\n3148\n3158\n4\n3138\n3238\n3238\n3338\n4\n3138\n4138\n4138\n5138\n", "output": "1\n3139\n3138\n0138\n3137\n1\n3138\n3148\n0148\n3158\n1\n3138\n3238\n0238\n3338\n1\n3138\n4138\n0138\n5138\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n3\n0000\n0000\n0001\n", "output": "1\n0000\n1000\n0001\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "14\n3\n0000\n0000\n0001\n3\n0000\n0001\n0000\n3\n0001\n0000\n0000\n3\n0000\n0000\n1000\n3\n0000\n1000\n0000\n3\n1000\n0000\n0000\n3\n0000\n0001\n0001\n3\n0001\n0000\n0001\n3\n0001\n0001\n0000\n3\n0000\n1000\n1000\n3\n1000\n0000\n1000\n3\n1000\n1000\n0000\n4\n0000\n0001\n0001\n0002\n4\n0000\n1000\n1000\n2000\n", "output": "1\n0000\n1000\n0001\n1\n0000\n0001\n1000\n1\n0001\n0000\n1000\n1\n0000\n2000\n1000\n1\n0000\n1000\n2000\n1\n1000\n0000\n2000\n1\n0000\n0001\n1001\n1\n0001\n0000\n1001\n1\n0001\n1001\n0000\n1\n0000\n1000\n2000\n1\n1000\n0000\n2000\n1\n1000\n2000\n0000\n1\n0000\n0001\n1001\n0002\n1\n0000\n1000\n3000\n2000\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1669
Solve the following coding problem using the programming language python: International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics. You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings. Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line. Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below: A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process. A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive. A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit. Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead. During the minification process words are renamed in a systematic fashion using the following algorithm: Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on. The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules. -----Input----- The first line of the input contains a single integer $n$ ($0 \le n \le 40$) — the number of reserved tokens. The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35). The third line of the input contains a single integer $m$ ($1 \le m \le 40$) — the number of lines in the input source code. Next $m$ lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens. -----Output----- Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way. -----Examples----- Input 16 fun while return var { } ( ) , ; > = + ++ - -- 9 fun fib(num) { # compute fibs var return_value = 1, prev = 0, temp; while (num > 0) { temp = return_value; return_value = return_value + prev; prev = temp; num--; } return return_value; } Output fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;} Input 10 ( ) + ++ : -> >> >>: b c) 2 ($val1++ + +4 kb) >> :out b-> + 10 >>: t # using >>: Output (a+++ +4c )>> :d b->+10>>:e The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): t = int(input()) reserved = set(input().split()) lines = int(input()) code = '' for i in range(lines): code += input() + '\n' def is_word(suspect): if suspect[0].isdigit(): return False for x in suspect: if (not x.isalpha()) and (not x in {'_', '$'}) and (not x.isdigit()): return False return True def is_token(suspect): if suspect in reserved: return True if is_word(suspect): return True if suspect.isdigit(): return True return False def remove_comments(code): rez = '' state = None for i in range(len(code)): if code[i] == '#': state = 'comment' elif code[i] == '\n': rez += code[i] state = None else: if state != 'comment': rez += code[i] return rez code = remove_comments(code) code = code.replace('\n', ' ') def split(code): tokens = [] i = 0 while i < len(code): if code[i] == ' ': i += 1 continue for l in range(min(len(code), 90), 0, -1): if is_token(code[i:i + l]): tokens.append(code[i:i + l]) i += l break else: return [] return tokens def minmize(tokens): all = [] pref = [chr(i + ord('a')) for i in range(26)] all.extend(pref) for ext in range(3): cur = [] for i in range(26): for p in pref: cur.append(p + chr(i + ord('a'))) cur.sort() all.extend(cur) pref = cur[::] all.reverse() zip = dict() for i in range(len(tokens)): if not tokens[i] in reserved and not tokens[i][0].isdigit(): if not zip.get(tokens[i], None): while all[-1] in reserved: all.pop() zip[tokens[i]] = all[-1] all.pop() tokens[i] = zip[tokens[i]] return tokens tokens = (minmize(split(code))) def cmp(a, b): if len(a) != len(b): return False for i in range(len(a)): if a[i] != b[i]: return False return True final = [] for i in range(len(tokens)): p = 0 for j in range(i - 1, -1, -1): if len(''.join(tokens[j:i + 1])) > 23: p = j break st = '' if i and (not cmp(tokens[p:i + 1], split(''.join(final[p:i]) + tokens[i]))): st += ' ' final.append(st + tokens[i]) print(''.join(final)) main() ```
vfc_16430
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1089/J", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "16\nfun while return var { } ( ) , ; > = + ++ - --\n9\nfun fib(num) { # compute fibs\n var return_value = 1, prev = 0, temp;\n while (num > 0) {\n temp = return_value; return_value = return_value + prev;\n prev = temp;\n num--;\n }\n return return_value;\n}\n", "output": "fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10\n( ) + ++ : -> >> >>: b c)\n2\n($val1++ + +4 kb) >> :out\nb-> + 10 >>: t # using >>: \n", "output": "(a+++ +4c )>> :d b->+10>>:e\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1670
Solve the following coding problem using the programming language python: Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card. Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya. -----Input----- The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs; then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1 ≤ m ≤ 99); then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute. -----Output----- For each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards). -----Examples----- Input MC CSKA 9 28 a 3 y 62 h 25 y 66 h 42 y 70 h 25 y 77 a 4 y 79 a 25 y 82 h 42 r 89 h 16 y 90 a 13 r Output MC 25 70 MC 42 82 CSKA 13 90 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s1=input() s2=input() L={} L['h']=s1 L['a']=s2 n=int(input()) D={} F={} for i in range(n): a=input().split() m=int(a[0]) t=L[a[1]] num=int(a[2]) c=a[3] if((t,num) in D): continue if(c=='r' or (c=='y' and ((t,num) in F))): D[(t,num)]=1 print(t,num,m) else: F[(t,num)]=1 ```
vfc_16434
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/493/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "MC\nCSKA\n9\n28 a 3 y\n62 h 25 y\n66 h 42 y\n70 h 25 y\n77 a 4 y\n79 a 25 y\n82 h 42 r\n89 h 16 y\n90 a 13 r\n", "output": "MC 25 70\nMC 42 82\nCSKA 13 90\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "REAL\nBARCA\n3\n27 h 7 y\n44 a 10 y\n87 h 3 r\n", "output": "REAL 3 87\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "MASFF\nSAFBDSRG\n5\n1 h 1 y\n15 h 1 r\n27 a 1 y\n58 a 1 y\n69 h 10 y\n", "output": "MASFF 1 15\nSAFBDSRG 1 58\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "ARMENIA\nBULGARIA\n12\n33 h 17 y\n42 h 21 y\n56 a 17 y\n58 a 6 y\n61 a 7 y\n68 a 10 y\n72 h 13 y\n73 h 21 y\n74 a 8 r\n75 a 4 y\n77 a 10 y\n90 a 23 y\n", "output": "ARMENIA 21 73\nBULGARIA 8 74\nBULGARIA 10 77\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "PORTUGAL\nNETHERLANDS\n16\n2 a 18 y\n7 a 3 y\n20 h 18 y\n31 h 6 y\n45 h 6 y\n50 h 8 y\n59 a 5 y\n60 h 7 y\n63 a 3 y\n72 a 20 y\n73 h 20 y\n74 a 10 y\n75 h 1 y\n76 h 14 y\n78 h 20 y\n90 a 5 y\n", "output": "PORTUGAL 6 45\nNETHERLANDS 3 63\nPORTUGAL 20 78\nNETHERLANDS 5 90\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1671
Solve the following coding problem using the programming language python: In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are m_{i} tasks assigned to the i-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression m_{a} - m_{b}, where a is the most loaded server and b is the least loaded one. In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another. Write a program to find the minimum number of seconds needed to balance the load of servers. -----Input----- The first line contains positive number n (1 ≤ n ≤ 10^5) — the number of the servers. The second line contains the sequence of non-negative integers m_1, m_2, ..., m_{n} (0 ≤ m_{i} ≤ 2·10^4), where m_{i} is the number of tasks assigned to the i-th server. -----Output----- Print the minimum number of seconds required to balance the load. -----Examples----- Input 2 1 6 Output 2 Input 7 10 11 10 11 10 11 11 Output 0 Input 5 1 2 3 4 5 Output 3 -----Note----- In the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2. In the second example the load is already balanced. A possible sequence of task movements for the third example is: move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5); then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4); then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python diff=0 x = int(input()) l = list(map(int, input().split(' '))) s = sum(l) k = s//x knum = (k+1)*x-s kpnum = x - knum a = knum * [k] + [k+1] * kpnum a.sort() l.sort() for i in range(len(a)): diff += abs(a[i]-l[i]) print(int(diff/2)) ```
vfc_16438
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/609/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n1 6\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n10 11 10 11 10 11 11\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\n1 2 3 4 5\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10\n0 0 0 0 0 0 0 0 0 0\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n0\n", "output": "0\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1672
Solve the following coding problem using the programming language python: Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other. Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. [Image] Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed. -----Input----- The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position. -----Output----- On the single line of the output print the number of groups of magnets. -----Examples----- Input 6 10 10 10 01 10 10 Output 3 Input 4 01 01 10 10 Output 2 -----Note----- The first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets. The second testcase has two groups, each consisting of two magnets. 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()) s = '' s1 = '' ans = 0 for i in range(n): s = input() if (s != s1): ans += 1 s1 = s print(ans) ```
vfc_16442
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/344/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "6\n10\n10\n10\n01\n10\n10\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\n01\n01\n10\n10\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n10\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n01\n10\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n10\n10\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1673
Solve the following coding problem using the programming language python: Let's call beauty of an array $b_1, b_2, \ldots, b_n$ ($n > 1$)  — $\min\limits_{1 \leq i < j \leq n} |b_i - b_j|$. You're given an array $a_1, a_2, \ldots a_n$ and a number $k$. Calculate the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $998244353$. A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. -----Input----- The first line contains integers $n, k$ ($2 \le k \le n \le 1000$). The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^5$). -----Output----- Output one integer — the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $998244353$. -----Examples----- Input 4 3 1 7 3 5 Output 8 Input 5 5 1 10 100 1000 10000 Output 9 -----Note----- In the first example, there are $4$ subsequences of length $3$ — $[1, 7, 3]$, $[1, 3, 5]$, $[7, 3, 5]$, $[1, 7, 5]$, each of which has beauty $2$, so answer is $8$. In the second example, there is only one subsequence of length $5$ — the whole array, which has the beauty equal to $|10-1| = 9$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import defaultdict import sys input = sys.stdin.readline ''' for CASES in range(int(input())): n, m = map(int, input().split()) n = int(input()) A = list(map(int, input().split())) S = input().strip() sys.stdout.write(" ".join(map(str,ans))+"\n") ''' inf = 100000000000000000 # 1e17 mod = 998244353 n, m = list(map(int, input().split())) A = [0] + sorted(list(map(int, input().split()))) ans = 0 f = [[0] * (n + 10) for _ in range(m + 10)] for x in range(1,(A[n] - A[1]) // (m - 1) + 1): for i in range(1, n + 1): f[1][i] = 1 for i in range(2, m + 1): sum = 0 pre = 1 for j in range(1, n + 1): while pre <= n and A[pre] + x <= A[j]: sum += f[i - 1][pre] sum %= mod pre += 1 f[i][j] = sum for i in range(1, n + 1): ans += f[m][i] ans %= mod print(ans) # the end ```
vfc_16446
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1189/F", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4 3\n1 7 3 5\n", "output": "8", "type": "stdin_stdout" } ] }
apps
verifiable_code
1674
Solve the following coding problem using the programming language python: You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct. You are given a sequence of hits, the $i$-th hit deals $a_i$ units of damage to the opponent's character. To perform the $i$-th hit you have to press the button $s_i$ on your gamepad. Hits are numbered from $1$ to $n$. You know that if you press some button more than $k$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons. To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $a_i$ over all $i$ for the hits which weren't skipped. Note that if you skip the hit then the counter of consecutive presses the button won't reset. Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons. -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the damage of the $i$-th hit. The third line of the input contains the string $s$ consisting of exactly $n$ lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit). -----Output----- Print one integer $dmg$ — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons. -----Examples----- Input 7 3 1 5 16 18 7 2 10 baaaaca Output 54 Input 5 5 2 4 1 3 1000 aaaaa Output 1010 Input 5 4 2 4 1 3 1000 aaaaa Output 1009 Input 8 1 10 15 2 1 4 8 15 16 qqwweerr Output 41 Input 6 3 14 18 9 19 2 15 cccccc Output 52 Input 2 1 10 10 qq Output 10 -----Note----- In the first example you can choose hits with numbers $[1, 3, 4, 5, 6, 7]$ with the total damage $1 + 16 + 18 + 7 + 2 + 10 = 54$. In the second example you can choose all hits so the total damage is $2 + 4 + 1 + 3 + 1000 = 1010$. In the third example you can choose all hits expect the third one so the total damage is $2 + 4 + 3 + 1000 = 1009$. In the fourth example you can choose hits with numbers $[2, 3, 6, 8]$. Only this way you can reach the maximum total damage $15 + 2 + 8 + 16 = 41$. In the fifth example you can choose only hits with numbers $[2, 4, 6]$ with the total damage $18 + 19 + 15 = 52$. In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $10$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def ii(): return int(input()) def mi(): return list(map(int, input().split())) def li(): return list(mi()) n, k = mi() a = li() s = input().strip() ans = 0 i = 0 while i < n: j = i + 1 while j < n and s[j] == s[i]: j += 1 b = sorted(a[i:j]) ans += sum(b[-k:]) i = j print(ans) ```
vfc_16450
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1107/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "7 3\n1 5 16 18 7 2 10\nbaaaaca\n", "output": "54\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 5\n2 4 1 3 1000\naaaaa\n", "output": "1010\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 4\n2 4 1 3 1000\naaaaa\n", "output": "1009\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "8 1\n10 15 2 1 4 8 15 16\nqqwweerr\n", "output": "41\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 3\n14 18 9 19 2 15\ncccccc\n", "output": "52\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1675
Solve the following coding problem using the programming language python: Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color x_{i} and the kit for away games of this team has color y_{i} (x_{i} ≠ y_{i}). In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit. Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers x_{i}, y_{i} (1 ≤ x_{i}, y_{i} ≤ 10^5; x_{i} ≠ y_{i}) — the color numbers for the home and away kits of the i-th team. -----Output----- For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input. -----Examples----- Input 2 1 2 2 1 Output 2 0 2 0 Input 3 1 2 2 1 1 3 Output 3 1 4 0 2 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): n = int(input()) teams = [input().split() for _ in range(n)] ans = [list((0, 0)) for _ in range(n)] home = dict() for i in range(n): home[teams[i][0]] = home.get(teams[i][0], 0) + 1 for i in range(n): ans[i][0] = n - 1 + home.get(teams[i][1], 0) ans[i][1] = n - 1 - home.get(teams[i][1], 0) for i in range(n): ans[i] = '{} {}'.format(ans[i][0], ans[i][1]) print('\n'.join(ans)) def __starting_point(): main() __starting_point() ```
vfc_16454
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/432/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n1 2\n2 1\n", "output": "2 0\n2 0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n1 2\n2 1\n1 3\n", "output": "3 1\n4 0\n2 2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n1 2\n1 2\n", "output": "1 1\n1 1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1676
Solve the following coding problem using the programming language python: In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment t_{i} and needs to be processed for d_{i} units of time. All t_{i} are guaranteed to be distinct. When a query appears server may react in three possible ways: If server is free and query queue is empty, then server immediately starts to process this query. If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue. If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed. As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears. For each query find the moment when the server will finish to process it or print -1 if this query will be rejected. -----Input----- The first line of the input contains two integers n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue. Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers t_{i} and d_{i} (1 ≤ t_{i}, d_{i} ≤ 10^9), where t_{i} is the moment of time when the i-th query appears and d_{i} is the time server needs to process it. It is guaranteed that t_{i} - 1 < t_{i} for all i > 1. -----Output----- Print the sequence of n integers e_1, e_2, ..., e_{n}, where e_{i} is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or - 1 if the corresponding query will be rejected. -----Examples----- Input 5 1 2 9 4 8 10 9 15 2 19 1 Output 11 19 -1 21 22 Input 4 1 2 8 4 8 10 9 15 2 Output 10 18 27 -1 -----Note----- Consider the first sample. The server will start to process first query at the moment 2 and will finish to process it at the moment 11. At the moment 4 second query appears and proceeds to the queue. At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected. At the moment 11 server will finish to process first query and will take the second query from the queue. At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue. At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there. Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue. Server finishes to process query number 5 at the moment 22. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import deque n, b = map(int, input().split()) q = deque() for _ in range(n): t, d = map(int, input().split()) while q and q[0] <= t: q.popleft() if len(q) == b + 1: print(-1, end = ' ') else: if q: t = q[-1] print(t + d, end = ' ') q.append(t + d) ```
vfc_16458
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/644/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 1\n2 9\n4 8\n10 9\n15 2\n19 1\n", "output": "11 19 -1 21 22 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 1\n2 8\n4 8\n10 9\n15 2\n", "output": "10 18 27 -1 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1000000000 1000000000\n", "output": "2000000000 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 3\n999999996 1000000000\n999999997 1000000000\n999999998 1000000000\n999999999 1000000000\n", "output": "1999999996 2999999996 3999999996 4999999996 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 1\n2 1\n3 6\n4 5\n6 4\n7 2\n", "output": "3 9 14 -1 -1 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 2\n4 14\n5 2\n6 6\n7 11\n8 6\n9 5\n10 13\n11 8\n13 2\n20 2\n", "output": "18 20 26 -1 -1 -1 -1 -1 -1 28 \n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1677
Solve the following coding problem using the programming language python: Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: a_1 = p, where p is some integer; a_{i} = a_{i} - 1 + ( - 1)^{i} + 1·q (i > 1), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression. Sequence s_1, s_2, ..., s_{k} is a subsequence of sequence b_1, b_2, ..., b_{n}, if there is such increasing sequence of indexes i_1, i_2, ..., i_{k} (1 ≤ i_1 < i_2 < ... < i_{k} ≤ n), that b_{i}_{j} = s_{j}. In other words, sequence s can be obtained from b by crossing out some elements. -----Input----- The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6). -----Output----- Print a single integer — the length of the required longest subsequence. -----Examples----- Input 2 3 5 Output 2 Input 4 10 20 10 30 Output 3 -----Note----- In the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python d, n, t = 0, int(input()), list(map(int, input().split())) p = {a: 0 for a in set(t)} for i in range(n): a = t[i] if not a in p: continue p.pop(a) s = t.count(a) - 1 if 2 * s < d: continue if s > d: d = s k = i + 1 for j in range(k, n): if t[j] == a: for b in set(t[k: j]): if b in p: p[b] += 2 k = j + 1 for b in set(t[k: n]): if b in p: p[b] += 1 for b in p: if p[b] > d: d = p[b] p[b] = 0 print(d + 1) ```
vfc_16462
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/255/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n3 5\n", "output": "2\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1678
Solve the following coding problem using the programming language python: Petya has an array $a$ consisting of $n$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array. Now he wonders what is the number of segments in his array with the sum less than $t$. Help Petya to calculate this number. More formally, you are required to calculate the number of pairs $l, r$ ($l \le r$) such that $a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$. -----Input----- The first line contains two integers $n$ and $t$ ($1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$). The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($|a_{i}| \le 10^{9}$) — the description of Petya's array. Note that there might be negative, zero and positive elements. -----Output----- Print the number of segments in Petya's array with the sum of elements less than $t$. -----Examples----- Input 5 4 5 -1 3 4 -1 Output 5 Input 3 0 -1 2 -3 Output 4 Input 4 -1 -2 1 -2 3 Output 3 -----Note----- In the first example the following segments have sum less than $4$: $[2, 2]$, sum of elements is $-1$ $[2, 3]$, sum of elements is $2$ $[3, 3]$, sum of elements is $3$ $[4, 5]$, sum of elements is $3$ $[5, 5]$, sum of elements is $-1$ 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 from bisect import bisect_left def read_bit(tree, idx): s = 0 while idx > 0: s += tree[idx] idx -= (idx & -idx) return s def update_bit(tree, idx, val): while idx < len(tree): tree[idx] += val idx += (idx & -idx) n,t=list(map(int,stdin.readline().split())) a=[int(x) for x in stdin.readline().split()] pref=[0]*n pref[0]=a[0] for i in range(1,n): pref[i]=pref[i-1]+a[i] pref.sort() before=ans=0 tree=[0]*(n+2) for i in range(n): ind = bisect_left(pref, t + before) if ind>0: ans += ind-read_bit(tree, ind) before += a[i] before_ind=bisect_left(pref, before) update_bit(tree, before_ind+1, 1) print(ans) ```
vfc_16466
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1042/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 4\n5 -1 3 4 -1\n", "output": "5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 0\n-1 2 -3\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 -1\n-2 1 -2 3\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1000000001\n1000000000\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1679
Solve the following coding problem using the programming language python: Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). Digits are written one by one in order corresponding to number and separated by single '0' character. Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number. -----Input----- The first line contains one integer number n (1 ≤ n ≤ 89) — length of the string s. The second line contains string s — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 10^9. The string always starts with '1'. -----Output----- Print the decoded number. -----Examples----- Input 3 111 Output 3 Input 9 110011101 Output 2031 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python input() print(''.join(str(len(x)) for x in input().split('0'))) ```
vfc_16470
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/825/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n111\n", "output": "3\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1680
Solve the following coding problem using the programming language python: Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits. Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers a_{i} and a_{j} is k-interesting. Your task is to help Vasya and determine this number. -----Input----- The first line contains two integers n and k (2 ≤ n ≤ 10^5, 0 ≤ k ≤ 14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ. The second line contains the sequence a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^4), which Vasya has. -----Output----- Print the number of pairs (i, j) so that i < j and the pair of integers a_{i} and a_{j} is k-interesting. -----Examples----- Input 4 1 0 3 2 1 Output 4 Input 6 0 200 100 100 100 200 200 Output 6 -----Note----- In the first test there are 4 k-interesting pairs: (1, 3), (1, 4), (2, 3), (2, 4). In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs: (1, 5), (1, 6), (2, 3), (2, 4), (3, 4), (5, 6). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def binary(n): curr=0 while(n>0): if(n%2): curr+=1 n=n//2 return curr l=input().split() n=int(l[0]) k=int(l[1]) l=input().split() li=[int(i) for i in l] arr=[] for i in range(2**15): if(binary(i)==k): arr.append(i) hashi=dict() for i in li: if i in hashi: hashi[i]+=1 else: hashi[i]=1 count=0 for i in hashi: for j in arr: if((i^j) in hashi): if((i^j)==i): count=count+(hashi[i]*(hashi[i]-1)) else: count=count+(hashi[i]*hashi[i^j]) print(count//2) ```
vfc_16474
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/769/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4 1\n0 3 2 1\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 0\n200 100 100 100 200 200\n", "output": "6\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 0\n1 1\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 0\n0 0\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 0\n10000 10000\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1681
Solve the following coding problem using the programming language python: Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter. The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland. Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​m pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get. -----Input----- The first line contains a non-empty sequence of n (1 ≤ n ≤ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1 ≤ m ≤ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make. -----Output----- Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer. -----Examples----- Input aaabbac aabbccac Output 6 Input a z Output -1 -----Note----- In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6. In the second test sample Vasya cannot make a garland at all — he doesn't have a sheet of color z. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = input().rstrip() m = input().rstrip() cnt1 = [0] * 26 cnt2 = [0] * 26 for i in n: cnt1[ord(i) - ord("a")] += 1 for i in m: cnt2[ord(i) - ord("a")] += 1 res = 0 for i in range(26): a1 = cnt1[i] a2 = cnt2[i] if a1 == 0 and a2 != 0: print(-1) return res += min(a1, a2) print(res) ```
vfc_16478
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/408/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "aaabbac\naabbccac\n", "output": "6\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "a\nz\n", "output": "-1", "type": "stdin_stdout" }, { "fn_name": null, "input": "r\nr\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "stnsdn\nndnndsn\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "yqfqfp\ntttwtqq\n", "output": "-1", "type": "stdin_stdout" } ] }
apps
verifiable_code
1682
Solve the following coding problem using the programming language python: Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is a_{i}, and after a week of discounts its price will be b_{i}. Not all of sellers are honest, so now some products could be more expensive than after a week of discounts. Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. -----Input----- In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·10^5, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^4) — prices of items after discounts (i.e. after a week). -----Output----- Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. -----Examples----- Input 3 1 5 4 6 3 1 5 Output 10 Input 5 3 3 4 7 10 3 4 5 5 12 5 Output 25 -----Note----- In the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10. In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python read = lambda: map(int, input().split()) n, k = read() a = list(read()) b = list(read()) c = [(a[i], b[i]) for i in range(n)] c.sort(key = lambda x: x[0] - x[1]) ans = sum(c[i][0] for i in range(k)) for i in range(k, n): ans += min(c[i][0], c[i][1]) print(ans) ```
vfc_16482
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/779/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 1\n5 4 6\n3 1 5\n", "output": "10\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 3\n3 4 7 10 3\n4 5 5 12 5\n", "output": "25\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 0\n9\n8\n", "output": "8\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 0\n4 10\n1 2\n", "output": "3\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1683
Solve the following coding problem using the programming language python: This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$. A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem. Let's denote a function that alternates digits of two numbers $f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$, where $a_1 \dots a_p$ and $b_1 \dots b_q$ are digits of two integers written in the decimal notation without leading zeros. In other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below. For example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$ Formally, if $p \ge q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$; if $p < q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$. Mishanya gives you an array consisting of $n$ integers $a_i$, your task is to help students to calculate $\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\,244\,353$. -----Input----- The first line of the input contains a single integer $n$ ($1 \le n \le 100\,000$) — the number of elements in the array. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the elements of the array. -----Output----- Print the answer modulo $998\,244\,353$. -----Examples----- Input 3 12 3 45 Output 12330 Input 2 123 456 Output 1115598 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, exit mod = 998244353 n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) ans = 0 def l(x): if x == 0: return 0 return 1 + l(x//10) lens = [0]*15 for x in a: lens[l(x)] += 1 def space_out(x, l): ans = [] for i,c in enumerate(reversed(str(x))): ans.append(c) if i < l: ans.append("0") return int(''.join(reversed(ans))) for i in range(n): x = a[i] cur_head = x//10 cur = x prev = x for l in range(11): # print(cur, cur_head) if l > 0: ans += lens[l]*(cur+10*prev)#space_out(x,l) ans %= mod prev = cur cur -= cur_head*10**(2*l+1) cur += cur_head*10**(2*l+2) cur_head //=10 stdout.write(str(ans) + "\n") ```
vfc_16486
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1195/D2", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n12 3 45\n", "output": "12330", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n123 456\n", "output": "1115598", "type": "stdin_stdout" }, { "fn_name": null, "input": "20\n80 9 55 1 98 29 81 10 96 100 70 87 86 12 58 82 10 22 59 13\n", "output": "2248760", "type": "stdin_stdout" }, { "fn_name": null, "input": "100\n3615 1436 2205 5695 9684 7621 391 1579 557 420 1756 5265 247 5494 3509 6089 2931 7372 4939 8030 2901 1150 5389 7168 6213 2723 4301 7250 3857 9178 4723 1932 1161 1412 8200 5226 1474 3495 9533 8555 6372 1517 8034 6547 1148 9651 2399 3065 9675 3418 7758 3226 9844 4234 510 7652 162 8010 8162 2732 2112 4041 3392 6344 671 4120 4659 7718 8660 7102 9098 6195 6999 9411 6710 2261 4388 7125 3808 978 398 9286 1280 7382 1095 8203 5687 9281 3722 8159 470 5735 4210 3694 2197 5422 816 7546 9965 2963\n", "output": "674832474", "type": "stdin_stdout" } ] }
apps
verifiable_code
1684
Solve the following coding problem using the programming language python: Inaka has a disc, the circumference of which is $n$ units. The circumference is equally divided by $n$ points numbered clockwise from $1$ to $n$, such that points $i$ and $i + 1$ ($1 \leq i < n$) are adjacent, and so are points $n$ and $1$. There are $m$ straight segments on the disc, the endpoints of which are all among the aforementioned $n$ points. Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $k$ ($1 \leq k < n$), such that if all segments are rotated clockwise around the center of the circle by $k$ units, the new image will be the same as the original one. -----Input----- The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100\,000$, $1 \leq m \leq 200\,000$) — the number of points and the number of segments, respectively. The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) that describe a segment connecting points $a_i$ and $b_i$. It is guaranteed that no segments coincide. -----Output----- Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower). -----Examples----- Input 12 6 1 3 3 7 5 7 7 11 9 11 11 3 Output Yes Input 9 6 4 5 5 6 7 8 8 9 1 2 2 3 Output Yes Input 10 3 1 2 3 2 7 2 Output No Input 10 2 1 6 2 7 Output Yes -----Note----- The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $120$ degrees around the center. [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math class CodeforcesTask1147BSolution: def __init__(self): self.result = '' self.n_m = [] self.points = [] def read_input(self): self.n_m = [int(x) for x in input().split(" ")] for x in range(self.n_m[1]): self.points.append([int(y) for y in input().split(" ")]) def process_task(self): can = False segm = {} for point in self.points: segm["{0}_{1}".format(*point)] = True segm["{1}_{0}".format(*point)] = True for k in range(1, self.n_m[0]): if not self.n_m[0] % k: #print(k) do = True for p in self.points: a, b = (p[0] + k) % self.n_m[0], (p[1] + k) % self.n_m[0] if not a: a = self.n_m[0] if not b: b = self.n_m[0] if not "{0}_{1}".format(a, b) in segm: do = False break if do: can = do break self.result = "Yes" if can else "No" def get_result(self): return self.result def __starting_point(): Solution = CodeforcesTask1147BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) __starting_point() ```
vfc_16490
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1147/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 3\n1 2\n3 2\n7 2\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 2\n1 6\n2 7\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 1\n2 1\n", "output": "Yes\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1685
Solve the following coding problem using the programming language python: T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n + 1 is a power of 2. In the picture you can see a complete binary tree with n = 15. [Image] Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric. You have to write a program that for given n answers q queries to the tree. Each query consists of an integer number u_{i} (1 ≤ u_{i} ≤ n) and a string s_{i}, where u_{i} is the number of vertex, and s_{i} represents the path starting from this vertex. String s_{i} doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from s_{i} have to be processed from left to right, considering that u_{i} is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by s_{i} ends. For example, if u_{i} = 4 and s_{i} = «UURL», then the answer is 10. -----Input----- The first line contains two integer numbers n and q (1 ≤ n ≤ 10^18, q ≥ 1). n is such that n + 1 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains u_{i} (1 ≤ u_{i} ≤ n), the second contains non-empty string s_{i}. s_{i} doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of s_{i} (for each i such that 1 ≤ i ≤ q) doesn't exceed 10^5. -----Output----- Print q numbers, i-th number must be the answer to the i-th query. -----Example----- Input 15 2 4 UURL 8 LRLLLLLLLL Output 10 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def mask(n): if not n: return 0; m = 1 while not (m & n): m *= 2 return m n, T = list(map(int, input().split())) for t in range(T): cur = int(input()) for ch in input(): m = mask(cur) #print(ch, ":", m, cur, "->", end = " ") if ch == "U": next = (cur - m) | (m * 2) if next < n: cur = next elif ch == "L" and m > 1: cur -= m//2 elif ch == "R" and m > 1: cur += m//2 #print(cur) print(cur) ```
vfc_16494
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/792/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "15 2\n4\nUURL\n8\nLRLLLLLLLL\n", "output": "10\n5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1\nL\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1\nR\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1\nU\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 10\n1\nURLRLULUR\n1\nLRRRURULULL\n1\nLURURRUUUU\n1\nRRULLLRRUL\n1\nUULLUURL\n1\nRLRRULUL\n1\nLURRLRUULRR\n1\nLULLULUUUL\n1\nURULLULL\n1\nLRRLRUUUURRLRRL\n", "output": "1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 10\n2\nRUUUULULULUU\n1\nULLLURLU\n3\nLLURLULU\n2\nRRLURLURLLR\n3\nLRURURLRLLL\n3\nLRLULRRUURURRL\n1\nRULLR\n2\nLRULLURUL\n3\nRLL\n1\nULRUULURLULLLLLLRLL\n", "output": "2\n2\n2\n3\n3\n3\n1\n1\n3\n1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1686
Solve the following coding problem using the programming language python: The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively. Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address. Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess. The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000. To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one. Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so. -----Input----- The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 10^5) — the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct. -----Output----- In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1. -----Examples----- Input 5 3 0.0.0.1 0.1.1.2 0.0.2.1 0.1.1.0 0.0.2.3 Output 255.255.254.0 Input 5 2 0.0.0.1 0.1.1.2 0.0.2.1 0.1.1.0 0.0.2.3 Output 255.255.0.0 Input 2 1 255.0.0.1 0.0.0.2 Output -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math import re from fractions import Fraction from collections import Counter class Task: ips = [] k = 0 answer = '' def __init__(self): n, self.k = [int(x) for x in input().split()] self.ips = ['' for _ in range(n)] for i in range(len(self.ips)): self.ips[i] = input() def solve(self): ips, k = self.ips, self.k ipAsNumbers = [] for currentIp in ips: number = 0 parts = currentIp.split('.') for i in range(0, len(parts)): number += int(parts[i]) * 2**(32 - (i + 1) * 8) ipAsNumbers += [number] mask = 0 for i in range(31, -1, -1): mask += 2**i netAddresses = set() for ip in ipAsNumbers: netAddresses.add(mask & ip) if len(netAddresses) == k: mask = bin(mask)[2:] self.answer = '.'.join([str(int(mask[i : i + 8], 2)) \ for i in range(0, len(mask), 8)]) return self.answer = '-1' def printAnswer(self): print(self.answer) #for line in self.answer: # print(line) task = Task() task.solve() task.printAnswer() ```
vfc_16498
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/291/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 3\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n", "output": "255.255.254.0", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 2\n0.0.0.1\n0.1.1.2\n0.0.2.1\n0.1.1.0\n0.0.2.3\n", "output": "255.255.0.0", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 1\n255.0.0.1\n0.0.0.2\n", "output": "-1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 2\n57.11.146.42\n200.130.164.235\n52.119.155.71\n113.10.216.20\n28.23.6.128\n190.112.90.85\n7.37.210.55\n20.190.120.226\n170.124.158.110\n122.157.34.141\n", "output": "128.0.0.0", "type": "stdin_stdout" } ] }
apps
verifiable_code
1687
Solve the following coding problem using the programming language python: Ksusha is a beginner coder. Today she starts studying arrays. She has array a_1, a_2, ..., a_{n}, consisting of n positive integers. Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number! -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5), showing how many numbers the array has. The next line contains integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the array elements. -----Output----- Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them. -----Examples----- Input 3 2 2 4 Output 2 Input 5 2 1 3 1 6 Output 1 Input 3 2 3 5 Output -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python input() a = [int(x) for x in input().split()] b = min(a) print(-1 if any(x % b for x in a) else b) ```
vfc_16502
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/299/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n2 2 4\n", "output": "2\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1688
Solve the following coding problem using the programming language python: Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of $n$ tracks numbered from $1$ to $n$. The playlist is automatic and cyclic: whenever track $i$ finishes playing, track $i+1$ starts playing automatically; after track $n$ goes track $1$. For each track $i$, you have estimated its coolness $a_i$. The higher $a_i$ is, the cooler track $i$ is. Every morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness $x$ of already played tracks. Once you hear that a track with coolness strictly less than $\frac{x}{2}$ (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood. For each track $i$, find out how many tracks you will listen to before turning off the music if you start your morning with track $i$, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 10^5$), denoting the number of tracks in the playlist. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$), denoting coolnesses of the tracks. -----Output----- Output $n$ integers $c_1, c_2, \ldots, c_n$, where $c_i$ is either the number of tracks you will listen to if you start listening from track $i$ or $-1$ if you will be listening to music indefinitely. -----Examples----- Input 4 11 5 2 7 Output 1 1 3 2 Input 4 3 2 5 3 Output 5 4 3 6 Input 3 4 3 6 Output -1 -1 -1 -----Note----- In the first example, here is what will happen if you start with... track $1$: listen to track $1$, stop as $a_2 < \frac{a_1}{2}$. track $2$: listen to track $2$, stop as $a_3 < \frac{a_2}{2}$. track $3$: listen to track $3$, listen to track $4$, listen to track $1$, stop as $a_2 < \frac{\max(a_3, a_4, a_1)}{2}$. track $4$: listen to track $4$, listen to track $1$, stop as $a_2 < \frac{\max(a_4, a_1)}{2}$. In the second example, if you start with track $4$, you will listen to track $4$, listen to track $1$, listen to track $2$, listen to track $3$, listen to track $4$ again, listen to track $1$ again, and stop as $a_2 < \frac{max(a_4, a_1, a_2, a_3, a_4, a_1)}{2}$. Note that both track $1$ and track $4$ are counted twice towards the result. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #TO MAKE THE PROGRAM FAST ''' ---------------------------------------------------------------------------------------------------- ''' import sys input = sys.stdin.readline sys.setrecursionlimit(100000) from collections import deque ''' ---------------------------------------------------------------------------------------------------- ''' #FOR TAKING INPUTS ''' ---------------------------------------------------------------------------------------------------- ''' def li():return [int(i) for i in input().rstrip('\n').split(' ')] def val():return int(input().rstrip('\n')) def st():return input().rstrip('\n') def sttoli():return [int(i) for i in input().rstrip('\n')] ''' ---------------------------------------------------------------------------------------------------- ''' #MAIN PROGRAM ''' ---------------------------------------------------------------------------------------------------- ''' d = deque() n = val() l = li() j = x = 0 currmax = -10000000000000 ans = [] for i in range(n): while len(d) and d[0] < i:d.popleft() currmax = l[d[0]%n] if len(d) else l[i] while j<3*n: currmax = max(currmax,l[j%n]) while len(d) and l[d[-1]%n] <= l[j%n]:d.pop() d.append(j) if currmax/2 > l[j%n]: ans.append(j-i) break j += 1 if j == 3*n: print(*([-1 for _______ in range(n)])) return print(*ans) ''' ---------------------------------------------------------------------------------------------------- ''' ```
vfc_16506
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1237/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\n11 5 2 7\n", "output": "1 1 3 2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\n3 2 5 3\n", "output": "5 4 3 6\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1691
Solve the following coding problem using the programming language python: PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex. Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides. -----Input----- There are only two numbers in the input: n and k (5 ≤ n ≤ 10^6, 2 ≤ k ≤ n - 2, gcd(n, k) = 1). -----Output----- You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines. -----Examples----- Input 5 2 Output 2 3 5 8 11 Input 10 3 Output 2 3 4 6 9 12 16 21 26 31 -----Note----- The greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder. For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines. [Image] [Image] [Image] [Image] [Image] [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = [int(i) for i in input().split()] if m > n//2: m = n-m ans = [1] count = 0 c = 1 for i in range(n): count+=m if count>n: c+=1 count-=n ans.append(ans[-1] +c) c+=1 else: ans.append(ans[-1] +c) ans = ans[1:] print(*ans) ```
vfc_16518
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/755/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 2\n", "output": "2 3 5 8 11 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 3\n", "output": "2 3 4 6 9 12 16 21 26 31 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "17 5\n", "output": "2 3 4 6 9 12 16 21 26 31 37 44 51 59 68 77 86 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 3\n", "output": "2 3 5 8 11 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "7 5\n", "output": "2 3 4 6 9 12 15 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "7 4\n", "output": "2 3 5 8 12 17 22 ", "type": "stdin_stdout" } ] }
apps
verifiable_code
1693
Solve the following coding problem using the programming language python: This is a harder version of the problem. In this version $n \le 500\,000$ The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $n$ plots along the highway and is preparing to build $n$ skyscrapers, one skyscraper per plot. Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it. Formally, let's number the plots from $1$ to $n$. Then if the skyscraper on the $i$-th plot has $a_i$ floors, it must hold that $a_i$ is at most $m_i$ ($1 \le a_i \le m_i$). Also there mustn't be integers $j$ and $k$ such that $j < i < k$ and $a_j > a_i < a_k$. Plots $j$ and $k$ are not required to be adjacent to $i$. The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 500\,000$) — the number of plots. The second line contains the integers $m_1, m_2, \ldots, m_n$ ($1 \leq m_i \leq 10^9$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot. -----Output----- Print $n$ integers $a_i$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them. -----Examples----- Input 5 1 2 3 2 1 Output 1 2 3 2 1 Input 3 10 6 8 Output 10 6 6 -----Note----- In the first example, you can build all skyscrapers with the highest possible height. In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $[10, 6, 6]$ is optimal. Note that the answer of $[6, 6, 8]$ also satisfies all restrictions, but is not optimal. 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 def solve(): n = int(stdin.readline()) m = list(map(int, stdin.readline().split())) msl = [-1] * n msp = [n] * n q = [] for i in range(n): while q and m[q[-1]] > m[i]: q.pop() if q: msl[i] = q[-1] q.append(i) q = [] for i in range(n - 1, -1, -1): while q and m[q[-1]] > m[i]: q.pop() if q: msp[i] = q[-1] q.append(i) dp1 = [0] * n for i in range(n): dp1[i] = m[i] * (i - msl[i]) if msl[i] != -1: dp1[i] += dp1[msl[i]] dp2 = [0] * n for i in range(n - 1, -1, -1): dp2[i] += m[i] * (msp[i] - i) if msp[i] != n: dp2[i] += dp2[msp[i]] ansm = 0 answc = 0 for i in range(n): cur = dp1[i] + dp2[i] - m[i] if cur > answc: answc = cur ansm = i i = ansm cur = [0] * n cur[i] = m[i] for j in range(i + 1, n): cur[j] = min(cur[j - 1], m[j]) for j in range(i - 1, -1, -1): cur[j] = min(cur[j + 1], m[j]) print(*cur) for i in range(1): solve() ```
vfc_16526
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1313/C2", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 2 3 2 1\n", "output": "1 2 3 2 1 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n10 6 8\n", "output": "10 6 6 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n1 2 1 2 1 2 1\n", "output": "1 2 1 1 1 1 1 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n1 2 1 2 1 3 1\n", "output": "1 1 1 1 1 3 1 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\n1 1 4 2 2\n", "output": "1 1 4 2 2 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\n1 3 4 3 5 4\n", "output": "1 3 3 3 5 4 \n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1694
Solve the following coding problem using the programming language python: Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone. But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step t_{i} (steps are numbered from 1) Xenia watches spies numbers l_{i}, l_{i} + 1, l_{i} + 2, ..., r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him. You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps). -----Input----- The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 10^5; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers t_{i}, l_{i}, r_{i} (1 ≤ t_{i} ≤ 10^9, 1 ≤ l_{i} ≤ r_{i} ≤ n). It is guaranteed that t_1 < t_2 < t_3 < ... < t_{m}. -----Output----- Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists. -----Examples----- Input 3 5 1 3 1 1 2 2 2 3 3 3 3 4 1 1 10 1 3 Output XXRR 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,m,s,f=list(map(int,sys.stdin.readline().split())) L=[] R=[] T=[] for i in range(m): t,l,r=list(map(int,sys.stdin.readline().split())) T.append(t) L.append(l) R.append(r) if(f>s): i=s step=1 ind=0 Ans="" while(i!=f): if(ind>=m or T[ind]!=step): Ans+="R" i+=1 else: if((i>=L[ind] and i<=R[ind]) or (i+1>=L[ind] and i+1<=R[ind])): Ans+="X" else: Ans+="R" i+=1 ind+=1 step+=1 else: i=s step=1 ind=0 Ans="" while(i!=f): if(ind>=m or T[ind]!=step): Ans+="L" i-=1 else: if((i>=L[ind] and i<=R[ind]) or (i-1>=L[ind] and i-1<=R[ind])): Ans+="X" else: Ans+="L" i-=1 ind+=1 step+=1 sys.stdout.write(Ans+"\n") ```
vfc_16530
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/342/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 5 1 3\n1 1 2\n2 2 3\n3 3 3\n4 1 1\n10 1 3\n", "output": "XXRR\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 3 2 1\n1 1 2\n2 1 2\n4 1 2\n", "output": "XXL\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 11 1 5\n1 1 5\n2 2 2\n3 1 1\n4 3 3\n5 3 3\n6 1 1\n7 4 4\n8 4 5\n10 1 3\n11 5 5\n13 1 5\n", "output": "XXXRXRXXRR\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 6 4 2\n2 2 2\n3 3 3\n4 1 1\n10 1 4\n11 2 3\n12 2 4\n", "output": "LXXL\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7 5 7 6\n1 4 5\n2 7 7\n3 6 6\n4 3 4\n5 1 3\n", "output": "L\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 4 3 4\n1 2 4\n2 1 2\n3 3 4\n4 2 3\n", "output": "XR\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1695
Solve the following coding problem using the programming language python: A class of students wrote a multiple-choice test. There are $n$ students in the class. The test had $m$ questions, each of them had $5$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $i$ worth $a_i$ points. Incorrect answers are graded with zero points. The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class. -----Input----- The first line contains integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of students in the class and the number of questions in the test. Each of the next $n$ lines contains string $s_i$ ($|s_i| = m$), describing an answer of the $i$-th student. The $j$-th character represents the student answer (A, B, C, D or E) on the $j$-th question. The last line contains $m$ integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le 1000$) — the number of points for the correct answer for every question. -----Output----- Print a single integer — the maximum possible total score of the class. -----Examples----- Input 2 4 ABCD ABCE 1 2 3 4 Output 16 Input 3 3 ABC BCD CDE 5 4 12 Output 21 -----Note----- In the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $16$. In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $5 + 4 + 12 = 21$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import Counter n, m = map(int, input().split()) l = [input() for _ in range(n)] v = [*map(int, input().split())] res = 0 for i in range(m): res += v[i] * max(Counter(s[i] for s in l).values()) print(res) ```
vfc_16534
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1201/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 4\nABCD\nABCE\n1 2 3 4\n", "output": "16", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 3\nABC\nBCD\nCDE\n5 4 12\n", "output": "21", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 5\nABCDE\nABCDE\n2 3 5 7 11\n", "output": "56", "type": "stdin_stdout" } ] }
apps
verifiable_code
1696
Solve the following coding problem using the programming language python: The capital of Berland looks like a rectangle of size n × m of the square blocks of same size. Fire! It is known that k + 1 blocks got caught on fire (k + 1 ≤ n·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct. The fire goes the following way: during the zero minute of fire only these k + 1 centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner. Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of k blocks (centers of ignition) are known and (k + 1)-th can be positioned in any other block. Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city. -----Input----- The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^9, 1 ≤ k ≤ 500). Each of the next k lines contain two integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n, 1 ≤ y_{i} ≤ m) — coordinates of the i-th center of ignition. It is guaranteed that the locations of all centers of ignition are distinct. -----Output----- Print the minimal time it takes the fire to lighten up the whole city (in minutes). -----Examples----- Input 7 7 3 1 2 2 1 5 5 Output 3 Input 10 5 1 3 3 Output 2 -----Note----- In the first example the last block can have coordinates (4, 4). In the second example the last block can have coordinates (8, 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 from collections import Counter from operator import itemgetter from heapq import heappop, heappush n, m, k = list(map(int, input().split())) points = [list(map(int, line.split())) for line in sys.stdin] pts_sorted_x = sorted(points) pts_sorted_y = sorted(points, key=itemgetter(1, 0)) inf = 10**9+1 OK = (inf, inf) def solve2(imos, t): acc, cur = 0, 0 for k in sorted(imos.keys()): if t < k: break if acc <= 0 and cur+1 < k or acc + imos[k] <= 0: acc = 0 break acc += imos[k] return acc <= 0 def add_imos(imos, x, y): imos[x] += y if imos[x] == 0: del imos[x] def solve(t, px=-1, py=-1): set_x = {1, n} set_y = {1, m} for x, y in points: set_x.update((max(1, x-t), max(1, x-t-1), min(n, x+t), min(n, x+t+1))) set_y.update((max(1, y-t), max(1, y-t-1), min(m, y+t), min(m, y+t+1))) ans_x = ans_y = inf pi, imos, hq = 0, Counter(), [] if px != -1: imos[py] += 1 imos[py+t*2+1] -= 1 for cx in sorted(set_x): while hq and hq[0][0] < cx: add_imos(imos, hq[0][1], -1) add_imos(imos, hq[0][2], +1) heappop(hq) while pi < k and pts_sorted_x[pi][0]-t <= cx <= pts_sorted_x[pi][0]+t: x, y = pts_sorted_x[pi] add_imos(imos, max(1, y-t), 1) add_imos(imos, y+t+1, -1) heappush(hq, (x+t, max(1, y-t), y+t+1)) pi += 1 if solve2(imos, m): ans_x = cx break pi = 0 imos.clear() hq.clear() if px != -1: imos[px] += 1 imos[px+t*2+1] -= 1 for cy in sorted(set_y): while hq and hq[0][0] < cy: add_imos(imos, hq[0][1], -1) add_imos(imos, hq[0][2], +1) heappop(hq) while pi < k and pts_sorted_y[pi][1]-t <= cy <= pts_sorted_y[pi][1]+t: x, y = pts_sorted_y[pi] add_imos(imos, max(1, x-t), 1) add_imos(imos, x+t+1, -1) heappush(hq, (y+t, max(1, x-t), x+t+1)) pi += 1 if solve2(imos, n): ans_y = cy break return ans_x, ans_y ok, ng = 10**9+1, -1 while abs(ok - ng) > 1: mid = (ok + ng) >> 1 p = solve(mid) if p == OK: ok = mid continue if solve(mid, p[0], p[1]) == OK: ok = mid else: ng = mid print(ok) ```
vfc_16538
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/845/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "7 7 3\n1 2\n2 1\n5 5\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 5 1\n3 3\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 5 19\n1 1\n1 2\n1 3\n1 4\n1 5\n2 1\n2 2\n2 3\n2 5\n3 1\n3 2\n3 3\n3 4\n3 5\n4 1\n4 2\n4 3\n4 4\n4 5\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 5 24\n1 2\n1 3\n1 4\n1 5\n2 1\n2 2\n2 3\n2 4\n2 5\n3 1\n3 2\n3 3\n3 4\n3 5\n4 1\n4 2\n4 3\n4 4\n4 5\n5 1\n5 2\n5 3\n5 4\n5 5\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 10 20\n7 5\n4 5\n5 4\n7 4\n1 5\n6 7\n9 5\n8 4\n1 4\n2 10\n3 10\n4 10\n3 6\n5 7\n6 2\n1 1\n10 9\n7 6\n6 4\n8 2\n", "output": "2\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1697
Solve the following coding problem using the programming language python: Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this: [Image] Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d_1, d_2, ..., d_{k} a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then d_{i} is different from d_{j}. k is at least 4. All dots belong to the same color. For all 1 ≤ i ≤ k - 1: d_{i} and d_{i} + 1 are adjacent. Also, d_{k} and d_1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field. -----Input----- The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter. -----Output----- Output "Yes" if there exists a cycle, and "No" otherwise. -----Examples----- Input 3 4 AAAA ABCA AAAA Output Yes Input 3 4 AAAA ABCA AADA Output No Input 4 4 YYYR BYBY BBBY BBBY Output Yes Input 7 6 AAAAAB ABBBAB ABAAAB ABABBB ABAAAB ABBBAB AAAAAB Output Yes Input 2 13 ABCDEFGHIJKLM NOPQRSTUVWXYZ Output No -----Note----- In first sample test all 'A' form a cycle. In second sample there is no such cycle. The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/env python import sys sys.setrecursionlimit(10000) n, m = list(map(int, input().split(' '))) def neighbors(i, j): return [(i+1, j), (i-1, j), (i, j+1), (i, j-1)] def valid(i, j): nonlocal n, m if i < 0 or i >= n or j < 0 or j >= m: return False return True def dfs(f, i, j): color = f[i][j] f[i][j] = color.lower() c = 0 for n, m in neighbors(i, j): if valid(n, m): if f[n][m] == color: cycle_found = dfs(f, n, m) if cycle_found: return True elif f[n][m] == color.lower(): c += 1 if c > 1: return True f[i][j] = None return False f = [] for i in range(n): f.append(list(input().strip())) for i in range(n): for j in range(m): if f[i][j]: cycle_found = dfs(f, i, j) if cycle_found: print("Yes") return print("No") ```
vfc_16542
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/510/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 4\nAAAA\nABCA\nAAAA\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 4\nAAAA\nABCA\nAADA\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 4\nYYYR\nBYBY\nBBBY\nBBBY\n", "output": "Yes\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1699
Solve the following coding problem using the programming language python: While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square. Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 10^8. -----Input----- The first line contains two integers n and m (1 ≤ n, m ≤ 100)  — the size of the table. -----Output----- Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer. -----Examples----- Input 1 1 Output 1 Input 1 2 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 """ Codeforces Round 241 Div 1 Problem E Author : chaotic_iak Language: Python 3.3.4 """ class InputHandlerObject(object): inputs = [] def getInput(self, n = 0): res = "" inputs = self.inputs if not inputs: inputs.extend(input().split(" ")) if n == 0: res = inputs[:] inputs[:] = [] while n > len(inputs): inputs.extend(input().split(" ")) if n > 0: res = inputs[:n] inputs[:n] = [] return res InputHandler = InputHandlerObject() g = InputHandler.getInput ############################## SOLUTION ############################## n,m = [int(x) for x in g()] def sqr(n): if n == 1: return [1] if n == 2: return [4,3] if n % 2: return [(n+1)//2, 2] + [1] * (n-2) return [(n-2)//2] + [1] * (n-1) a = sqr(n) b = sqr(m) for i in range(n): res = [str(a[i]*x) for x in b] print(" ".join(res)) ```
vfc_16550
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/417/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "1 1\n", "output": "1 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 2\n", "output": "3 4 \n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 1\n", "output": "1 \n1 \n1 \n1 \n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1700
Solve the following coding problem using the programming language python: A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not. We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the $2$-nd pair lies inside the $1$-st one, the $3$-rd one — inside the $2$-nd one and so on. For example, nesting depth of "" is $0$, "()()()" is $1$ and "()((())())" is $3$. Now, you are given RBS $s$ of even length $n$. You should color each bracket of $s$ into one of two colors: red or blue. Bracket sequence $r$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $b$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $s$, $r$ or $b$. No brackets can be left uncolored. Among all possible variants you should choose one that minimizes maximum of $r$'s and $b$'s nesting depth. If there are multiple solutions you can print any of them. -----Input----- The first line contains an even integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of RBS $s$. The second line contains regular bracket sequence $s$ ($|s| = n$, $s_i \in \{$"(", ")"$\}$). -----Output----- Print single string $t$ of length $n$ consisting of "0"-s and "1"-s. If $t_i$ is equal to 0 then character $s_i$ belongs to RBS $r$, otherwise $s_i$ belongs to $b$. -----Examples----- Input 2 () Output 11 Input 4 (()) Output 0101 Input 10 ((()())()) Output 0110001111 -----Note----- In the first example one of optimal solutions is $s = $ "$\color{blue}{()}$". $r$ is empty and $b = $ "$()$". The answer is $\max(0, 1) = 1$. In the second example it's optimal to make $s = $ "$\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}$". $r = b = $ "$()$" and the answer is $1$. In the third example we can make $s = $ "$\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}$". $r = $ "$()()$" and $b = $ "$(()())$" and the answer is $2$. 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() ) s = input() d = 0 l = [] for c in s: if c == '(': l.append(d) d ^= 1 else: d ^= 1 l.append( d ) print( "".join( [ str(i) for i in l ])) ```
vfc_16554
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1167/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n()\n", "output": "00\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\n(())\n", "output": "0110\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10\n((()())())\n", "output": "0100001110\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "20\n(())(()()())(())()()\n", "output": "01100111111001100000\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "20\n(()()()())(()())()()\n", "output": "01111111100111100000\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1701
Solve the following coding problem using the programming language python: As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. [Image] Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip. Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him. -----Input----- The first line of input contains two integers n and m (1 ≤ n, m ≤ 1000). The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1 ≤ |name| ≤ 10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct. The next m lines contain the commands in the configuration file. Each line is of form "command ip;" (1 ≤ |command| ≤ 10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers. -----Output----- Print m lines, the commands in the configuration file after Dustin did his task. -----Examples----- Input 2 2 main 192.168.0.2 replica 192.168.0.1 block 192.168.0.1; proxy 192.168.0.2; Output block 192.168.0.1; #replica proxy 192.168.0.2; #main Input 3 5 google 8.8.8.8 codeforces 212.193.33.27 server 138.197.64.57 redirect 138.197.64.57; block 8.8.8.8; cf 212.193.33.27; unblock 8.8.8.8; check 138.197.64.57; Output redirect 138.197.64.57; #server block 8.8.8.8; #google cf 212.193.33.27; #codeforces unblock 8.8.8.8; #google check 138.197.64.57; #server The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = map(int, input().split()) a = {} for i in range(n): x, y = input().split() a[y] = x for i in range(m): x, y = input().split() print(x, y, "#" + a[y.replace(';', '')]) ```
vfc_16558
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/918/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 2\nmain 192.168.0.2\nreplica 192.168.0.1\nblock 192.168.0.1;\nproxy 192.168.0.2;\n", "output": "block 192.168.0.1; #replica\nproxy 192.168.0.2; #main\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 5\ngoogle 8.8.8.8\ncodeforces 212.193.33.27\nserver 138.197.64.57\nredirect 138.197.64.57;\nblock 8.8.8.8;\ncf 212.193.33.27;\nunblock 8.8.8.8;\ncheck 138.197.64.57;\n", "output": "redirect 138.197.64.57; #server\nblock 8.8.8.8; #google\ncf 212.193.33.27; #codeforces\nunblock 8.8.8.8; #google\ncheck 138.197.64.57; #server\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 10\nittmcs 112.147.123.173\njkt 228.40.73.178\nfwckqtz 88.28.31.198\nkal 224.226.34.213\nnacuyokm 49.57.13.44\nfouynv 243.18.250.17\ns 45.248.83.247\ne 75.69.23.169\nauwoqlch 100.44.219.187\nlkldjq 46.123.169.140\ngjcylatwzi 46.123.169.140;\ndxfi 88.28.31.198;\ngv 46.123.169.140;\nety 88.28.31.198;\notbmgcrn 46.123.169.140;\nw 112.147.123.173;\np 75.69.23.169;\nvdsnigk 46.123.169.140;\nmmc 46.123.169.140;\ngtc 49.57.13.44;\n", "output": "gjcylatwzi 46.123.169.140; #lkldjq\ndxfi 88.28.31.198; #fwckqtz\ngv 46.123.169.140; #lkldjq\nety 88.28.31.198; #fwckqtz\notbmgcrn 46.123.169.140; #lkldjq\nw 112.147.123.173; #ittmcs\np 75.69.23.169; #e\nvdsnigk 46.123.169.140; #lkldjq\nmmc 46.123.169.140; #lkldjq\ngtc 49.57.13.44; #nacuyokm\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\nervbfot 185.32.99.2\nzygoumbmx 185.32.99.2;\n", "output": "zygoumbmx 185.32.99.2; #ervbfot\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1702
Solve the following coding problem using the programming language python: Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round. $\left. \begin{array}{|l|r|} \hline \text{Solvers fraction} & {\text{Maximum point value}} \\ \hline(1 / 2,1 ] & {500} \\ \hline(1 / 4,1 / 2 ] & {1000} \\ \hline(1 / 8,1 / 4 ] & {1500} \\ \hline(1 / 16,1 / 8 ] & {2000} \\ \hline(1 / 32,1 / 16 ] & {2500} \\ \hline [ 0,1 / 32 ] & {3000} \\ \hline \end{array} \right.$ Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500. If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem. There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem. With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing. Unfortunately, Vasya is a cheater. He has registered 10^9 + 7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved. Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts. Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 120) — the number of round participants, including Vasya and Petya. Each of the next n lines contains five integers a_{i}, 1, a_{i}, 2..., a_{i}, 5 ( - 1 ≤ a_{i}, j ≤ 119) — the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j. It is guaranteed that each participant has made at least one successful submission. Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order. -----Output----- Output a single integer — the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal. -----Examples----- Input 2 5 15 40 70 115 50 45 40 30 15 Output 2 Input 3 55 80 10 -1 -1 15 -1 79 60 -1 42 -1 13 -1 -1 Output 3 Input 5 119 119 119 119 119 0 0 0 0 -1 20 65 12 73 77 78 112 22 23 11 1 78 60 111 62 Output 27 Input 4 -1 20 40 77 119 30 10 73 50 107 21 29 -1 64 98 117 65 -1 -1 -1 Output -1 -----Note----- In the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980 + 940 + 420 + 360 + 270 = 2970 points, while Petya will score just 800 + 820 + 420 + 440 + 470 = 2950 points. In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points. In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one. 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()) a=[list(map(int,input().split())) for i in range(n)] solved=[0 for i in range(5)] score=[0 for i in range(5)] for i in range(n): for j in range(5): solved[j]+=int(a[i][j]>-1) for k in range(31*n+1): for i in range(5): tot=n+k cur=solved[i] if a[0][i]>-1 and a[1][i]>-1 and a[0][i]>a[1][i]: cur+=k score[i]=500 while score[i]<3000 and 2*cur<=tot: cur*=2; score[i]+=500 res=[0,0] for j in range(2): for i in range(5): if a[j][i]>-1: res[j]+=score[i]/250*(250-a[j][i]) if res[0]>res[1]: print(k) return print("-1") ```
vfc_16562
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/773/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n5 15 40 70 115\n50 45 40 30 15\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n55 80 10 -1 -1\n15 -1 79 60 -1\n42 -1 13 -1 -1\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\n119 119 119 119 119\n0 0 0 0 -1\n20 65 12 73 77\n78 112 22 23 11\n1 78 60 111 62\n", "output": "27\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\n-1 20 40 77 119\n30 10 73 50 107\n21 29 -1 64 98\n117 65 -1 -1 -1\n", "output": "-1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n33 15 51 7 101\n41 80 40 13 46\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "9\n57 52 60 56 91\n32 40 107 89 36\n80 0 45 92 119\n62 9 107 24 61\n43 28 4 26 113\n31 91 86 13 95\n4 2 88 38 68\n83 35 57 101 28\n12 40 37 56 73\n", "output": "9\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1703
Solve the following coding problem using the programming language python: A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not. You are given $n$ bracket sequences $s_1, s_2, \dots , s_n$. Calculate the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. Operation $+$ means concatenation i.e. "()(" + ")()" = "()()()". If $s_i + s_j$ and $s_j + s_i$ are regular bracket sequences and $i \ne j$, then both pairs $(i, j)$ and $(j, i)$ must be counted in the answer. Also, if $s_i + s_i$ is a regular bracket sequence, the pair $(i, i)$ must be counted in the answer. -----Input----- The first line contains one integer $n \, (1 \le n \le 3 \cdot 10^5)$ — the number of bracket sequences. The following $n$ lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed $3 \cdot 10^5$. -----Output----- In the single line print a single integer — the number of pairs $i, j \, (1 \le i, j \le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. -----Examples----- Input 3 ) () ( Output 2 Input 2 () () Output 4 -----Note----- In the first example, suitable pairs are $(3, 1)$ and $(2, 2)$. In the second example, any pair is suitable, namely $(1, 1), (1, 2), (2, 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 n = int(input()) from collections import defaultdict first = defaultdict(int) second = defaultdict(int) for _ in range(n): s = input().strip() count = 0 min_count = 0 for c in s: if c == '(': count += 1 else: count -= 1 min_count = min(count, min_count) if min_count >= 0: first[count] += 1 if count == min_count: second[count] += 1 res = 0 for k, v in list(first.items()): res += v * second[-k] print(res) ```
vfc_16566
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/990/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n)\n()\n(\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n()\n()\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n()(\n)\n)(\n())\n(((\n()()()\n()\n", "output": "6\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\n(\n((\n(((\n))))\n)))))\n))))))\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "9\n(()\n((())\n(\n)\n(()()(()())))\n)\n)(()(\n)())(\n)()(\n", "output": "9\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1704
Solve the following coding problem using the programming language python: Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $7$ segments, which can be turned on or off to display different numbers. The picture shows how all $10$ decimal digits are displayed: [Image] After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $k$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $k$ sticks (which are off now)? It is allowed that the number includes leading zeros. -----Input----- The first line contains integer $n$ $(1 \leq n \leq 2000)$  — the number of digits on scoreboard and $k$ $(0 \leq k \leq 2000)$  — the number of segments that stopped working. The next $n$ lines contain one binary string of length $7$, the $i$-th of which encodes the $i$-th digit of the scoreboard. Each digit on the scoreboard consists of $7$ segments. We number them, as in the picture below, and let the $i$-th place of the binary string be $0$ if the $i$-th stick is not glowing and $1$ if it is glowing. Then a binary string of length $7$ will specify which segments are glowing now. [Image] Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from $0$ to $9$ inclusive. -----Output----- Output a single number consisting of $n$ digits  — the maximum number that can be obtained if you turn on exactly $k$ sticks or $-1$, if it is impossible to turn on exactly $k$ sticks so that a correct number appears on the scoreboard digits. -----Examples----- Input 1 7 0000000 Output 8 Input 2 5 0010010 0010010 Output 97 Input 3 5 0100001 1001001 1010011 Output -1 -----Note----- In the first test, we are obliged to include all $7$ sticks and get one $8$ digit on the scoreboard. In the second test, we have sticks turned on so that units are formed. For $5$ of additionally included sticks, you can get the numbers $07$, $18$, $34$, $43$, $70$, $79$, $81$ and $97$, of which we choose the maximum  — $97$. In the third test, it is impossible to turn on exactly $5$ sticks so that a sequence of numbers appears on the scoreboard. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class Solution: def __init__(self): self.n, self.k = list(map(int, input().split())) self.s = [input() for i in range(0, self.n)] self.state = [ (119, 6), (36, 2), (93, 5), (109, 5), (46, 4), (107, 5), (123, 6), (37, 3), (127, 7), (111, 6), ] self.p = [] self.dp = [[False for j in range(0, self.k + 1)] for i in range(0, self.n)] def solve(self): for a in self.s: state = int(a[::-1], 2) stick = a.count("1") v = [] for i, (dState, dStick) in enumerate(self.state): if dState & state == state: v.append((i, dStick - stick)) self.p.append(v) for i in range(self.n - 1, -1, -1): for j, stick in self.p[i]: if i == self.n - 1: if stick <= self.k: self.dp[i][stick] = True else: for d in range(stick, self.k + 1): self.dp[i][d] |= self.dp[i + 1][d - stick] if not self.dp[0][self.k]: return "-1" result = "" for i, v in enumerate(self.p): for j, stick in v[::-1]: ok = (self.k == stick) if i == self.n - 1 else (self.k >= stick and self.dp[i + 1][self.k - stick]) if ok: self.k -= stick result += str(j) break return result print(Solution().solve()) ```
vfc_16570
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1341/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "1 7\n0000000\n", "output": "8", "type": "stdin_stdout" } ] }
apps
verifiable_code
1705
Solve the following coding problem using the programming language python: Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house. There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $k$ such that Mr. Black can exit the house after opening the first $k$ doors. We have to note that Mr. Black opened each door at most once, and in the end all doors became open. -----Input----- The first line contains integer $n$ ($2 \le n \le 200\,000$) — the number of doors. The next line contains $n$ integers: the sequence in which Mr. Black opened the doors. The $i$-th of these integers is equal to $0$ in case the $i$-th opened door is located in the left exit, and it is equal to $1$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit. -----Output----- Print the smallest integer $k$ such that after Mr. Black opened the first $k$ doors, he was able to exit the house. -----Examples----- Input 5 0 0 1 0 0 Output 3 Input 4 1 0 0 1 Output 3 -----Note----- In the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment. When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house. In the second example when the first two doors were opened, there was open closed door in each of the exit. With three doors opened Mr. Black was able to use the left exit. 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()) S = list(map(int,input().split()))[::-1] print(min(N - S.index(0), N - S.index(1))) ```
vfc_16574
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1143/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n0 0 1 0 0\n", "output": "3\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1706
Solve the following coding problem using the programming language python: Ringo found a string $s$ of length $n$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $s$ into a palindrome by applying two types of operations to the string. The first operation allows him to choose $i$ ($2 \le i \le n-1$) and to append the substring $s_2s_3 \ldots s_i$ ($i - 1$ characters) reversed to the front of $s$. The second operation allows him to choose $i$ ($2 \le i \le n-1$) and to append the substring $s_i s_{i + 1}\ldots s_{n - 1}$ ($n - i$ characters) reversed to the end of $s$. Note that characters in the string in this problem are indexed from $1$. For example suppose $s=$abcdef. If he performs the first operation with $i=3$ then he appends cb to the front of $s$ and the result will be cbabcdef. Performing the second operation on the resulted string with $i=5$ will yield cbabcdefedc. Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $30$ times. The length of the resulting palindrome must not exceed $10^6$ It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints. -----Input----- The only line contains the string $S$ ($3 \le |s| \le 10^5$) of lowercase letters from the English alphabet. -----Output----- The first line should contain $k$ ($0\le k \le 30$)  — the number of operations performed. Each of the following $k$ lines should describe an operation in form L i or R i. $L$ represents the first operation, $R$ represents the second operation, $i$ represents the index chosen. The length of the resulting palindrome must not exceed $10^6$. -----Examples----- Input abac Output 2 R 2 R 5 Input acccc Output 2 L 4 L 2 Input hannah Output 0 -----Note----- For the first example the following operations are performed: abac $\to$ abacab $\to$ abacaba The second sample performs the following operations: acccc $\to$ cccacccc $\to$ ccccacccc The third example is already a palindrome so no operations are required. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n = len(input()) print(3) print("R", n-1) print("L", n) print("L", 2) ```
vfc_16578
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1421/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "abac\n", "output": "3\nL 2\nR 2\nR 7\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "acccc\n", "output": "3\nL 2\nR 2\nR 9\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "hannah\n", "output": "3\nL 2\nR 2\nR 11\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "vux\n", "output": "3\nL 2\nR 2\nR 5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "evmo\n", "output": "3\nL 2\nR 2\nR 7\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "nxccb\n", "output": "3\nL 2\nR 2\nR 9\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1707
Solve the following coding problem using the programming language python: The legend of the foundation of Vectorland talks of two integers $x$ and $y$. Centuries ago, the array king placed two markers at points $|x|$ and $|y|$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $|x - y|$ and $|x + y|$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland. Here $|z|$ denotes the absolute value of $z$. Now, Jose is stuck on a question of his history exam: "What are the values of $x$ and $y$?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $n$ integers $a_1, a_2, \dots, a_n$. Now, he wants to know the number of unordered pairs formed by two different elements from these $n$ integers such that the legend could be true if $x$ and $y$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$)  — the number of choices. The second line contains $n$ pairwise distinct integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$) — the choices Jose is considering. -----Output----- Print a single integer number — the number of unordered pairs $\{x, y\}$ formed by different numbers from Jose's choices that could make the legend true. -----Examples----- Input 3 2 5 -3 Output 2 Input 2 3 6 Output 1 -----Note----- Consider the first sample. For the pair $\{2, 5\}$, the situation looks as follows, with the Arrayland markers at $|2| = 2$ and $|5| = 5$, while the Vectorland markers are located at $|2 - 5| = 3$ and $|2 + 5| = 7$: [Image] The legend is not true in this case, because the interval $[2, 3]$ is not conquered by Vectorland. For the pair $\{5, -3\}$ the situation looks as follows, with Arrayland consisting of the interval $[3, 5]$ and Vectorland consisting of the interval $[2, 8]$: [Image] As Vectorland completely contains Arrayland, the legend is true. It can also be shown that the legend is true for the pair $\{2, -3\}$, for a total of two pairs. In the second sample, the only pair is $\{3, 6\}$, and the situation looks as follows: [Image] Note that even though Arrayland and Vectorland share $3$ as endpoint, we still consider Arrayland to be completely inside of Vectorland. 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()) nums = (abs(int(x)) for x in input().split()) nums = list(sorted(nums)) left = 0 right = 0 ans = 0 while left < n: while right < n and nums[right] <= 2 * nums[left]: right += 1 ans += right - left - 1 left += 1 print(ans) ```
vfc_16582
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1166/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n2 5 -3\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n3 6\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n0 1\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n0 1000000000 -1000000000\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1708
Solve the following coding problem using the programming language python: Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's". The restaurant "Alice's" serves $n$ kinds of food. The cost for the $i$-th kind is always $c_i$. Initially, the restaurant has enough ingredients for serving exactly $a_i$ dishes of the $i$-th kind. In the New Year's Eve, $m$ customers will visit Alice's one after another and the $j$-th customer will order $d_j$ dishes of the $t_j$-th kind of food. The $(i + 1)$-st customer will only come after the $i$-th customer is completely served. Suppose there are $r_i$ dishes of the $i$-th kind remaining (initially $r_i = a_i$). When a customer orders $1$ dish of the $i$-th kind, the following principles will be processed. If $r_i > 0$, the customer will be served exactly $1$ dish of the $i$-th kind. The cost for the dish is $c_i$. Meanwhile, $r_i$ will be reduced by $1$. Otherwise, the customer will be served $1$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $1$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $0$. If the customer doesn't leave after the $d_j$ dishes are served, the cost for the customer will be the sum of the cost for these $d_j$ dishes. Please determine the total cost for each of the $m$ customers. -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 10^5$), representing the number of different kinds of food and the number of customers, respectively. The second line contains $n$ positive integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^7$), where $a_i$ denotes the initial remain of the $i$-th kind of dishes. The third line contains $n$ positive integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq 10^6$), where $c_i$ denotes the cost of one dish of the $i$-th kind. The following $m$ lines describe the orders of the $m$ customers respectively. The $j$-th line contains two positive integers $t_j$ and $d_j$ ($1 \leq t_j \leq n$, $1 \leq d_j \leq 10^7$), representing the kind of food and the number of dishes the $j$-th customer orders, respectively. -----Output----- Print $m$ lines. In the $j$-th line print the cost for the $j$-th customer. -----Examples----- Input 8 5 8 6 2 1 4 5 7 5 6 3 3 2 6 2 3 2 2 8 1 4 4 7 3 4 6 10 Output 22 24 14 10 39 Input 6 6 6 6 6 6 6 6 6 66 666 6666 66666 666666 1 6 2 6 3 6 4 6 5 6 6 66 Output 36 396 3996 39996 399996 0 Input 6 6 6 6 6 6 6 6 6 66 666 6666 66666 666666 1 6 2 13 3 6 4 11 5 6 6 6 Output 36 11058 99996 4333326 0 0 -----Note----- In the first sample, $5$ customers will be served as follows. Customer $1$ will be served $6$ dishes of the $2$-nd kind, $1$ dish of the $4$-th kind, and $1$ dish of the $6$-th kind. The cost is $6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22$. The remain of the $8$ kinds of food will be $\{8, 0, 2, 0, 4, 4, 7, 5\}$. Customer $2$ will be served $4$ dishes of the $1$-st kind. The cost is $4 \cdot 6 = 24$. The remain will be $\{4, 0, 2, 0, 4, 4, 7, 5\}$. Customer $3$ will be served $4$ dishes of the $6$-th kind, $3$ dishes of the $8$-th kind. The cost is $4 \cdot 2 + 3 \cdot 2 = 14$. The remain will be $\{4, 0, 2, 0, 4, 0, 7, 2\}$. Customer $4$ will be served $2$ dishes of the $3$-rd kind, $2$ dishes of the $8$-th kind. The cost is $2 \cdot 3 + 2 \cdot 2 = 10$. The remain will be $\{4, 0, 0, 0, 4, 0, 7, 0\}$. Customer $5$ will be served $7$ dishes of the $7$-th kind, $3$ dishes of the $1$-st kind. The cost is $7 \cdot 3 + 3 \cdot 6 = 39$. The remain will be $\{1, 0, 0, 0, 4, 0, 0, 0\}$. In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $6$ dishes of the second kind, so the cost is $66 \cdot 6 = 396$. In the third sample, some customers may not be served what they order. For example, the second customer is served $6$ dishes of the second kind, $6$ of the third and $1$ of the fourth, so the cost is $66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = map(int, input().split()) a = list(map(int, input().split())) c = list(map(int, input().split())) mc = sorted(((y, x) for x, y in enumerate(c)), reverse=True) for _ in range(m): t, d = map(int, input().split()) t -= 1 if a[t] >= d: print(c[t] * d) a[t] -= d else: x = a[t] * c[t] d -= a[t] a[t] = 0 while d: if not mc: print(0) break cost, index = mc[-1] if a[index] >= d: x += cost * d a[index] -= d d = 0 else: x += cost * a[index] d -= a[index] a[index] = 0 if a[index] == 0: mc.pop() else: print(x) ```
vfc_16586
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1106/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "8 5\n8 6 2 1 4 5 7 5\n6 3 3 2 6 2 3 2\n2 8\n1 4\n4 7\n3 4\n6 10\n", "output": "22\n24\n14\n10\n39\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 6\n6 6 6 6 6 6\n6 66 666 6666 66666 666666\n1 6\n2 6\n3 6\n4 6\n5 6\n6 66\n", "output": "36\n396\n3996\n39996\n399996\n0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 6\n6 6 6 6 6 6\n6 66 666 6666 66666 666666\n1 6\n2 13\n3 6\n4 11\n5 6\n6 6\n", "output": "36\n11058\n99996\n4333326\n0\n0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n411017\n129875\n1 8160563\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 15\n132 138 38 75 14 115 129 68 119 118\n728344 513371 120930 757031 137753 453796 348671 185533 966778 521678\n4 58\n1 8\n8 22\n3 98\n2 111\n6 158\n2 82\n1 170\n1 26\n1 4\n4 76\n10 106\n5 100\n4 116\n7 62\n", "output": "43907798\n5826752\n4081726\n15058400\n56984181\n67179393\n33037922\n108948627\n13563628\n2086712\n43648529\n96247068\n0\n0\n0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n8494441\n646015\n1 2198012\n", "output": "1419948722180\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1709
Solve the following coding problem using the programming language python: ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right. Initially, tree i has color c_{i}. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ c_{i} ≤ m, where c_{i} = 0 means that tree i is uncolored. ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with c_{i} = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly p_{i}, j litres of paint. The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job. Please note that the friends can't color the trees that are already colored. -----Input----- The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively. The second line contains n integers c_1, c_2, ..., c_{n} (0 ≤ c_{i} ≤ m), the initial colors of the trees. c_{i} equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color c_{i}. Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes p_{i}, j (1 ≤ p_{i}, j ≤ 10^9) — the amount of litres the friends need to color i-th tree with color j. p_{i}, j's are specified even for the initially colored trees, but such trees still can't be colored. -----Output----- Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1. -----Examples----- Input 3 2 2 0 0 0 1 2 3 4 5 6 Output 10 Input 3 2 2 2 1 2 1 3 2 4 3 5 Output -1 Input 3 2 2 2 0 0 1 3 2 4 3 5 Output 5 Input 3 2 3 2 1 2 1 3 2 4 3 5 Output 0 -----Note----- In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color). In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1. In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the 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 INF = 10 ** 18 MX_SZ = 112 dp = [[[INF for k in range (MX_SZ)] for j in range (MX_SZ)] for i in range (MX_SZ)] best = [[[(INF, INF) for k in range (MX_SZ)] for j in range (MX_SZ)] for i in range (MX_SZ)] def read(): return [int(x) for x in input().split()] n, m, k_res = read() arr = read() cost = [] for i in range (n): cost.append(read()) dp[0][0][MX_SZ - 1] = 0 #[trees painted][group amount][last color] best[0][0][0] = (0, MX_SZ - 1) #print(best[0][0][0][1]) #return for i in range (1, n + 1): clr = arr[i - 1] if clr == 0: for j in range (1, k_res + 1): for k in range (1, m + 1): dp[i][j][k] = dp[i - 1][j][k] + cost[i - 1][k - 1] if k == best[i - 1][j - 1][0][1]: dp[i][j][k] = min(dp[i][j][k], best[i - 1][j - 1][1][0] + cost[i - 1][k - 1]) else: dp[i][j][k] = min(dp[i][j][k], best[i - 1][j - 1][0][0] + cost[i - 1][k - 1]) if dp[i][j][k] < best[i][j][0][0]: best[i][j][1] = best[i][j][0] best[i][j][0] = (dp[i][j][k], k) elif dp[i][j][k] < best[i][j][1][0]: best[i][j][1] = (dp[i][j][k], k) else: for j in range (1, n + 1): dp[i][j][clr] = dp[i - 1][j][clr] if clr == best[i - 1][j - 1][0][1]: dp[i][j][clr] = min(dp[i][j][clr], best[i - 1][j - 1][1][0]) else: dp[i][j][clr] = min(dp[i][j][clr], best[i - 1][j - 1][0][0]) best[i][j][0] = (dp[i][j][clr], clr) ans = INF for k in range (1, m + 1): if dp[n][k_res][k] < ans: ans = dp[n][k_res][k] if ans == INF: ans = -1 print(ans) ```
vfc_16590
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/711/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 2 2\n0 0 0\n1 2\n3 4\n5 6\n", "output": "10", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 2 2\n2 1 2\n1 3\n2 4\n3 5\n", "output": "-1", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 2 2\n2 0 0\n1 3\n2 4\n3 5\n", "output": "5", "type": "stdin_stdout" } ] }
apps
verifiable_code
1710
Solve the following coding problem using the programming language python: Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that $\frac{p}{s} = k$, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments. Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array. -----Input----- The first line contains two integers n and k (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ 10^5), where n is the length of the array and k is the constant described above. The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^8) — the elements of the array. -----Output----- In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k. -----Examples----- Input 1 1 1 Output 1 Input 4 2 6 3 8 1 Output 2 -----Note----- In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because $\frac{1}{1} = 1$. There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because $\frac{18}{9} = 2$. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because $\frac{24}{12} = 2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/env python3 [n, k] = list(map(int, input().strip().split())) ais = list(map(int, input().strip().split())) n1 = ais.count(1) one_serie = [0 for _ in range(n)] for i in reversed(list(range(n))): if ais[i] == 1: one_serie[i] = (0 if i == n - 1 else one_serie[i + 1]) + 1 n1_head = 0 count = 0 for i in range(n): p = 1 s = 0 if i > 0 and ais[i - 1] == 1: n1_head += 1 n1_tail = n1 - n1_head j = i while j < n: if ais[j] == 1: if p % k == 0 and 1 <= p // k - s <= one_serie[j]: count += 1 n1_tail -= one_serie[j] s += one_serie[j] j += one_serie[j] else: p *= ais[j] s += ais[j] if p == s * k: count += 1 elif p > (s + n1_tail) * k: break j += 1 print (count) ```
vfc_16594
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/992/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "1 1\n1\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 2\n6 3 8 1\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "94 58\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 29 58 1 1 1 29 58 58 1 1 29 1 1 1 1 2 1 58 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 29 1 1 1 1 1 58 1 29 1 1 1 1 1 1 1 1 1 1 1 1 58 1 1 1 1 1 2 1 1 1\n", "output": "5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 76\n1 38 1 1 1 1\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "16 53\n53 1 1 1 1 1 53 1 1 1 1 1 1 1 1 1\n", "output": "0\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1712
Solve the following coding problem using the programming language python: Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1 / x seconds for the first character and 1 / y seconds for the second one). The i-th monster dies after he receives a_{i} hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit. -----Input----- The first line contains three integers n,x,y (1 ≤ n ≤ 10^5, 1 ≤ x, y ≤ 10^6) — the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the number of hits needed do destroy the i-th monster. -----Output----- Print n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time. -----Examples----- Input 4 3 2 1 2 3 4 Output Vanya Vova Vanya Both Input 2 1 1 1 2 Output Both Both -----Note----- In the first sample Vanya makes the first hit at time 1 / 3, Vova makes the second hit at time 1 / 2, Vanya makes the third hit at time 2 / 3, and both boys make the fourth and fifth hit simultaneously at the time 1. In the second sample Vanya and Vova make the first and second hit simultaneously at time 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from fractions import gcd n, x, y = map(int, input().split()) g = gcd(x, y) x //= g y //= g a = sorted([y * i for i in range(1, x)] + [x * i for i in range(1, y)]) def f(n): n %= x + y if n == 0 or n == x + y - 1: return "Both" return "Vova" if a[n - 1] % x == 0 else "Vanya" for _ in range(n): print(f(int(input()))) ```
vfc_16602
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/492/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4 3 2\n1\n2\n3\n4\n", "output": "Vanya\nVova\nVanya\nBoth\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 1 1\n1\n2\n", "output": "Both\nBoth\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7 5 20\n26\n27\n28\n29\n30\n31\n32\n", "output": "Vova\nVova\nVova\nBoth\nBoth\nVova\nVova\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1713
Solve the following coding problem using the programming language python: Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p_1, the glass from the second position to position p_2 and so on. That is, a glass goes from position i to position p_{i}. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in. After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t. -----Input----- The first line contains three integers: n, s, t (1 ≤ n ≤ 10^5; 1 ≤ s, t ≤ n) — the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the shuffling operation parameters. It is guaranteed that all p_{i}'s are distinct. Note that s can equal t. -----Output----- If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1. -----Examples----- Input 4 2 1 2 3 4 1 Output 3 Input 4 3 3 4 1 3 2 Output 0 Input 4 3 4 1 2 3 4 Output -1 Input 3 1 3 2 1 3 Output -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python rd = lambda: list(map(int, input().split())) n, s, t = rd() p = rd() for i in range(n): if s == t : print(i); return s = p[s-1] print(-1) ```
vfc_16606
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/285/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4 2 1\n2 3 4 1\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 3 3\n4 1 3 2\n", "output": "0\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1714
Solve the following coding problem using the programming language python: A permutation p is an ordered group of numbers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p_1, p_2, ..., p_{n}. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: $\sum_{i = 1}^{n}|a_{2 i - 1} - a_{2i}|-|\sum_{i = 1}^{n} a_{2 i - 1} - a_{2i}|= 2 k$. -----Input----- The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). -----Output----- Print 2n integers a_1, a_2, ..., a_2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. -----Examples----- Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 -----Note----- Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, k = map(int, input().split()) A = [i for i in range(2*n, 0, -1)] for i in range(k): if i > n: i %= n A[2*i], A[2*i + 1] = A[2*i + 1], A[2*i] print(' '.join(map(str, A))) ```
vfc_16610
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/359/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "1 0\n", "output": "1 2", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 1\n", "output": "3 2 1 4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 0\n", "output": "2 7 4 6 1 3 5 8\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 0\n", "output": "1 2 3 4", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 0\n", "output": "1 2 3 4 5 6", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 1\n", "output": "2 1 3 4 5 6 7 8", "type": "stdin_stdout" } ] }
apps
verifiable_code
1720
Solve the following coding problem using the programming language python: Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks. Formally, her room can be represented as a field of n × m cells, each cell of which is empty or littered with cans. Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells. Now Olya needs to get from cell (x_1, y_1) to cell (x_2, y_2). How many seconds will it take her if she moves optimally? It's guaranteed that cells (x_1, y_1) and (x_2, y_2) are empty. These cells can coincide. -----Input----- The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 1000) — the sizes of the room and Olya's speed. Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise. The last line contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — the coordinates of the first and the last cells. -----Output----- Print a single integer — the minimum time it will take Olya to get from (x_1, y_1) to (x_2, y_2). If it's impossible to get from (x_1, y_1) to (x_2, y_2), print -1. -----Examples----- Input 3 4 4 .... ###. .... 1 1 3 1 Output 3 Input 3 4 1 .... ###. .... 1 1 3 1 Output 8 Input 2 2 1 .# #. 1 1 2 2 Output -1 -----Note----- In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second. In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds. Olya does not recommend drinking energy drinks and generally believes that this is bad. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**15 mod = 10**9+7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): n,m,k = LI() a = [[-1] * (m+2)] a += [[-1] + [inf if c=='.' else -1 for c in S()] + [-1] for _ in range(n)] a += [[-1] * (m+2)] x1,y1,x2,y2 = LI() a[x1][y1] = 0 q = [(x1,y1)] qi = 0 dy = [-1,1,0,0] dx = [0,0,-1,1] while qi < len(q): x,y = q[qi] qi += 1 nd = a[x][y] + 1 for di in range(4): for j in range(1,k+1): ny = y + dy[di] * j nx = x + dx[di] * j if a[nx][ny] > nd: if ny == y2 and nx == x2: return nd a[nx][ny] = nd q.append((nx,ny)) elif a[nx][ny] < nd: break if a[x2][y2] < inf: return a[x2][y2] return -1 print(main()) ```
vfc_16634
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/877/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 4 4\n....\n###.\n....\n1 1 3 1\n", "output": "3", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 4 1\n....\n###.\n....\n1 1 3 1\n", "output": "8", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 2 1\n.#\n#.\n1 1 2 2\n", "output": "-1", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 10 1\n##########\n#.........\n#.#######.\n#.#.....#.\n#.#.###.#.\n#.#.#.#.#.\n#.#.#.#.#.\n#.#.#...#.\n#.#.#####.\n#.#.......\n6 6 10 2\n", "output": "48", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 10 3\n##########\n##########\n##########\n##########\n##########\n##########\n##########\n#########.\n#########.\n####..###.\n10 6 10 5\n", "output": "1", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 10 3\n...##..#..\n#.#..#...#\n..#.##.#..\n##..#..#.#\n..#...##..\n.#.#.#....\n#......#..\n.#.####.##\n......#...\n.#.##...##\n4 6 8 1\n", "output": "7", "type": "stdin_stdout" } ] }
apps
verifiable_code
1721
Solve the following coding problem using the programming language python: You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string. -----Input----- The first line contains one integer $n$ ($2 \le n \le 200\,000$) — the length of $s$. The second line contains $s$ — a string consisting of $n$ lowercase Latin letters. -----Output----- Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string. -----Examples----- Input 5 aaaza Output 2 Input 6 cbaabc Output 0 Input 9 icpcsguru Output 30 -----Note----- In the first example, you have to swap the third and the fourth elements, so the string becomes "aazaa". Then you have to swap the second and the third elements, so the string becomes "azaaa". So, it is possible to reverse the string in two swaps. Since the string in the second example is a palindrome, you don't have to do anything to reverse it. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class BIT(): def __init__(self,n): self.BIT=[0]*(n+1) self.num=n def query(self,idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): while idx <= self.num: self.BIT[idx] += x idx += idx&(-idx) return al = [chr(97+i) for i in range(26)] n = int(input()) s = input() s = [s[i] for i in range(n)] goal = s[::-1] dic = {a:[] for a in al} for i in range(n): dic[goal[i]].append(i) for a in dic: dic[a] = dic[a][::-1] seq = [-1 for i in range(n)] for i in range(n): seq[i] = dic[s[i]].pop() + 1 res = 0 bit = BIT(n) for i in range(n): res += i - bit.query(seq[i]) bit.update(seq[i],1) print(res) ```
vfc_16638
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1430/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\naaaza\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\ncbaabc\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "9\nicpcsguru\n", "output": "30\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "50\nfhakqhdhrgfjruxndgfhdvcxhsrjfgdhsyrhfjcbfgdvrtdysf\n", "output": "482\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1722
Solve the following coding problem using the programming language python: There are $n$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $x$ be the number of such pairs of students in a split. Pairs $(a, b)$ and $(b, a)$ are the same and counted only once. For example, if there are $6$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then: splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $x=4$ ($3$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom), splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $x=1$ ($0$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom). You are given the list of the $n$ names. What is the minimum $x$ we can obtain by splitting the students into classrooms? Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty. -----Input----- The first line contains a single integer $n$ ($1\leq n \leq 100$) — the number of students. After this $n$ lines follow. The $i$-th line contains the name of the $i$-th student. It is guaranteed each name is a string of lowercase English letters of length at most $20$. Note that multiple students may share the same name. -----Output----- The output must consist of a single integer $x$ — the minimum possible number of chatty pairs. -----Examples----- Input 4 jorge jose oscar jerry Output 1 Input 7 kambei gorobei shichiroji kyuzo heihachi katsushiro kikuchiyo Output 2 Input 5 mike mike mike mike mike Output 4 -----Note----- In the first sample the minimum number of pairs is $1$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair. In the second sample the minimum number of pairs is $2$. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo. In the third sample the minimum number of pairs is $4$. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom. 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()) a = [0] * 27 for i in range(n): s = input() a[ord(s[0]) - ord('a')] += 1 ans = 0 for i in range(26): t = a[i] // 2 k = a[i] - t ans += t * (t - 1) // 2 ans += k * (k - 1) // 2 print(ans) ```
vfc_16642
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1166/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\njorge\njose\noscar\njerry\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\nkambei\ngorobei\nshichiroji\nkyuzo\nheihachi\nkatsushiro\nkikuchiyo\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\nmike\nmike\nmike\nmike\nmike\n", "output": "4\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1724
Solve the following coding problem using the programming language python: Valera has array a, consisting of n integers a_0, a_1, ..., a_{n} - 1, and function f(x), taking an integer from 0 to 2^{n} - 1 as its single argument. Value f(x) is calculated by formula $f(x) = \sum_{i = 0}^{n - 1} a_{i} \cdot b i t(i)$, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise. For example, if n = 4 and x = 11 (11 = 2^0 + 2^1 + 2^3), then f(x) = a_0 + a_1 + a_3. Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of array elements. The next line contains n space-separated integers a_0, a_1, ..., a_{n} - 1 (0 ≤ a_{i} ≤ 10^4) — elements of array a. The third line contains a sequence of digits zero and one without spaces s_0s_1... s_{n} - 1 — the binary representation of number m. Number m equals $\sum_{i = 0}^{n - 1} 2^{i} \cdot s_{i}$. -----Output----- Print a single integer — the maximum value of function f(x) for all $x \in [ 0 . . m ]$. -----Examples----- Input 2 3 8 10 Output 3 Input 5 17 0 10 2 1 11010 Output 27 -----Note----- In the first test case m = 2^0 = 1, f(0) = 0, f(1) = a_0 = 3. In the second sample m = 2^0 + 2^1 + 2^3 = 11, the maximum value of function equals f(5) = a_0 + a_2 = 17 + 10 = 27. 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()) a = list(map(int, input().split())) k = input() pref = [a[0]] for i in range(1, n): pref.append(pref[-1] + a[i]) cur = 0 ans = 0 for i in range(n - 1, -1, -1): if k[i] == '0': continue if cur + (pref[i - 1] if i > 0 else 0) > ans: ans = cur + (pref[i - 1] if i > 0 else 0) cur += a[i] cur = 0 for i in range(n): if k[i] == '1': cur += a[i] ans = max(ans, cur) print(ans) ```
vfc_16650
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/353/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n3 8\n10\n", "output": "3\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1725
Solve the following coding problem using the programming language python: Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as a_{ij}. In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so. -----Input----- The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 10^4) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element a_{ij} (1 ≤ a_{ij} ≤ 10^4). -----Output----- In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes). -----Examples----- Input 2 2 2 2 4 6 8 Output 4 Input 1 2 7 6 7 Output -1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import re import itertools from collections import Counter, deque class Task: a = [] d = 0 answer = 0 def getData(self): n, m, self.d = [int(x) for x in input().split(' ')] for _ in range(n): self.a += [int(x) for x in input().split(' ')] #inFile = open('input.txt', 'r') #inFile.readline().rstrip() #self.childs = inFile.readline().rstrip() def solve(self): a = self.a for x in a: if x % self.d != a[0] % self.d: self.answer = -1 return a = [x // self.d for x in a] a.sort() d = [sum(a)] + [0 for _ in range(1, a[-1] + 1)] lessCurrentLevel = 0 counter = Counter(a) for level in range(1, a[-1] + 1): lessCurrentLevel += counter[level - 1] d[level] = d[level - 1] + lessCurrentLevel - \ (len(a) - lessCurrentLevel) self.answer = min(d) def solve2(self): a, d = self.a, self.d for i in range(1, len(a)): if a[i] % d != a[0] % d: self.answer = -1 return a = [x // d for x in a] d = [abs(a[0] - i) for i in range(10000 + 1)] for i in range(1, len(a)): for j in range(0, len(d)): d[j] += abs(a[i] - j) self.answer = min(d) def printAnswer(self): print(self.answer) #print(re.sub('[\[\],]', '', str(self.answer))) #outFile = open('output.txt', 'w') #outFile.write(self.answer) task = Task() task.getData() task.solve() task.printAnswer() ```
vfc_16654
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/289/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 2 2\n2 4\n6 8\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 2 7\n6 7\n", "output": "-1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 2 1\n5 7\n1 2\n5 100\n", "output": "104\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 3 3\n5 8 5\n11 11 17\n14 5 2\n", "output": "12\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1726
Solve the following coding problem using the programming language python: Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can. But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is a_{i}. If some free time remains, she can spend it on reading. Help Luba to determine the minimum number of day when she finishes reading. It is guaranteed that the answer doesn't exceed n. Remember that there are 86400 seconds in a day. -----Input----- The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 10^6) — the number of days and the time required to read the book. The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 86400) — the time Luba has to spend on her work during i-th day. -----Output----- Print the minimum day Luba can finish reading the book. It is guaranteed that answer doesn't exceed n. -----Examples----- Input 2 2 86400 86398 Output 2 Input 2 86400 0 86400 Output 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python R=lambda:list(map(int,input().split())) n,t=R() a=R() for i in range(n): t-=86400-a[i] if t<1: print(i+1) return ```
vfc_16658
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/884/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 2\n86400 86398\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 86400\n0 86400\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1727
Solve the following coding problem using the programming language python: Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x_1, x_2, ..., x_{n}. Each tree has its height h_{i}. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [x_{i} - h_{i}, x_{i}] or [x_{i};x_{i} + h_{i}]. The tree that is not cut down occupies a single point with coordinate x_{i}. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of trees. Next n lines contain pairs of integers x_{i}, h_{i} (1 ≤ x_{i}, h_{i} ≤ 10^9) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending x_{i}. No two trees are located at the point with the same coordinate. -----Output----- Print a single number — the maximum number of trees that you can cut down by the given rules. -----Examples----- Input 5 1 2 2 1 5 10 10 9 19 1 Output 3 Input 5 1 2 2 1 5 10 10 9 20 1 Output 4 -----Note----- In the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. 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()) p = -float("INF") ans = 1 A = [] for i in range(n) : x, h = list(map(int, input().split())) A.append([x,h]) for i in range(n-1) : x, h = A[i] if x-h > p : ans += 1 p = x elif x+h < A[i+1][0] : ans += 1 p = x+h else : p = x print(ans) ```
vfc_16662
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/545/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 2\n2 1\n5 10\n10 9\n19 1\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\n1 2\n2 1\n5 10\n10 9\n20 1\n", "output": "4\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1730
Solve the following coding problem using the programming language python: You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1. A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v_1, v_2, ..., v_{d} such, that nodes v_1 and v_{d} are connected by an edge of the graph, also for any integer i (1 ≤ i < d) nodes v_{i} and v_{i} + 1 are connected by an edge of the graph. -----Input----- The first line contains three integers n, m, k (3 ≤ n, m ≤ 10^5; 2 ≤ k ≤ n - 1) — the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) — the indexes of the graph nodes that are connected by the i-th edge. It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph. -----Output----- In the first line print integer r (r ≥ k + 1) — the length of the found cycle. In the next line print r distinct integers v_1, v_2, ..., v_{r} (1 ≤ v_{i} ≤ n) — the found simple cycle. It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them. -----Examples----- Input 3 3 2 1 2 2 3 3 1 Output 3 1 2 3 Input 4 6 3 4 3 1 2 1 3 1 4 2 3 2 4 Output 4 3 4 1 2 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, m, k = map(int, input().split()) p = [[] for i in range(n + 1)] for i in range(m): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) t, r = [0] * (n + 1), [1] x = t[1] = 1 i = 0 - k while True: for y in p[x]: if t[y] == 2: return r[r.index(y): ] if t[y]: continue t[y], x = 1, y r.append(x) i += 1 if i >= 0: t[r[i]] = 2 break t = f() print(len(t)) print(' '.join(map(str, t))) ```
vfc_16674
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/263/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 3 2\n1 2\n2 3\n3 1\n", "output": "3\n1 2 3 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 6 3\n4 3\n1 2\n1 3\n1 4\n2 3\n2 4\n", "output": "4\n3 4 1 2 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "9 9 2\n5 6\n6 7\n7 8\n8 9\n9 5\n1 2\n2 3\n3 4\n4 1\n", "output": "4\n1 2 3 4 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 10 4\n1 2\n2 3\n1 3\n1 5\n4 1\n2 5\n2 4\n5 3\n5 4\n3 4\n", "output": "5\n1 2 3 5 4 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 15 3\n9 4\n4 8\n4 2\n2 9\n9 6\n6 2\n6 5\n1 10\n1 7\n10 5\n10 7\n1 8\n8 3\n3 5\n3 7\n", "output": "7\n6 9 4 8 1 10 5 ", "type": "stdin_stdout" } ] }
apps
verifiable_code
1731
Solve the following coding problem using the programming language python: You are given two integers $n$ and $m$. Calculate the number of pairs of arrays $(a, b)$ such that: the length of both arrays is equal to $m$; each element of each array is an integer between $1$ and $n$ (inclusive); $a_i \le b_i$ for any index $i$ from $1$ to $m$; array $a$ is sorted in non-descending order; array $b$ is sorted in non-ascending order. As the result can be very large, you should print it modulo $10^9+7$. -----Input----- The only line contains two integers $n$ and $m$ ($1 \le n \le 1000$, $1 \le m \le 10$). -----Output----- Print one integer – the number of arrays $a$ and $b$ satisfying the conditions described above modulo $10^9+7$. -----Examples----- Input 2 2 Output 5 Input 10 1 Output 55 Input 723 9 Output 157557417 -----Note----- In the first test there are $5$ suitable arrays: $a = [1, 1], b = [2, 2]$; $a = [1, 2], b = [2, 2]$; $a = [2, 2], b = [2, 2]$; $a = [1, 1], b = [2, 1]$; $a = [1, 1], b = [1, 1]$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = list(map(int,input().split())) M = 10 ** 9 + 7 def inv(x): return pow(x, M - 2, M) def binomial(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 ntok %= M ktok %= M return (ntok * inv(ktok))%M else: return 0 print(binomial(n+2*m-1, 2 * m)) ```
vfc_16678
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1288/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 2\n", "output": "5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 1\n", "output": "55\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1732
Solve the following coding problem using the programming language python: Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0. There are also n cards, each card has 2 attributes: length l_{i} and cost c_{i}. If she pays c_{i} dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length l_{i}, i. e. from cell x to cell (x - l_{i}) or cell (x + l_{i}). She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost. -----Input----- The first line contains an integer n (1 ≤ n ≤ 300), number of cards. The second line contains n numbers l_{i} (1 ≤ l_{i} ≤ 10^9), the jump lengths of cards. The third line contains n numbers c_{i} (1 ≤ c_{i} ≤ 10^5), the costs of cards. -----Output----- If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards. -----Examples----- Input 3 100 99 9900 1 1 1 Output 2 Input 5 10 20 30 40 50 1 1 1 1 1 Output -1 Input 7 15015 10010 6006 4290 2730 2310 1 1 1 1 1 1 1 10 Output 6 Input 8 4264 4921 6321 6984 2316 8432 6120 1026 4264 4921 6321 6984 2316 8432 6120 1026 Output 7237 -----Note----- In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell. In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. 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 = [int(x) for x in input().split()] c = [int(x) for x in input().split()] def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) gcds = {0: 0} for i in range(n): adds = {} for g in list(gcds.keys()): x = gcd(g, l[i]) y = gcds.get(x) u = gcds[g] if y is not None: if u + c[i] < y: t = adds.get(x) if t and t > u + c[i] or t is None: adds[x] = u + c[i] else: t = adds.get(x) if t and t > u + c[i]or t is None: adds[x] = u + c[i] gcds.update(adds) if gcds.get(1): print(gcds[1]) else: print(-1) ```
vfc_16682
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/510/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n100 99 9900\n1 1 1\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\n10 20 30 40 50\n1 1 1 1 1\n", "output": "-1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1733
Solve the following coding problem using the programming language python: Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$). Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him. Kuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem. -----Input----- The first line contains three integers $n$, $x$ and $y$ ($1 \leq n \leq 3 \cdot 10^5$, $1 \leq x, y \leq n$, $x \ne y$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively. $n - 1$ lines follow, each line contains two integers $a$ and $b$ ($1 \leq a, b \leq n$, $a \ne b$), describes a road connecting two towns $a$ and $b$. It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree. -----Output----- A single integer resembles the number of pair of towns $(u, v)$ that Kuro can use as his walking route. -----Examples----- Input 3 1 3 1 2 2 3 Output 5 Input 3 1 3 1 2 1 3 Output 4 -----Note----- On the first example, Kuro can choose these pairs: $(1, 2)$: his route would be $1 \rightarrow 2$, $(2, 3)$: his route would be $2 \rightarrow 3$, $(3, 2)$: his route would be $3 \rightarrow 2$, $(2, 1)$: his route would be $2 \rightarrow 1$, $(3, 1)$: his route would be $3 \rightarrow 2 \rightarrow 1$. Kuro can't choose pair $(1, 3)$ since his walking route would be $1 \rightarrow 2 \rightarrow 3$, in which Kuro visits town $1$ (Flowrisa) and then visits town $3$ (Beetopia), which is not allowed (note that pair $(3, 1)$ is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order). On the second example, Kuro can choose the following pairs: $(1, 2)$: his route would be $1 \rightarrow 2$, $(2, 1)$: his route would be $2 \rightarrow 1$, $(3, 2)$: his route would be $3 \rightarrow 1 \rightarrow 2$, $(3, 1)$: his route would be $3 \rightarrow 1$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import defaultdict n, flower, bee = list(map(int, input().split())) roads = {} for _ in range(n-1): x, y = list(map(int, input().split())) if x not in roads: roads[x] = [y] else: roads[x].append(y) if y not in roads: roads[y] = [x] else: roads[y].append(x) flowers = defaultdict(int) def dfs(bee, flower): q = [] visited = set() visited.add(flower) last = -1 for y in roads[flower]: if y == bee: last = y continue q.append([y, y]) while q: now = q.pop() visited.add(now[0]) flowers[now[1]] += 1 for y in roads[now[0]]: if y not in visited: if y == bee: last = now[1] continue q.append([y, now[1]]) return last rem = dfs(bee, flower) flower_total = sum(flowers.values())+1 print(n*(n-1)-(flower_total - flowers[rem])*(n-(flower_total))) ```
vfc_16686
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/979/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 1 3\n1 2\n2 3\n", "output": "5", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 1 3\n1 2\n1 3\n", "output": "4", "type": "stdin_stdout" }, { "fn_name": null, "input": "61 26 12\n33 38\n32 8\n27 59\n1 21\n61 57\n61 22\n35 18\n61 14\n39 56\n50 10\n1 42\n21 43\n61 41\n31 30\n35 9\n23 28\n39 34\n39 4\n39 25\n27 60\n45 51\n1 11\n35 26\n29 15\n23 44\n31 2\n35 27\n39 20\n1 24\n1 53\n35 58\n39 37\n61 13\n61 16\n1 12\n32 17\n1 40\n33 47\n29 52\n1 39\n35 19\n39 50\n27 6\n26 3\n26 55\n35 31\n1 61\n1 23\n27 45\n39 7\n1 35\n39 29\n27 5\n39 32\n27 48\n35 49\n29 54\n1 46\n35 36\n31 33\n", "output": "3657", "type": "stdin_stdout" }, { "fn_name": null, "input": "8 5 1\n5 8\n1 5\n1 3\n1 4\n5 6\n6 7\n1 2\n", "output": "40", "type": "stdin_stdout" } ] }
apps
verifiable_code
1734
Solve the following coding problem using the programming language python: There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number. -----Input----- The first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct. -----Output----- Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them. -----Examples----- Input 3 123456789 100000000 100123456 Output 9 000 01 Input 4 123456789 193456789 134567819 934567891 Output 2 193 81 91 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def rec(i): nonlocal a return i import sys from collections import Counter sys.setrecursionlimit(10**6) n=int(input()) #n,m=list(map(int,input().split())) a=[input() for i in range(n)] b=[] a0=set() c0=set() for i in a: c=set() for i0 in range(1,10): for i1 in range(0,10-i0): c.add(i[i1:i1+i0]) b.append(c) c0.update(a0&c) a0.update(c) for i in b: c=i-c0 z='0'*10 for i0 in c: if len(i0)<len(z): z=i0 print(z) ```
vfc_16690
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/858/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n123456789\n100000000\n100123456\n", "output": "9\n000\n01\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4\n123456789\n193456789\n134567819\n934567891\n", "output": "2\n193\n81\n91\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n167038488\n", "output": "4\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1735
Solve the following coding problem using the programming language python: Two people are playing a game with a string $s$, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses. Your task is to determine which player will win if both play optimally. -----Input----- The only line contains the string $s$, consisting of lowercase latin letters ($1 \leq |s| \leq 100\,000$), where $|s|$ means the length of a string $s$. -----Output----- If the first player wins, print "Yes". If the second player wins, print "No". -----Examples----- Input abacaba Output No Input iiq Output Yes Input abba Output No -----Note----- In the first example the first player is unable to make a turn, so he loses. In the second example first player turns the string into "q", then second player is unable to move, so he loses. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = input() l = [] t = 0 for i in range(len(s)): if len(l) > 0: if s[i] == l[-1]: l.pop() t += 1 else: l.append(s[i]) else: l.append(s[i]) if t % 2 == 0: print("No") else: print("Yes") ```
vfc_16694
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1104/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "abacaba\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "iiq\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "abba\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "a\n", "output": "No\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1736
Solve the following coding problem using the programming language python: When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs a_{i} minutes to read the i-th book. Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read. -----Input----- The first line contains two integers n and t (1 ≤ n ≤ 10^5; 1 ≤ t ≤ 10^9) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4), where number a_{i} shows the number of minutes that the boy needs to read the i-th book. -----Output----- Print a single integer — the maximum number of books Valera can read. -----Examples----- Input 4 5 3 1 2 1 Output 3 Input 3 3 2 2 3 Output 1 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python l = 0 r = -1 segL, time = [int(x) for x in input().split()] a = [int(x) for x in input().split()] segSum = 0 segments = [] ##while r < segL-1: ## r += 1 ## segSum += a[r] ## if segSum == time: ## segments.append(r+1-l) ## elif segSum > time: ## segments.append(r-l) ## while segSum > time or l < r: ## # Shifting l to the right ## # until reaching next suitable segment sum ## segSum -= a[l] ## l += 1 ## #segments.append(r+1-l) ## ##[1,2,5,3,7,4,5] while r < segL-1: r += 1 segSum += a[r] if segSum == time: segments.append(r+1-l) segSum -= a[l] l += 1 elif segSum > time: segments.append(r-l) while segSum >= time: segSum -= a[l] l += 1 else: segments.append(r+1-l) print(max(segments)) ```
vfc_16698
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/279/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4 5\n3 1 2 1\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 3\n2 2 3\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 3\n5\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 10\n4\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 10\n6 4\n", "output": "2\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1737
Solve the following coding problem using the programming language python: Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity. A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 10^6. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies. You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored. More formal, choose such a set of projects of minimum possible size that the following conditions hold: Polycarp's project is chosen; Polycarp's project depends (directly or indirectly) on all other projects in the set; no two projects share the name; for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order. -----Input----- The first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja. The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n - 1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding. It's guaranteed that there are no cyclic dependencies. -----Output----- Output all Polycarp's project's dependencies in lexicographical order. -----Examples----- Input 4 a 3 2 b 1 c 1   b 2 0   b 1 1 b 2   c 1 1 b 2 Output 2 b 1 c 1 Input 9 codehorses 5 3 webfrmk 6 mashadb 1 mashadb 2   commons 2 0   mashadb 3 0   webfrmk 6 2 mashadb 3 commons 2   extra 4 1 extra 3   extra 3 0   extra 1 0   mashadb 1 1 extra 3   mashadb 2 1 extra 1 Output 4 commons 2 extra 1 mashadb 2 webfrmk 6 Input 3 abc 1 2 abc 3 cba 2 abc 3 0 cba 2 0 Output 1 cba 2 -----Note----- The first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «a» (version 3) depends on are painted black. [Image] The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «codehorses» (version 5) depends on are paint it black. Note that «extra 1» is chosen instead of «extra 3» since «mashadb 1» and all of its dependencies are ignored due to «mashadb 2». [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from collections import defaultdict n=int(input()) d=defaultdict(dict) for i in range(n): x=input() x=x.split() if i==0: P = x q=int(input()) Con=[] for j in range(q): Con.append(input().split()) if i!=n-1: input() d[x[0]][x[1]]=Con ver=[P] ans={} while ver: next_ans = {} for v in ver: C=d[v[0]][v[1]] for n_v in C: if n_v[0] not in ans and n_v[0]!=P[0]: if n_v[0] in next_ans: if int(n_v[1])>int(next_ans[n_v[0]]): next_ans[n_v[0]]=n_v[1] else: next_ans[n_v[0]]=n_v[1] ans.update(next_ans) ver=list(next_ans.items()) l=list(ans.items()) print(len(l)) l.sort() for k,v in l: print(k,v) ```
vfc_16702
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/928/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\na 3\n2\nb 1\nc 1\n\nb 2\n0\n\nb 1\n1\nb 2\n\nc 1\n1\nb 2\n", "output": "2\nb 1\nc 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "9\ncodehorses 5\n3\nwebfrmk 6\nmashadb 1\nmashadb 2\n\ncommons 2\n0\n\nmashadb 3\n0\n\nwebfrmk 6\n2\nmashadb 3\ncommons 2\n\nextra 4\n1\nextra 3\n\nextra 3\n0\n\nextra 1\n0\n\nmashadb 1\n1\nextra 3\n\nmashadb 2\n1\nextra 1\n", "output": "4\ncommons 2\nextra 1\nmashadb 2\nwebfrmk 6\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1738
Solve the following coding problem using the programming language python: Ivan wants to write a letter to his friend. The letter is a string s consisting of lowercase Latin letters. Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string s instead of the string itself. The compressed version of string s is a sequence of strings c_1, s_1, c_2, s_2, ..., c_{k}, s_{k}, where c_{i} is the decimal representation of number a_{i} (without any leading zeroes) and s_{i} is some string consisting of lowercase Latin letters. If Ivan writes string s_1 exactly a_1 times, then string s_2 exactly a_2 times, and so on, the result will be string s. The length of a compressed version is |c_1| + |s_1| + |c_2| + |s_2|... |c_{k}| + |s_{k}|. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length. -----Input----- The only line of input contains one string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 8000). -----Output----- Output one integer number — the minimum possible length of a compressed version of s. -----Examples----- Input aaaaaaaaaa Output 3 Input abcab Output 6 Input cczabababab Output 7 -----Note----- In the first example Ivan will choose this compressed version: c_1 is 10, s_1 is a. In the second example Ivan will choose this compressed version: c_1 is 1, s_1 is abcab. In the third example Ivan will choose this compressed version: c_1 is 2, s_1 is c, c_2 is 1, s_2 is z, c_3 is 4, s_3 is ab. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def prefix(s): p = [0] for i in range(1, len(s)): j = p[-1] while j > 0 and s[j] != s[i]: j = p[j - 1] if s[i] == s[j]: j += 1 p.append(j) return p s = input() n = len(s) ans = [0] * (n + 1) i = n - 1 while i >= 0: p = prefix(s[i:]) ans[i] = 2 + ans[i + 1] for j in range(len(p)): z = 1 if (j + 1) % (j + 1 - p[j]) == 0: z = (j + 1) // (j + 1 - p[j]) res = len(str(z)) + (j + 1) // z + ans[i + j + 1] ans[i] = min(ans[i], res) i -= 1 print(ans[0]) ```
vfc_16706
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/825/F", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "aaaaaaaaaa\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "abcab\n", "output": "6\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "cczabababab\n", "output": "7\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "kbyjorwqjk\n", "output": "11\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "baaabbbaba\n", "output": "9\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "aaaaaaaaaa\n", "output": "3\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1739
Solve the following coding problem using the programming language python: Simon has a prime number x and an array of non-negative integers a_1, a_2, ..., a_{n}. Simon loves fractions very much. Today he wrote out number $\frac{1}{x^{a} 1} + \frac{1}{x^{a_{2}}} + \ldots + \frac{1}{x^{a_{n}}}$ on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: $\frac{s}{t}$, where number t equals x^{a}_1 + a_2 + ... + a_{n}. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (10^9 + 7). -----Input----- The first line contains two positive integers n and x (1 ≤ n ≤ 10^5, 2 ≤ x ≤ 10^9) — the size of the array and the prime number. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n} ≤ 10^9). -----Output----- Print a single number — the answer to the problem modulo 1000000007 (10^9 + 7). -----Examples----- Input 2 2 2 2 Output 8 Input 3 3 1 2 3 Output 27 Input 2 2 29 29 Output 73741817 Input 4 5 0 0 0 0 Output 1 -----Note----- In the first sample $\frac{1}{4} + \frac{1}{4} = \frac{4 + 4}{16} = \frac{8}{16}$. Thus, the answer to the problem is 8. In the second sample, $\frac{1}{3} + \frac{1}{9} + \frac{1}{27} = \frac{243 + 81 + 27}{729} = \frac{351}{729}$. The answer to the problem is 27, as 351 = 13·27, 729 = 27·27. In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817. In the fourth sample $\frac{1}{1} + \frac{1}{1} + \frac{1}{1} + \frac{1}{1} = \frac{4}{1}$. Thus, the answer to the problem is 1. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, x = map(int, input().split()) a = [int(x) for x in input().split()] def solve(a, s): #print (a) a.append((-1, 0)) a.sort() b = [] for i in range(1, len(a)): if a[i][0] != a[i-1][0]: b.append(a[i]) else: b[-1] = (a[i][0], b[-1][1] + a[i][1]) for i in range(len(b)): t = b[i][1] cnt = 0 while t%x == 0: t //= x cnt += 1 b[i] = (b[i][0] + cnt, t) #print (b) z = min(min(b)[0], s) if z == 0: return 0 return z + solve([(x[0]-z, x[1]) for x in b], s-z) s = sum(a) print(pow(x, solve([(s-x, 1) for x in a], s), 10**9+7)) ```
vfc_16710
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/359/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 2\n2 2\n", "output": "8\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 3\n1 2 3\n", "output": "27\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 2\n29 29\n", "output": "73741817\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 5\n0 0 0 0\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1740
Solve the following coding problem using the programming language python: Asya loves animals very much. Recently, she purchased $n$ kittens, enumerated them from $1$ and $n$ and then put them into the cage. The cage consists of one row of $n$ cells, enumerated with integers from $1$ to $n$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $n - 1$ partitions originally. Initially, each cell contained exactly one kitten with some number. Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $i$, Asya: Noticed, that the kittens $x_i$ and $y_i$, located in neighboring cells want to play together. Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after $n - 1$ days the cage contained a single cell, having all kittens. For every day, Asya remembers numbers of kittens $x_i$ and $y_i$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $n$ cells. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 150\,000$) — the number of kittens. Each of the following $n - 1$ lines contains integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$) — indices of kittens, which got together due to the border removal on the corresponding day. It's guaranteed, that the kittens $x_i$ and $y_i$ were in the different cells before this day. -----Output----- For every cell from $1$ to $n$ print a single integer — the index of the kitten from $1$ to $n$, who was originally in it. All printed integers must be distinct. It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them. -----Example----- Input 5 1 4 2 5 3 1 4 5 Output 3 1 4 2 5 -----Note----- The answer for the example contains one of several possible initial arrangements of the kittens. The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells. [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline n=int(input()) P=[list(map(int,input().split())) for i in range(n-1)] Group=[i for i in range(n+1)] def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): Group[find(y)]=Group[find(x)]=min(find(y),find(x)) ANS=[[i] for i in range(n+1)] for i,j in P: if find(j)<find(i): ANS[find(j)]+=ANS[find(i)] else: ANS[find(i)]+=ANS[find(j)] Union(i,j) for a in ANS[1]: print(a,end=" ") ```
vfc_16714
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1131/F", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 4\n2 5\n3 1\n4 5\n", "output": "3 1 4 2 5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n1 2\n", "output": "1 2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n2 1\n", "output": "2 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n1 2\n2 3\n", "output": "3 1 2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n3 1\n2 3\n", "output": "2 3 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n3 1\n2 1\n", "output": "2 3 1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1741
Solve the following coding problem using the programming language python: There is a forest that we model as a plane and live $n$ rare animals. Animal number $i$ has its lair in the point $(x_{i}, y_{i})$. In order to protect them, a decision to build a nature reserve has been made. The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river. For convenience, scientists have made a transformation of coordinates so that the river is defined by $y = 0$. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve. -----Input----- The first line contains one integer $n$ ($1 \le n \le 10^5$) — the number of animals. Each of the next $n$ lines contains two integers $x_{i}$, $y_{i}$ ($-10^7 \le x_{i}, y_{i} \le 10^7$) — the coordinates of the $i$-th animal's lair. It is guaranteed that $y_{i} \neq 0$. No two lairs coincide. -----Output----- If the reserve cannot be built, print $-1$. Otherwise print the minimum radius. Your answer will be accepted if absolute or relative error does not exceed $10^{-6}$. Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$. -----Examples----- Input 1 0 1 Output 0.5 Input 3 0 1 0 2 0 -3 Output -1 Input 2 0 1 1 1 Output 0.625 -----Note----- In the first sample it is optimal to build the reserve with the radius equal to $0.5$ and the center in $(0,\ 0.5)$. In the second sample it is impossible to build a reserve. In the third sample it is optimal to build the reserve with the radius equal to $\frac{5}{8}$ and the center in $(\frac{1}{2},\ \frac{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 sys input = sys.stdin.readline class Point: def __init__(self, x, y): self.x = x self.y = y def get(x0, a, n): r = 0 for i in range(n): p = (x0 - a[i].x)*(x0 - a[i].x) + 1.0*a[i].y*a[i].y p = p/2.0/a[i].y if p < 0: p = -p r = max(r, p) return r def main(): n = int(input()) pos, neg = False, False a = [] for i in range(n): x, y = map(int, input().split()) t = Point(x, y) if t.y > 0: pos = True else: neg = True a.append(t) if pos and neg: return -1 if neg: for i in range(n): a[i].y = -a[i].y L, R = -1e8, 1e8 for i in range(120): x1 = L + (R-L)/3 x2 = R - (R-L)/3 if get(x1, a, n) < get(x2, a, n): R = x2 else: L = x1 return get(L, a, n) def __starting_point(): print(main()) __starting_point() ```
vfc_16718
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1059/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "1\n0 1\n", "output": "0.4999999998750000\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n0 1\n0 2\n0 -3\n", "output": "-1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n0 1\n1 1\n", "output": "0.6249999997500000\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1742
Solve the following coding problem using the programming language python: At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils. Formally, there are some pairs $u$, $v$ such that if the pupil with number $u$ stands directly in front of the pupil with number $v$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward. -----Input----- The first line contains two integers $n$ and $m$ ($1 \leq n \leq 3 \cdot 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $n$ integers $p_1$, $p_2$, ..., $p_n$ — the initial arrangement of pupils in the queue, from the queue start to its end ($1 \leq p_i \leq n$, $p$ is a permutation of integers from $1$ to $n$). In other words, $p_i$ is the number of the pupil who stands on the $i$-th position in the queue. The $i$-th of the following $m$ lines contains two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), denoting that the pupil with number $u_i$ agrees to change places with the pupil with number $v_i$ if $u_i$ is directly in front of $v_i$. It is guaranteed that if $i \neq j$, than $v_i \neq v_j$ or $u_i \neq u_j$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $p_n$. -----Output----- Print a single integer — the number of places in queue she can move forward. -----Examples----- Input 2 1 1 2 1 2 Output 1 Input 3 3 3 1 2 1 2 3 1 3 2 Output 2 Input 5 2 3 1 5 4 2 5 2 5 4 Output 1 -----Note----- In the first example Nastya can just change places with the first pupil in the queue. Optimal sequence of changes in the second example is change places for pupils with numbers $1$ and $3$. change places for pupils with numbers $3$ and $2$. change places for pupils with numbers $1$ and $2$. The queue looks like $[3, 1, 2]$, then $[1, 3, 2]$, then $[1, 2, 3]$, and finally $[2, 1, 3]$ after these operations. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = list(map(int, input().split())) line = list(map(int, input().split())) pairs = set() for i in range(m): a, b = list(map(int, input().split())) pairs.add((a,b)) req = [line.pop()] out = 0 while line != []: nex = line.pop() works = True for pers in req: if not (nex, pers) in pairs: works = False break if works: out += 1 else: req.append(nex) print(out) ```
vfc_16722
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1136/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2 1\n1 2\n1 2\n", "output": "1", "type": "stdin_stdout" } ] }
apps
verifiable_code
1743
Solve the following coding problem using the programming language python: Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them? Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares. Help Inna maximize the total joy the hares radiate. :) -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a_1 a_2 ... a_{n}. The second line contains b_1, b_2, ..., b_{n}. The third line contains c_1, c_2, ..., c_{n}. The following limits are fulfilled: 0 ≤ a_{i}, b_{i}, c_{i} ≤ 10^5. Number a_{i} in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number b_{i} in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number с_{i} in the third line shows the joy that hare number i radiates if both his adjacent hares are full. -----Output----- In a single line, print the maximum possible total joy of the hares Inna can get by feeding them. -----Examples----- Input 4 1 2 3 4 4 3 2 1 0 1 1 0 Output 13 Input 7 8 5 7 6 1 8 9 2 7 9 5 4 3 1 2 3 3 4 1 1 3 Output 44 Input 3 1 1 1 1 2 1 1 1 1 Output 4 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()) a = list(map(int, input().split())) b = list(map(int, input().split())) c = list(map(int, input().split())) fed_left = {0 : a[0]} not_fed_left = {0 : b[0]} for i in range(1, n): fed_left[i] = max(fed_left[i-1] + b[i], not_fed_left[i-1] + a[i]) # max(fed left, fed right) not_fed_left[i] = max(fed_left[i-1] + c[i], not_fed_left[i-1] + b[i]) # max(fed left and right, fed right) print(fed_left[n-1]) ```
vfc_16726
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/358/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\n1 2 3 4\n4 3 2 1\n0 1 1 0\n", "output": "13\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3\n", "output": "44\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n1 1 1\n1 2 1\n1 1 1\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n1 3 8 9 3 4 4\n6 0 6 6 1 8 4\n9 6 3 7 8 8 2\n", "output": "42\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "2\n3 5\n9 8\n4 0\n", "output": "14\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1744
Solve the following coding problem using the programming language python: The only difference between easy and hard versions is constraints. If you write a solution in Python, then prefer to send it in PyPy to speed up execution time. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following: The $i$-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student. The duration of the whole exam for all students is $M$ minutes ($\max t_i \le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam. For each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to pass the exam. For each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home. -----Input----- The first line of the input contains two integers $n$ and $M$ ($1 \le n \le 2 \cdot 10^5$, $1 \le M \le 2 \cdot 10^7$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $n$ integers $t_i$ ($1 \le t_i \le 100$) — time in minutes that $i$-th student spends to answer to a ticket. It's guaranteed that all values of $t_i$ are not greater than $M$. -----Output----- Print $n$ numbers: the $i$-th number must be equal to the minimum number of students who have to leave the exam in order to $i$-th student has enough time to pass the exam. -----Examples----- Input 7 15 1 2 3 4 5 6 7 Output 0 0 0 0 0 2 3 Input 5 100 80 40 40 40 60 Output 0 1 1 2 3 -----Note----- The explanation for the example 1. Please note that the sum of the first five exam times does not exceed $M=15$ (the sum is $1+2+3+4+5=15$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $0$. In order for the $6$-th student to pass the exam, it is necessary that at least $2$ students must fail it before (for example, the $3$-rd and $4$-th, then the $6$-th will finish its exam in $1+2+5+6=14$ minutes, which does not exceed $M$). In order for the $7$-th student to pass the exam, it is necessary that at least $3$ students must fail it before (for example, the $2$-nd, $5$-th and $6$-th, then the $7$-th will finish its exam in $1+3+4+7=15$ minutes, which does not exceed $M$). The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys input = sys.stdin.readline n, M = list(map(int, input().split())) t = list(map(int, input().split())) ans = [] tmp = [0] * 101 for i in range(n): num = 0 T = t[i] for j in range(1, 101): if T + j * tmp[j] <= M: num += tmp[j] T += j * tmp[j] else: m = M - T num += m // j break ans.append(i - num) tmp[t[i]] += 1 print(*ans) ```
vfc_16730
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1185/C2", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "7 15\n1 2 3 4 5 6 7\n", "output": "0 0 0 0 0 2 3 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 100\n80 40 40 40 60\n", "output": "0 1 1 2 3 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1\n", "output": "0 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 20000000\n100\n", "output": "0 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 100\n100\n", "output": "0 ", "type": "stdin_stdout" } ] }
apps
verifiable_code
1745
Solve the following coding problem using the programming language python: On a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city. The city is an n × m rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are denoted by character '.', occupied squares are denoted by character '#'. The pipe must meet the following criteria: the pipe is a polyline of width 1, the pipe goes in empty squares, the pipe starts from the edge of the field, but not from a corner square, the pipe ends at the edge of the field but not in a corner square, the pipe has at most 2 turns (90 degrees), the border squares of the field must share exactly two squares with the pipe, if the pipe looks like a single segment, then the end points of the pipe must lie on distinct edges of the field, for each non-border square of the pipe there are exacly two side-adjacent squares that also belong to the pipe, for each border square of the pipe there is exactly one side-adjacent cell that also belongs to the pipe. Here are some samples of allowed piping routes: ....# ....# .*..# ***** ****. .***. ..#.. ..#*. ..#*. #...# #..*# #..*# ..... ...*. ...*. Here are some samples of forbidden piping routes: .**.# *...# .*.*# ..... ****. .*.*. ..#.. ..#*. .*#*. #...# #..*# #*.*# ..... ...*. .***. In these samples the pipes are represented by characters ' * '. You were asked to write a program that calculates the number of distinct ways to make exactly one pipe in the city. The two ways to make a pipe are considered distinct if they are distinct in at least one square. -----Input----- The first line of the input contains two integers n, m (2 ≤ n, m ≤ 2000) — the height and width of Berland map. Each of the next n lines contains m characters — the map of the city. If the square of the map is marked by character '.', then the square is empty and the pipe can through it. If the square of the map is marked by character '#', then the square is full and the pipe can't through it. -----Output----- In the first line of the output print a single integer — the number of distinct ways to create a pipe. -----Examples----- Input 3 3 ... ..# ... Output 3 Input 4 2 .. .. .. .. Output 2 Input 4 5 #...# #...# ###.# ###.# Output 4 -----Note----- In the first sample there are 3 ways to make a pipe (the squares of the pipe are marked by characters ' * '): .*. .*. ... .*# **# **# .*. ... .*. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, m = [int(x) for x in input().split()] a = [[int(c == '.') for c in input()] for i in range(n)] def rotate(a): n = len(a) m = len(a[0]) b = [[0] * n for i in range(m)] for i in range(n): for j in range(m): b[j][n - 1 - i] = a[i][j] return b def calc(a): n = len(a) m = len(a[0]) alive = a[0][:] alive[0], alive[m - 1] = 0, 0 ans_l, ans_r, ans_u = 0, 0, 0 ans_bs = [0] * m for i in range(1, n - 1): s = 0 for j in range(1, m - 1): if a[i][j]: if alive[j]: ans_u += s - alive[j - 1] ans_bs[j] += s s += alive[j] else: s = 0 ans_bs[j] = 0 alive[j] = 0 if a[i][m - 1]: ans_r += s s = 0 for j in range(m - 2, 0, -1): if a[i][j]: if alive[j]: ans_u += s - alive[j + 1] ans_bs[j] += s s += alive[j] else: s = 0 ans_bs[j] = 0 alive[j] = 0 if a[i][0]: ans_l += s ans_u //= 2 ans_b = sum(a[n - 1][i] * (ans_bs[i] + alive[i]) for i in range(1, m - 1)) return ans_l, ans_r, ans_u, ans_b ans = 0 ans_l, ans_r, ans_u, ans_b = calc(a) ans += ans_l + ans_r + ans_u + ans_b a = rotate(a) ans_l, _, ans_u, ans_b = calc(a) ans += ans_l + ans_u + ans_b a = rotate(a) ans_l, _, ans_u, _= calc(a) ans += ans_l + ans_u a = rotate(a) _, _, ans_u, _= calc(a) ans += ans_u print(ans) ```
vfc_16734
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/518/F", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 3\n...\n..#\n...\n", "output": "3\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 2\n..\n..\n..\n..\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 5\n#...#\n#...#\n###.#\n###.#\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 4\n####\n####\n....\n####\n####\n####\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 6\n######\n######\n......\n######\n", "output": "1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1746
Solve the following coding problem using the programming language python: Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent. Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce. The definition of a rooted tree can be found here. -----Input----- The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer p_{i} (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ p_{i} ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children. -----Output----- Print "Yes" if the tree is a spruce and "No" otherwise. -----Examples----- Input 4 1 1 1 Output Yes Input 7 1 1 1 2 2 2 Output No Input 8 1 1 1 1 3 3 3 Output Yes -----Note----- The first example: [Image] The second example: $8$ It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children. The third example: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python #!/usr/bin/env python3 def main(): class Node: def __init__(self): self.children = [ ] n = int(input()) nodes = [Node() for i in range(n)] for i in range(1, n): p = int(input()) nodes[p - 1].children.append(nodes[i]) ok = all( len([child for child in node.children if not child.children]) >= 3 for node in nodes if node.children ) print("Yes" if ok else "No") try: while True: main() except EOFError: pass ```
vfc_16738
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/913/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\n1\n1\n1\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n1\n1\n1\n2\n2\n2\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "8\n1\n1\n1\n1\n3\n3\n3\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n1\n1\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "13\n1\n2\n2\n2\n1\n6\n6\n6\n1\n10\n10\n10\n", "output": "No\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1747
Solve the following coding problem using the programming language python: The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values. Find any longest k-good segment. As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. -----Input----- The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·10^5) — the number of elements in a and the parameter k. The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^6) — the elements of the array a. -----Output----- Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right. -----Examples----- Input 5 5 1 2 3 4 5 Output 1 5 Input 9 3 6 5 1 2 3 2 1 4 5 Output 3 7 Input 3 1 1 2 3 Output 1 1 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, m = list(map(int, sys.stdin.readline().split())) vis = [0] * 1000005 num = list(map(int, sys.stdin.readline().split())) flag = 0 temp = num[0] for i in range(n): if num[i] != temp: flag = 1 break if flag == 0: print("{0} {1}".format(1, n)) else: l = 0 r = 0 al = 0 ar = 0 ans = 0 now = 0 for i in range(n): vis[num[i]] += 1 if vis[num[i]] == 1: now += 1 while now > m: vis[num[l]] -= 1 if vis[num[l]] == 0: now -= 1 l += 1 if i - l + 1 > ar - al + 1: ar = i al = l print('{0} {1}'.format(al+1, ar+1)) ```
vfc_16742
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/616/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 5\n1 2 3 4 5\n", "output": "1 5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "9 3\n6 5 1 2 3 2 1 4 5\n", "output": "3 7\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 1\n1 2 3\n", "output": "1 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n747391\n", "output": "1 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 2\n171230 171230 171230 171230 171230\n", "output": "1 5\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1748
Solve the following coding problem using the programming language python: Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume V_{i} and put it in her garden. Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is T_{i}, each pile will reduce its volume by T_{i}. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other. Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day. You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day. -----Input----- The first line contains a single integer N (1 ≤ N ≤ 10^5) — the number of days. The second line contains N integers V_1, V_2, ..., V_{N} (0 ≤ V_{i} ≤ 10^9), where V_{i} is the initial size of a snow pile made on the day i. The third line contains N integers T_1, T_2, ..., T_{N} (0 ≤ T_{i} ≤ 10^9), where T_{i} is the temperature on the day i. -----Output----- Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i. -----Examples----- Input 3 10 10 5 5 7 2 Output 5 12 4 Input 5 30 25 20 15 10 9 10 12 4 13 Output 9 20 35 11 25 -----Note----- In the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day. 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()) vs = [int(x) for x in input().split()] ts = [int(x) for x in input().split()] sumt = 0 for i, t in enumerate(ts): vs[i]+=sumt sumt+=t vs.sort() tl, tr = 0, 0 il, ir = 0, 0 for ind, t in enumerate(ts): #check tl = tr tr += t while ir < n and vs[ir] <= tr: ir += 1 cur_sum = 0 while il < ir: cur_sum += vs[il]-tl il+=1 ## print(ir, tl, tr, cur_sum) cur_sum += t * ((n-ir) - (n-ind-1)) print(cur_sum, end=" ") ```
vfc_16746
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/923/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n10 10 5\n5 7 2\n", "output": "5 12 4\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1750
Solve the following coding problem using the programming language python: Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them. The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct. Andryusha wants to use as little different colors as possible. Help him to choose the colors! -----Input----- The first line contains single integer n (3 ≤ n ≤ 2·10^5) — the number of squares in the park. Each of the next (n - 1) lines contains two integers x and y (1 ≤ x, y ≤ n) — the indices of two squares directly connected by a path. It is guaranteed that any square is reachable from any other using the paths. -----Output----- In the first line print single integer k — the minimum number of colors Andryusha has to use. In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k. -----Examples----- Input 3 2 3 1 3 Output 3 1 3 2 Input 5 2 3 5 3 4 3 1 3 Output 5 1 3 2 5 4 Input 5 2 1 3 2 4 3 5 4 Output 3 1 2 3 1 2 -----Note----- In the first sample the park consists of three squares: 1 → 3 → 2. Thus, the balloon colors have to be distinct. [Image] Illustration for the first sample. In the second example there are following triples of consequently connected squares: 1 → 3 → 2 1 → 3 → 4 1 → 3 → 5 2 → 3 → 4 2 → 3 → 5 4 → 3 → 5 We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. [Image] Illustration for the second sample. In the third example there are following triples: 1 → 2 → 3 2 → 3 → 4 3 → 4 → 5 We can see that one or two colors is not enough, but there is an answer that uses three colors only. [Image] Illustration for the third sample. 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(200000) n = int(input()) arr = [[] for i in range(n)] for i in range(n - 1): a, b = map(int, input().split()) arr[a - 1].append(b - 1) arr[b - 1].append(a - 1) s = max([len(p) for p in arr]) + 1 print(s) colored = [0] * n def dfs(v, c, d): colored[v] = p = c for u in arr[v]: if not colored[u]: c = c + 1 if c < s else 1 if c == d: c = c + 1 if c < s else 1 dfs(u, c, p) if s > 3: dfs(0, 1, 0) else: i = 0 c = 1 while len(arr[i]) != 1: i += 1 for j in range(n): colored[i] = c c = c + 1 if c < s else 1 if j < n - 1: i = arr[i][0] if not colored[arr[i][0]] else arr[i][1] print(" ".join(map(str, colored))) ```
vfc_16754
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/780/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n2 3\n1 3\n", "output": "3\n1 3 2 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "5\n2 3\n5 3\n4 3\n1 3\n", "output": "5\n1 3 2 5 4 ", "type": "stdin_stdout" } ] }
apps
verifiable_code
1751
Solve the following coding problem using the programming language python: A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). Consider a permutation $p$ of length $n$, we build a graph of size $n$ using it as follows: For every $1 \leq i \leq n$, find the largest $j$ such that $1 \leq j < i$ and $p_j > p_i$, and add an undirected edge between node $i$ and node $j$ For every $1 \leq i \leq n$, find the smallest $j$ such that $i < j \leq n$ and $p_j > p_i$, and add an undirected edge between node $i$ and node $j$ In cases where no such $j$ exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices. For clarity, consider as an example $n = 4$, and $p = [3,1,4,2]$; here, the edges of the graph are $(1,3),(2,1),(2,3),(4,3)$. A permutation $p$ is cyclic if the graph built using $p$ has at least one simple cycle. Given $n$, find the number of cyclic permutations of length $n$. Since the number may be very large, output it modulo $10^9+7$. Please refer to the Notes section for the formal definition of a simple cycle -----Input----- The first and only line contains a single integer $n$ ($3 \le n \le 10^6$). -----Output----- Output a single integer $0 \leq x < 10^9+7$, the number of cyclic permutations of length $n$ modulo $10^9+7$. -----Examples----- Input 4 Output 16 Input 583291 Output 135712853 -----Note----- There are $16$ cyclic permutations for $n = 4$. $[4,2,1,3]$ is one such permutation, having a cycle of length four: $4 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 4$. Nodes $v_1$, $v_2$, $\ldots$, $v_k$ form a simple cycle if the following conditions hold: $k \geq 3$. $v_i \neq v_j$ for any pair of indices $i$ and $j$. ($1 \leq i < j \leq k$) $v_i$ and $v_{i+1}$ share an edge for all $i$ ($1 \leq i < k$), and $v_1$ and $v_k$ share an edge. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python MOD = 10 ** 9 + 7 out = 1 n = int(input()) for i in range(n): out *= (i + 1) out %= MOD out -= pow(2, n - 1, MOD) print(out % MOD) ```
vfc_16758
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1391/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\n", "output": "16", "type": "stdin_stdout" }, { "fn_name": null, "input": "583291\n", "output": "135712853", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n", "output": "2", "type": "stdin_stdout" }, { "fn_name": null, "input": "1000000\n", "output": "23581336", "type": "stdin_stdout" }, { "fn_name": null, "input": "66\n", "output": "257415584", "type": "stdin_stdout" }, { "fn_name": null, "input": "33\n", "output": "762187807", "type": "stdin_stdout" } ] }
apps
verifiable_code
1752
Solve the following coding problem using the programming language python: Cowboy Vlad has a birthday today! There are $n$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible. Formally, let's number children from $1$ to $n$ in a circle order, that is, for every $i$ child with number $i$ will stand next to the child with number $i+1$, also the child with number $1$ stands next to the child with number $n$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other. Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible. -----Input----- The first line contains a single integer $n$ ($2 \leq n \leq 100$) — the number of the children who came to the cowboy Vlad's birthday. The second line contains integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) denoting heights of every child. -----Output----- Print exactly $n$ integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them. -----Examples----- Input 5 2 1 1 3 2 Output 1 2 3 2 1 Input 3 30 10 20 Output 10 20 30 -----Note----- In the first example, the discomfort of the circle is equal to $1$, since the corresponding absolute differences are $1$, $1$, $1$ and $0$. Note, that sequences $[2, 3, 2, 1, 1]$ and $[3, 2, 1, 1, 2]$ form the same circles and differ only by the selection of the starting point. In the second example, the discomfort of the circle is equal to $20$, since the absolute difference of $10$ and $30$ is equal to $20$. 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()) a = list(map(int,input().split())) a = sorted(a) out = [0 for x in range(n)] if n%2: out[n//2] = a[-1] for x in range(n//2): out[x] = a[x*2] out[-(1+x)] = a[(x*2)+1] print (" ".join(str(c) for c in out)) ```
vfc_16762
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1131/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n2 1 1 3 2\n", "output": "1 2 3 2 1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n30 10 20\n", "output": "10 30 20\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1755
Solve the following coding problem using the programming language python: You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$. In one operation, you may choose two integers $i$ and $x$ ($1 \le i \le n$, $x$ can be any integer) and assign $a_i := x$. This operation can be done only if $i$ does not belong to the set $b$. Calculate the minimum number of operations you should perform so the array $a$ is increasing (that is, $a_1 < a_2 < a_3 < \dots < a_n$), or report that it is impossible. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le n \le 5 \cdot 10^5$, $0 \le k \le n$) — the size of the array $a$ and the set $b$, respectively. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$). Then, if $k \ne 0$, the third line follows, containing $k$ integers $b_1$, $b_2$, ..., $b_k$ ($1 \le b_1 < b_2 < \dots < b_k \le n$). If $k = 0$, this line is skipped. -----Output----- If it is impossible to make the array $a$ increasing using the given operations, print $-1$. Otherwise, print one integer — the minimum number of operations you have to perform. -----Examples----- Input 7 2 1 2 1 1 3 5 1 3 5 Output 4 Input 3 3 1 3 2 1 2 3 Output -1 Input 5 0 4 3 1 2 3 Output 2 Input 10 3 1 3 5 6 12 9 8 10 13 15 2 4 9 Output 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 from sys import stdin import bisect def LIS(lis , end): seq = [] for c in lis: ind = bisect.bisect_right(seq,c) if ind == len(seq): seq.append(c) else: if ind != 0: seq[ind] = c return bisect.bisect_right(seq,end) tt = 1 for loop in range(tt): n,k = list(map(int,stdin.readline().split())) a = list(map(int,stdin.readline().split())) b = list(map(int,stdin.readline().split())) a = [float("-inf")] + a + [float("inf")] b = [0] + b + [n+1] for i in range(n+2): a[i] -= i for i in range(len(b)-1): if a[b[i]] > a[b[i+1]]: print(-1) return ans = n+1 for i in range(len(b)-1): now = LIS(a[ b[i]:b[i+1] ] , a[b[i+1]]) ans -= now print (ans) ```
vfc_16774
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1437/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "7 2\n1 2 1 1 3 5 1\n3 5\n", "output": "4\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1756
Solve the following coding problem using the programming language python: You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of days you will spend visiting your friend. You will spend exactly $x$ consecutive (successive) days visiting Coronavirus-chan. They use a very unusual calendar in Naha: there are $n$ months in a year, $i$-th month lasts exactly $d_i$ days. Days in the $i$-th month are numbered from $1$ to $d_i$. There are no leap years in Naha. The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get $j$ hugs if you visit Coronavirus-chan on the $j$-th day of the month. You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan). Please note that your trip should not necessarily begin and end in the same year. -----Input----- The first line of input contains two integers $n$ and $x$ ($1 \le n \le 2 \cdot 10^5$) — the number of months in the year and the number of days you can spend with your friend. The second line contains $n$ integers $d_1, d_2, \ldots, d_n$, $d_i$ is the number of days in the $i$-th month ($1 \le d_i \le 10^6$). It is guaranteed that $1 \le x \le d_1 + d_2 + \ldots + d_n$. -----Output----- Print one integer — the maximum number of hugs that you can get from Coronavirus-chan during the best vacation in your life. -----Examples----- Input 3 2 1 3 1 Output 5 Input 3 6 3 3 3 Output 12 Input 5 6 4 2 3 1 3 Output 15 -----Note----- In the first test case, the numbers of the days in a year are (indices of days in a corresponding month) $\{1,1,2,3,1\}$. Coronavirus-chan will hug you the most if you come on the third day of the year: $2+3=5$ hugs. In the second test case, the numbers of the days are $\{1,2,3,1,2,3,1,2,3\}$. You will get the most hugs if you arrive on the third day of the year: $3+1+2+3+1+2=12$ hugs. In the third test case, the numbers of the days are $\{1,2,3,4,1,2, 1,2,3, 1, 1,2,3\}$. You will get the most hugs if you come on the twelfth day of the year: your friend will hug you $2+3+1+2+3+4=15$ times. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def sum_first(di): return di * (di + 1) // 2 n, x = list(map(int, input().split())) n *= 2 d = tuple(map(int, input().split())) * 2 ans = 0 i = 0 j = 0 cur_ans = 0 total_days = 0 while j <= n: if total_days < x: if j == n: break cur_ans += sum_first(d[j]) total_days += d[j] j += 1 else: ans = max(ans, cur_ans - sum_first(total_days - x)) cur_ans -= sum_first(d[i]) total_days -= d[i] i += 1 print(ans) ```
vfc_16778
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1358/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 2\n1 3 1\n", "output": "5", "type": "stdin_stdout" } ] }
apps
verifiable_code
1757
Solve the following coding problem using the programming language python: Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. [Image] Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where f_1 = 1, f_2 = 1, f_{n} = f_{n} - 2 + f_{n} - 1 (n > 2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name. -----Input----- The first and only line of input contains an integer n (1 ≤ n ≤ 1000). -----Output----- Print Eleven's new name on the first and only line of output. -----Examples----- Input 8 Output OOOoOooO Input 15 Output OOOoOooOooooOoo The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python d = [1, 1] n = int(input()) while d[-1] < n: d.append(d[-1] + d[-2]) s = set(d) res = '' for i in range(1, n + 1): if i in s: res += 'O' else: res += 'o' print(res) ```
vfc_16782
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/918/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "8\n", "output": "OOOoOooO\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "15\n", "output": "OOOoOooOooooOoo\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "85\n", "output": "OOOoOooOooooOoooooooOooooooooooooOooooooooooooooooooooOoooooooooooooooooooooooooooooo\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1758
Solve the following coding problem using the programming language python: Naman has two binary strings $s$ and $t$ of length $n$ (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert $s$ into $t$ using the following operation as few times as possible. In one operation, he can choose any subsequence of $s$ and rotate it clockwise once. For example, if $s = 1\textbf{1}101\textbf{00}$, he can choose a subsequence corresponding to indices ($1$-based) $\{2, 6, 7 \}$ and rotate them clockwise. The resulting string would then be $s = 1\textbf{0}101\textbf{10}$. A string $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the ordering of the remaining characters. To perform a clockwise rotation on a sequence $c$ of size $k$ is to perform an operation which sets $c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$ simultaneously. Determine the minimum number of operations Naman has to perform to convert $s$ into $t$ or say that it is impossible. -----Input----- The first line contains a single integer $n$ $(1 \le n \le 10^6)$ — the length of the strings. The second line contains the binary string $s$ of length $n$. The third line contains the binary string $t$ of length $n$. -----Output----- If it is impossible to convert $s$ to $t$ after any number of operations, print $-1$. Otherwise, print the minimum number of operations required. -----Examples----- Input 6 010000 000001 Output 1 Input 10 1111100000 0000011111 Output 5 Input 8 10101010 01010101 Output 1 Input 10 1111100000 1111100001 Output -1 -----Note----- In the first test, Naman can choose the subsequence corresponding to indices $\{2, 6\}$ and rotate it once to convert $s$ into $t$. In the second test, he can rotate the subsequence corresponding to all indices $5$ times. It can be proved, that it is the minimum required number of operations. In the last test, it is impossible to convert $s$ into $t$. 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()) s = input() t = input() curr = 0 currs = [] for i in range(n): if s[i] == '1': curr += 1 if t[i] == '1': curr -= 1 currs.append(curr) if curr != 0: print(-1) else: print(max(currs)-min(currs)) ```
vfc_16786
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1370/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "6\n010000\n000001\n", "output": "1", "type": "stdin_stdout" }, { "fn_name": null, "input": "10\n1111100000\n0000011111\n", "output": "5", "type": "stdin_stdout" }, { "fn_name": null, "input": "8\n10101010\n01010101\n", "output": "1", "type": "stdin_stdout" }, { "fn_name": null, "input": "10\n1111100000\n1111100001\n", "output": "-1", "type": "stdin_stdout" } ] }
apps
verifiable_code
1759
Solve the following coding problem using the programming language python: A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter t_{ij} units of time. Order is important everywhere, so the painters' work is ordered by the following rules: Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n); each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale. -----Input----- The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers t_{i}1, t_{i}2, ..., t_{in} (1 ≤ t_{ij} ≤ 1000), where t_{ij} is the time the j-th painter needs to work on the i-th picture. -----Output----- Print the sequence of m integers r_1, r_2, ..., r_{m}, where r_{i} is the moment when the n-th painter stopped working on the i-th picture. -----Examples----- Input 5 1 1 2 3 4 5 Output 1 3 6 10 15 Input 4 2 2 5 3 1 5 3 10 1 Output 7 8 13 21 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Codeforces Round 241 Div 1 Problem B Author : chaotic_iak Language: Python 3.3.4 """ class InputHandlerObject(object): inputs = [] def getInput(self, n = 0): res = "" inputs = self.inputs if not inputs: inputs.extend(input().split(" ")) if n == 0: res = inputs[:] inputs[:] = [] while n > len(inputs): inputs.extend(input().split(" ")) if n > 0: res = inputs[:n] inputs[:n] = [] return res InputHandler = InputHandlerObject() g = InputHandler.getInput ############################## SOLUTION ############################## m,n = [int(x) for x in g()] q = [] for i in range(m): q.append([int(x) for x in g()]) p = q[:] for j in range(n): for i in range(m): if i == 0 and j == 0: continue if i == 0: p[i][j] = p[i][j-1] + q[i][j] continue if j == 0: p[i][j] = p[i-1][j] + q[i][j] continue p[i][j] = max(p[i-1][j], p[i][j-1]) + q[i][j] for i in range(m): print(p[i][n-1], end=" ") ```
vfc_16790
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/416/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 1\n1\n2\n3\n4\n5\n", "output": "1 3 6 10 15 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 2\n2 5\n3 1\n5 3\n10 1\n", "output": "7 8 13 21 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n66\n", "output": "66 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 2\n1 1\n1 1\n", "output": "2 3 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "2 2\n10 1\n10 1\n", "output": "11 21 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 5\n1 95 44 14 35\n", "output": "189 ", "type": "stdin_stdout" } ] }
apps
verifiable_code
1760
Solve the following coding problem using the programming language python: The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs. The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest step has number 1, and the highest step has number n. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction "up" changes to "down", the direction "down"  —  to the direction "up". Olga always moves to the next step in the direction which is shown on the pointer above the step. If Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the n-th) step. In one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second. For each step find the duration of the dream if Olga was at this step at the beginning of the dream. Olga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second. -----Input----- The first line contains single integer n (1 ≤ n ≤ 10^6) — the number of steps on the stairs. The second line contains a string s with the length n — it denotes the initial direction of pointers on the stairs. The i-th character of string s denotes the direction of the pointer above i-th step, and is either 'U' (it means that this pointer is directed up), or 'D' (it means this pointed is directed down). The pointers are given in order from bottom to top. -----Output----- Print n numbers, the i-th of which is equal either to the duration of Olga's dream or to - 1 if Olga never goes beyond the stairs, if in the beginning of sleep she was on the i-th step. -----Examples----- Input 3 UUD Output 5 6 3 Input 10 UUDUDUUDDU Output 5 12 23 34 36 27 18 11 6 1 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()) string = input() q1,q2,B,C=[],[],[],[] A=0 for i in range(n): if string[i] == "D": q1.append(i) else: q2.append(n-1-i) for i in range(len(q1)): A+=(q1[i]-i)*2+1 B.append(A) A=0 temp = [] for i in range(len(q2)): A+=(q2[len(q2)-1-i]-i)*2+1 C.append(A) C.reverse() B=list(map(str,B+C)) print(" ".join(B)) ```
vfc_16794
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/733/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\nUUD\n", "output": "5 6 3 ", "type": "stdin_stdout" }, { "fn_name": null, "input": "10\nUUDUDUUDDU\n", "output": "5 12 23 34 36 27 18 11 6 1 ", "type": "stdin_stdout" } ] }
apps
verifiable_code
1761
Solve the following coding problem using the programming language python: Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word_1<3word_2<3 ... word_{n}<3. Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message. Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 10^5. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 10^5. A text message can contain only small English letters, digits and signs more and less. -----Output----- In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise. -----Examples----- Input 3 i love you <3i<3love<23you<3 Output yes Input 7 i am not main in the family <3i<>3am<3the<3<main<3in<3the<3><3family<3 Output no -----Note----- Please note that Dima got a good old kick in the pants for the second sample from the statement. 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()) arr = [] for i in range(n): s = input() arr.append('<') arr.append('3') for j in range(len(s)): arr.append(s[j]) arr.append('<') arr.append('3') s = input() cur = 0 i = 0 while cur < len(s) and i < len(arr): if s[cur] == arr[i]: i+=1 cur+=1 if i == len(arr): print('yes') else: print('no') ```
vfc_16798
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/358/B", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\ni\nlove\nyou\n<3i<3love<23you<3\n", "output": "yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3\n", "output": "no\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1762
Solve the following coding problem using the programming language python: A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network. We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video. We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video. For each video find the moment it stops being recompressed. -----Input----- The first line of the input contains integers n and k (1 ≤ n, k ≤ 5·10^5) — the number of videos and servers, respectively. Next n lines contain the descriptions of the videos as pairs of integers s_{i}, m_{i} (1 ≤ s_{i}, m_{i} ≤ 10^9), where s_{i} is the time in seconds when the i-th video appeared and m_{i} is its duration in minutes. It is guaranteed that all the s_{i}'s are distinct and the videos are given in the chronological order of upload, that is in the order of increasing s_{i}. -----Output----- Print n numbers e_1, e_2, ..., e_{n}, where e_{i} is the time in seconds after the servers start working, when the i-th video will be recompressed. -----Examples----- Input 3 2 1 5 2 5 3 5 Output 6 7 11 Input 6 1 1 1000000000 2 1000000000 3 1000000000 4 1000000000 5 1000000000 6 3 Output 1000000001 2000000001 3000000001 4000000001 5000000001 5000000004 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # tested by Hightail - https://github.com/dj3500/hightail from heapq import heappop, heappush from sys import stdin, stdout read, read_array = stdin.readline, lambda: stdin.readline().split() write = lambda *args, **kw: stdout.write(kw.get('sep', ' ').join(str(a) for a in args) + kw.get('end', '\n')) write_array = lambda arr, **kw: stdout.write(kw.get('sep', ' ').join(str(a) for a in arr) + kw.get('end', '\n')) read_int, read_int_array = lambda: int(read()), lambda: [int(p) for p in read_array()] read_float, read_float_array = lambda: float(read()), lambda: [float(p) for p in read_array()] n, k = read_int_array() heap = [] busy = 0 time = 0 finish = [0] * n for i in range(n): if busy == k: time = heappop(heap) busy -= 1 else: time = 0 start, minutes = read_int_array() if start > time: time = start heappush(heap, time + minutes) finish[i] = time + minutes busy += 1 write_array(finish, sep='\n') ```
vfc_16802
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/523/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 2\n1 5\n2 5\n3 5\n", "output": "6\n7\n11\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6 1\n1 1000000000\n2 1000000000\n3 1000000000\n4 1000000000\n5 1000000000\n6 3\n", "output": "1000000001\n2000000001\n3000000001\n4000000001\n5000000001\n5000000004\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1 1\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 1\n1000000000 10000\n", "output": "1000010000\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 6\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1\n8 1\n9 1\n10 1\n", "output": "2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 4\n1 1\n2 2\n3 1\n4 1\n5 1\n6 1\n7 1\n8 2\n9 1\n10 1\n", "output": "2\n4\n4\n5\n6\n7\n8\n10\n10\n11\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1763
Solve the following coding problem using the programming language python: You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights. You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $A$; remove a brick from the top of one non-empty pillar, the cost of this operation is $R$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $M$. You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $0$. What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height? -----Input----- The first line of input contains four integers $N$, $A$, $R$, $M$ ($1 \le N \le 10^{5}$, $0 \le A, R, M \le 10^{4}$) — the number of pillars and the costs of operations. The second line contains $N$ integers $h_{i}$ ($0 \le h_{i} \le 10^{9}$) — initial heights of pillars. -----Output----- Print one integer — the minimal cost of restoration. -----Examples----- Input 3 1 100 100 1 3 8 Output 12 Input 3 100 1 100 1 3 8 Output 9 Input 3 100 100 1 1 3 8 Output 4 Input 5 1 2 4 5 5 3 6 5 Output 4 Input 5 1 2 2 5 5 3 6 5 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, a, r, m = map(int, input().split()) h = list(map(int, input().split())) m = min(m, a+r) def get(M): up = 0 dw = 0 for e in h: if e > M: up += e - M else: dw += M - e ans = m * min(dw, up) if dw > up: ans += (dw - up) * a else: ans += (up - dw) * r return ans L = 0 R = int(1e9) mn = int(1e18) while R - L > 10: M1 = L + (R - L) // 3 M2 = R - (R - L) // 3 V1 = get(M1) V2 = get(M2) mn = min(mn, V1) mn = min(mn, V2) if V1 < V2: R = M2 elif V2 < V1: L = M1 else: L = M1 R = M2 for it in range(L, R+1): mn = min(mn, get(it)) print(mn) ```
vfc_16806
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1355/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3 1 100 100\n1 3 8\n", "output": "12\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 100 1 100\n1 3 8\n", "output": "9\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3 100 100 1\n1 3 8\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 1 2 4\n5 5 3 6 5\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "5 1 2 2\n5 5 3 6 5\n", "output": "3\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1764
Solve the following coding problem using the programming language python: Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers. To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets. Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options? -----Input----- The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 10^5). The second line contains n space-separated integers a_{i}. If a_{i} = 1, then the i-th serve was won by Petya, if a_{i} = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record. -----Output----- In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers s_{i} and t_{i} — the option for numbers s and t. Print the options in the order of increasing s_{i}, and for equal s_{i} — in the order of increasing t_{i}. -----Examples----- Input 5 1 2 1 2 1 Output 2 1 3 3 1 Input 4 1 1 1 1 Output 3 1 4 2 2 4 1 Input 4 1 2 1 2 Output 0 Input 8 2 1 2 1 1 1 1 1 Output 3 1 6 2 3 6 1 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()) line = input().split() lst = [] for num in line: lst.append(int(num)) cnt1 = [0] cnt2 = [0] c1 = 0 c2 = 0 for num in lst: if num == 1: c1 += 1 cnt1.append(c2) else: c2 += 1 cnt2.append(c1) w = lst[n - 1] ans = [] c1 = len(cnt1) c2 = len(cnt2) for t in range(n, 0, -1): s1 = 0 s2 = 0 i1 = 0 i2 = 0 l = 1 while i1 < c1 and i2 < c2: if i1 + t >= c1 and i2 + t >= c2: if l == 1 and l == w and i1 + 1 == c1 and s1 > s2: ans.append((s1, t)) elif l == 2 and l == w and i2 + 1 == c2 and s2 > s1: ans.append((s2, t)) break elif i2 + t >= c2: s1 += 1 l = 1 i1 += t i2 = cnt1[i1] elif i1 + t >= c1: s2 += 1 l = 2 i2 += t i1 = cnt2[i2] else: if cnt1[i1 + t] < i2 + t: s1 += 1 l = 1 i1 += t i2 = cnt1[i1] else: s2 += 1 l = 2 i2 += t i1 = cnt2[i2] ans.sort() print(int(len(ans))) for line in ans: print(str(line[0]) + ' ' + str(line[1])) ```
vfc_16810
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/496/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 2 1 2 1\n", "output": "2\n1 3\n3 1\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1765
Solve the following coding problem using the programming language python: Vasily the bear has got a sequence of positive integers a_1, a_2, ..., a_{n}. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b_1, b_2, ..., b_{k} is such maximum non-negative integer v, that number b_1 and b_2 and ... and b_{k} is divisible by number 2^{v} without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b_1 and b_2 and ... and b_{k} is divisible by 2^{v} without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible. Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and". -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_1 < a_2 < ... < a_{n} ≤ 10^9). -----Output----- In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b_1, b_2, ..., b_{k} — the numbers to write out. You are allowed to print numbers b_1, b_2, ..., b_{k} in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them. -----Examples----- Input 5 1 2 3 4 5 Output 2 4 5 Input 3 1 2 4 Output 1 4 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()) a = list(map(int, input().split())) mxa = max(a) v = 1 << 30 while v > mxa: v >>= 1 while True: d = -1 for i in range(n): if a[i] & v: d &= a[i] if d % v == 0: break v >>= 1 b = [i for i in a if i & v] print(len(b)) print(' '.join(map(str,b))) ```
vfc_16814
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/336/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 2 3 4 5\n", "output": "2\n4 5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n1 2 4\n", "output": "1\n4\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1766
Solve the following coding problem using the programming language python: Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins. Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move. Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her. -----Input----- The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000. -----Output----- On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game. -----Examples----- Input 4 4 1 2 10 Output 12 5 Input 7 1 2 3 4 5 6 7 Output 16 12 -----Note----- In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5. 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()) a=list(map(int,input().split())) b=True l=0 r=n-1 ans1=0 ans2=0 while l<=r: if a[l]>a[r]: if b: ans1+=a[l] b=False else: ans2+=a[l] b=True l+=1 else: if b: ans1+=a[r] b=False else: ans2+=a[r] b=True r-=1 print(ans1,ans2) ```
vfc_16818
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/381/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "4\n4 1 2 10\n", "output": "12 5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "7\n1 2 3 4 5 6 7\n", "output": "16 12\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "42\n15 29 37 22 16 5 26 31 6 32 19 3 45 36 33 14 25 20 48 7 42 11 24 28 9 18 8 21 47 17 38 40 44 4 35 1 43 39 41 27 12 13\n", "output": "613 418\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "43\n32 1 15 48 38 26 25 14 20 44 11 30 3 42 49 19 18 46 5 45 10 23 34 9 29 41 2 52 6 17 35 4 50 22 33 51 7 28 47 13 39 37 24\n", "output": "644 500\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n3\n", "output": "3 0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "45\n553 40 94 225 415 471 126 190 647 394 515 303 189 159 308 6 139 132 326 78 455 75 85 295 135 613 360 614 351 228 578 259 258 591 444 29 33 463 561 174 368 183 140 168 646\n", "output": "6848 6568\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1767
Solve the following coding problem using the programming language python: Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function f(x, l, r) as a bitwise OR of integers x_{l}, x_{l} + 1, ..., x_{r}, where x_{i} is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. [Image] -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays. The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^9). The third line contains n integers b_{i} (0 ≤ b_{i} ≤ 10^9). -----Output----- Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. -----Examples----- Input 5 1 2 4 3 2 2 3 3 12 1 Output 22 Input 10 13 2 7 11 8 4 9 8 5 1 5 7 18 9 2 3 0 11 8 6 Output 46 -----Note----- Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation. In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5. In the second sample, the maximum value is obtained for l = 1 and r = 9. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def f(m): v = 0 for x in m: v |= x return v input() print(f(map(int, input().split())) + f(map(int, input().split()))) ```
vfc_16822
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/631/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n1 2 4 3 2\n2 3 3 12 1\n", "output": "22", "type": "stdin_stdout" } ] }
apps
verifiable_code
1768
Solve the following coding problem using the programming language python: Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it! Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour s_{i}, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland. For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3. But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer m_{i} and a lowercase letter c_{i}, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan. -----Input----- The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland. The second line contains n lowercase English letters s_1s_2... s_{n} as a string — the initial colours of paper pieces on the garland. The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has. The next q lines describe one plan each: the i-th among them contains an integer m_{i} (1 ≤ m_{i} ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter c_{i} — Koyomi's possible favourite colour. -----Output----- Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it. -----Examples----- Input 6 koyomi 3 1 o 4 o 4 m Output 3 6 5 Input 15 yamatonadeshiko 10 1 a 2 a 3 a 4 a 5 a 1 b 2 b 3 b 4 b 5 b Output 3 4 5 7 8 1 2 3 4 5 Input 10 aaaaaaaaaa 2 10 b 10 z Output 10 10 -----Note----- In the first sample, there are three plans: In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable; In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6; In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5. 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().strip()) s = sys.stdin.readline().strip() dp = [[-1] * (n + 1) for i in range(26)] for c in range(26): for j in range(n): tst = 1 if s[j] == chr(c + 97) else 0 dp[c][1 - tst] = max(dp[c][1 - tst], 1) for k in range(j + 1, n): if s[k] == chr(c + 97):tst += 1 dp[c][k - j + 1 - tst] = max(dp[c][k - j + 1 - tst], k - j + 1) #for c in range(26): # for j in range(n): # dp[c][j + 1] = max(dp[c][j], dp[c][j + 1]) q = int(sys.stdin.readline().strip()) for i in range(q): m, c = [item for item in sys.stdin.readline().strip().split()] m = int(m) #print(max([dp[ord(c) - 97][u] for u in range(m + 1)])) print(dp[ord(c) - 97][m]) if dp[ord(c) - 97][m] != -1 else print(n) ```
vfc_16826
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/814/C", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "6\nkoyomi\n3\n1 o\n4 o\n4 m\n", "output": "3\n6\n5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "15\nyamatonadeshiko\n10\n1 a\n2 a\n3 a\n4 a\n5 a\n1 b\n2 b\n3 b\n4 b\n5 b\n", "output": "3\n4\n5\n7\n8\n1\n2\n3\n4\n5\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1769
Solve the following coding problem using the programming language python: Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through. It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop N - 1 to the stop N and successfully finished their expedition. They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill. Help them by suggesting some possible stop heights satisfying numbers from the travel journal. -----Input----- In the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number B — the number of days of walking down the hill (A + B + 1 = N, 1 ≤ N ≤ 100 000). -----Output----- Output N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting. -----Examples----- Input 0 1 Output 2 1 Input 2 1 Output 1 3 4 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a=int(input()) b=int(input()) n=a+b+1 L=list(range(n-a,n+1)) for item in L: print(item,end=" ") x=n-a-1 while(x>0): print(x,end=" ") x-=1 ```
vfc_16830
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/491/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "0\n1\n", "output": "2 1 \n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1770
Solve the following coding problem using the programming language python: Vasya is reading a e-book. The file of the book consists of $n$ pages, numbered from $1$ to $n$. The screen is currently displaying the contents of page $x$, and Vasya wants to read the page $y$. There are two buttons on the book which allow Vasya to scroll $d$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $10$ pages, and $d = 3$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth. Help Vasya to calculate the minimum number of times he needs to press a button to move to page $y$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^3$) — the number of testcases. Each testcase is denoted by a line containing four integers $n$, $x$, $y$, $d$ ($1\le n, d \le 10^9$, $1 \le x, y \le n$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively. -----Output----- Print one line for each test. If Vasya can move from page $x$ to page $y$, print the minimum number of times he needs to press a button to do it. Otherwise print $-1$. -----Example----- Input 3 10 4 5 2 5 1 3 4 20 4 19 3 Output 4 -1 5 -----Note----- In the first test case the optimal sequence is: $4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$. In the second test case it is possible to get to pages $1$ and $5$. In the third test case the optimal sequence is: $4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$. 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, x, y, d = map(int, input().split()) tt = abs(x - y) if tt % d != 0: ans = -1 if (y - 1) % d == 0: ans = (x - 1 + d - 1) // d + (y - 1) // d if (n - y) % d == 0: cc = (n - x + d - 1) // d + (n - y) // d if ans == -1 or cc < ans: ans = cc print(ans) else: print(tt // d) ```
vfc_16834
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/1082/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "3\n10 4 5 2\n5 1 3 4\n20 4 19 3\n", "output": "4\n-1\n5\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n12345 1 1 2\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n999999999 3 4 5\n", "output": "399999999\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n400000001 2 200000001 2\n", "output": "100000001\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n1000000000 3 1000000000 2\n", "output": "499999999\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1771
Solve the following coding problem using the programming language python: Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river. "To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino. "See? The clouds are coming." Kanno gazes into the distance. "That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$. There are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (endpoints excluded). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$. Furthermore, no pair of clouds intersect initially, that is, for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. With a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction. You are to help Mino count the number of pairs $(i, j)$ ($i < j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs. -----Input----- The first line contains three space-separated integers $n$, $l$, and $w_\mathrm{max}$ ($1 \leq n \leq 10^5$, $1 \leq l, w_\mathrm{max} \leq 10^8$) — the number of clouds, the length of each cloud and the maximum wind speed, respectively. The $i$-th of the following $n$ lines contains two space-separated integers $x_i$ and $v_i$ ($-10^8 \leq x_i \leq 10^8$, $v_i \in \{-1, 1\}$) — the initial position and the velocity of the $i$-th cloud, respectively. The input guarantees that for all $1 \leq i \lt j \leq n$, $\lvert x_i - x_j \rvert \geq l$. -----Output----- Output one integer — the number of unordered pairs of clouds such that it's possible that clouds from each pair cover the moon at the same future moment with a proper choice of wind velocity $w$. -----Examples----- Input 5 1 2 -2 1 2 1 3 -1 5 -1 7 -1 Output 4 Input 4 10 1 -20 1 -10 -1 0 1 10 -1 Output 1 -----Note----- In the first example, the initial positions and velocities of clouds are illustrated below. [Image] The pairs are: $(1, 3)$, covering the moon at time $2.5$ with $w = -0.4$; $(1, 4)$, covering the moon at time $3.5$ with $w = -0.6$; $(1, 5)$, covering the moon at time $4.5$ with $w = -0.7$; $(2, 5)$, covering the moon at time $2.5$ with $w = -2$. Below is the positions of clouds at time $2.5$ with $w = -0.4$. At this moment, the $1$-st and $3$-rd clouds both cover the moon. [Image] In the second example, the only pair is $(1, 4)$, covering the moon at time $15$ with $w = 0$. Note that all the times and wind velocities given above are just examples among infinitely many choices. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # Codeforces Round #487 (Div. 2)import collections from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import sys def getIntList(): return list(map(int, input().split())) import bisect N,L,WM = getIntList() z = {} z[-1] = {1:[], -1:[]} z[0] = {1:[], -1:[]} z[1] = {1:[], -1:[]} for i in range(N): x0,v = getIntList() t = (x0,v) if x0+L <=0: z[-1][v].append(t) elif x0>=0: z[1][v].append(t) else: z[0][v].append(t) res = 0 res += len(z[-1][1] ) * len(z[ 1][-1] ) res += len(z[0][1] ) * len(z[ 1][-1] ) res += len(z[-1][1] ) * len(z[ 0][-1] ) if WM==1: print(res) return z[1][-1].sort() z[-1][1].sort() #print(z[-1][1]) tn = len(z[1][-1]) for t in z[1][1]: g = (-WM-1) * t[0] / (-WM+1) - L g = max(g, t[0]+ 0.5) p = bisect.bisect_right(z[1][-1], (g,2) ) res += tn-p tn = len(z[-1][1]) for t in z[-1][-1]: g = (WM+1) * (t[0] + L)/ (WM-1) g = min(g, t[0] - 0.1) p = bisect.bisect_left(z[-1][1], (g,-2) ) res += p print(res) ```
vfc_16838
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/989/D", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5 1 2\n-2 1\n2 1\n3 -1\n5 -1\n7 -1\n", "output": "4\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "4 10 1\n-20 1\n-10 -1\n0 1\n10 -1\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1 100000000 98765432\n73740702 1\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "10 2 3\n-1 -1\n-4 1\n-6 -1\n1 1\n10 -1\n-8 -1\n6 1\n8 1\n4 -1\n-10 -1\n", "output": "5\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1772
Solve the following coding problem using the programming language python: A flower shop has got n bouquets, and the i-th bouquet consists of a_{i} flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet. Determine the maximum possible number of large bouquets Vasya can make. -----Input----- The first line contains a single positive integer n (1 ≤ n ≤ 10^5) — the number of initial bouquets. The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^6) — the number of flowers in each of the initial bouquets. -----Output----- Print the maximum number of large bouquets Vasya can make. -----Examples----- Input 5 2 3 4 2 7 Output 2 Input 6 2 2 6 8 6 12 Output 0 Input 3 11 4 10 Output 1 -----Note----- In the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers. In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25. 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()) a = 0 b = 0 for x in input().split(): x = int(x) if x % 2 == 0: a += 1 else: b += 1 res = b if a < b: res = a + (b-a)//3 print(res) ```
vfc_16842
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/926/G", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "5\n2 3 4 2 7\n", "output": "2\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "6\n2 2 6 8 6 12\n", "output": "0\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n11 4 10\n", "output": "1\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "1\n1\n", "output": "0\n", "type": "stdin_stdout" } ] }
apps
verifiable_code
1773
Solve the following coding problem using the programming language python: Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere. Lala Land has exactly n apple trees. Tree number i is located in a position x_{i} and has a_{i} apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing. What is the maximum number of apples he can collect? -----Input----- The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land. The following n lines contains two integers each x_{i}, a_{i} ( - 10^5 ≤ x_{i} ≤ 10^5, x_{i} ≠ 0, 1 ≤ a_{i} ≤ 10^5), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0. -----Output----- Output the maximum number of apples Amr can collect. -----Examples----- Input 2 -1 5 1 5 Output 10 Input 3 -2 2 1 4 -1 3 Output 9 Input 3 1 9 3 5 7 10 Output 9 -----Note----- In the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples. In the second sample test the optimal solution is to go left to x = - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x = - 2. In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left. 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()) pos=[] neg=[] for _ in range(n): x,a=list(map(int,input().split())) if x > 0: pos.append((x, a)) else: neg.append((-x, a)) pos=[a for x,a in sorted(pos)] neg=[a for x,a in sorted(neg)] if len(pos)==len(neg): print(sum(pos)+sum(neg)) else: if len(pos)<len(neg): pos,neg=neg,pos print(sum(neg)+sum(pos[:len(neg)+1])) ```
vfc_16846
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/558/A", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "2\n-1 5\n1 5\n", "output": "10", "type": "stdin_stdout" }, { "fn_name": null, "input": "3\n-2 2\n1 4\n-1 3\n", "output": "9", "type": "stdin_stdout" } ] }
apps
verifiable_code
1774
Solve the following coding problem using the programming language python: The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ... -----Input----- The only line of the input is a string between 1 and 10^6 characters long. -----Output----- Output "Yes" or "No". -----Examples----- Input HHHH Output Yes Input HQHQH Output No Input HHQHHQH Output No Input HHQQHHQQHH Output Yes -----Note----- The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys s = input() qc = s.count('Q') qs = int(qc ** 0.5) hc = s.count('H') if qs == 0: print('Yes') return if not qc == qs ** 2: print('No') return if not hc % (qs + 1) == 0: print('No') return t = s.split('Q') pre = len(t[0]) // 2 suf = 0 if len(t) == 1 else len(t[-1]) // 2 a = ['H' * pre] + t[1 : qs] + ['H' * suf] o = [c for c in 'Q'.join(a)] g = [] for c in o: if c == 'H': g += ['H'] else: g += o print('Yes' if ''.join(g) == s else 'No') ```
vfc_16850
{ "difficulty": "interview", "memory_limit": null, "memory_limit_bytes": null, "problem_url": "https://codeforces.com/problemset/problem/290/E", "time_limit": "None" }
{ "language": "python", "test_cases": [ { "fn_name": null, "input": "HHHH\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "HQHQH\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "HHQHHQH\n", "output": "No\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "HHQQHHQQHH\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "Q\n", "output": "Yes\n", "type": "stdin_stdout" }, { "fn_name": null, "input": "HHHHHHHHHHQHHH\n", "output": "No\n", "type": "stdin_stdout" } ] }