source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
4
problem
stringlengths
488
6.07k
gold_standard_solution
stringlengths
19
30.1k
verification_info
dict
metadata
dict
problem_id
stringlengths
5
9
apps
verifiable_code
2190
Solve the following coding problem using the programming language python: There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise. -----Input----- The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 10^5). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right. -----Output----- Print the number of steps, so that the line remains the same afterward. -----Examples----- Input 10 10 9 7 8 6 5 3 4 2 1 Output 2 Input 6 1 2 3 4 5 6 Output 0 -----Note----- In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] → [10 8 4] → [10]. So, there are two steps. 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()) ans = 0 stk = [] for v in map(int, input().split()): last = 0 while len(stk) and stk[-1][0] < v and stk[-1][1]: last = max(last, stk[-1][1]) del stk[-1] if not len(stk) or stk[-1][0] < v: stk.append((v, 0)) else: stk.append((v, last + 1)); ans = max(ans, last + 1) print(ans) ```
{ "language": "python", "test_cases": [ { "input": "10\n10 9 7 8 6 5 3 4 2 1\n", "output": "2\n", "type": "stdin_stdout" }, { "input": "6\n1 2 3 4 5 6\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "6\n6 5 4 3 2 1\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "10\n10 7 4 2 5 8 9 6 3 1\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "15\n15 9 5 10 7 11 14 6 2 3 12 1 8 13 4\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "1\n1\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2\n1 2\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2\n2 1\n", "output": "1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/319/B" }
vfc_6306
apps
verifiable_code
2191
Solve the following coding problem using the programming language python: You are given a sequence a consisting of n integers. Find the maximum possible value of $a_{i} \operatorname{mod} a_{j}$ (integer remainder of a_{i} divided by a_{j}), where 1 ≤ i, j ≤ n and a_{i} ≥ a_{j}. -----Input----- The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·10^5). The second line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 10^6). -----Output----- Print the answer to the problem. -----Examples----- Input 3 3 4 5 Output 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(): input() aa = sorted(map(int, input().split())) maxa = max(aa) m = [False] * (maxa + 1) x = [] b = 0 for a in aa: if b != a: m[a] = True for i in range(b, a): x.append(b) b = a x.append(b) ans = 0 for i in range(maxa - 1, 1, -1): if i < ans: break if m[i]: for j in range(1, maxa // i + 1): ans = max(ans, x[min(i * (j + 1) - 1, maxa)] % i) print(ans) def __starting_point(): main() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "3\n3 4 5\n", "output": "2\n", "type": "stdin_stdout" }, { "input": "3\n1 2 4\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "1\n1\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "1\n1000000\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2\n1000000 999999\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "12\n4 4 10 13 28 30 41 43 58 61 70 88\n", "output": "30\n", "type": "stdin_stdout" }, { "input": "7\n2 13 22 32 72 91 96\n", "output": "27\n", "type": "stdin_stdout" }, { "input": "5\n5 11 12 109 110\n", "output": "10\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/484/B" }
vfc_6310
apps
verifiable_code
2195
Solve the following coding problem using the programming language python: You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case. Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal. -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array. -----Output----- Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array. -----Examples----- Input 7 10 1 1 1 5 5 3 Output 4 Input 5 1 1 1 1 1 Output 0 -----Note----- In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4. In the second sample, there is no way to increase any element with a permutation, so 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 from collections import Counter n = int(input()) a = list(map(int, input().split())) c = Counter(a) res = 0 cur = 0 for i in sorted(c.keys()): d = min(c[i], cur) cur -= d res += d cur += c[i] print(res) ```
{ "language": "python", "test_cases": [ { "input": "7\n10 1 1 1 5 5 3\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "5\n1 1 1 1 1\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "6\n300000000 200000000 300000000 200000000 1000000000 300000000\n", "output": "3\n", "type": "stdin_stdout" }, { "input": "10\n1 2 3 4 5 6 7 8 9 10\n", "output": "9\n", "type": "stdin_stdout" }, { "input": "1\n1\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "7\n3 5 2 2 5 2 4\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "5\n1 5 4 2 3\n", "output": "4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1007/A" }
vfc_6326
apps
verifiable_code
2197
Solve the following coding problem using the programming language python: You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest". A palindrome is a string that reads the same forward or backward. The length of string B should be at most 10^4. It is guaranteed that there always exists such string. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 10^4. -----Input----- First line contains a string A (1 ≤ |A| ≤ 10^3) consisting of lowercase Latin letters, where |A| is a length of A. -----Output----- Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 10^4. If there are many possible B, print any of them. -----Examples----- Input aba Output aba Input ab Output aabaa -----Note----- In the first example, "aba" is a subsequence of "aba" which is a palindrome. In the second example, "ab" is a subsequence of "aabaa" which is a palindrome. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python a = input() b = a[::-1] print(a + b) ```
{ "language": "python", "test_cases": [ { "input": "aba\n", "output": "abaaba", "type": "stdin_stdout" }, { "input": "ab\n", "output": "abba", "type": "stdin_stdout" }, { "input": "abcab\n", "output": "abcabbacba", "type": "stdin_stdout" }, { "input": "baaaaaaa\n", "output": "baaaaaaaaaaaaaab", "type": "stdin_stdout" }, { "input": "baaaaaa\n", "output": "baaaaaaaaaaaab", "type": "stdin_stdout" }, { "input": "baaaaaaaaa\n", "output": "baaaaaaaaaaaaaaaaaab", "type": "stdin_stdout" }, { "input": "baaaaaaaa\n", "output": "baaaaaaaaaaaaaaaab", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/932/A" }
vfc_6334
apps
verifiable_code
2198
Solve the following coding problem using the programming language python: There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name. There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account? Formally, we assume that two words denote the same name, if using the replacements "u" [Image] "oo" and "h" [Image] "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements. For example, the following pairs of words denote the same name: "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" $\rightarrow$ "kuuper" and "kuooper" $\rightarrow$ "kuuper". "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" $\rightarrow$ "khoon" and "kkkhoon" $\rightarrow$ "kkhoon" $\rightarrow$ "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name. -----Input----- The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive. -----Output----- Print the minimal number of groups where the words in each group denote the same name. -----Examples----- Input 10 mihail oolyana kooooper hoon ulyana koouper mikhail khun kuooper kkkhoon Output 4 Input 9 hariton hkariton buoi kkkhariton boooi bui khariton boui boi Output 5 Input 2 alex alex Output 1 -----Note----- There are four groups of words in the first example. Words in each group denote same name: "mihail", "mikhail" "oolyana", "ulyana" "kooooper", "koouper" "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name: "hariton", "kkkhariton", "khariton" "hkariton" "buoi", "boooi", "boui" "bui" "boi" In the third example the words are equal, so they denote the same name. 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 = set() for a in range(n): name = input() name = name.replace('u', 'oo') while (name.count('kh') > 0): name = name.replace('kh', 'h') s.add(name) print(len(s)) ```
{ "language": "python", "test_cases": [ { "input": "10\nmihail\noolyana\nkooooper\nhoon\nulyana\nkoouper\nmikhail\nkhun\nkuooper\nkkkhoon\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "9\nhariton\nhkariton\nbuoi\nkkkhariton\nboooi\nbui\nkhariton\nboui\nboi\n", "output": "5\n", "type": "stdin_stdout" }, { "input": "2\nalex\nalex\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "40\nuok\nkuu\nku\no\nkku\nuh\nu\nu\nhh\nk\nkh\nh\nh\nou\nokh\nukk\nou\nuhk\nuo\nuko\nu\nuu\nh\nh\nhk\nuhu\nuoh\nooo\nk\nh\nuk\nk\nkku\nh\nku\nok\nk\nkuu\nou\nhh\n", "output": "21\n", "type": "stdin_stdout" }, { "input": "40\noooo\nhu\no\nhoh\nkhk\nuuh\nhu\nou\nuuoh\no\nkouk\nuouo\nu\nok\nuu\nuuuo\nhoh\nuu\nkuu\nh\nu\nkkoh\nkhh\nuoh\nouuk\nkuo\nk\nu\nuku\nh\nu\nk\nhuho\nku\nh\noo\nuh\nk\nuo\nou\n", "output": "25\n", "type": "stdin_stdout" }, { "input": "100\nuh\nu\nou\nhk\nokh\nuou\nk\no\nuhh\nk\noku\nk\nou\nhuh\nkoo\nuo\nkk\nkok\nhhu\nuu\noou\nk\nk\noh\nhk\nk\nu\no\nuo\no\no\no\nhoh\nkuo\nhuh\nkhu\nuu\nk\noku\nk\nh\nuu\nuo\nhuo\noo\nhu\nukk\nok\no\noh\nuo\nkko\nok\nouh\nkoh\nhhu\nku\nko\nhho\nkho\nkho\nkhk\nho\nhk\nuko\nukh\nh\nkh\nkk\nuku\nkkk\no\nuo\no\nouh\nou\nuhk\nou\nk\nh\nkko\nuko\no\nu\nho\nu\nooo\nuo\no\nko\noh\nkh\nuk\nohk\noko\nuko\nh\nh\noo\no\n", "output": "36\n", "type": "stdin_stdout" }, { "input": "2\nkkkhkkh\nhh\n", "output": "1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/883/F" }
vfc_6338
apps
verifiable_code
2199
Solve the following coding problem using the programming language python: Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. [Image]  There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure. As the queen, Linova plans to choose exactly $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city. A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique). Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path. In order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her? -----Input----- The first line contains two integers $n$ and $k$ ($2\le n\le 2 \cdot 10^5$, $1\le k< n$)  — the number of cities and industry cities respectively. Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1\le u,v\le n$), denoting there is a road connecting city $u$ and city $v$. It is guaranteed that from any city, you can reach any other city by the roads. -----Output----- Print the only line containing a single integer  — the maximum possible sum of happinesses of all envoys. -----Examples----- Input 7 4 1 2 1 3 1 4 3 5 3 6 4 7 Output 7 Input 4 1 1 2 1 3 2 4 Output 2 Input 8 5 7 5 1 7 6 1 3 7 8 3 2 1 4 5 Output 9 -----Note----- [Image] In the first example, Linova can choose cities $2$, $5$, $6$, $7$ to develop industry, then the happiness of the envoy from city $2$ is $1$, the happiness of envoys from cities $5$, $6$, $7$ is $2$. The sum of happinesses is $7$, and it can be proved to be the maximum one. [Image] In the second example, choosing cities $3$, $4$ developing industry can reach a sum of $3$, but remember that Linova plans to choose exactly $k$ cities developing industry, then the maximum sum is $2$. 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, k = list(map(int, input().split())) begin = [-1] * n end = [-1] * n hurt = [-1] * n adj = [[] for i in range(n)] for _ in range(n-1): u ,v = list(map(int, input().split())) adj[u-1].append(v-1) adj[v-1].append(u-1) hurt[0] = 1 begin[0] = 0 stack = [0] curr = 1 while stack: nex = stack[-1] if adj[nex]: v = adj[nex].pop() if begin[v] == -1: begin[v] = curr curr += 1 stack.append(v) hurt[v] = len(stack) else: end[nex] = curr stack.pop() desc = [end[i] - begin[i]-hurt[i] for i in range(n)] desc.sort(reverse = True) out = 0 for i in range(n - k): out += desc[i] print(out) ```
{ "language": "python", "test_cases": [ { "input": "7 4\n1 2\n1 3\n1 4\n3 5\n3 6\n4 7\n", "output": "7", "type": "stdin_stdout" }, { "input": "4 1\n1 2\n1 3\n2 4\n", "output": "2", "type": "stdin_stdout" }, { "input": "8 5\n7 5\n1 7\n6 1\n3 7\n8 3\n2 1\n4 5\n", "output": "9", "type": "stdin_stdout" }, { "input": "2 1\n1 2\n", "output": "1", "type": "stdin_stdout" }, { "input": "20 7\n9 7\n3 7\n15 9\n1 3\n11 9\n18 7\n17 18\n20 1\n4 11\n2 11\n12 18\n8 18\n13 2\n19 2\n10 9\n6 13\n5 8\n14 1\n16 13\n", "output": "38", "type": "stdin_stdout" }, { "input": "3 2\n1 2\n1 3\n", "output": "2", "type": "stdin_stdout" }, { "input": "3 1\n1 2\n2 3\n", "output": "2", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1336/A" }
vfc_6342
apps
verifiable_code
2200
Solve the following coding problem using the programming language python: Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute $$ (a_1 + a_2) \oplus (a_1 + a_3) \oplus \ldots \oplus (a_1 + a_n) \\ \oplus (a_2 + a_3) \oplus \ldots \oplus (a_2 + a_n) \\ \ldots \\ \oplus (a_{n-1} + a_n) \\ $$ Here $x \oplus y$ is a bitwise XOR operation (i.e. $x$ ^ $y$ in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation. -----Input----- The first line contains a single integer $n$ ($2 \leq n \leq 400\,000$) — the number of integers in the array. The second line contains integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^7$). -----Output----- Print a single integer — xor of all pairwise sums of integers in the given array. -----Examples----- Input 2 1 2 Output 3 Input 3 1 2 3 Output 2 -----Note----- In the first sample case there is only one sum $1 + 2 = 3$. In the second sample case there are three sums: $1 + 2 = 3$, $1 + 3 = 4$, $2 + 3 = 5$. In binary they are represented as $011_2 \oplus 100_2 \oplus 101_2 = 010_2$, thus the answer is 2. $\oplus$ is the bitwise xor operation. To define $x \oplus y$, consider binary representations of integers $x$ and $y$. We put the $i$-th bit of the result to be 1 when exactly one of the $i$-th bits of $x$ and $y$ is 1. Otherwise, the $i$-th bit of the result is put to be 0. For example, $0101_2 \, \oplus \, 0011_2 = 0110_2$. 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()) a = list(map(int, input().split())) b = a ans = 0 for k in range(29): a0 = [] a1 = [] a0a = a0.append a1a = a1.append b0 = [] b1 = [] b0a = b0.append b1a = b1.append for i in a: if i&(1<<k): a1a(i) else: a0a(i) for i in b: if i&(1<<k): b1a(i) else: b0a(i) a = a0+a1 b = b0+b1 mask = (1<<(k+1))-1 aa = [i&mask for i in a] bb = [i&mask for i in b] res = 0 p1 = 1<<k p2 = mask+1 p3 = p1+p2 j1 = j2 = j3 = 0 for jj, ai in enumerate(reversed(aa)): while j1 < n and ai+bb[j1] < p1: j1 += 1 while j2 < n and ai+bb[j2] < p2: j2 += 1 while j3 < n and ai+bb[j3] < p3: j3 += 1 res += max(n, n - jj) - max(j3, n - jj) res += max(j2, n - jj) - max(j1, n - jj) ans |= (res & 1) << k print(ans) ```
{ "language": "python", "test_cases": [ { "input": "2\n1 2\n", "output": "3", "type": "stdin_stdout" }, { "input": "3\n1 2 3\n", "output": "2", "type": "stdin_stdout" }, { "input": "2\n1 1\n", "output": "2", "type": "stdin_stdout" }, { "input": "100\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\n", "output": "102", "type": "stdin_stdout" }, { "input": "50\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50\n", "output": "3", "type": "stdin_stdout" }, { "input": "51\n50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\n", "output": "148", "type": "stdin_stdout" }, { "input": "3\n2 2 8\n", "output": "4", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1322/B" }
vfc_6346
apps
verifiable_code
2201
Solve the following coding problem using the programming language python: You are given a sequence of n integers a_1, a_2, ..., a_{n}. Determine a real number x such that the weakness of the sequence a_1 - x, a_2 - x, ..., a_{n} - x is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poorness of a segment is defined as the absolute value of sum of the elements of segment. -----Input----- The first line contains one integer n (1 ≤ n ≤ 200 000), the length of a sequence. The second line contains n integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10 000). -----Output----- Output a real number denoting the minimum possible weakness of a_1 - x, a_2 - x, ..., a_{n} - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 6}. -----Examples----- Input 3 1 2 3 Output 1.000000000000000 Input 4 1 2 3 4 Output 2.000000000000000 Input 10 1 10 2 9 3 8 4 7 5 6 Output 4.500000000000000 -----Note----- For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case. 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()) a = [int(x) for x in sys.stdin.readline().split()] eps = 1e-12 def f(x): mx = a[0] - x tsmx = 0.0 mn = a[0] - x tsmn = 0.0 for ai in a: tsmx = max(tsmx + ai - x, ai - x) mx = max(tsmx, mx) tsmn = min(tsmn + ai - x, ai - x) mn = min(tsmn, mn) return abs(mx), abs(mn) l = min(a) r = max(a) f1, f2 = f(l) for i in range(0, 90): m = (l + r) / 2 f1, f2 = f(m) if f1 > f2: l = m else: r = m A, B = f(l) print(min(A,B)) ```
{ "language": "python", "test_cases": [ { "input": "3\n1 2 3\n", "output": "1.000000000000000\n", "type": "stdin_stdout" }, { "input": "4\n1 2 3 4\n", "output": "2.000000000000000\n", "type": "stdin_stdout" }, { "input": "10\n1 10 2 9 3 8 4 7 5 6\n", "output": "4.500000000000000\n", "type": "stdin_stdout" }, { "input": "1\n-10000\n", "output": "0.000000000000000\n", "type": "stdin_stdout" }, { "input": "3\n10000 -10000 10000\n", "output": "10000.000000000000000\n", "type": "stdin_stdout" }, { "input": "20\n-16 -23 29 44 -40 -50 -41 34 -38 30 -12 28 -44 -49 15 50 -28 38 -2 0\n", "output": "113.875000000000000\n", "type": "stdin_stdout" }, { "input": "10\n-405 -230 252 -393 -390 -259 97 163 81 -129\n", "output": "702.333333333333370\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/578/C" }
vfc_6350
apps
verifiable_code
2202
Solve the following coding problem using the programming language python: An array of integers $p_{1},p_{2}, \ldots,p_{n}$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3,1,2], [1], [1,2,3,4,5]$ and $[4,3,1,2]$. The following arrays are not permutations: $[2], [1,1], [2,3,4]$. There is a hidden permutation of length $n$. For each index $i$, you are given $s_{i}$, which equals to the sum of all $p_{j}$ such that $j < i$ and $p_{j} < p_{i}$. In other words, $s_i$ is the sum of elements before the $i$-th element that are smaller than the $i$-th element. Your task is to restore the permutation. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the size of the permutation. The second line contains $n$ integers $s_{1}, s_{2}, \ldots, s_{n}$ ($0 \le s_{i} \le \frac{n(n-1)}{2}$). It is guaranteed that the array $s$ corresponds to a valid permutation of length $n$. -----Output----- Print $n$ integers $p_{1}, p_{2}, \ldots, p_{n}$ — the elements of the restored permutation. We can show that the answer is always unique. -----Examples----- Input 3 0 0 0 Output 3 2 1 Input 2 0 1 Output 1 2 Input 5 0 1 1 1 10 Output 1 4 3 2 5 -----Note----- In the first example for each $i$ there is no index $j$ satisfying both conditions, hence $s_i$ are always $0$. In the second example for $i = 2$ it happens that $j = 1$ satisfies the conditions, so $s_2 = p_1$. In the third example for $i = 2, 3, 4$ only $j = 1$ satisfies the conditions, so $s_2 = s_3 = s_4 = 1$. For $i = 5$ all $j = 1, 2, 3, 4$ are possible, so $s_5 = p_1 + p_2 + p_3 + p_4 = 10$. 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()) A=list(map(int,input().split())) BIT=[0]*(n+1) def update(v,w): while v<=n: BIT[v]+=w v+=(v&(-v)) def getvalue(v): ANS=0 while v!=0: ANS+=BIT[v] v-=(v&(-v)) return ANS for i in range(1,n+1): update(i,i) ANS=[-1]*n for i in range(n-1,-1,-1): MIN=0 MAX=n k=A[i] while True: x=(MIN+MAX+1)//2 if getvalue(x)>k: if getvalue(x-1)==k: ANS[i]=x break else: MAX=x else: MIN=x update(x,-x) print(*ANS) ```
{ "language": "python", "test_cases": [ { "input": "3\n0 0 0\n", "output": "3 2 1\n", "type": "stdin_stdout" }, { "input": "2\n0 1\n", "output": "1 2\n", "type": "stdin_stdout" }, { "input": "5\n0 1 1 1 10\n", "output": "1 4 3 2 5\n", "type": "stdin_stdout" }, { "input": "1\n0\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "15\n0 0 3 3 13 3 6 34 47 12 20 6 6 21 55\n", "output": "2 1 15 10 12 3 6 13 14 8 9 5 4 7 11\n", "type": "stdin_stdout" }, { "input": "20\n0 1 7 15 30 15 59 42 1 4 1 36 116 36 16 136 10 36 46 36\n", "output": "1 6 8 15 17 12 18 16 3 4 2 14 20 13 7 19 5 10 11 9\n", "type": "stdin_stdout" }, { "input": "100\n0 0 57 121 57 0 19 251 19 301 19 160 57 578 664 57 19 50 0 621 91 5 263 34 5 96 713 649 22 22 22 5 108 198 1412 1147 84 1326 1777 0 1780 132 2000 479 1314 525 68 690 1689 1431 1288 54 1514 1593 1037 1655 807 465 1674 1747 1982 423 837 139 1249 1997 1635 1309 661 334 3307 2691 21 3 533 1697 250 3920 0 343 96 242 2359 3877 3877 150 1226 96 358 829 228 2618 27 2854 119 1883 710 0 4248 435\n", "output": "94 57 64 90 58 19 53 71 50 67 38 56 45 86 89 42 31 36 5 68 37 10 49 24 7 32 65 59 14 12 11 6 27 34 91 72 21 87 98 3 97 25 100 46 85 48 18 51 88 83 70 13 79 82 62 80 55 43 73 76 81 40 52 22 60 77 69 61 47 35 92 84 9 4 41 66 28 99 2 33 17 26 74 96 95 20 54 15 29 44 23 75 8 78 16 63 39 1 93 30\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1208/D" }
vfc_6354
apps
verifiable_code
2203
Solve the following coding problem using the programming language python: Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as p_{i}. For all pairs of distinct integers i, j between 1 and n, he wrote the number a_{i}, j = min(p_{i}, p_{j}). He writes a_{i}, i = 0 for all integer i from 1 to n. Bob gave you all the values of a_{i}, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given. -----Input----- The first line of the input will contain a single integer n (2 ≤ n ≤ 50). The next n lines will contain the values of a_{i}, j. The j-th number on the i-th line will represent a_{i}, j. The i-th number on the i-th line will be 0. It's guaranteed that a_{i}, j = a_{j}, i and there is at least one solution consistent with the information given. -----Output----- Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them. -----Examples----- Input 2 0 1 1 0 Output 2 1 Input 5 0 2 2 1 2 2 0 4 1 3 2 4 0 1 3 1 1 1 0 1 2 3 3 1 0 Output 2 5 4 1 3 -----Note----- In the first case, the answer can be {1, 2} or {2, 1}. In the second case, another possible answer is {2, 4, 5, 1, 3}. 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()) a = [[int(i) for i in input().split()] for j in range(n)] result = [-1] * n for i in range(n - 1): for j in range(n): d = set(a[j][k] for k in range(n) if result[k] == -1 and j != k) if len(d) == 1: result[j] = d.pop() result[result.index(-1)] = n print(' '.join(str(i) for i in result)) main() ```
{ "language": "python", "test_cases": [ { "input": "2\n0 1\n1 0\n", "output": "2 1\n", "type": "stdin_stdout" }, { "input": "5\n0 2 2 1 2\n2 0 4 1 3\n2 4 0 1 3\n1 1 1 0 1\n2 3 3 1 0\n", "output": "2 5 4 1 3\n", "type": "stdin_stdout" }, { "input": "10\n0 1 5 2 5 3 4 5 5 5\n1 0 1 1 1 1 1 1 1 1\n5 1 0 2 6 3 4 6 6 6\n2 1 2 0 2 2 2 2 2 2\n5 1 6 2 0 3 4 8 8 7\n3 1 3 2 3 0 3 3 3 3\n4 1 4 2 4 3 0 4 4 4\n5 1 6 2 8 3 4 0 9 7\n5 1 6 2 8 3 4 9 0 7\n5 1 6 2 7 3 4 7 7 0\n", "output": "5 1 6 2 8 3 4 10 9 7\n", "type": "stdin_stdout" }, { "input": "4\n0 1 3 2\n1 0 1 1\n3 1 0 2\n2 1 2 0\n", "output": "4 1 3 2\n", "type": "stdin_stdout" }, { "input": "7\n0 3 2 4 1 4 4\n3 0 2 3 1 3 3\n2 2 0 2 1 2 2\n4 3 2 0 1 5 5\n1 1 1 1 0 1 1\n4 3 2 5 1 0 6\n4 3 2 5 1 6 0\n", "output": "4 3 2 5 1 7 6\n", "type": "stdin_stdout" }, { "input": "10\n0 4 4 1 4 4 4 2 3 4\n4 0 5 1 6 8 9 2 3 7\n4 5 0 1 5 5 5 2 3 5\n1 1 1 0 1 1 1 1 1 1\n4 6 5 1 0 6 6 2 3 6\n4 8 5 1 6 0 8 2 3 7\n4 9 5 1 6 8 0 2 3 7\n2 2 2 1 2 2 2 0 2 2\n3 3 3 1 3 3 3 2 0 3\n4 7 5 1 6 7 7 2 3 0\n", "output": "4 10 5 1 6 8 9 2 3 7\n", "type": "stdin_stdout" }, { "input": "13\n0 5 5 2 5 4 5 5 3 5 5 5 1\n5 0 6 2 6 4 6 6 3 6 6 6 1\n5 6 0 2 10 4 7 10 3 8 10 9 1\n2 2 2 0 2 2 2 2 2 2 2 2 1\n5 6 10 2 0 4 7 12 3 8 11 9 1\n4 4 4 2 4 0 4 4 3 4 4 4 1\n5 6 7 2 7 4 0 7 3 7 7 7 1\n5 6 10 2 12 4 7 0 3 8 11 9 1\n3 3 3 2 3 3 3 3 0 3 3 3 1\n5 6 8 2 8 4 7 8 3 0 8 8 1\n5 6 10 2 11 4 7 11 3 8 0 9 1\n5 6 9 2 9 4 7 9 3 8 9 0 1\n1 1 1 1 1 1 1 1 1 1 1 1 0\n", "output": "5 6 10 2 13 4 7 12 3 8 11 9 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/618/B" }
vfc_6358
apps
verifiable_code
2205
Solve the following coding problem using the programming language python: Please notice the unusual memory limit of this problem. Orac likes games. Recently he came up with the new game, "Game of Life". You should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white. For each iteration of the game (the initial iteration is $0$), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different. Two cells are adjacent if they have a mutual edge. Now Orac has set an initial situation, and he wants to know for the cell $(i,j)$ (in $i$-th row and $j$-th column), what will be its color at the iteration $p$. He may ask you these questions several times. -----Input----- The first line contains three integers $n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$, representing the number of rows, columns, and the number of Orac queries. Each of the following $n$ lines contains a binary string of length $m$, the $j$-th character in $i$-th line represents the initial color of cell $(i,j)$. '0' stands for white, '1' stands for black. Each of the following $t$ lines contains three integers $i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$, representing a query from Orac. -----Output----- Print $t$ lines, in $i$-th line you should print the answer to the $i$-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'. -----Examples----- Input 3 3 3 000 111 000 1 1 1 2 2 2 3 3 3 Output 1 1 1 Input 5 2 2 01 10 01 10 01 1 1 4 5 1 4 Output 0 0 Input 5 5 3 01011 10110 01101 11010 10101 1 1 4 1 2 3 5 5 3 Output 1 0 1 Input 1 1 3 0 1 1 1 1 1 2 1 1 3 Output 0 0 0 -----Note----- [Image] For the first example, the picture above shows the initial situation and the color of cells at the iteration $1$, $2$, and $3$. We can see that the color of $(1,1)$ at the iteration $1$ is black, the color of $(2,2)$ at the iteration $2$ is black, and the color of $(3,3)$ at the iteration $3$ is also black. For the second example, you can prove that the cells will never change their colors. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): import sys from array import array from collections import deque input = sys.stdin.readline H, W, Q = list(map(int, input().split())) grid = array('b', [0] * (H*W)) #flg_0 = 0 #flg_1 = 0 for h in range(H): line = input().rstrip('\n') """ if "0" in line: flg_0 = 1 if "1" in line: flg_1 = 1 """ for w in range(W): if line[w] == "1": grid[h*W + w] ^= 1 """ if flg_0 == 0: for _ in range(Q): print(1) return if flg_1 == 0: for _ in range(Q): print(0) return """ que = deque() start_change = [-1] * (H*W) d = [(1, 0), (-1, 0), (0, 1), (0, -1)] for h in range(H): for w in range(W): same = 0 hw = h*W+w for dh, dw in d: h_new, w_new = h+dh, w+dw hw_new = h_new * W + w_new if 0 <= h_new < H and 0 <= w_new < W: if grid[hw] == grid[hw_new]: same = 1 break if same: que.append(hw) start_change[hw] = 0 while que: hw = que.popleft() h, w = divmod(hw, W) for dh, dw in d: h_new, w_new = h + dh, w + dw hw_new = h_new * W + w_new if 0 <= h_new < H and 0 <= w_new < W: if start_change[hw_new] == -1: start_change[hw_new] = start_change[hw] + 1 que.append(hw_new) for _ in range(Q): h, w, p = list(map(int, input().split())) h -= 1 w -= 1 hw = h*W + w if start_change[hw] == -1: print(grid[hw]) continue if p <= start_change[hw]: print(grid[hw]) else: if (p - start_change[hw]) % 2 == 0: print(grid[hw]) else: print(grid[hw] ^ 1) def __starting_point(): main() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "3 3 3\n000\n111\n000\n1 1 1\n2 2 2\n3 3 3\n", "output": "1\n1\n1\n", "type": "stdin_stdout" }, { "input": "5 2 2\n01\n10\n01\n10\n01\n1 1 4\n5 1 4\n", "output": "0\n0\n", "type": "stdin_stdout" }, { "input": "5 5 3\n01011\n10110\n01101\n11010\n10101\n1 1 4\n1 2 3\n5 5 3\n", "output": "1\n0\n1\n", "type": "stdin_stdout" }, { "input": "1 1 3\n0\n1 1 1\n1 1 2\n1 1 3\n", "output": "0\n0\n0\n", "type": "stdin_stdout" }, { "input": "1 1 1\n1\n1 1 1\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "2 2 1\n10\n11\n1 2 1000000000000000000\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "1 1 1\n1\n1 1 1000000000000000000\n", "output": "1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1349/C" }
vfc_6366
apps
verifiable_code
2206
Solve the following coding problem using the programming language python: Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one. Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. -----Input----- The first line contains single integer n (1 ≤ n ≤ 300 000) — number of coins that Sasha puts behind Dima. Second line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p_1, then coin located at position p_2 and so on. Coins are numbered from left to right. -----Output----- Print n + 1 numbers a_0, a_1, ..., a_{n}, where a_0 is a hardness of ordering at the beginning, a_1 is a hardness of ordering after the first replacement and so on. -----Examples----- Input 4 1 3 4 2 Output 1 2 3 2 1 Input 8 6 8 3 4 7 2 1 5 Output 1 2 2 3 4 3 4 5 1 -----Note----- Let's denote as O coin out of circulation, and as X — coin is circulation. At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges. After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process. XOOO → OOOX After replacement of the third coin, Dima's actions look this way: XOXO → OXOX → OOXX After replacement of the fourth coin, Dima's actions look this way: XOXX → OXXX Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. 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())) p = [0] * (n + 1) ans = [1] * (n + 1) ind = n for i in range(n): p[a[i] - 1] = 1 while ind > 0 and p[ind - 1] == 1: ind -= 1 ans[i + 1] = 1 + (i + 1) - (n - ind) print(' '.join(map(str, ans))) ```
{ "language": "python", "test_cases": [ { "input": "4\n1 3 4 2\n", "output": "1 2 3 2 1\n", "type": "stdin_stdout" }, { "input": "8\n6 8 3 4 7 2 1 5\n", "output": "1 2 2 3 4 3 4 5 1\n", "type": "stdin_stdout" }, { "input": "1\n1\n", "output": "1 1\n", "type": "stdin_stdout" }, { "input": "11\n10 8 9 4 6 3 5 1 11 7 2\n", "output": "1 2 3 4 5 6 7 8 9 6 2 1\n", "type": "stdin_stdout" }, { "input": "11\n10 8 9 4 3 5 1 11 7 2 6\n", "output": "1 2 3 4 5 6 7 8 5 5 6 1\n", "type": "stdin_stdout" }, { "input": "100\n1 72 43 50 58 87 10 94 29 51 99 86 92 80 36 31 9 100 85 59 66 30 3 78 17 73 93 37 57 71 45 15 24 2 64 44 65 22 38 79 23 8 16 52 98 97 96 95 91 90 89 88 84 83 82 81 77 76 75 74 70 69 68 67 63 62 61 60 56 55 54 53 49 48 47 46 42 41 40 39 35 34 33 32 28 27 26 25 21 20 19 18 14 13 12 11 7 6 5 4\n", "output": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 43 43 43 40 40 40 40 37 37 37 37 34 34 34 34 31 31 31 31 28 28 28 28 25 25 25 25 22 22 22 22 19 19 19 19 16 16 16 16 13 13 13 13 10 10 10 10 7 7 7 7 4 4 4 4 1\n", "type": "stdin_stdout" }, { "input": "100\n98 52 63 2 18 96 31 58 84 40 41 45 66 100 46 71 26 48 81 20 73 91 68 76 13 93 17 29 64 95 79 21 55 75 19 85 54 51 89 78 15 87 43 59 36 1 90 35 65 56 62 28 86 5 82 49 3 99 33 9 92 32 74 69 27 22 77 16 44 94 34 6 57 70 23 12 61 25 8 11 67 47 83 88 10 14 30 7 97 60 42 37 24 38 53 50 4 80 72 39\n", "output": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 70 71 72 73 74 75 76 77 78 71 39 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/875/B" }
vfc_6370
apps
verifiable_code
2207
Solve the following coding problem using the programming language python: Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost. Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers t_{i}, x_{i}, y_{i} (1 ≤ t_{i} ≤ 2; x_{i}, y_{i} ≥ 0; x_{i} + y_{i} = 10). If t_{i} = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers x_{i}, y_{i} represent the result of executing this command, that is, x_{i} packets reached the corresponding server successfully and y_{i} packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command. -----Output----- In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format. -----Examples----- Input 2 1 5 5 2 6 4 Output LIVE LIVE Input 3 1 0 10 2 0 10 1 10 0 Output LIVE DEAD -----Note----- Consider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network. 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()) ta,tb,da,db=[0]*4 for i in range (n): t,x,y=list(map(int,input().split())) if t==1: ta+=(x+y) da+=y if (t==2): tb+=(x+y) db+=y if (ta-da>=0.5*ta): print ('LIVE') else : print ('DEAD') if (tb-db>=0.5*tb): print ('LIVE') else : print ('DEAD') ```
{ "language": "python", "test_cases": [ { "input": "2\n1 5 5\n2 6 4\n", "output": "LIVE\nLIVE\n", "type": "stdin_stdout" }, { "input": "3\n1 0 10\n2 0 10\n1 10 0\n", "output": "LIVE\nDEAD\n", "type": "stdin_stdout" }, { "input": "10\n1 3 7\n2 4 6\n1 2 8\n2 5 5\n2 10 0\n2 10 0\n1 8 2\n2 2 8\n2 10 0\n1 1 9\n", "output": "DEAD\nLIVE\n", "type": "stdin_stdout" }, { "input": "11\n1 8 2\n1 6 4\n1 9 1\n1 7 3\n2 0 10\n2 0 10\n1 8 2\n2 2 8\n2 6 4\n2 7 3\n2 9 1\n", "output": "LIVE\nDEAD\n", "type": "stdin_stdout" }, { "input": "12\n1 5 5\n1 0 10\n1 4 6\n1 2 8\n1 2 8\n1 5 5\n1 9 1\n2 9 1\n1 5 5\n1 1 9\n2 9 1\n2 7 3\n", "output": "DEAD\nLIVE\n", "type": "stdin_stdout" }, { "input": "13\n1 8 2\n1 4 6\n1 5 5\n1 5 5\n2 10 0\n2 9 1\n1 3 7\n2 6 4\n2 6 4\n2 5 5\n1 7 3\n2 3 7\n2 9 1\n", "output": "LIVE\nLIVE\n", "type": "stdin_stdout" }, { "input": "14\n1 7 3\n1 0 10\n1 7 3\n1 1 9\n2 2 8\n2 0 10\n1 1 9\n2 8 2\n2 6 4\n1 3 7\n1 3 7\n2 6 4\n2 1 9\n2 7 3\n", "output": "DEAD\nDEAD\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/245/A" }
vfc_6374
apps
verifiable_code
2208
Solve the following coding problem using the programming language python: The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo! There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way. -----Input----- The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests. The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest. -----Output----- Output one integer, the smallest possible number of sad guests. -----Examples----- Input 5 4 1 2 4 3 1 4 3 4 Output 1 Input 6 5 2 3 2 1 3 4 6 5 4 5 Output 0 -----Note----- In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad. In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be satisfied. 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 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == "\n": return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 #A def A(): n = I() a = LI() a.sort() f = [1]*n p = 0 ans = 0 while p < n: while p < n and not f[p]: p += 1 if p == n: break ans += 1 for i in range(n): if a[i]%a[p] == 0: f[i] = 0 print(ans) return #B def B(): n = I() s = list(map(int, input())) g = LIR(n) ans = sum(s) for t in range(30000): for i in range(n): ai,bi = g[i] if t < bi: continue if (t-bi)%ai == 0: s[i] ^= 1 su = sum(s) if ans < su: ans = su print(ans) return #C def C(): t = I() for _ in range(t): n = I() s = list(map(int, input())) mi = [s[-1]] for i in s[:-1][::-1]: mi.append(min(mi[-1],i)) mi = mi[::-1] ans = [None]*n for i in range(n): if mi[i] == s[i]: ans[i] = 1 else: ans[i] = 2 q = [s[i] for i in range(n) if ans[i] > 1] p = [q[i] for i in range(len(q))] p.sort() if p == q: print(*ans,sep = "") else: print("-") return #D def D(): def root(x): if x == par[x]: return x par[x] = root(par[x]) return par[x] def unite(x,y): x = root(x) y = root(y) if rank[x] < rank[y]: par[x] = y else: par[y] = x if rank[x] == rank[y]: rank[x] += 1 n,k = LI() par = [i for i in range(n)] rank = [0]*n for i in range(k): x,y = LI() x -= 1 y -= 1 if root(x) != root(y): unite(x,y) size = [0]*n for i in range(n): size[root(i)] += 1 ans = 0 for i in size: if i > 0: ans += i-1 print(k-ans) return #E def E(): return #F def F(): return #G def G(): return #H def H(): return #Solve def __starting_point(): D() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "5 4\n1 2\n4 3\n1 4\n3 4\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "6 5\n2 3\n2 1\n3 4\n6 5\n4 5\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2 1\n1 2\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "100000 12\n8 7\n1 9\n5 4\n11 12\n7 8\n3 4\n3 5\n12 15\n15 13\n13 14\n7 8\n11 14\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "10 15\n1 2\n2 3\n3 4\n4 5\n5 1\n1 6\n2 7\n3 8\n4 9\n5 10\n6 8\n7 9\n8 10\n9 6\n10 7\n", "output": "6\n", "type": "stdin_stdout" }, { "input": "4 2\n1 2\n2 3\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "4 2\n1 3\n2 4\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1209/D" }
vfc_6378
apps
verifiable_code
2211
Solve the following coding problem using the programming language python: Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $(0,0)$ to $(x,0)$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $n$ favorite numbers: $a_1, a_2, \ldots, a_n$. What is the minimum number of hops Rabbit needs to get from $(0,0)$ to $(x,0)$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination. Recall that the Euclidean distance between points $(x_i, y_i)$ and $(x_j, y_j)$ is $\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$. For example, if Rabbit has favorite numbers $1$ and $3$ he could hop from $(0,0)$ to $(4,0)$ in two hops as shown below. Note that there also exists other valid ways to hop to $(4,0)$ in $2$ hops (e.g. $(0,0)$ $\rightarrow$ $(2,-\sqrt{5})$ $\rightarrow$ $(4,0)$). $1$ Here is a graphic for the first example. Both hops have distance $3$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $a_i$ and hops with distance equal to $a_i$ in any direction he wants. The same number can be used multiple times. -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$)  — the number of test cases. Next $2t$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $n$ and $x$ ($1 \le n \le 10^5$, $1 \le x \le 10^9$)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $n$ over all the test cases will not exceed $10^5$. -----Output----- For each test case, print a single integer — the minimum number of hops needed. -----Example----- Input 4 2 4 1 3 3 12 3 4 5 1 5 5 2 10 15 4 Output 2 3 1 2 -----Note----- The first test case of the sample is shown in the picture above. Rabbit can hop to $(2,\sqrt{5})$, then to $(4,0)$ for a total of two hops. Each hop has a distance of $3$, which is one of his favorite numbers. In the second test case of the sample, one way for Rabbit to hop $3$ times is: $(0,0)$ $\rightarrow$ $(4,0)$ $\rightarrow$ $(8,0)$ $\rightarrow$ $(12,0)$. In the third test case of the sample, Rabbit can hop from $(0,0)$ to $(5,0)$. In the fourth test case of the sample, Rabbit can hop: $(0,0)$ $\rightarrow$ $(5,10\sqrt{2})$ $\rightarrow$ $(10,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 #sys.stdin=open("data.txt") input=sys.stdin.readline mii=lambda:list(map(int,input().split())) for _ in range(int(input())): n,x=mii() has=0 a=0 for i in mii(): if x==i: has=1 a=max(a,i) if has: print(1) else: print(max(2,(x-1)//a+1)) ```
{ "language": "python", "test_cases": [ { "input": "4\n2 4\n1 3\n3 12\n3 4 5\n1 5\n5\n2 10\n15 4\n", "output": "2\n3\n1\n2\n", "type": "stdin_stdout" }, { "input": "1\n10 999999733\n25 68 91 55 36 29 96 4 63 3\n", "output": "10416664\n", "type": "stdin_stdout" }, { "input": "1\n19 1000000000\n15 8 22 12 10 16 2 17 14 7 20 23 9 18 3 19 21 11 1\n", "output": "43478261\n", "type": "stdin_stdout" }, { "input": "1\n1 11\n5\n", "output": "3\n", "type": "stdin_stdout" }, { "input": "1\n1 5\n2\n", "output": "3\n", "type": "stdin_stdout" }, { "input": "1\n2 9\n2 4\n", "output": "3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1307/B" }
vfc_6390
apps
verifiable_code
2212
Solve the following coding problem using the programming language python: Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: [Image] You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes. -----Input----- The first line contains two integers n and q (1 ≤ n ≤ 10^18, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer. Next q lines contain integers x_{i} (1 ≤ x_{i} ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes. -----Output----- For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes. -----Examples----- Input 4 3 2 3 4 Output 3 2 4 Input 13 4 10 5 4 8 Output 13 3 8 9 -----Note----- The first example is shown in the picture. In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7]. 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, q] = map(int, sys.stdin.readline().strip().split()) qis = [int(sys.stdin.readline().strip()) for _ in range(q)] def query(n, q): d = 2 * n - q while d % 2 == 0: d //= 2 return (n - d // 2) for qi in qis: print (query(n, qi)) ```
{ "language": "python", "test_cases": [ { "input": "4 3\n2\n3\n4\n", "output": "3\n2\n4\n", "type": "stdin_stdout" }, { "input": "13 4\n10\n5\n4\n8\n", "output": "13\n3\n8\n9\n", "type": "stdin_stdout" }, { "input": "2 2\n1\n2\n", "output": "1\n2\n", "type": "stdin_stdout" }, { "input": "1 1\n1\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "3 3\n3\n2\n1\n", "output": "2\n3\n1\n", "type": "stdin_stdout" }, { "input": "12 12\n9\n11\n5\n3\n7\n2\n8\n6\n4\n10\n12\n1\n", "output": "5\n6\n3\n2\n4\n7\n12\n8\n10\n9\n11\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/949/B" }
vfc_6394
apps
verifiable_code
2213
Solve the following coding problem using the programming language python: Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: $f(0) = a$; $f(1) = b$; $f(n) = f(n-1) \oplus f(n-2)$ when $n > 1$, where $\oplus$ denotes the bitwise XOR operation. You are given three integers $a$, $b$, and $n$, calculate $f(n)$. You have to answer for $T$ independent test cases. -----Input----- The input contains one or more independent test cases. The first line of input contains a single integer $T$ ($1 \le T \le 10^3$), the number of test cases. Each of the $T$ following lines contains three space-separated integers $a$, $b$, and $n$ ($0 \le a, b, n \le 10^9$) respectively. -----Output----- For each test case, output $f(n)$. -----Example----- Input 3 3 4 2 4 5 0 325 265 1231232 Output 7 4 76 -----Note----- In the first example, $f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python T = int(input()) for t in range(T): a, b, n = [int(i) for i in input().split()] if n%3 == 2: print(a^b) elif n%3 == 1: print(b) else: print(a) ```
{ "language": "python", "test_cases": [ { "input": "3\n3 4 2\n4 5 0\n325 265 1231232\n", "output": "7\n4\n76\n", "type": "stdin_stdout" }, { "input": "10\n0 0 1000000000\n1002 2003 36523\n233 5656 898989\n0 2352 0\n21132 23256 2323256\n12313 454878 11000\n1213 0 21\n11 1 1\n1 1 98532\n1000000000 1000000000 1000000000\n", "output": "0\n2003\n233\n0\n2132\n442567\n1213\n1\n1\n1000000000\n", "type": "stdin_stdout" }, { "input": "1\n25369 85223 58963241\n", "output": "77822\n", "type": "stdin_stdout" }, { "input": "2\n168342 440469 517112\n841620 806560 140538\n", "output": "272643\n841620\n", "type": "stdin_stdout" }, { "input": "10\n669924290 408119795 804030560\n663737793 250734602 29671646\n431160679 146708815 289491233\n189259304 606497663 379372476\n707829111 49504411 81710658\n54555019 65618101 626948607\n578351356 288589794 974275296\n400531973 205638174 323247740\n219131617 178762989 799964854\n825160173 502080627 608216046\n", "output": "1069371953\n696139211\n286024744\n189259304\n707829111\n54555019\n578351356\n463366171\n178762989\n825160173\n", "type": "stdin_stdout" }, { "input": "1\n1 2 3\n", "output": "1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1208/A" }
vfc_6398
apps
verifiable_code
2214
Solve the following coding problem using the programming language python: The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road. Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (10^9 + 7). -----Input----- The first line of the input contains a single integer n (2 ≤ n ≤ 2·10^5) — the number of cities in the country. Next line contains n - 1 positive integers p_2, p_3, p_4, ..., p_{n} (1 ≤ p_{i} ≤ i - 1) — the description of the roads in the country. Number p_{i} means that the country has a road connecting city p_{i} and city i. -----Output----- Print n integers a_1, a_2, ..., a_{n}, where a_{i} is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (10^9 + 7), if the capital of the country is at city number i. -----Examples----- Input 3 1 1 Output 4 3 3 Input 5 1 2 3 4 Output 5 8 9 8 5 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class Graph: def __init__(self, n_vertices, edges, directed=True, weighted=False): self.n_vertices = n_vertices self.edges = edges self.directed = directed self.weighted = weighted @property def adj(self): try: return self._adj except AttributeError: adj = [[] for _ in range(self.n_vertices)] def d_w(e): adj[e[0]].append((e[1],e[2])) def ud_w(e): adj[e[0]].append((e[1],e[2])) adj[e[1]].append((e[0],e[2])) def d_uw(e): adj[e[0]].append(e[1]) def ud_uw(e): adj[e[0]].append(e[1]) adj[e[1]].append(e[0]) helper = (ud_uw, d_uw, ud_w, d_w)[self.directed+self.weighted*2] for e in self.edges: helper(e) self._adj = adj return adj class RootedTree(Graph): def __init__(self, n_vertices, edges, root_vertex): self.root = root_vertex super().__init__(n_vertices, edges, False, False) @property def parent(self): try: return self._parent except AttributeError: adj = self.adj parent = [None]*self.n_vertices parent[self.root] = -1 stack = [self.root] for i in range(self.n_vertices): v = stack.pop() for u in adj[v]: if parent[u] is None: parent[u] = v stack.append(u) self._parent = parent return parent @property def children(self): try: return self._children except AttributeError: children = [None]*self.n_vertices for v,(l,p) in enumerate(zip(self.adj,self.parent)): children[v] = [u for u in l if u != p] self._children = children return children @property def dfs_order(self): try: return self._dfs_order except AttributeError: order = [None]*self.n_vertices children = self.children stack = [self.root] for i in range(self.n_vertices): v = stack.pop() order[i] = v for u in children[v]: stack.append(u) self._dfs_order = order return order from functools import reduce from itertools import accumulate,chain def rerooting(rooted_tree, merge, identity, finalize): N = rooted_tree.n_vertices parent = rooted_tree.parent children = rooted_tree.children order = rooted_tree.dfs_order # from leaf to parent dp_down = [None]*N for v in reversed(order[1:]): dp_down[v] = finalize(reduce(merge, (dp_down[c] for c in children[v]), identity)) # from parent to leaf dp_up = [None]*N dp_up[0] = identity for v in order: if len(children[v]) == 0: continue temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,) left = tuple(accumulate(temp,merge)) right = tuple(accumulate(reversed(temp[2:]),merge)) for u,l,r in zip(children[v],left,reversed(right)): dp_up[u] = finalize(merge(l,r)) res = [None]*N for v,l in enumerate(children): res[v] = reduce(merge, (dp_down[u] for u in children[v]), identity) res[v] = finalize(merge(res[v], dp_up[v])) return res def solve(T): MOD = 10**9 + 7 def merge(x,y): return (x*y)%MOD def finalize(x): return x+1 return [v-1 for v in rerooting(T,merge,1,finalize)] def __starting_point(): N = int(input()) edges = [(i+1,p-1) for i,p in enumerate(map(int,input().split()))] T = RootedTree(N, edges, 0) print(*solve(T)) __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "3\n1 1\n", "output": "4 3 3", "type": "stdin_stdout" }, { "input": "5\n1 2 3 4\n", "output": "5 8 9 8 5", "type": "stdin_stdout" }, { "input": "31\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n", "output": "73741817 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913", "type": "stdin_stdout" }, { "input": "29\n1 2 2 4 4 6 6 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28\n", "output": "191 380 191 470 236 506 254 506 504 500 494 486 476 464 450 434 416 396 374 350 324 296 266 234 200 164 126 86 44", "type": "stdin_stdout" }, { "input": "2\n1\n", "output": "2 2", "type": "stdin_stdout" }, { "input": "3\n1 2\n", "output": "3 4 3", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/543/D" }
vfc_6402
apps
verifiable_code
2216
Solve the following coding problem using the programming language python: Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q_1q_2... q_{k}. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string s = s_1s_2... s_{n}, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring s_{l}_{i}s_{l}_{i} + 1... s_{r}_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (l_{i}, r_{i}) determine if the algorithm works correctly on this test or not. -----Input----- The first line contains non-empty string s, its length (n) doesn't exceed 10^5. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 10^5) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). -----Output----- For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. -----Examples----- Input zyxxxxxxyyz 5 5 5 1 3 1 11 1 4 3 6 Output YES YES NO YES NO -----Note----- In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. 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=sys.stdin.readline().split()[0] m=int(sys.stdin.readline()) Numx=[] Numy=[] Numz=[] x=0 y=0 z=0 for i in range(len(s)): if(s[i]=='x'): x+=1 if(s[i]=='y'): y+=1 if(s[i]=='z'): z+=1 Numx.append(x) Numy.append(y) Numz.append(z) Ans="" for M in range(m): s,e=list(map(int,sys.stdin.readline().split())) if(e-s+1<=2): Ans+="YES\n" continue s-=1 e-=1 x=Numx[e] y=Numy[e] z=Numz[e] if(s!=0): x-=Numx[s-1] y-=Numy[s-1] z-=Numz[s-1] if(x==y==z): Ans+="YES\n" continue L=[x,y,z] L.sort() if(L[0]==L[1] and L[2]==L[1]+1): Ans+="YES\n" continue if(L[1]==L[2] and L[0]==L[1]-1): Ans+="YES\n" else: Ans+="NO\n" sys.stdout.write(Ans) ```
{ "language": "python", "test_cases": [ { "input": "zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6\n", "output": "YES\nYES\nNO\nYES\nNO\n", "type": "stdin_stdout" }, { "input": "yxzyzxzzxyyzzxxxzyyzzyzxxzxyzyyzxyzxyxxyzxyxzyzxyzxyyxzzzyzxyyxyzxxy\n10\n17 67\n6 35\n12 45\n56 56\n14 30\n25 54\n1 1\n46 54\n3 33\n19 40\n", "output": "NO\nNO\nNO\nYES\nYES\nNO\nYES\nNO\nNO\nYES\n", "type": "stdin_stdout" }, { "input": "xxxxyyxyyzzyxyxzxyzyxzyyyzyzzxxxxzyyzzzzyxxxxzzyzzyzx\n5\n4 4\n3 3\n1 24\n3 28\n18 39\n", "output": "YES\nYES\nNO\nNO\nNO\n", "type": "stdin_stdout" }, { "input": "yzxyzxyzxzxzyzxyzyzzzyxzyz\n9\n4 6\n2 7\n3 5\n14 24\n3 13\n2 24\n2 5\n2 14\n3 15\n", "output": "YES\nYES\nYES\nNO\nYES\nNO\nYES\nNO\nNO\n", "type": "stdin_stdout" }, { "input": "zxyzxyzyyzxzzxyzxyzx\n15\n7 10\n17 17\n6 7\n8 14\n4 7\n11 18\n12 13\n1 1\n3 8\n1 1\n9 17\n4 4\n5 11\n3 15\n1 1\n", "output": "NO\nYES\nYES\nYES\nYES\nYES\nYES\nYES\nNO\nYES\nNO\nYES\nYES\nNO\nYES\n", "type": "stdin_stdout" }, { "input": "x\n1\n1 1\n", "output": "YES\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/367/A" }
vfc_6410
apps
verifiable_code
2217
Solve the following coding problem using the programming language python: Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer d_{i}, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, d_{i} = - 1 or it's degree modulo 2 is equal to d_{i}. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. -----Input----- The first line contains two integers n, m (1 ≤ n ≤ 3·10^5, n - 1 ≤ m ≤ 3·10^5) — number of vertices and edges. The second line contains n integers d_1, d_2, ..., d_{n} ( - 1 ≤ d_{i} ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. -----Output----- Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. -----Examples----- Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 -----Note----- In the first sample we have single vertex without edges. It's degree is 0 and we can not get 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())) d = list(map(int, sys.stdin.readline().split())) gph = [[] for _ in range(n)] for _ in range(m): u, v = list(map(int, sys.stdin.readline().split())) u -= 1 v -= 1 gph[u].append((v, _)) gph[v].append((u, _)) t = -1 if d.count(1) % 2 == 1: if -1 not in d: print(-1) return t = d.index(-1) ans = [False] * m vis = [False] * n ed = [(-1, -1)] * n rets = [(d[u] == 1) or (u == t) for u in range(n)] stk = [[0, iter(gph[0])]] while len(stk) > 0: u = stk[-1][0] vis[u] = True try: while True: v, i = next(stk[-1][1]) if not vis[v]: ed[v] = (u, i) stk.append([v, iter(gph[v])]) break except StopIteration: p, e = ed[u] if p >= 0 and rets[u]: rets[p] = not rets[p] ans[e] = True stk.pop() pass print(ans.count(True)) print("\n".join([str(i+1) for i in range(m) if ans[i]])) #1231 ```
{ "language": "python", "test_cases": [ { "input": "1 0\n1\n", "output": "-1\n", "type": "stdin_stdout" }, { "input": "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2 1\n1 1\n1 2\n", "output": "1\n1\n", "type": "stdin_stdout" }, { "input": "3 3\n0 -1 1\n1 2\n2 3\n1 3\n", "output": "1\n2\n", "type": "stdin_stdout" }, { "input": "10 10\n-1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n6 7\n8 3\n6 4\n4 2\n9 2\n5 10\n9 8\n10 7\n5 1\n6 2\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "3 2\n1 0 1\n1 2\n2 3\n", "output": "2\n2\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/840/B" }
vfc_6414
apps
verifiable_code
2218
Solve the following coding problem using the programming language python: There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt. You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the numer of citizens. The next line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_{i} \le 10^{9}$) — the initial balances of citizens. The next line contains a single integer $q$ ($1 \le q \le 2 \cdot 10^{5}$) — the number of events. Each of the next $q$ lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x ($1 \le p \le n$, $0 \le x \le 10^{9}$), or 2 x ($0 \le x \le 10^{9}$). In the first case we have a receipt that the balance of the $p$-th person becomes equal to $x$. In the second case we have a payoff with parameter $x$. -----Output----- Print $n$ integers — the balances of all citizens after all events. -----Examples----- Input 4 1 2 3 4 3 2 3 1 2 2 2 1 Output 3 2 3 4 Input 5 3 50 2 1 10 3 1 2 0 2 8 1 3 20 Output 8 8 20 8 10 -----Note----- In the first example the balances change as follows: 1 2 3 4 $\rightarrow$ 3 3 3 4 $\rightarrow$ 3 2 3 4 $\rightarrow$ 3 2 3 4 In the second example the balances change as follows: 3 50 2 1 10 $\rightarrow$ 3 0 2 1 10 $\rightarrow$ 8 8 8 8 10 $\rightarrow$ 8 8 20 8 10 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())) q=int(input()) changes=[0]*q for i in range(q): changes[-i-1]=tuple(map(int,input().split())) final=[-1]*n curr=0 for guy in changes: if guy[0]==1: if final[guy[1]-1]==-1: final[guy[1]-1]=max(guy[2],curr) else: curr=max(curr,guy[1]) for i in range(n): if final[i]==-1: final[i]=max(curr,a[i]) final=[str(guy) for guy in final] print(" ".join(final)) ```
{ "language": "python", "test_cases": [ { "input": "4\n1 2 3 4\n3\n2 3\n1 2 2\n2 1\n", "output": "3 2 3 4 \n", "type": "stdin_stdout" }, { "input": "5\n3 50 2 1 10\n3\n1 2 0\n2 8\n1 3 20\n", "output": "8 8 20 8 10 \n", "type": "stdin_stdout" }, { "input": "10\n1 2 3 4 5 6 7 8 9 10\n10\n2 1\n2 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n", "output": "10 10 10 10 10 10 10 10 10 10 \n", "type": "stdin_stdout" }, { "input": "5\n1 2 3 4 5\n10\n1 1 0\n2 1\n1 2 0\n2 2\n1 3 0\n2 3\n1 4 0\n2 4\n1 5 0\n2 5\n", "output": "5 5 5 5 5 \n", "type": "stdin_stdout" }, { "input": "10\n7 9 4 4 7 6 3 7 9 8\n10\n1 3 2\n1 10 5\n1 5 3\n1 5 2\n1 2 9\n1 2 9\n1 2 10\n1 5 7\n1 6 10\n1 10 9\n", "output": "7 10 2 4 7 10 3 7 9 9 \n", "type": "stdin_stdout" }, { "input": "1\n1\n3\n2 4\n1 1 2\n2 10\n", "output": "10 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1198/B" }
vfc_6418
apps
verifiable_code
2219
Solve the following coding problem using the programming language python: During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters. The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: $1$, $2$, $3$, so that each character is painted in at most one color, and the description of the $i$-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color $i$. The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace. -----Input----- The first line of the input contains two integers $n, q$ ($1 \leq n \leq 100\,000$, $1 \leq q \leq 1000$) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length $n$ consisting of lowercase English characters. Each of the following line describes a single evolution and is in one of the following formats: + $i$ $c$ ($i \in \{1, 2, 3\}$, $c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}$: append the character $c$ to the end of $i$-th religion description. - $i$ ($i \in \{1, 2, 3\}$) – remove the last character from the $i$-th religion description. You can assume that the pattern is non-empty. You can assume that no religion will have description longer than $250$ characters. -----Output----- Write $q$ lines. The $i$-th of them should be YES if the religions could coexist in peace after the $i$-th evolution, or NO otherwise. You can print each character in any case (either upper or lower). -----Examples----- Input 6 8 abdabc + 1 a + 1 d + 2 b + 2 c + 3 a + 3 b + 1 c - 2 Output YES YES YES YES YES YES NO YES Input 6 8 abbaab + 1 a + 2 a + 3 a + 1 b + 2 b + 3 b - 1 + 2 z Output YES YES YES YES YES NO YES NO -----Note----- In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe: $\left. \begin{array}{|c|c|c|c|c|c|c|} \hline \text{Word} & {a} & {b} & {d} & {a} & {b} & {c} \\ \hline ad & {a} & {} & {d} & {} & {} & {} \\ \hline bc & {} & {b} & {} & {} & {} & {c} \\ \hline ab & {} & {} & {} & {a} & {b} & {} \\ \hline \end{array} \right.$ The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, q = map(int, input().split()) s = '!' + input() nxt = [[n + 1] * (n + 2) for _ in range(26)] for i in range(n - 1, -1, -1): c = ord(s[i + 1]) - 97 for j in range(26): nxt[j][i] = nxt[j][i + 1] nxt[c][i] = i + 1 w = [[-1], [-1], [-1]] idx = lambda i, j, k: i * 65536 + j * 256 + k dp = [0] * (256 * 256 * 256) def calc(fix=None): r = list(map(range, (len(w[0]), len(w[1]), len(w[2])))) if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix])) for i in r[0]: for j in r[1]: for k in r[2]: dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1, nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1, nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1) if i == j == k == 0: dp[idx(i, j, k)] = 0 out = [] for _ in range(q): t, *r = input().split() if t == '+': i, c = int(r[0]) - 1, ord(r[1]) - 97 w[i].append(c) calc(i) else: i = int(r[0]) - 1 w[i].pop() req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)] out.append('YES' if req <= n else 'NO') print(*out, sep='\n') ```
{ "language": "python", "test_cases": [ { "input": "6 8\nabdabc\n+ 1 a\n+ 1 d\n+ 2 b\n+ 2 c\n+ 3 a\n+ 3 b\n+ 1 c\n- 2\n", "output": "YES\nYES\nYES\nYES\nYES\nYES\nNO\nYES\n", "type": "stdin_stdout" }, { "input": "6 8\nabbaab\n+ 1 a\n+ 2 a\n+ 3 a\n+ 1 b\n+ 2 b\n+ 3 b\n- 1\n+ 2 z\n", "output": "YES\nYES\nYES\nYES\nYES\nNO\nYES\nNO\n", "type": "stdin_stdout" }, { "input": "1 1\nz\n+ 3 z\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "1 1\nt\n+ 2 p\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "2 12\naa\n+ 1 a\n+ 2 a\n+ 3 a\n- 1\n+ 1 a\n- 2\n+ 2 a\n- 3\n+ 3 a\n+ 2 a\n- 1\n- 3\n", "output": "YES\nYES\nNO\nYES\nNO\nYES\nNO\nYES\nNO\nNO\nNO\nYES\n", "type": "stdin_stdout" }, { "input": "2 10\nuh\n+ 1 h\n+ 2 u\n+ 3 h\n- 1\n- 2\n+ 2 h\n+ 3 u\n- 2\n+ 1 u\n- 3\n", "output": "YES\nYES\nNO\nYES\nYES\nNO\nNO\nNO\nNO\nYES\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1149/B" }
vfc_6422
apps
verifiable_code
2220
Solve the following coding problem using the programming language python: Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him. Initially there are $n$ dishes with costs $a_1, a_2, \ldots, a_n$. As you already know, there are the queue of $m$ pupils who have $b_1, \ldots, b_m$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $b_1$ togrogs and the last one has $b_m$ togrogs) Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...) But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining. Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $q$ queries: change $a_i$ to $x$. It means that the price of the $i$-th dish becomes $x$ togrogs. change $b_i$ to $x$. It means that the $i$-th pupil in the queue has $x$ togrogs now. Nobody leaves the queue during those queries because a saleswoman is late. After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $-1$ if there are no dishes at this point, according to rules described above. -----Input----- The first line contains integers $n$ and $m$ ($1 \leq n, m \leq 300\ 000$) — number of dishes and pupils respectively. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^{6}$) — elements of array $a$. The third line contains $m$ integers $b_1, b_2, \ldots, b_{m}$ ($1 \leq b_i \leq 10^{6}$) — elements of array $b$. The fourth line conatins integer $q$ ($1 \leq q \leq 300\ 000$) — number of queries. Each of the following $q$ lines contains as follows: if a query changes price of some dish, it contains $1$, and two integers $i$ and $x$ ($1 \leq i \leq n$, $1 \leq x \leq 10^{6}$), what means $a_i$ becomes $x$. if a query changes number of togrogs of some pupil, it contains $2$, and two integers $i$ and $x$ ($1 \leq i \leq m$, $1 \leq x \leq 10^{6}$), what means $b_i$ becomes $x$. -----Output----- For each of $q$ queries prints the answer as the statement describes, the answer of the $i$-th query in the $i$-th line (the price of the dish which Serge will buy or $-1$ if nothing remains) -----Examples----- Input 1 1 1 1 1 1 1 100 Output 100 Input 1 1 1 1 1 2 1 100 Output -1 Input 4 6 1 8 2 4 3 3 6 1 5 2 3 1 1 1 2 5 10 1 1 6 Output 8 -1 4 -----Note----- In the first sample after the first query, there is one dish with price $100$ togrogs and one pupil with one togrog, so Serge will buy the dish with price $100$ togrogs. In the second sample after the first query, there is one dish with price one togrog and one pupil with $100$ togrogs, so Serge will get nothing. In the third sample after the first query, nobody can buy the dish with price $8$, so Serge will take it. After the second query, all dishes will be bought, after the third one the third and fifth pupils will by the first and the second dishes respectively and nobody will by the fourth one. 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 itertools import accumulate class Lazysegtree: #RAQ def __init__(self, A, intv, initialize = True, segf = min): #区間は 1-indexed で管理 self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv self.segf = segf self.lazy = [0]*(2*self.N0) if initialize: self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N) for i in range(self.N0-1, 0, -1): self.data[i] = self.segf(self.data[2*i], self.data[2*i+1]) else: self.data = [intv]*(2*self.N0) def _ascend(self, k): k = k >> 1 c = k.bit_length() for j in range(c): idx = k >> j self.data[idx] = self.segf(self.data[2*idx], self.data[2*idx+1]) \ + self.lazy[idx] def _descend(self, k): k = k >> 1 idx = 1 c = k.bit_length() for j in range(1, c+1): idx = k >> (c - j) ax = self.lazy[idx] if not ax: continue self.lazy[idx] = 0 self.data[2*idx] += ax self.data[2*idx+1] += ax self.lazy[2*idx] += ax self.lazy[2*idx+1] += ax def query(self, l, r): L = l+self.N0 R = r+self.N0 Li = L//(L & -L) Ri = R//(R & -R) self._descend(Li) self._descend(Ri - 1) s = self.intv while L < R: if R & 1: R -= 1 s = self.segf(s, self.data[R]) if L & 1: s = self.segf(s, self.data[L]) L += 1 L >>= 1 R >>= 1 return s def add(self, l, r, x): L = l+self.N0 R = r+self.N0 Li = L//(L & -L) Ri = R//(R & -R) while L < R : if R & 1: R -= 1 self.data[R] += x self.lazy[R] += x if L & 1: self.data[L] += x self.lazy[L] += x L += 1 L >>= 1 R >>= 1 self._ascend(Li) self._ascend(Ri-1) def binsearch(self, l, r, check, reverse = False): L = l+self.N0 R = r+self.N0 Li = L//(L & -L) Ri = R//(R & -R) self._descend(Li) self._descend(Ri-1) SL, SR = [], [] while L < R: if R & 1: R -= 1 SR.append(R) if L & 1: SL.append(L) L += 1 L >>= 1 R >>= 1 if reverse: for idx in (SR + SL[::-1]): if check(self.data[idx]): break else: return -1 while idx < self.N0: ax = self.lazy[idx] self.lazy[idx] = 0 self.data[2*idx] += ax self.data[2*idx+1] += ax self.lazy[2*idx] += ax self.lazy[2*idx+1] += ax idx = idx << 1 if check(self.data[idx+1]): idx += 1 return idx - self.N0 else: for idx in (SL + SR[::-1]): if check(self.data[idx]): break else: return -1 while idx < self.N0: ax = self.lazy[idx] self.lazy[idx] = 0 self.data[2*idx] += ax self.data[2*idx+1] += ax self.lazy[2*idx] += ax self.lazy[2*idx+1] += ax idx = idx << 1 if not check(self.data[idx]): idx += 1 return idx - self.N0 def provfunc(self): idx = 1 if self.data[1] >= 0: return -1 while idx < self.N0: ax = self.lazy[idx] self.lazy[idx] = 0 self.data[2*idx] += ax self.data[2*idx+1] += ax self.lazy[2*idx] += ax self.lazy[2*idx+1] += ax idx = idx << 1 if self.data[idx+1] < 0: idx += 1 return idx - self.N0 N, M = list(map(int, input().split())) A = list(map(int, input().split())) B = list(map(int, input().split())) table = [0]*(10**6+1) for a in A: table[a] -= 1 for b in B: table[b] += 1 table = list(accumulate(table[::-1]))[::-1] T = Lazysegtree(table, 0, True, min) Q = int(input()) Ans = [None]*Q for q in range(Q): t, i, x = list(map(int, sys.stdin.readline().split())) i -= 1 if t == 1: T.add(0, x+1, -1) T.add(0, A[i]+1, 1) A[i] = x else: T.add(0, x+1, 1) T.add(0, B[i]+1, -1) B[i] = x Ans[q] = T.provfunc() print('\n'.join(map(str, Ans))) ```
{ "language": "python", "test_cases": [ { "input": "1 1\n1\n1\n1\n1 1 100\n", "output": "100\n", "type": "stdin_stdout" }, { "input": "1 1\n1\n1\n1\n2 1 100\n", "output": "-1\n", "type": "stdin_stdout" }, { "input": "4 6\n1 8 2 4\n3 3 6 1 5 2\n3\n1 1 1\n2 5 10\n1 1 6\n", "output": "8\n-1\n4\n", "type": "stdin_stdout" }, { "input": "3 5\n3 2 8\n1 2 8 1 1\n4\n1 3 3\n1 2 2\n2 2 10\n1 1 5\n", "output": "3\n3\n2\n2\n", "type": "stdin_stdout" }, { "input": "4 1\n7 6 1 1\n3\n3\n2 1 9\n2 1 10\n2 1 6\n", "output": "6\n6\n7\n", "type": "stdin_stdout" }, { "input": "5 1\n8 4 8 7 3\n9\n5\n2 1 3\n1 5 1\n2 1 8\n2 1 7\n2 1 3\n", "output": "8\n8\n8\n8\n8\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1179/C" }
vfc_6426
apps
verifiable_code
2222
Solve the following coding problem using the programming language python: The mobile application store has a new game called "Subway Roller". The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field. All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel. Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column. [Image] -----Input----- Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains. -----Output----- For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise. -----Examples----- Input 2 16 4 ...AAAAA........ s.BBB......CCCCC ........DDDDD... 16 4 ...AAAAA........ s.BBB....CCCCC.. .......DDDDD.... Output YES NO Input 2 10 4 s.ZZ...... .....AAABB .YYYYYY... 10 4 s.ZZ...... ....AAAABB .YYYYYY... Output YES NO -----Note----- In the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel. Note that in this problem the challenges are restricted to tests that contain only one testset. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def dfs(x, y): vis.append((x, y)) y += 1 nonlocal flag if flag or str.isalpha(grid[x][y]): return if y >= n - 1: flag = True return # stay idle if not str.isalpha(grid[x][y + 1]) and not str.isalpha(grid[x][y + 2]) and (x, y + 2) not in vis: dfs(x, y + 2) # move down if x > 0 and not str.isalpha(grid[x - 1][y]) and not str.isalpha(grid[x - 1][y + 1]) and not str.isalpha(grid[x - 1][y + 2]) and (x - 1, y + 2) not in vis: dfs(x - 1, y + 2) #move up if x < 2 and not str.isalpha(grid[x + 1][y]) and not str.isalpha(grid[x + 1][y + 1]) and not str.isalpha(grid[x + 1][y + 2]) and (x + 1, y + 2) not in vis: dfs(x + 1, y + 2) T = int(input()) for loop in range(T): n, k = [ int(i) for i in input().split() ] grid = list() grid.append(input() + " ") grid.append(input() + " ") grid.append(input() + " ") vis = list() flag = False for i in range(3): if grid[i][0] == 's': grid[i] = " " + grid[i][1:] dfs(i, 0) break if flag: print("YES") else: print("NO") ```
{ "language": "python", "test_cases": [ { "input": "2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....\n", "output": "YES\nNO\n", "type": "stdin_stdout" }, { "input": "2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY...\n", "output": "YES\nNO\n", "type": "stdin_stdout" }, { "input": "1\n100 26\ns................PPPP.CCCCC..UUUUUU.........YYYQQQQQQQ...GGGGG............MMM.....JJJJ..............\n.OOOOOO....EEE....................................................SSSSSS........LLLLLL......NNNIIII.\n......FFFFFF...VVVV..ZZZBBB...KKKKK..WWWWWWWXXX..RRRRRRR......AAAAADDDDDDD.HHH............TTTTTTT...\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....\n", "output": "YES\nNO\n", "type": "stdin_stdout" }, { "input": "2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY...\n", "output": "YES\nNO\n", "type": "stdin_stdout" }, { "input": "1\n100 26\ns................PPPP.CCCCC..UUUUUU.........YYYQQQQQQQ...GGGGG............MMM.....JJJJ..............\n.OOOOOO....EEE....................................................SSSSSS........LLLLLL......NNNIIII.\n......FFFFFF...VVVV..ZZZBBB...KKKKK..WWWWWWWXXX..RRRRRRR......AAAAADDDDDDD.HHH............TTTTTTT...\n", "output": "YES\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/585/B" }
vfc_6434
apps
verifiable_code
2223
Solve the following coding problem using the programming language python: You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format. The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description). Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m. -----Input----- The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·10^6 (in particular, this means that the length of some line does not exceed 5·10^6 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty. -----Output----- If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m. -----Examples----- Input 60 3 2012-03-16 16:15:25: Disk size is 2012-03-16 16:15:25: Network failute 2012-03-16 16:16:29: Cant write varlog 2012-03-16 16:16:42: Unable to start process 2012-03-16 16:16:43: Disk size is too small 2012-03-16 16:16:53: Timeout detected Output 2012-03-16 16:16:43 Input 1 2 2012-03-16 23:59:59:Disk size 2012-03-17 00:00:00: Network 2012-03-17 00:00:01:Cant write varlog Output -1 Input 2 2 2012-03-16 23:59:59:Disk size is too sm 2012-03-17 00:00:00:Network failute dete 2012-03-17 00:00:01:Cant write varlogmysq Output 2012-03-17 00:00:00 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python # import atexit # import io # import sys # # _INPUT_LINES = sys.stdin.read().splitlines() # input = iter(_INPUT_LINES).__next__ # _OUTPUT_BUFFER = io.StringIO() # sys.stdout = _OUTPUT_BUFFER # # # @atexit.register # def write(): # sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisect from datetime import datetime def main(): n, m = list(map(int, input().split())) n -= 1 timestamps = [] raw = [] while True: s = "" try: s = input() except: print(-1) return d = datetime.strptime(s[0:19], "%Y-%m-%d %H:%M:%S") timestamps.append(int(d.timestamp())) raw.append(s[0:19]) idx = bisect.bisect_left(timestamps, timestamps[-1] - n) if len(timestamps) - idx == m: print(raw[-1]) return def __starting_point(): main() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "60 3\n2012-03-16 16:15:25: Disk size is\n2012-03-16 16:15:25: Network failute\n2012-03-16 16:16:29: Cant write varlog\n2012-03-16 16:16:42: Unable to start process\n2012-03-16 16:16:43: Disk size is too small\n2012-03-16 16:16:53: Timeout detected\n", "output": "2012-03-16 16:16:43\n", "type": "stdin_stdout" }, { "input": "1 2\n2012-03-16 23:59:59:Disk size\n2012-03-17 00:00:00: Network\n2012-03-17 00:00:01:Cant write varlog\n", "output": "-1\n", "type": "stdin_stdout" }, { "input": "2 2\n2012-03-16 23:59:59:Disk size is too sm\n2012-03-17 00:00:00:Network failute dete\n2012-03-17 00:00:01:Cant write varlogmysq\n", "output": "2012-03-17 00:00:00\n", "type": "stdin_stdout" }, { "input": "10 30\n2012-02-03 10:01:10: qQsNeHR.BLmZVMsESEKKDvqcQHHzBeddbKiIb,aDQnBKNtdcvitwtpUDGVFSh.Lx,FPBZXdSrsSDZtIJDgx!mSovndGiqHlCwCFAHy\n", "output": "-1\n", "type": "stdin_stdout" }, { "input": "2 3\n2012-02-20 16:15:00: Dis\n2012-03-16 16:15:01: Net\n2012-03-16 16:15:02: Cant write varlog\n2012-03-16 16:15:02: Unable to start process\n2012-03-16 16:16:43: Dis\n2012-03-16 16:16:53: Timeout detected\n", "output": "2012-03-16 16:15:02\n", "type": "stdin_stdout" }, { "input": "2 4\n2012-02-20 16:15:00: Dis\n2012-03-16 16:15:01: Net\n2012-03-16 16:15:02: Cant write varlog\n2012-03-16 16:15:02: Unable to start process\n2012-03-16 16:16:43: Dis\n2012-03-16 16:16:53: Timeout detected\n", "output": "-1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/245/F" }
vfc_6438
apps
verifiable_code
2224
Solve the following coding problem using the programming language python: Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers $a$ and $b$ of length $n$. How many different ways of swapping two digits in $a$ (only in $a$, not $b$) so that bitwise OR of these two numbers will be changed? In other words, let $c$ be the bitwise OR of $a$ and $b$, you need to find the number of ways of swapping two bits in $a$ so that bitwise OR will not be equal to $c$. Note that binary numbers can contain leading zeros so that length of each number is exactly $n$. Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $01010_2$ OR $10011_2$ = $11011_2$. Well, to your surprise, you are not Rudolf, and you don't need to help him$\ldots$ You are the security staff! Please find the number of ways of swapping two bits in $a$ so that bitwise OR will be changed. -----Input----- The first line contains one integer $n$ ($2\leq n\leq 10^5$) — the number of bits in each number. The second line contains a binary number $a$ of length $n$. The third line contains a binary number $b$ of length $n$. -----Output----- Print the number of ways to swap two bits in $a$ so that bitwise OR will be changed. -----Examples----- Input 5 01011 11001 Output 4 Input 6 011000 010011 Output 6 -----Note----- In the first sample, you can swap bits that have indexes $(1, 4)$, $(2, 3)$, $(3, 4)$, and $(3, 5)$. In the second example, you can swap bits that have indexes $(1, 2)$, $(1, 3)$, $(2, 4)$, $(3, 4)$, $(3, 5)$, and $(3, 6)$. 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 = [int(x) for x in input().strip()] b = [int(x) for x in input().strip()] p, q, r, s = 0, 0, 0, 0 for i in range(n): if a[i] * 2 + b[i] == 0: p += 1 if a[i] * 2 + b[i] == 1: q += 1 if a[i] * 2 + b[i] == 2: r += 1 if a[i] * 2 + b[i] == 3: s += 1 print(p*r + p*s + q*r) ```
{ "language": "python", "test_cases": [ { "input": "5\n01011\n11001\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "6\n011000\n010011\n", "output": "6\n", "type": "stdin_stdout" }, { "input": "10\n0110101101\n1010000101\n", "output": "21\n", "type": "stdin_stdout" }, { "input": "30\n011110110100010000011001000100\n110111101001011001100001101101\n", "output": "146\n", "type": "stdin_stdout" }, { "input": "2\n00\n00\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2\n00\n11\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1017/B" }
vfc_6442
apps
verifiable_code
2226
Solve the following coding problem using the programming language python: Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange. Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let $f(l,r)$ be the longest contiguous sequence of apples in the substring $s_{l}s_{l+1}\ldots s_{r}$. Help Zookeeper find $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$, or the sum of $f$ across all substrings. -----Input----- The first line contains a single integer $n$ $(1 \leq n \leq 5 \cdot 10^5)$. The next line contains a binary string $s$ of length $n$ $(s_i \in \{0,1\})$ -----Output----- Print a single integer: $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$. -----Examples----- Input 4 0110 Output 12 Input 7 1101001 Output 30 Input 12 011100011100 Output 156 -----Note----- In the first test, there are ten substrings. The list of them (we let $[l,r]$ be the substring $s_l s_{l+1} \ldots s_r$): $[1,1]$: 0 $[1,2]$: 01 $[1,3]$: 011 $[1,4]$: 0110 $[2,2]$: 1 $[2,3]$: 11 $[2,4]$: 110 $[3,3]$: 1 $[3,4]$: 10 $[4,4]$: 0 The lengths of the longest contiguous sequence of ones in each of these ten substrings are $0,1,2,2,1,2,2,1,1,0$ respectively. Hence, the answer is $0+1+2+2+1+2+2+1+1+0 = 12$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(list(range(_size))): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) n = int(input()) s = input() pref = [] curr = 0 for c in s: if c == '1': curr += 1 else: curr = 0 pref.append(curr) suff = [] curr = 0 for c in s[::-1]: if c == '1': curr += 1 else: curr = 0 suff.append(curr) suff.reverse() st = SegmentTree(suff) out = 0 add = 0 for i in range(n): if s[i] == '1': lo = -1 hi = i - pref[i] + 1 while hi - lo > 1: t = (lo + hi) // 2 if st.query(t, i - pref[i] + 1) >= pref[i]: lo = t else: hi = t add += (i - lo) #print(add) out += add print(out) ```
{ "language": "python", "test_cases": [ { "input": "4\n0110\n", "output": "12\n", "type": "stdin_stdout" }, { "input": "7\n1101001\n", "output": "30\n", "type": "stdin_stdout" }, { "input": "12\n011100011100\n", "output": "156\n", "type": "stdin_stdout" }, { "input": "100\n0110110011011111001110000110010010000111111001100001011101101000001011001101100111011111100111101110\n", "output": "23254\n", "type": "stdin_stdout" }, { "input": "1\n0\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1428/F" }
vfc_6450
apps
verifiable_code
2228
Solve the following coding problem using the programming language python: There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least $k$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends. For each day, find the maximum number of people that can go on the trip on that day. -----Input----- The first line contains three integers $n$, $m$, and $k$ ($2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$, $1 \le k < n$) — the number of people, the number of days and the number of friends each person on the trip should have in the group. The $i$-th ($1 \leq i \leq m$) of the next $m$ lines contains two integers $x$ and $y$ ($1\leq x, y\leq n$, $x\ne y$), meaning that persons $x$ and $y$ become friends on the morning of day $i$. It is guaranteed that $x$ and $y$ were not friends before. -----Output----- Print exactly $m$ lines, where the $i$-th of them ($1\leq i\leq m$) contains the maximum number of people that can go on the trip on the evening of the day $i$. -----Examples----- Input 4 4 2 2 3 1 2 1 3 1 4 Output 0 0 3 3 Input 5 8 2 2 1 4 2 5 4 5 2 4 3 5 1 4 1 3 2 Output 0 0 0 3 3 4 4 5 Input 5 7 2 1 5 3 2 2 5 3 4 1 2 5 3 1 3 Output 0 0 0 0 3 4 4 -----Note----- In the first example, $1,2,3$ can go on day $3$ and $4$. In the second example, $2,4,5$ can go on day $4$ and $5$. $1,2,4,5$ can go on day $6$ and $7$. $1,2,3,4,5$ can go on day $8$. In the third example, $1,2,5$ can go on day $5$. $1,2,3,5$ can go on day $6$ and $7$. 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 def solve(adj, m, k, uv): n = len(adj) nn = [len(a) for a in adj] q = deque() for i in range(n): if nn[i] < k: q.append(i) while q: v = q.popleft() for u in adj[v]: nn[u] -= 1 if nn[u] == k-1: q.append(u) res = [0]*m nk = len([1 for i in nn if i >= k]) res[-1] = nk for i in range(m-1, 0, -1): u1, v1 = uv[i] if nn[u1] < k or nn[v1] < k: res[i - 1] = nk continue if nn[u1] == k: q.append(u1) nn[u1] -= 1 if not q and nn[v1] == k: q.append(v1) nn[v1] -= 1 if not q: nn[u1] -= 1 nn[v1] -= 1 adj[u1].remove(v1) adj[v1].remove(u1) while q: v = q.popleft() nk -= 1 for u in adj[v]: nn[u] -= 1 if nn[u] == k - 1: q.append(u) res[i - 1] = nk return res n, m, k = map(int, input().split()) a = [set() for i in range(n)] uv = [] for i in range(m): u, v = map(int, input().split()) a[u - 1].add(v - 1) a[v - 1].add(u - 1) uv.append((u-1, v-1)) res = solve(a, m, k, uv) print(str(res)[1:-1].replace(' ', '').replace(',', '\n')) ```
{ "language": "python", "test_cases": [ { "input": "4 4 2\n2 3\n1 2\n1 3\n1 4\n", "output": "0\n0\n3\n3\n", "type": "stdin_stdout" }, { "input": "5 8 2\n2 1\n4 2\n5 4\n5 2\n4 3\n5 1\n4 1\n3 2\n", "output": "0\n0\n0\n3\n3\n4\n4\n5\n", "type": "stdin_stdout" }, { "input": "5 7 2\n1 5\n3 2\n2 5\n3 4\n1 2\n5 3\n1 3\n", "output": "0\n0\n0\n0\n3\n4\n4\n", "type": "stdin_stdout" }, { "input": "2 1 1\n2 1\n", "output": "2\n", "type": "stdin_stdout" }, { "input": "16 20 2\n10 3\n5 3\n10 5\n12 7\n7 6\n9 12\n9 6\n1 10\n11 16\n11 1\n16 2\n10 2\n14 4\n15 14\n4 13\n13 15\n1 8\n7 15\n1 7\n8 15\n", "output": "0\n0\n3\n3\n3\n3\n7\n7\n7\n7\n7\n11\n11\n11\n11\n15\n15\n15\n15\n16\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1037/E" }
vfc_6458
apps
verifiable_code
2229
Solve the following coding problem using the programming language python: Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a_1... a_{|}t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya" $\rightarrow$ "nastya". Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey. It is guaranteed that the word p can be obtained by removing the letters from word t. -----Input----- The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a_1, a_2, ..., a_{|}t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ a_{i} ≤ |t|, all a_{i} are distinct). -----Output----- Print a single integer number, the maximum number of letters that Nastya can remove. -----Examples----- Input ababcba abb 5 3 4 1 7 6 2 Output 3 Input bbbabb bb 1 6 3 4 2 5 Output 4 -----Note----- In the first sample test sequence of removing made by Nastya looks like this: "ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba" $\rightarrow$ "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba". So, Nastya will remove only three letters. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def sub(a, s): pa = 0 ps = 0 while pa < len(a) and ps < len(s): if a[pa] == s[ps]: ps += 1 pa += 1 else: pa += 1 return ps == len(s) def subword(t, ord_ar, n): t_copy = [] for i in range(len(ord_ar)): if ord_ar[i] >= n: t_copy.append(t[i]) return t_copy def check(t, p, ord_ar, n): s = subword(t, ord_ar, n) return sub(s, p) def bin_s(l, r, f): while r > l + 1: m = (r + l) // 2 if f(m): l = m else: r = m return l def main(): t = input().strip() p = input().strip() ord_ar = [0]*len(t) seq = list(map(int, input().strip().split())) for i,x in enumerate(seq): ord_ar[x-1] = i ans = bin_s(0, len(t), lambda n: check(t, p, ord_ar, n)) print(ans) main() ```
{ "language": "python", "test_cases": [ { "input": "ababcba\nabb\n5 3 4 1 7 6 2\n", "output": "3", "type": "stdin_stdout" }, { "input": "bbbabb\nbb\n1 6 3 4 2 5\n", "output": "4", "type": "stdin_stdout" }, { "input": "cacaccccccacccc\ncacc\n10 9 14 5 1 7 15 3 6 12 4 8 11 13 2\n", "output": "9", "type": "stdin_stdout" }, { "input": "aaaabaaabaabaaaaaaaa\naaaa\n18 5 4 6 13 9 1 3 7 8 16 10 12 19 17 15 14 11 20 2\n", "output": "16", "type": "stdin_stdout" }, { "input": "aaaaaaaadbaaabbbbbddaaabdadbbbbbdbbabbbabaabdbbdababbbddddbdaabbddbbbbabbbbbabadaadabaaaadbbabbbaddb\naaaaaaaaaaaaaa\n61 52 5 43 53 81 7 96 6 9 34 78 79 12 8 63 22 76 18 46 41 56 3 20 57 21 75 73 100 94 35 69 32 4 70 95 88 44 68 10 71 98 23 89 36 62 28 51 24 30 74 55 27 80 38 48 93 1 19 84 13 11 86 60 87 33 39 29 83 91 67 72 54 2 17 85 82 14 15 90 64 50 99 26 66 65 31 49 40 45 77 37 25 42 97 47 58 92 59 16\n", "output": "57", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/778/A" }
vfc_6462
apps
verifiable_code
2230
Solve the following coding problem using the programming language python: A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers p_{i}, a_{i} and b_{i}, where p_{i} is the price of the i-th t-shirt, a_{i} is front color of the i-th t-shirt and b_{i} is back color of the i-th t-shirt. All values p_{i} are distinct, and values a_{i} and b_{i} are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color c_{j}. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. -----Input----- The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1 000 000 000), where p_{i} equals to the price of the i-th t-shirt. The following line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3), where a_{i} equals to the front color of the i-th t-shirt. The following line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3), where b_{i} equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers. The following line contains sequence c_1, c_2, ..., c_{m} (1 ≤ c_{j} ≤ 3), where c_{j} equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. -----Output----- Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. -----Examples----- Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000 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 = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] s = [] for i in range(n): s.append([p[i], a[i], b[i]]) s = sorted(s) m = int(input()) c = [int(i) for i in input().split()] idx = [0]*4 ans = [] for i in range(m): ci = c[i] while idx[ci] < n: if s[idx[ci]][1] == ci or s[idx[ci]][2] == ci: s[idx[ci]][1] = 0 s[idx[ci]][2] = 0 ans.append(s[idx[ci]][0]) break idx[ci]+=1 if idx[ci] == n: ans.append(-1) print(*ans) ```
{ "language": "python", "test_cases": [ { "input": "5\n300 200 400 500 911\n1 2 1 2 3\n2 1 3 2 1\n6\n2 3 1 2 1 1\n", "output": "200 400 300 500 911 -1 \n", "type": "stdin_stdout" }, { "input": "2\n1000000000 1\n1 1\n1 2\n2\n2 1\n", "output": "1 1000000000 \n", "type": "stdin_stdout" }, { "input": "10\n251034796 163562337 995167403 531046374 341924810 828969071 971837553 183763940 857690534 687685084\n3 2 1 3 2 3 1 3 2 1\n2 3 3 1 2 3 2 3 3 2\n10\n1 3 2 3 2 3 3 1 2 3\n", "output": "531046374 163562337 251034796 183763940 341924810 828969071 857690534 687685084 971837553 995167403 \n", "type": "stdin_stdout" }, { "input": "20\n414468312 20329584 106106409 584924603 666547477 670032002 726095027 276840253 368277336 940941705 531635095 213813062 440421387 959075599 240727854 495316522 838268432 786936631 586382273 806443734\n3 1 2 3 3 2 2 1 3 2 3 2 3 3 3 2 1 3 1 2\n3 1 2 2 2 2 3 1 2 3 2 1 1 2 3 1 2 3 3 2\n40\n1 1 2 1 3 2 3 1 3 3 1 2 3 1 1 1 2 3 3 1 3 1 3 1 2 2 3 3 1 2 1 2 3 2 2 1 2 1 2 2\n", "output": "20329584 213813062 106106409 276840253 240727854 368277336 414468312 440421387 531635095 584924603 495316522 666547477 586382273 838268432 -1 -1 670032002 726095027 786936631 -1 940941705 -1 959075599 -1 806443734 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 \n", "type": "stdin_stdout" }, { "input": "1\n529469903\n1\n3\n1\n3\n", "output": "529469903 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/799/B" }
vfc_6466
apps
verifiable_code
2231
Solve the following coding problem using the programming language python: You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $r \times c$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $a$, passes by another country $b$, they change the dominant religion of country $b$ to the dominant religion of country $a$. In particular, a single use of your power is this: You choose a horizontal $1 \times x$ subgrid or a vertical $x \times 1$ subgrid. That value of $x$ is up to you; You choose a direction $d$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; You choose the number $s$ of steps; You command each country in the subgrid to send a missionary group that will travel $s$ steps towards direction $d$. In each step, they will visit (and in effect convert the dominant religion of) all $s$ countries they pass through, as detailed above. The parameters $x$, $d$, $s$ must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $1 \times 4$ subgrid, the direction NORTH, and $s = 2$ steps. [Image] You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. -----Input----- The first line of input contains a single integer $t$ ($1 \le t \le 2\cdot 10^4$) denoting the number of test cases. The first line of each test case contains two space-separated integers $r$ and $c$ denoting the dimensions of the grid ($1 \le r, c \le 60$). The next $r$ lines each contains $c$ characters describing the dominant religions in the countries. In particular, the $j$-th character in the $i$-th line describes the dominant religion in the country at the cell with row $i$ and column $j$, where: "A" means that the dominant religion is Beingawesomeism; "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the $r \cdot c$ in a single file is at most $3 \cdot 10^6$. -----Output----- For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. -----Example----- Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 -----Note----- In the first test case, it can be done in two usages, as follows: Usage 1: [Image] Usage 2: [Image] In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". 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 MOD = 10**9 + 7 t = int(input()) for _ in range(t): r, c = list(map(int, input().split())) s = [list(input()) for i in range(r)] cnt_a = 0 flag_kado = False flag_hen = False flag_hen2 = False if s[0][0] == "A" or s[0][c-1] == "A" or s[r-1][0] == "A" or s[r-1][c-1] == "A": flag_kado = True for i in range(r): tmp = 0 for j in range(c): if s[i][j] == "A": if i == 0 or j == 0 or i == r-1 or j == c-1: flag_hen2 = True tmp += 1 cnt_a += tmp if tmp == c and (i == 0 or i == r-1): flag_hen = True elif tmp == c: flag_kado = True for i in range(c): tmp = 0 for j in range(r): if s[j][i] == "A": tmp += 1 if tmp == r and (i == 0 or i == c-1): flag_hen = True elif tmp == r: flag_kado = True if cnt_a == c*r: print(0) elif flag_hen: print(1) elif flag_kado: print(2) elif flag_hen2: print(3) elif cnt_a != 0: print(4) else: print("MORTAL") ```
{ "language": "python", "test_cases": [ { "input": "4\n7 8\nAAPAAAAA\nPPPPAAAA\nPPPPAAAA\nAPAAPPPP\nAPAPPAPP\nAAAAPPAP\nAAAAPPAA\n6 5\nAAAAA\nAAAAA\nAAPAA\nAAPAP\nAAAPP\nAAAPP\n4 4\nPPPP\nPPPP\nPPPP\nPPPP\n3 4\nPPPP\nPAAP\nPPPP\n", "output": "2\n1\nMORTAL\n4\n", "type": "stdin_stdout" }, { "input": "1\n1 1\nA\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "1\n3 3\nAAA\nAAA\nAAA\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "1\n4 4\nAAAA\nAAAA\nAAAA\nAAAA\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "1\n2 2\nAA\nAA\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1280/B" }
vfc_6470
apps
verifiable_code
2232
Solve the following coding problem using the programming language python: ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '$\sqrt{}$' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : Press the ' + ' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes x + k. Press the '$\sqrt{}$' button. Let the number on the screen be x. After pressing this button, the number becomes $\sqrt{x}$. After that, ZS the Coder levels up, so his current level becomes k + 1. This button can only be pressed when x is a perfect square, i.e. x = m^2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '$\sqrt{}$' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5. ZS the Coder needs your help in beating the game — he wants to reach level n + 1. In other words, he needs to press the '$\sqrt{}$' button n times. Help him determine the number of times he should press the ' + ' button before pressing the '$\sqrt{}$' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level n + 1, but not necessarily a sequence minimizing the number of presses. -----Input----- The first and only line of the input contains a single integer n (1 ≤ n ≤ 100 000), denoting that ZS the Coder wants to reach level n + 1. -----Output----- Print n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the ' + ' button before pressing the '$\sqrt{}$' button at level i. Each number in the output should not exceed 10^18. However, the number on the screen can be greater than 10^18. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. -----Examples----- Input 3 Output 14 16 46 Input 2 Output 999999999999999998 44500000000 Input 4 Output 2 17 46 97 -----Note----- In the first sample case: On the first level, ZS the Coder pressed the ' + ' button 14 times (and the number on screen is initially 2), so the number became 2 + 14·1 = 16. Then, ZS the Coder pressed the '$\sqrt{}$' button, and the number became $\sqrt{16} = 4$. After that, on the second level, ZS pressed the ' + ' button 16 times, so the number becomes 4 + 16·2 = 36. Then, ZS pressed the '$\sqrt{}$' button, levelling up and changing the number into $\sqrt{36} = 6$. After that, on the third level, ZS pressed the ' + ' button 46 times, so the number becomes 6 + 46·3 = 144. Then, ZS pressed the '$\sqrt{}$' button, levelling up and changing the number into $\sqrt{144} = 12$. Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4. Also, note that pressing the ' + ' button 10 times on the third level before levelling up does not work, because the number becomes 6 + 10·3 = 36, and when the '$\sqrt{}$' button is pressed, the number becomes $\sqrt{36} = 6$ and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution. In the second sample case: On the first level, ZS the Coder pressed the ' + ' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2 + 999999999999999998·1 = 10^18. Then, ZS the Coder pressed the '$\sqrt{}$' button, and the number became $\sqrt{10^{18}} = 10^{9}$. After that, on the second level, ZS pressed the ' + ' button 44500000000 times, so the number becomes 10^9 + 44500000000·2 = 9·10^10. Then, ZS pressed the '$\sqrt{}$' button, levelling up and changing the number into $\sqrt{9 \cdot 10^{10}} = 300000$. Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Codeforces Round 372 Div 1 Problem A Author : chaotic_iak Language: Python 3.5.2 """ ################################################### SOLUTION def main(): n, = read() curr = 2 for lv in range(1, n+1): tgt = (lv*(lv+1))**2 print((tgt - curr) // lv) curr = lv*(lv+1) return #################################################### HELPERS def read(typ=int): # None: String, non-split # Not None: Split input_line = input().strip() if typ is None: return input_line return list(map(typ, input_line.split())) def write(s="\n"): if s is None: s = "" if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") write(main()) ```
{ "language": "python", "test_cases": [ { "input": "3\n", "output": "2\n17\n46\n", "type": "stdin_stdout" }, { "input": "2\n", "output": "2\n17\n", "type": "stdin_stdout" }, { "input": "4\n", "output": "2\n17\n46\n97\n", "type": "stdin_stdout" }, { "input": "1\n", "output": "2\n", "type": "stdin_stdout" }, { "input": "7\n", "output": "2\n17\n46\n97\n176\n289\n442\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/715/A" }
vfc_6474
apps
verifiable_code
2233
Solve the following coding problem using the programming language python: The Bubble Cup hypothesis stood unsolved for $130$ years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem: Given a number $m$, how many polynomials $P$ with coefficients in set ${\{0,1,2,3,4,5,6,7\}}$ have: $P(2)=m$? Help Jerry Mao solve the long standing problem! -----Input----- The first line contains a single integer $t$ $(1 \leq t \leq 5\cdot 10^5)$ - number of test cases. On next line there are $t$ numbers, $m_i$ $(1 \leq m_i \leq 10^{18})$ - meaning that in case $i$ you should solve for number $m_i$. -----Output----- For each test case $i$, print the answer on separate lines: number of polynomials $P$ as described in statement such that $P(2)=m_i$, modulo $10^9 + 7$. -----Example----- Input 2 2 4 Output 2 4 -----Note----- In first case, for $m=2$, polynomials that satisfy the constraint are $x$ and $2$. In second case, for $m=4$, polynomials that satisfy the constraint are $x^2$, $x + 2$, $2x$ and $4$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") MOD = 10 ** 9 + 7 memo = dict() def solve(m): if m not in memo: if m < 0: memo[m] = 0 if m == 0: memo[m] = 1 half = m//2 memo[m] = (solve(half) + solve(half - 1) + solve(half - 2) + solve(half - 3)) % MOD return memo[m] t = int(input()) out = [] for m in map(int, input().split()): #out.append(solve(m)) v = m//2 u = v//2 w = (v-u) out.append((u*w+u+w+1)%MOD) print('\n'.join(map(str,out))) ```
{ "language": "python", "test_cases": [ { "input": "2\n2 4\n", "output": "2\n4\n", "type": "stdin_stdout" }, { "input": "1\n9\n", "output": "9\n", "type": "stdin_stdout" }, { "input": "5\n4 1 8 3 9\n", "output": "4\n1\n9\n2\n9\n", "type": "stdin_stdout" }, { "input": "6\n8 7 8 6 8 9\n", "output": "9\n6\n9\n6\n9\n9\n", "type": "stdin_stdout" }, { "input": "8\n1 1 7 6 1 5 8 7\n", "output": "1\n1\n6\n6\n1\n4\n9\n6\n", "type": "stdin_stdout" }, { "input": "7\n9 6 3 1 3 1 7\n", "output": "9\n6\n2\n1\n2\n1\n6\n", "type": "stdin_stdout" }, { "input": "3\n9 2 8\n", "output": "9\n2\n9\n", "type": "stdin_stdout" }, { "input": "5\n3 7 3 4 7\n", "output": "2\n6\n2\n4\n6\n", "type": "stdin_stdout" }, { "input": "5\n4 8 3 2 6\n", "output": "4\n9\n2\n2\n6\n", "type": "stdin_stdout" }, { "input": "5\n2 7 4 8 3\n", "output": "2\n6\n4\n9\n2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1423/J" }
vfc_6478
apps
verifiable_code
2234
Solve the following coding problem using the programming language python: Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible. The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities. What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan. Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city. Help the King to calculate this characteristic for each of his plan. -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom. Each of the next n - 1 lines contains two distinct integers u_{i}, v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans. Each of the next q lines looks as follows: first goes number k_{i} — the number of important cities in the King's plan, (1 ≤ k_{i} ≤ n), then follow exactly k_{i} space-separated pairwise distinct numbers from 1 to n — the numbers of important cities in this plan. The sum of all k_{i}'s does't exceed 100 000. -----Output----- For each plan print a single integer — the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective. -----Examples----- Input 4 1 3 2 3 4 3 4 2 1 2 3 2 3 4 3 1 2 4 4 1 2 3 4 Output 1 -1 1 -1 Input 7 1 2 2 3 3 4 1 5 5 6 5 7 1 4 2 4 6 7 Output 2 -----Note----- In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective. In the second sample the cities to capture are 3 and 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 from collections import deque def solve(): sys.setrecursionlimit(10**6) readline = sys.stdin.readline writelines = sys.stdout.writelines N = int(readline()) G = [[] for i in range(N)] for i in range(N-1): u, v = map(int, readline().split()) G[u-1].append(v-1) G[v-1].append(u-1) # Euler tour technique S = [] FS = [0]*N; LS = [0]*N depth = [0]*N stk = [-1, 0] it = [0]*N while len(stk) > 1: v = stk[-1] i = it[v] if i == 0: FS[v] = len(S) depth[v] = len(stk) if i < len(G[v]) and G[v][i] == stk[-2]: it[v] += 1 i += 1 if i == len(G[v]): LS[v] = len(S) stk.pop() else: stk.append(G[v][i]) it[v] += 1 S.append(v) L = len(S) lg = [0]*(L+1) # Sparse Table for i in range(2, L+1): lg[i] = lg[i >> 1] + 1 st = [[L]*(L - (1 << i) + 1) for i in range(lg[L]+1)] st[0][:] = S b = 1 for i in range(lg[L]): st0 = st[i] st1 = st[i+1] for j in range(L - (b<<1) + 1): st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b]) b <<= 1 INF = 10**18 ans = [] Q = int(readline()) G0 = [[]]*N P = [0]*N deg = [0]*N KS = [0]*N A = [0]*N B = [0]*N for t in range(Q): k, *vs = map(int, readline().split()) for i in range(k): vs[i] -= 1 KS[vs[i]] = 1 vs.sort(key=FS.__getitem__) for i in range(k-1): x = FS[vs[i]]; y = FS[vs[i+1]] l = lg[y - x + 1] w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1] vs.append(w) vs.sort(key=FS.__getitem__) stk = [] prv = -1 for v in vs: if v == prv: continue while stk and LS[stk[-1]] < FS[v]: stk.pop() if stk: G0[stk[-1]].append(v) G0[v] = [] it[v] = 0 stk.append(v) prv = v que = deque() prv = -1 P[vs[0]] = -1 for v in vs: if v == prv: continue for w in G0[v]: P[w] = v deg[v] = len(G0[v]) if deg[v] == 0: que.append(v) prv = v while que: v = que.popleft() if KS[v]: a = 0 for w in G0[v]: ra = A[w]; rb = B[w] if depth[v]+1 < depth[w]: a += min(ra, rb+1) else: a += ra A[v] = INF B[v] = a else: a = 0; b = c = INF for w in G0[v]: ra = A[w]; rb = B[w] a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb)) A[v] = min(a, b+1, c+1) B[v] = b p = P[v] if p != -1: deg[p] -= 1 if deg[p] == 0: que.append(p) v = min(A[vs[0]], B[vs[0]]) if v >= INF: ans.append("-1\n") else: ans.append("%d\n" % v) for v in vs: KS[v] = 0 writelines(ans) solve() ```
{ "language": "python", "test_cases": [ { "input": "4\n1 3\n2 3\n4 3\n4\n2 1 2\n3 2 3 4\n3 1 2 4\n4 1 2 3 4\n", "output": "1\n-1\n1\n-1\n", "type": "stdin_stdout" }, { "input": "7\n1 2\n2 3\n3 4\n1 5\n5 6\n5 7\n1\n4 2 4 6 7\n", "output": "2\n", "type": "stdin_stdout" }, { "input": "7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n5\n4 1 3 5 7\n3 2 4 6\n2 1 7\n2 3 4\n3 1 6 7\n", "output": "3\n2\n1\n-1\n-1\n", "type": "stdin_stdout" }, { "input": "30\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n4 8\n4 9\n6 10\n6 11\n11 30\n11 23\n30 24\n30 25\n25 26\n25 27\n27 29\n27 28\n23 20\n23 22\n20 21\n20 19\n3 12\n3 13\n13 14\n13 15\n15 16\n15 17\n15 18\n2\n6 17 25 20 5 9 13\n10 2 4 3 14 16 18 22 29 30 19\n", "output": "3\n6\n", "type": "stdin_stdout" }, { "input": "4\n1 2\n2 3\n1 4\n1\n3 1 3 4\n", "output": "-1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/613/D" }
vfc_6482
apps
verifiable_code
2235
Solve the following coding problem using the programming language python: Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements. Right now he has a map of some imaginary city with $n$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once. One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them. Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $u$ and $v$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $w$ that the original map has a tunnel between $u$ and $w$ and a tunnel between $w$ and $v$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map. -----Input----- The first line of the input contains a single integer $n$ ($2 \leq n \leq 200\,000$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $n - 1$ lines contains two integers $u_i$ and $v_i$ ($1 \leq u_i, v_i \leq n$, $u_i \ne v_i$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $n$ stations and $n - 1$ tunnels form a tree. -----Output----- Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map. -----Examples----- Input 4 1 2 1 3 1 4 Output 6 Input 4 1 2 2 3 3 4 Output 7 -----Note----- In the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $6$. In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $(1, 4)$. For these two stations the distance is $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(): def countchildren(graph,vert,memo,pard=None): dumi=0 for child in graph[vert]: if child!=pard: if len(graph[child])==1: memo[child]=0 else: memo[child]=countchildren(graph,child,memo,vert)[0] dumi+=memo[child]+1 return((dumi,memo)) n=int(input()) neigh=[] for i in range(n): neigh.append([]) for i in range(n-1): a,b=map(int,input().split()) neigh[a-1].append(b-1) neigh[b-1].append(a-1) same=1 layer=[0] pars=[None] j=0 while layer!=[]: j+=1 newlayer=[] newpars=[] for i in range(len(layer)): for vert in neigh[layer[i]]: if vert!=pars[i]: newlayer.append(vert) newpars.append(layer[i]) layer=newlayer pars=newpars if j%2==0: same+=len(layer) bipartite=same*(n-same) info=countchildren(neigh,0,[None]*n)[1] dist=0 for guy in info: if guy!=None: dist+=(guy+1)*(n-guy-1) print((dist+bipartite)//2) import sys import threading sys.setrecursionlimit(2097152) threading.stack_size(134217728) main_thread=threading.Thread(target=main) main_thread.start() main_thread.join() ```
{ "language": "python", "test_cases": [ { "input": "4\n1 2\n1 3\n1 4\n", "output": "6\n", "type": "stdin_stdout" }, { "input": "4\n1 2\n2 3\n3 4\n", "output": "7\n", "type": "stdin_stdout" }, { "input": "2\n2 1\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "3\n2 1\n3 2\n", "output": "3\n", "type": "stdin_stdout" }, { "input": "10\n2 3\n3 9\n6 3\n9 8\n9 10\n4 8\n3 1\n3 5\n7 1\n", "output": "67\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1060/E" }
vfc_6486
apps
verifiable_code
2237
Solve the following coding problem using the programming language python: You are given a permutation $p_1, p_2, \ldots, p_n$. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment $1,2,\ldots, k$, in other words in the end there should be an integer $i$, $1 \leq i \leq n-k+1$ such that $p_i = 1, p_{i+1} = 2, \ldots, p_{i+k-1}=k$. Let $f(k)$ be the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation. You need to find $f(1), f(2), \ldots, f(n)$. -----Input----- The first line of input contains one integer $n$ ($1 \leq n \leq 200\,000$): the number of elements in the permutation. The next line of input contains $n$ integers $p_1, p_2, \ldots, p_n$: given permutation ($1 \leq p_i \leq n$). -----Output----- Print $n$ integers, the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation, for $k=1, 2, \ldots, n$. -----Examples----- Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 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 reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ class Binary_Indexed_Tree(): def __init__(self, n): self.n = n self.data = [0]*(n+1) def add(self, i, x): while i <= self.n: self.data[i] += x i += i & -i def get(self, i): return self.sum_range(i, i) def sum(self, i): ret = 0 while i: ret += self.data[i] i &= i-1 return ret def sum_range(self, l, r): return self.sum(r)-self.sum(l-1) def lower_bound(self, w): if w<=0: return 0 i = 0 k = 1<<(self.n.bit_length()) while k: if i+k <= self.n and self.data[i+k] < w: w -= self.data[i+k] i += k k >>= 1 return i+1 n = int(input()) a = list(map(int, input().split())) d = {j:i for i,j in enumerate(a)} BIT1 = Binary_Indexed_Tree(n) BIT2 = Binary_Indexed_Tree(n) BIT3 = Binary_Indexed_Tree(n) tentou = 0 ans = [] for i in range(n): tmp = 0 p = d[i+1] inv_p = n-p tentou += BIT1.sum(inv_p) BIT1.add(inv_p, 1) BIT2.add(p+1, 1) BIT3.add(p+1, p+1) m = i//2+1 mean = BIT2.lower_bound(i//2+1) tmp = 0 if i%2 == 0: tmp -= m*(m-1) else: tmp -= m*m tmp += tentou left = BIT3.sum_range(1, mean) right = BIT3.sum_range(mean, n) if i%2 == 0: left = mean*m - left right = right - mean*m else: left = mean*m - left right = right - mean*(m+1) tmp += left + right ans.append(tmp) print(*ans) ```
{ "language": "python", "test_cases": [ { "input": "5\n5 4 3 2 1\n", "output": "0 1 3 6 10 \n", "type": "stdin_stdout" }, { "input": "3\n1 2 3\n", "output": "0 0 0 \n", "type": "stdin_stdout" }, { "input": "1\n1\n", "output": "0 \n", "type": "stdin_stdout" }, { "input": "10\n5 1 6 2 8 3 4 10 9 7\n", "output": "0 1 2 3 8 9 12 12 13 13 \n", "type": "stdin_stdout" }, { "input": "100\n98 52 63 2 18 96 31 58 84 40 41 45 66 100 46 71 26 48 81 20 73 91 68 76 13 93 17 29 64 95 79 21 55 75 19 85 54 51 89 78 15 87 43 59 36 1 90 35 65 56 62 28 86 5 82 49 3 99 33 9 92 32 74 69 27 22 77 16 44 94 34 6 57 70 23 12 61 25 8 11 67 47 83 88 10 14 30 7 97 60 42 37 24 38 53 50 4 80 72 39\n", "output": "0 42 52 101 101 117 146 166 166 188 194 197 249 258 294 298 345 415 445 492 522 529 540 562 569 628 628 644 684 699 765 766 768 774 791 812 828 844 863 931 996 1011 1036 1040 1105 1166 1175 1232 1237 1251 1282 1364 1377 1409 1445 1455 1461 1534 1553 1565 1572 1581 1664 1706 1715 1779 1787 1837 1841 1847 1909 1919 1973 1976 2010 2060 2063 2087 2125 2133 2192 2193 2196 2276 2305 2305 2324 2327 2352 2361 2417 2418 2467 2468 2510 2598 2599 2697 2697 2770 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1268/C" }
vfc_6494
apps
verifiable_code
2238
Solve the following coding problem using the programming language python: Let's denote as $\text{popcount}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and $\text{popcount}(x)$ is maximum possible. If there are multiple such numbers find the smallest of them. -----Input----- The first line contains integer n — the number of queries (1 ≤ n ≤ 10000). Each of the following n lines contain two integers l_{i}, r_{i} — the arguments for the corresponding query (0 ≤ l_{i} ≤ r_{i} ≤ 10^18). -----Output----- For each query print the answer in a separate line. -----Examples----- Input 3 1 2 2 4 1 10 Output 1 3 7 -----Note----- The binary representations of numbers from 1 to 10 are listed below: 1_10 = 1_2 2_10 = 10_2 3_10 = 11_2 4_10 = 100_2 5_10 = 101_2 6_10 = 110_2 7_10 = 111_2 8_10 = 1000_2 9_10 = 1001_2 10_10 = 1010_2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def popcount(n): res = 0 while n > 0: res += n & 1 n >>= 2 def A(l, r): r += 1 t = 1 << 64 while t & (l ^ r) == 0: t >>= 1 res = l | (t - 1) #print(t, res) return res def __starting_point(): """assert(A(1, 2) == 1) assert(A(2, 4) == 3) assert(A(1, 10) == 7) assert(A(13, 13) == 13) assert(A(1, 7) == 7)""" n = int(input()) for _ in range(n): l, r = list(map(int, input().split())) res = A(l, r) print(res) __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "3\n1 2\n2 4\n1 10\n", "output": "1\n3\n7\n", "type": "stdin_stdout" }, { "input": "55\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n2 2\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n3 3\n3 4\n3 5\n3 6\n3 7\n3 8\n3 9\n3 10\n4 4\n4 5\n4 6\n4 7\n4 8\n4 9\n4 10\n5 5\n5 6\n5 7\n5 8\n5 9\n5 10\n6 6\n6 7\n6 8\n6 9\n6 10\n7 7\n7 8\n7 9\n7 10\n8 8\n8 9\n8 10\n9 9\n9 10\n10 10\n", "output": "1\n1\n3\n3\n3\n3\n7\n7\n7\n7\n2\n3\n3\n3\n3\n7\n7\n7\n7\n3\n3\n3\n3\n7\n7\n7\n7\n4\n5\n5\n7\n7\n7\n7\n5\n5\n7\n7\n7\n7\n6\n7\n7\n7\n7\n7\n7\n7\n7\n8\n9\n9\n9\n9\n10\n", "type": "stdin_stdout" }, { "input": "18\n1 10\n1 100\n1 1000\n1 10000\n1 100000\n1 1000000\n1 10000000\n1 100000000\n1 1000000000\n1 10000000000\n1 100000000000\n1 1000000000000\n1 10000000000000\n1 100000000000000\n1 1000000000000000\n1 10000000000000000\n1 100000000000000000\n1 1000000000000000000\n", "output": "7\n63\n511\n8191\n65535\n524287\n8388607\n67108863\n536870911\n8589934591\n68719476735\n549755813887\n8796093022207\n70368744177663\n562949953421311\n9007199254740991\n72057594037927935\n576460752303423487\n", "type": "stdin_stdout" }, { "input": "3\n0 0\n1 3\n2 4\n", "output": "0\n3\n3\n", "type": "stdin_stdout" }, { "input": "17\n0 0\n0 8\n1 8\n36 39\n3 4\n3 7\n2 17\n8 12\n9 12\n10 12\n10 15\n6 14\n8 15\n9 15\n15 15\n100000000000000000 1000000000000000000\n99999999999999999 1000000000000000000\n", "output": "0\n7\n7\n39\n3\n7\n15\n11\n11\n11\n15\n7\n15\n15\n15\n576460752303423487\n576460752303423487\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/484/A" }
vfc_6498
apps
verifiable_code
2239
Solve the following coding problem using the programming language python: As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter. [Image] Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time. Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game? You have to determine the winner of the game for all initial positions of the marbles. -----Input----- The first line of input contains two integers n and m (2 ≤ n ≤ 100, $1 \leq m \leq \frac{n(n - 1)}{2}$). The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic. -----Output----- Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise. -----Examples----- Input 4 4 1 2 b 1 3 a 2 4 c 3 4 b Output BAAA ABAA BBBA BBBB Input 5 8 5 3 h 1 2 c 3 1 c 3 2 r 5 1 r 4 3 z 5 4 r 5 2 h Output BABBB BBBBB AABBB AAABA AAAAB -----Note----- Here's the graph in the first sample test case: [Image] Here's the graph in the second sample test case: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def mat(shape, inital_val=None): if len(shape) > 1: return [mat(shape[1:], inital_val) for _ in range(shape[0])] else: return [inital_val] * shape[0] def main(): n, m = [int(x) for x in input().split()] graph = [{} for _ in range(n)] for _ in range(m): v, u, c = input().split() graph[int(v) - 1][int(u) - 1] = c winner_table = mat([n, n, 26]) def get_winner(u, v, char_to_beat): """ Args: u: The position of current turn's player. v: The position of next turn's player. char_to_beat: The character played in the previous round. Returns: 'A' if current turn's player wins, 'B' otherwise. """ char_idx = ord(char_to_beat) - ord('a') if not winner_table[u][v][char_idx]: winner = 'B' for w, c in list(graph[u].items()): if c >= char_to_beat and get_winner(v, w, c) == 'B': winner = 'A' break winner_table[u][v][char_idx] = winner return winner_table[u][v][char_idx] for i in range(n): print(''.join(get_winner(i, j, 'a') for j in range(n))) def __starting_point(): main() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "4 4\n1 2 b\n1 3 a\n2 4 c\n3 4 b\n", "output": "BAAA\nABAA\nBBBA\nBBBB\n", "type": "stdin_stdout" }, { "input": "5 8\n5 3 h\n1 2 c\n3 1 c\n3 2 r\n5 1 r\n4 3 z\n5 4 r\n5 2 h\n", "output": "BABBB\nBBBBB\nAABBB\nAAABA\nAAAAB\n", "type": "stdin_stdout" }, { "input": "2 1\n1 2 q\n", "output": "BA\nBB\n", "type": "stdin_stdout" }, { "input": "8 20\n2 4 a\n1 8 a\n1 2 v\n8 4 h\n1 7 w\n5 4 h\n2 8 h\n7 4 i\n4 3 w\n6 8 l\n1 4 v\n1 3 g\n5 3 b\n1 6 a\n7 3 w\n6 4 f\n6 7 g\n7 8 n\n5 8 g\n2 6 j\n", "output": "BAAAAAAA\nBBAAAABA\nBBBBBBBB\nBAABAABA\nBAAABABA\nBAAAABAA\nBAAAAABA\nBAAABABB\n", "type": "stdin_stdout" }, { "input": "3 2\n1 3 l\n2 1 v\n", "output": "BBA\nABA\nBBB\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/917/B" }
vfc_6502
apps
verifiable_code
2246
Solve the following coding problem using the programming language python: Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $X[i]$ grams on day $i$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $A$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $C[i]$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $K$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $-1$. -----Input----- The first one contains two integer numbers, integers $N$ $(1 \leq N \leq 10^5)$ and $K$ $(1 \leq K \leq 10^5)$ – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $N$ integer numbers $X[i]$ $(1 \leq X[i] \leq 10^9)$ separated by a single space representing how many grams Alan wants to lift on day $i$. The third line contains one integer number $A$ $(1 \leq A \leq 10^9)$ representing permanent performance gains from a single drink. The last line contains $N$ integer numbers $C[i]$ $(1 \leq C[i] \leq 10^9)$ , representing cost of performance booster drink in the gym he visits on day $i$. -----Output----- One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1. -----Examples----- Input 5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6 Output 5 Input 5 10000 10000 40000 30000 30000 20000 10000 5 2 8 3 6 Output -1 -----Note----- First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2. 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 heapq import heappop,heappush def main(): n,k = map(int,stdin.readline().split()) X = list(map(int,stdin.readline().split())) A = int(stdin.readline().strip()) C = list(map(int,stdin.readline().split())) l = list() i = 0;g = k;ans = 0;flag = True while i < n and flag: heappush(l,C[i]) if X[i] > g: while len(l)!= 0 and X[i] > g: ans+= heappop(l) g+= A if len(l) == 0 and X[i] > g: flag = False i+=1 if flag: print(ans) else: print(-1) main() ```
{ "language": "python", "test_cases": [ { "input": "5 10000\n10000 30000 30000 40000 20000\n20000\n5 2 8 3 6\n", "output": "5\n", "type": "stdin_stdout" }, { "input": "5 10000\n10000 40000 30000 30000 20000\n10000\n5 2 8 3 6\n", "output": "-1\n", "type": "stdin_stdout" }, { "input": "5 49\n22 23 11 17 49\n50\n102 55 77 34 977\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "5 1\n1 1 1 2 9\n1000000000\n10 20 30 40 50\n", "output": "10\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1218/F" }
vfc_6530
apps
verifiable_code
2248
Solve the following coding problem using the programming language python: Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division. To improve his division skills, Oleg came up with $t$ pairs of integers $p_i$ and $q_i$ and for each pair decided to find the greatest integer $x_i$, such that: $p_i$ is divisible by $x_i$; $x_i$ is not divisible by $q_i$. Oleg is really good at division and managed to find all the answers quickly, how about you? -----Input----- The first line contains an integer $t$ ($1 \le t \le 50$) — the number of pairs. Each of the following $t$ lines contains two integers $p_i$ and $q_i$ ($1 \le p_i \le 10^{18}$; $2 \le q_i \le 10^{9}$) — the $i$-th pair of integers. -----Output----- Print $t$ integers: the $i$-th integer is the largest $x_i$ such that $p_i$ is divisible by $x_i$, but $x_i$ is not divisible by $q_i$. One can show that there is always at least one value of $x_i$ satisfying the divisibility conditions for the given constraints. -----Example----- Input 3 10 4 12 6 179 822 Output 10 4 179 -----Note----- For the first pair, where $p_1 = 10$ and $q_1 = 4$, the answer is $x_1 = 10$, since it is the greatest divisor of $10$ and $10$ is not divisible by $4$. For the second pair, where $p_2 = 12$ and $q_2 = 6$, note that $12$ is not a valid $x_2$, since $12$ is divisible by $q_2 = 6$; $6$ is not valid $x_2$ as well: $6$ is also divisible by $q_2 = 6$. The next available divisor of $p_2 = 12$ is $4$, which is the answer, since $4$ is not divisible by $6$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline def PrimeDecomposition(N): ret = {} n = int(N ** 0.5) for d in range(2, n + 1): while N % d == 0: if d not in ret: ret[d] = 1 else: ret[d] += 1 N //= d if N == 1: break if N != 1: ret[N] = 1 return ret for _ in range(int(input())): p, q = list(map(int, input().split())) if p % q != 0: print(p) continue prime = PrimeDecomposition(q) C = {} mi = p for pr in prime: C = 0 tmp = p while tmp % pr == 0: C += 1 tmp //= pr mi = min(mi, pr ** (C - prime[pr] + 1)) print(p // mi) def __starting_point(): main() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "3\n10 4\n12 6\n179 822\n", "output": "10\n4\n179\n", "type": "stdin_stdout" }, { "input": "10\n246857872446986130 713202678\n857754240051582063 933416507\n873935277189052612 530795521\n557307185726829409 746530097\n173788420792057536 769449696\n101626841876448103 132345797\n598448092106640578 746411314\n733629261048200000 361714100\n981271355542147402 38\n559754147245184151 431517529\n", "output": "123428936223493065\n918940509\n37932865019708\n1\n57929473597352512\n767888699\n299224046053320289\n31896924393400000\n490635677771073701\n26946235365387\n", "type": "stdin_stdout" }, { "input": "10\n228282288 228282288\n1000000000000000000 1000000000\n1244094302301841 35271721\n998005893107997601 999002449\n999999874000003969 999999937\n956980859148255595 5\n1 323\n1 1000000000\n424001357601318819 537974673\n100000000 1000000000\n", "output": "114141144\n976562500000000\n5939\n31607\n1\n191396171829651119\n1\n1\n424001357601318819\n100000000\n", "type": "stdin_stdout" }, { "input": "1\n42034266112 80174\n", "output": "1048576\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1444/A" }
vfc_6538
apps
verifiable_code
2251
Solve the following coding problem using the programming language python: Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company. There are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company — initially, the $i$-th person earns $i$ rubles per day. On each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again. Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$. At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it? -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $0 \le m \le 100\,000$) — the number of employees in the company and the number of pairs of people who don't like each other. Each of the following $m$ lines contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$, $a_i \neq b_i$) denoting that employees $a_i$ and $b_i$ hate each other (that is, $a_i$ dislikes $b_i$ and $b_i$ dislikes $a_i$). Each such relationship will be mentioned exactly once. The next line contains an integer $q$ ($0 \le q \le 100\,000$) — the number of salary revisions. The $i$-th of the following $q$ lines contains a single integer $v_i$ ($1 \le v_i \le n$) denoting that at the end of the $i$-th day, employee $v_i$ will earn the most. -----Output----- Output $q + 1$ integers. The $i$-th of them should contain the number of dangerous triples in the company at the beginning of the $i$-th day. -----Examples----- Input 4 5 1 2 2 4 1 3 3 4 2 3 2 2 3 Output 4 3 2 Input 3 3 1 2 2 3 1 3 5 1 2 2 1 3 Output 1 1 1 1 1 1 -----Note----- Consider the first sample test. The $i$-th row in the following image shows the structure of the company at the beginning of the $i$-th day. A directed edge from $a$ to $b$ denotes that employee $a$ brags to employee $b$. The dangerous triples are marked by highlighted edges. [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 n, m = list(map(int, sys.stdin.readline().strip().split())) L = [0 for i in range (0, n)] H = [[] for i in range (0, n)] for i in range (0, m): x, y = list(map(int, sys.stdin.readline().strip().split())) x = x - 1 y = y - 1 if x > y: x, y = y, x L[y] = L[y] + 1 H[x].append(y) ans = 0 for i in range (0, n): ans = ans + L[i] * len(H[i]) print(ans) q = int(sys.stdin.readline().strip()) for i in range (0, q): v = int(sys.stdin.readline().strip()) - 1 ans = ans - L[v] * len(H[v]) L[v] = L[v] + len(H[v]) while len(H[v]) > 0: w = H[v].pop() H[w].append(v) L[w] = L[w] - 1 ans = ans + L[w] - len(H[w]) + 1 print(ans) ```
{ "language": "python", "test_cases": [ { "input": "4 5\n1 2\n2 4\n1 3\n3 4\n2 3\n2\n2\n3\n", "output": "4\n3\n2\n", "type": "stdin_stdout" }, { "input": "3 3\n1 2\n2 3\n1 3\n5\n1\n2\n2\n1\n3\n", "output": "1\n1\n1\n1\n1\n1\n", "type": "stdin_stdout" }, { "input": "1 0\n0\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "10 20\n9 1\n5 3\n7 9\n1 8\n10 7\n9 5\n5 7\n6 5\n10 9\n6 4\n8 7\n7 6\n2 3\n4 5\n10 1\n1 4\n1 2\n5 1\n5 10\n1 7\n40\n6\n9\n10\n4\n1\n3\n9\n4\n9\n4\n3\n7\n6\n4\n7\n2\n4\n2\n5\n3\n4\n3\n8\n7\n7\n2\n8\n3\n4\n4\n6\n4\n5\n10\n9\n3\n9\n5\n6\n7\n", "output": "30\n27\n27\n27\n25\n24\n17\n20\n22\n22\n22\n22\n20\n25\n25\n20\n21\n21\n21\n21\n28\n30\n30\n29\n24\n24\n24\n28\n28\n28\n28\n33\n33\n25\n23\n24\n25\n25\n18\n22\n24\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1229/C" }
vfc_6550
apps
verifiable_code
2252
Solve the following coding problem using the programming language python: After learning a lot about space exploration, a little girl named Ana wants to change the subject. Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it: You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $(i,j)$ is considered the same as the pair $(j,i)$. -----Input----- The first line contains a positive integer $N$ ($1 \le N \le 100\,000$), representing the length of the input array. Eacg of the next $N$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array. The total number of characters in the input array will be less than $1\,000\,000$. -----Output----- Output one number, representing how many palindrome pairs there are in the array. -----Examples----- Input 3 aa bb cd Output 1 Input 6 aab abcac dffe ed aa aade Output 6 -----Note----- The first example: aa $+$ bb $\to$ abba. The second example: aab $+$ abcac $=$ aababcac $\to$ aabccbaa aab $+$ aa $=$ aabaa abcac $+$ aa $=$ abcacaa $\to$ aacbcaa dffe $+$ ed $=$ dffeed $\to$ fdeedf dffe $+$ aade $=$ dffeaade $\to$ adfaafde ed $+$ aade $=$ edaade $\to$ aeddea 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 """ Created on Wed Feb 28 11:47:12 2018 @author: mikolajbinkowski """ import sys N = int(input()) string_count = {} for _ in range(N): s = str(input()) char_count = {} for c in s: char_count[c] = char_count.get(c, 0) + 1 s0 = [] for a in 'abcdefghijklmnopqrstuvwxyz': if char_count.get(a, 0) % 2 == 1: s0.append(a) s1 = ''.join(s0) string_count[s1] = string_count.get(s1, 0) + 1 pairs = 0 for s, v in list(string_count.items()): pairs += v * (v-1) // 2 for i in range(len(s)): pairs += v * string_count.get(s[:i] + s[i+1:], 0) print(pairs) ```
{ "language": "python", "test_cases": [ { "input": "3\naa\nbb\ncd\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "6\naab\nabcac\ndffe\ned\naa\naade\n", "output": "6\n", "type": "stdin_stdout" }, { "input": "20\niw\nix\nudb\nbg\noi\nuo\njsm\num\ns\nquy\nqo\nbxct\nng\nrmr\nnu\nps\nio\nkh\nw\nk\n", "output": "5\n", "type": "stdin_stdout" }, { "input": "17\npo\nuej\ndtc\nj\ncnj\ncn\nbt\nnrj\nyye\nkol\nz\ntm\narb\ne\nzq\nj\nk\n", "output": "4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1045/I" }
vfc_6554
apps
verifiable_code
2253
Solve the following coding problem using the programming language python: ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of n × m rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is denoted by (i, j). A player starts in the room (1, 1) and wants to reach the room (n, m). Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (i, j) and (i, j + 1) is locked, then we can't go from (i, j) to (i, j + 1). Also, one can only travel between the rooms downwards (from the room (i, j) to the room (i + 1, j)) or rightwards (from the room (i, j) to the room (i, j + 1)) provided the corresponding door is not locked. [Image] This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door. ZS the Coder considers a maze to have difficulty x if there is exactly x ways of travelling from the room (1, 1) to the room (n, m). Two ways are considered different if they differ by the sequence of rooms visited while travelling. Your task is to create a maze such that its difficulty is exactly equal to T. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right? -----Input----- The first and only line of the input contains a single integer T (1 ≤ T ≤ 10^18), the difficulty of the required maze. -----Output----- The first line should contain two integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the maze respectively. The next line should contain a single integer k (0 ≤ k ≤ 300) — the number of locked doors in the maze. Then, k lines describing locked doors should follow. Each of them should contain four integers, x_1, y_1, x_2, y_2. This means that the door connecting room (x_1, y_1) and room (x_2, y_2) is locked. Note that room (x_2, y_2) should be adjacent either to the right or to the bottom of (x_1, y_1), i.e. x_2 + y_2 should be equal to x_1 + y_1 + 1. There should not be a locked door that appears twice in the list. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. -----Examples----- Input 3 Output 3 2 0 Input 4 Output 4 3 3 1 2 2 2 3 2 3 3 1 3 2 3 -----Note----- Here are how the sample input and output looks like. The colored arrows denotes all the possible paths while a red cross denotes a locked door. In the first sample case: [Image] In the second sample case: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python corr = lambda x, y: 1 <= x <= n and 1 <= y <= m T = int(input()) a = [] while T: a.append(T % 6) T //= 6 L = len(a) n = m = L * 2 + 2 ans = [(1, 2, 2, 2), (2, 1, 2, 2)] f = [[1] * 9 for i in range(7)] f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0 f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0 p = [0] * 9 p[1] = 3, 1, 3, 2 p[2] = 4, 1, 4, 2 p[3] = 4, 2, 5, 2 p[4] = 4, 3, 5, 3 p[5] = 1, 3, 2, 3 p[6] = 1, 4, 2, 4 p[7] = 2, 4, 2, 5 p[8] = 3, 4, 3, 5 for i in range(L): bit = a[L - i - 1] for j in range(1, 9): if not f[bit][j]: continue x1, y1, x2, y2 = p[j]; D = 2 * i x1 += D; y1 += D; x2 += D; y2 += D if corr(x2, y2): ans.append((x1, y1, x2, y2)) for i in range(L - 1): x1, y1 = 5 + i * 2, 1 + i * 2 x2, y2 = 1 + i * 2, 5 + i * 2 ans.append((x1, y1, x1 + 1, y1)) ans.append((x1, y1 + 1, x1 + 1, y1 + 1)) ans.append((x2, y2, x2, y2 + 1)) ans.append((x2 + 1, y2, x2 + 1, y2 + 1)) print(n, m) print(len(ans)) [print(*i) for i in ans] ```
{ "language": "python", "test_cases": [ { "input": "3\n", "output": "4 4\n5\n1 2 2 2\n1 3 2 3\n1 4 2 4\n2 1 2 2\n4 1 4 2\n", "type": "stdin_stdout" }, { "input": "4\n", "output": "4 4\n4\n1 2 2 2\n1 3 2 3\n2 1 2 2\n4 1 4 2\n", "type": "stdin_stdout" }, { "input": "1\n", "output": "4 4\n5\n1 2 2 2\n1 3 2 3\n2 1 2 2\n3 1 3 2\n4 1 4 2\n", "type": "stdin_stdout" }, { "input": "2\n", "output": "4 4\n4\n1 2 2 2\n1 3 2 3\n2 1 2 2\n3 1 3 2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/715/D" }
vfc_6558
apps
verifiable_code
2254
Solve the following coding problem using the programming language python: Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. -----Input----- The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer type_{i} — type of the i-th event. If type_{i} = 1 or type_{i} = 2 then it is followed by an integer x_{i}. Otherwise it is followed by an integer t_{i} (1 ≤ type_{i} ≤ 3, 1 ≤ x_{i} ≤ n, 1 ≤ t_{i} ≤ q). -----Output----- Print the number of unread notifications after each event. -----Examples----- Input 3 4 1 3 1 1 1 2 2 3 Output 1 2 3 2 Input 4 6 1 2 1 4 1 2 3 3 1 3 1 3 Output 1 2 3 0 1 2 -----Note----- In the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). 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 #-*-coding:utf-8 -*- import sys,collections n,q=list(map(int,input().split())) M=collections.defaultdict(collections.deque) Q=collections.deque() L=[] s=n=m=0 for _ in range(q): y,x=list(map(int,input().split())) if 2>y: s+=1 Q.append(x) M[x].append(n) n+=1 elif 3>y: y=M.get(x) if y: s-=len(y) del M[x] else: while x>m: z=Q.popleft() y=M.get(z) if y and y[0]<x: s-=1 y.popleft() if not y:del M[z] m+=1 L.append(s) sys.stdout.write('\n'.join(map(str,L))) ```
{ "language": "python", "test_cases": [ { "input": "3 4\n1 3\n1 1\n1 2\n2 3\n", "output": "1\n2\n3\n2\n", "type": "stdin_stdout" }, { "input": "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3\n", "output": "1\n2\n3\n0\n1\n2\n", "type": "stdin_stdout" }, { "input": "10 85\n2 2\n1 10\n1 1\n2 6\n1 2\n1 4\n1 7\n2 1\n1 1\n3 3\n1 9\n1 6\n1 8\n1 10\n3 8\n2 8\n1 6\n1 3\n1 9\n1 6\n1 3\n1 8\n1 1\n1 6\n1 10\n2 1\n2 10\n1 10\n1 1\n1 10\n1 6\n1 2\n1 8\n1 3\n1 4\n1 9\n1 5\n1 5\n2 2\n2 4\n1 7\n1 1\n2 4\n1 9\n1 1\n1 7\n1 8\n3 33\n1 10\n2 2\n1 3\n1 10\n1 6\n3 32\n2 3\n1 5\n2 10\n2 2\n2 4\n2 3\n3 16\n1 3\n2 2\n1 1\n3 18\n2 2\n2 5\n1 5\n1 9\n2 4\n1 3\n1 4\n1 3\n1 6\n1 10\n2 2\n1 7\n1 7\n2 8\n1 1\n3 1\n1 8\n1 10\n1 7\n1 8\n", "output": "0\n1\n2\n2\n3\n4\n5\n4\n5\n3\n4\n5\n6\n7\n2\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n9\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n17\n16\n17\n18\n18\n19\n20\n21\n22\n3\n4\n4\n5\n6\n7\n7\n6\n7\n5\n5\n5\n5\n5\n6\n6\n7\n7\n7\n6\n7\n8\n8\n9\n10\n11\n12\n13\n13\n14\n15\n14\n15\n15\n16\n17\n18\n19\n", "type": "stdin_stdout" }, { "input": "300000 1\n1 300000\n", "output": "1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/704/A" }
vfc_6562
apps
verifiable_code
2255
Solve the following coding problem using the programming language python: Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided to upsolve the following problem: You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an even number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation. It is time to continue solving the contest, so Sasha asked you to solve this task. -----Input----- The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the size of the array. The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^{20}$) — array itself. -----Output----- Print one integer — the number of funny pairs. You should consider only pairs where $r - l + 1$ is even number. -----Examples----- Input 5 1 2 3 4 5 Output 1 Input 6 3 2 2 3 7 6 Output 3 Input 3 42 4 2 Output 0 -----Note----- Be as cool as Sasha, upsolve problems! In the first example, the only funny pair is $(2, 5)$, as $2 \oplus 3 = 4 \oplus 5 = 1$. In the second example, funny pairs are $(2, 3)$, $(1, 4)$, and $(3, 6)$. In the third example, there are no funny pairs. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) from collections import Counter as C n = ii() a = li() oe = [C(), C()] oe[1][0] = 1 x = 0 ans = 0 for i in range(n): x ^= a[i] ans += oe[i % 2][x] oe[i % 2][x] += 1 print(ans) ```
{ "language": "python", "test_cases": [ { "input": "5\n1 2 3 4 5\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "6\n3 2 2 3 7 6\n", "output": "3\n", "type": "stdin_stdout" }, { "input": "3\n42 4 2\n", "output": "0\n", "type": "stdin_stdout" }, { "input": "2\n60202 951227\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1109/A" }
vfc_6566
apps
verifiable_code
2256
Solve the following coding problem using the programming language python: This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle. After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task. In this task you are given a cell field $n \cdot m$, consisting of $n$ rows and $m$ columns, where point's coordinates $(x, y)$ mean it is situated in the $x$-th row and $y$-th column, considering numeration from one ($1 \leq x \leq n, 1 \leq y \leq m$). Initially, you stand in the cell $(1, 1)$. Every move you can jump from cell $(x, y)$, which you stand in, by any non-zero vector $(dx, dy)$, thus you will stand in the $(x+dx, y+dy)$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited). Tolik's uncle is a very respectful person. Help him to solve this task! -----Input----- The first and only line contains two positive integers $n, m$ ($1 \leq n \cdot m \leq 10^{6}$) — the number of rows and columns of the field respectively. -----Output----- Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print $n \cdot m$ pairs of integers, $i$-th from them should contain two integers $x_i, y_i$ ($1 \leq x_i \leq n, 1 \leq y_i \leq m$) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $(1, 1)$ coordinates, according to the statement. -----Examples----- Input 2 3 Output 1 1 1 3 1 2 2 2 2 3 2 1 Input 1 1 Output 1 1 -----Note----- The vectors from the first example in the order of making jumps are $(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$. 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())) ANS=[] for i in range(1,n//2+1): for j in range(1,m+1): sys.stdout.write("".join((str(i)," ",str(j),"\n"))) sys.stdout.write("".join((str(n-i+1)," ",str(m-j+1),"\n"))) if n%2==1: for j in range(1,m//2+1): sys.stdout.write("".join((str(n//2+1)," ",str(j),"\n"))) sys.stdout.write("".join((str(n//2+1)," ",str(m-j+1),"\n"))) if m%2==1: sys.stdout.write("".join((str(n//2+1)," ",str(m//2+1),"\n"))) ```
{ "language": "python", "test_cases": [ { "input": "2 3\n", "output": "1 1\n1 3\n1 2\n2 2\n2 3\n2 1", "type": "stdin_stdout" }, { "input": "1 1\n", "output": "1 1\n", "type": "stdin_stdout" }, { "input": "8 8\n", "output": "1 1\n8 8\n1 2\n8 7\n1 3\n8 6\n1 4\n8 5\n1 5\n8 4\n1 6\n8 3\n1 7\n8 2\n1 8\n8 1\n2 1\n7 8\n2 2\n7 7\n2 3\n7 6\n2 4\n7 5\n2 5\n7 4\n2 6\n7 3\n2 7\n7 2\n2 8\n7 1\n3 1\n6 8\n3 2\n6 7\n3 3\n6 6\n3 4\n6 5\n3 5\n6 4\n3 6\n6 3\n3 7\n6 2\n3 8\n6 1\n4 1\n5 8\n4 2\n5 7\n4 3\n5 6\n4 4\n5 5\n4 5\n5 4\n4 6\n5 3\n4 7\n5 2\n4 8\n5 1\n", "type": "stdin_stdout" }, { "input": "6 8\n", "output": "1 1\n6 8\n1 2\n6 7\n1 3\n6 6\n1 4\n6 5\n1 5\n6 4\n1 6\n6 3\n1 7\n6 2\n1 8\n6 1\n2 1\n5 8\n2 2\n5 7\n2 3\n5 6\n2 4\n5 5\n2 5\n5 4\n2 6\n5 3\n2 7\n5 2\n2 8\n5 1\n3 1\n4 8\n3 2\n4 7\n3 3\n4 6\n3 4\n4 5\n3 5\n4 4\n3 6\n4 3\n3 7\n4 2\n3 8\n4 1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1179/B" }
vfc_6570
apps
verifiable_code
2257
Solve the following coding problem using the programming language python: Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects must be strictly greater alphabetically than $x$ (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two strings $A$ and $B$ of the same length $n$ ($|A|=|B|=n$) consisting of the first $20$ lowercase English alphabet letters (ie. from a to t). In one move Koa: selects some subset of positions $p_1, p_2, \ldots, p_k$ ($k \ge 1; 1 \le p_i \le n; p_i \neq p_j$ if $i \neq j$) of $A$ such that $A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$ (ie. all letters on this positions are equal to some letter $x$). selects a letter $y$ (from the first $20$ lowercase letters in English alphabet) such that $y>x$ (ie. letter $y$ is strictly greater alphabetically than $x$). sets each letter in positions $p_1, p_2, \ldots, p_k$ to letter $y$. More formally: for each $i$ ($1 \le i \le k$) Koa sets $A_{p_i} = y$. Note that you can only modify letters in string $A$. Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($A = B$) or to determine that there is no way to make them equal. Help her! -----Input----- Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 10$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $n$ ($1 \le n \le 10^5$) — the length of strings $A$ and $B$. The second line of each test case contains string $A$ ($|A|=n$). The third line of each test case contains string $B$ ($|B|=n$). Both strings consists of the first $20$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($A = B$) or $-1$ if there is no way to make them equal. -----Example----- Input 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda Output 2 -1 3 2 -1 -----Note----- In the $1$-st test case Koa: selects positions $1$ and $2$ and sets $A_1 = A_2 = $ b ($\color{red}{aa}b \rightarrow \color{blue}{bb}b$). selects positions $2$ and $3$ and sets $A_2 = A_3 = $ c ($b\color{red}{bb} \rightarrow b\color{blue}{cc}$). In the $2$-nd test case Koa has no way to make string $A$ equal $B$. In the $3$-rd test case Koa: selects position $1$ and sets $A_1 = $ t ($\color{red}{a}bc \rightarrow \color{blue}{t}bc$). selects position $2$ and sets $A_2 = $ s ($t\color{red}{b}c \rightarrow t\color{blue}{s}c$). selects position $3$ and sets $A_3 = $ r ($ts\color{red}{c} \rightarrow ts\color{blue}{r}$). 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 = lambda: sys.stdin.readline().rstrip() T = int(input()) for _ in range(T): N = int(input()) A = [ord(a) - 97 for a in input()] B = [ord(a) - 97 for a in input()] X = [[0] * 20 for _ in range(20)] for a, b in zip(A, B): X[a][b] = 1 if a > b: print(-1) break else: ans = 0 for i in range(20): for j in range(i+1, 20): if X[i][j]: ans += 1 for jj in range(j+1, 20): if X[i][jj]: X[j][jj] = 1 break print(ans) ```
{ "language": "python", "test_cases": [ { "input": "5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda\n", "output": "2\n-1\n3\n2\n-1\n", "type": "stdin_stdout" }, { "input": "10\n1\na\nb\n1\nb\na\n3\nabc\ndef\n1\nt\nt\n2\nrt\ntr\n2\nrt\ntt\n2\nrt\nrr\n3\nasd\nqrt\n1\ns\nt\n1\nr\nt\n", "output": "1\n-1\n3\n0\n-1\n1\n-1\n-1\n1\n1\n", "type": "stdin_stdout" }, { "input": "3\n2\nab\nab\n1\nc\nd\n4\nqqqq\nrrrr\n", "output": "0\n1\n1\n", "type": "stdin_stdout" }, { "input": "4\n2\nee\nfe\n3\nlml\nmji\n3\nqoq\nqpp\n1\nd\ne\n", "output": "1\n-1\n-1\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1383/A" }
vfc_6574
apps
verifiable_code
2258
Solve the following coding problem using the programming language python: You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$. Find the number of different groups of three integers ($a$, $b$, $c$) such that $1\leq a\leq b\leq c$ and parallelepiped $A\times B\times C$ can be paved with parallelepipeds $a\times b\times c$. Note, that all small parallelepipeds have to be rotated in the same direction. For example, parallelepiped $1\times 5\times 6$ can be divided into parallelepipeds $1\times 3\times 5$, but can not be divided into parallelepipeds $1\times 2\times 3$. -----Input----- The first line contains a single integer $t$ ($1 \leq t \leq 10^5$) — the number of test cases. Each of the next $t$ lines contains three integers $A$, $B$ and $C$ ($1 \leq A, B, C \leq 10^5$) — the sizes of the parallelepiped. -----Output----- For each test case, print the number of different groups of three points that satisfy all given conditions. -----Example----- Input 4 1 1 1 1 6 1 2 2 2 100 100 100 Output 1 4 4 165 -----Note----- In the first test case, rectangular parallelepiped $(1, 1, 1)$ can be only divided into rectangular parallelepiped with sizes $(1, 1, 1)$. In the second test case, rectangular parallelepiped $(1, 6, 1)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 1, 3)$ and $(1, 1, 6)$. In the third test case, rectangular parallelepiped $(2, 2, 2)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 2, 2)$ and $(2, 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=100001 fac=[0 for i in range(N)] for i in range(1,N): for j in range(i,N,i): fac[j]+=1 def gcd(a,b): if a<b: a,b=b,a while b>0: a,b=b,a%b return a def ctt(A,B,C): la=fac[A] lb=fac[B] lc=fac[C] ab=gcd(A,B) ac=gcd(A,C) bc=gcd(B,C) abc=gcd(ab,C) dupabc=fac[abc] dupac=fac[ac]-dupabc dupbc=fac[bc]-dupabc dupab=fac[ab]-dupabc lax=la-dupabc-dupab-dupac lbx=lb-dupabc-dupab-dupbc lcx=lc-dupabc-dupac-dupbc ctx=lax*lbx*lcx ctx+=lax*lbx*(lc-lcx) ctx+=lax*lcx*(lb-lbx) ctx+=lcx*lbx*(la-lax) ctx+=lax*((lb-lbx)*(lc-lcx)-(dupabc+dupbc)*(dupabc+dupbc-1)/2) ctx+=lbx*((la-lax)*(lc-lcx)-(dupabc+dupac)*(dupabc+dupac-1)/2) ctx+=lcx*((la-lax)*(lb-lbx)-(dupabc+dupab)*(dupabc+dupab-1)/2) ctx+=dupab*dupac*dupbc ctx+=dupab*dupac*(dupab+dupac+2)/2 ctx+=dupab*dupbc*(dupab+dupbc+2)/2 ctx+=dupbc*dupac*(dupbc+dupac+2)/2 ctx+=dupabc*(dupab*dupac+dupab*dupbc+dupbc*dupac) ctx+=dupabc*(dupab*(dupab+1)+(dupbc+1)*dupbc+(dupac+1)*dupac)/2 ctx+=(dupabc+1)*dupabc*(dupab+dupac+dupbc)/2 ctx+=(dupabc*dupabc+dupabc*(dupabc-1)*(dupabc-2)/6) return int(ctx) n=int(input()) for _ in range(n): a,b,c = map(int,input().split()) print(ctt(a,b,c)) return ```
{ "language": "python", "test_cases": [ { "input": "4\n1 1 1\n1 6 1\n2 2 2\n100 100 100\n", "output": "1\n4\n4\n165\n", "type": "stdin_stdout" }, { "input": "10\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n", "output": "1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n", "type": "stdin_stdout" }, { "input": "10\n9 6 8\n5 5 2\n8 9 2\n2 7 9\n6 4 10\n1 1 8\n2 8 1\n10 6 3\n7 5 2\n9 5 4\n", "output": "41\n6\n21\n12\n39\n4\n7\n26\n8\n18\n", "type": "stdin_stdout" }, { "input": "1\n100000 100000 100000\n", "output": "8436\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1007/B" }
vfc_6578
apps
verifiable_code
2259
Solve the following coding problem using the programming language python: Let $a_1, \ldots, a_n$ be an array of $n$ positive integers. In one operation, you can choose an index $i$ such that $a_i = i$, and remove $a_i$ from the array (after the removal, the remaining parts are concatenated). The weight of $a$ is defined as the maximum number of elements you can remove. You must answer $q$ independent queries $(x, y)$: after replacing the $x$ first elements of $a$ and the $y$ last elements of $a$ by $n+1$ (making them impossible to remove), what would be the weight of $a$? -----Input----- The first line contains two integers $n$ and $q$ ($1 \le n, q \le 3 \cdot 10^5$)  — the length of the array and the number of queries. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \leq a_i \leq n$) — elements of the array. The $i$-th of the next $q$ lines contains two integers $x$ and $y$ ($x, y \ge 0$ and $x+y < n$). -----Output----- Print $q$ lines, $i$-th line should contain a single integer  — the answer to the $i$-th query. -----Examples----- Input 13 5 2 2 3 9 5 4 6 5 7 8 3 11 13 3 1 0 0 2 4 5 0 0 12 Output 5 11 6 1 0 Input 5 2 1 4 1 2 4 0 0 1 0 Output 2 0 -----Note----- Explanation of the first query: After making first $x = 3$ and last $y = 1$ elements impossible to remove, $a$ becomes $[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$ (we represent $14$ as $\times$ for clarity). Here is a strategy that removes $5$ elements (the element removed is colored in red): $[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$ $[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$ $[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$ $[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$ $[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$ $[\times, \times, \times, 9, 4, 5, 3, \times]$ (final state) It is impossible to remove more than $5$ elements, hence the weight is $5$. 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 bitadd(a,w,bit): x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(a,bit): ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret class RangeBIT: def __init__(self,N,indexed): self.bit1 = [0] * (N+2) self.bit2 = [0] * (N+2) self.mode = indexed def bitadd(self,a,w,bit): x = a while x <= (len(bit)-1): bit[x] += w x += x & (-1 * x) def bitsum(self,a,bit): ret = 0 x = a while x > 0: ret += bit[x] x -= x & (-1 * x) return ret def add(self,l,r,w): l = l + (1-self.mode) r = r + (1-self.mode) self.bitadd(l,-1*w*l,self.bit1) self.bitadd(r,w*r,self.bit1) self.bitadd(l,w,self.bit2) self.bitadd(r,-1*w,self.bit2) def sum(self,l,r): l = l + (1-self.mode) r = r + (1-self.mode) ret = self.bitsum(r,self.bit1) + r * self.bitsum(r,self.bit2) ret -= self.bitsum(l,self.bit1) + l * self.bitsum(l,self.bit2) return ret n,q = list(map(int,stdin.readline().split())) a = list(map(int,stdin.readline().split())) qs = [ [] for i in range(n+1) ] ans = [None] * q for loop in range(q): x,y = list(map(int,stdin.readline().split())) l = x+1 r = n-y qs[r].append((l,loop)) BIT = [0] * (n+1) for r in range(1,n+1): b = r-a[r-1] if b >= 0: L = 1 R = r+1 while R-L != 1: M = (L+R)//2 if bitsum(M,BIT) >= b: L = M else: R = M if bitsum(L,BIT) >= b: bitadd(1,1,BIT) bitadd(L+1,-1,BIT) for ql,qind in qs[r]: ans[qind] = bitsum(ql,BIT) for i in ans: print (i) ```
{ "language": "python", "test_cases": [ { "input": "13 5\n2 2 3 9 5 4 6 5 7 8 3 11 13\n3 1\n0 0\n2 4\n5 0\n0 12\n", "output": "5\n11\n6\n1\n0\n", "type": "stdin_stdout" }, { "input": "5 2\n1 4 1 2 4\n0 0\n1 0\n", "output": "2\n0\n", "type": "stdin_stdout" }, { "input": "1 1\n1\n0 0\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "30 10\n1 1 3 3 5 2 1 8 2 6 11 5 2 6 12 11 8 5 11 3 14 8 16 13 14 25 16 2 8 17\n6 3\n0 15\n1 0\n9 2\n12 16\n1 0\n17 3\n14 13\n0 22\n3 10\n", "output": "3\n15\n16\n2\n0\n16\n0\n0\n8\n4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1404/C" }
vfc_6582
apps
verifiable_code
2260
Solve the following coding problem using the programming language python: There are $n$ football teams in the world. The Main Football Organization (MFO) wants to host at most $m$ games. MFO wants the $i$-th game to be played between the teams $a_i$ and $b_i$ in one of the $k$ stadiums. Let $s_{ij}$ be the numbers of games the $i$-th team played in the $j$-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team $i$, the absolute difference between the maximum and minimum among $s_{i1}, s_{i2}, \ldots, s_{ik}$ should not exceed $2$. Each team has $w_i$ — the amount of money MFO will earn for each game of the $i$-th team. If the $i$-th team plays $l$ games, MFO will earn $w_i \cdot l$. MFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set. However, this problem is too complicated for MFO. Therefore, they are asking you to help them. -----Input----- The first line contains three integers $n$, $m$, $k$ ($3 \leq n \leq 100$, $0 \leq m \leq 1\,000$, $1 \leq k \leq 1\,000$) — the number of teams, the number of games, and the number of stadiums. The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($1 \leq w_i \leq 1\,000$) — the amount of money MFO will earn for each game of the $i$-th game. Each of the following $m$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) — the teams that can play the $i$-th game. It is guaranteed that each pair of teams can play at most one game. -----Output----- For each game in the same order, print $t_i$ ($1 \leq t_i \leq k$) — the number of the stadium, in which $a_i$ and $b_i$ will play the game. If the $i$-th game should not be played, $t_i$ should be equal to $0$. If there are multiple answers, print any. -----Example----- Input 7 11 3 4 7 8 10 10 9 3 6 2 6 1 7 6 4 3 4 6 3 1 5 3 7 5 7 3 4 2 1 4 Output 3 2 1 1 3 1 2 1 2 3 2 -----Note----- One of possible solutions to the example is shown below: [Image] The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import random import math def set_color(game, color): color_count[game[0]][game[2]] -= 1 color_count[game[1]][game[2]] -= 1 game[2] = color color_count[game[0]][game[2]] += 1 color_count[game[1]][game[2]] += 1 def fix(node): minimum = math.inf maximum = 0 for i in range(k): minimum = min(minimum, color_count[node][i]) maximum = max(maximum, color_count[node][i]) if maximum - minimum <= 2: return False rand = 0 for game in games: if (game[0] == node or game[1] == node) and color_count[node][game[2]] == maximum: rand = r(1,k) set_color(game, rand % k) return True return False n, m, k = list(map(int,input().split())) games = [[0 for _ in range(4)] for _ in range(m)] color_count = [[0 for _ in range(k)] for _ in range(n)] answers = [0 for _ in range(m)] _ = list(map(int,input().split())) color = 0 r = lambda x,y : random.randint(x,y) for i in range(m): a, b = list(map(int,input().split())) color = r(1,k) % k games[i] = [a-1,b-1,color,i] color_count[games[i][0]][color] += 1 color_count[games[i][1]][color] += 1 bad = True while bad: random.shuffle(games) bad = False for i in range(n): while(fix(i)): bad = True for game in games: answers[game[3]] = game[2] + 1 for i in range(m): print(answers[i]) ```
{ "language": "python", "test_cases": [ { "input": "7 11 3\n4 7 8 10 10 9 3\n6 2\n6 1\n7 6\n4 3\n4 6\n3 1\n5 3\n7 5\n7 3\n4 2\n1 4\n", "output": "3\n1\n3\n2\n2\n2\n1\n2\n3\n1\n1\n", "type": "stdin_stdout" }, { "input": "100 0 1\n629 909 904 632 485 339 719 758 724 769 180 866 743 470 103 114 871 523 19 826 224 381 445 978 978 814 729 622 75 899 94 484 108 719 29 897 671 311 421 965 616 381 394 866 681 990 826 65 443 3 495 997 708 956 47 181 756 856 783 518 335 614 4 223 222 63 512 620 685 545 163 740 303 718 935 667 885 691 723 592 171 929 762 344 316 696 857 329 336 831 492 48 541 965 305 84 131 971 451 640\n", "output": "", "type": "stdin_stdout" }, { "input": "3 0 1\n393 931 142\n", "output": "", "type": "stdin_stdout" }, { "input": "100 0 2\n374 91 262 112 764 327 874 941 867 513 270 299 258 387 826 376 593 467 959 604 733 764 302 891 199 971 42 492 302 170 489 917 216 616 758 972 613 230 522 887 101 835 391 949 196 530 444 235 557 351 780 625 900 894 934 802 611 364 294 839 966 891 35 885 7 186 599 458 234 627 178 444 178 852 392 250 539 7 470 49 797 753 401 16 288 342 311 956 274 948 803 5 450 459 413 231 969 692 424 106\n", "output": "", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1240/F" }
vfc_6586
apps
verifiable_code
2261
Solve the following coding problem using the programming language python: A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1. In the festival m fireworks will be launched. The i-th (1 ≤ i ≤ m) launching is on time t_{i} at section a_{i}. If you are at section x (1 ≤ x ≤ n) at the time of i-th launching, you'll gain happiness value b_{i} - |a_{i} - x| (note that the happiness value might be a negative value). You can move up to d length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness. Note that two or more fireworks can be launched at the same time. -----Input----- The first line contains three integers n, m, d (1 ≤ n ≤ 150000; 1 ≤ m ≤ 300; 1 ≤ d ≤ n). Each of the next m lines contains integers a_{i}, b_{i}, t_{i} (1 ≤ a_{i} ≤ n; 1 ≤ b_{i} ≤ 10^9; 1 ≤ t_{i} ≤ 10^9). The i-th line contains description of the i-th launching. It is guaranteed that the condition t_{i} ≤ t_{i} + 1 (1 ≤ i < m) will be satisfied. -----Output----- Print a single integer — the maximum sum of happiness that you can gain from watching all the fireworks. Please, do not write the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 50 3 1 49 1 1 26 1 4 6 1 10 Output -31 Input 10 2 1 1 1000 4 9 1000 4 Output 1992 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 def rollingmax(x, y, r, a): k = 2 * r + 1 d = deque() lx = len(x) for i in range(lx + r): if i < lx: while d and d[-1][1] <= x[i]: d.pop() d.append((i, x[i])) while d and d[0][0] <= i - k: d.popleft() if i >= r: y[i - r] = d[0][1] - abs(i - r - a) n, m, d = [int(x) for x in input().split()] a, ball, t0 = [int(x) for x in input().split()] f = [-abs(i - a) for i in range(1, n + 1)] g = [0] * n for _ in range(m - 1): a, b, t = [int(x) for x in input().split()] ball += b r = min(n - 1, (t - t0) * d) t0 = t rollingmax(f, g, r, a - 1) f, g = g, f print(max(f) + ball) ```
{ "language": "python", "test_cases": [ { "input": "50 3 1\n49 1 1\n26 1 4\n6 1 10\n", "output": "-31\n", "type": "stdin_stdout" }, { "input": "10 2 1\n1 1000 4\n9 1000 4\n", "output": "1992\n", "type": "stdin_stdout" }, { "input": "30 8 2\n15 97 3\n18 64 10\n20 14 20\n16 18 36\n10 23 45\n12 60 53\n17 93 71\n11 49 85\n", "output": "418\n", "type": "stdin_stdout" }, { "input": "100 20 5\n47 93 3\n61 49 10\n14 69 10\n88 2 14\n35 86 18\n63 16 20\n39 49 22\n32 45 23\n66 54 25\n77 2 36\n96 85 38\n33 28 45\n29 78 53\n78 13 60\n58 96 64\n74 39 71\n18 80 80\n18 7 85\n97 82 96\n74 99 97\n", "output": "877\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/372/C" }
vfc_6590
apps
verifiable_code
2273
Solve the following coding problem using the programming language python: Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest). For any integer $k$ and positive integer $n$, let $k\bmod n$ denote the remainder when $k$ is divided by $n$. More formally, $r=k\bmod n$ is the smallest non-negative integer such that $k-r$ is divisible by $n$. It always holds that $0\le k\bmod n\le n-1$. For example, $100\bmod 12=4$ and $(-1337)\bmod 3=1$. Then the shuffling works as follows. There is an array of $n$ integers $a_0,a_1,\ldots,a_{n-1}$. Then for each integer $k$, the guest in room $k$ is moved to room number $k+a_{k\bmod n}$. After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests. -----Input----- Each test consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 10^4$) — the number of test cases. Next $2t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 2\cdot 10^5$) — the length of the array. The second line of each test case contains $n$ integers $a_0,a_1,\ldots,a_{n-1}$ ($-10^9\le a_i\le 10^9$). It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$. -----Output----- For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower). -----Example----- Input 6 1 14 2 1 -1 4 5 5 5 1 3 3 2 1 2 0 1 5 -239 -2 -100 -3 -11 Output YES YES YES NO NO YES -----Note----- In the first test case, every guest is shifted by $14$ rooms, so the assignment is still unique. In the second test case, even guests move to the right by $1$ room, and odd guests move to the left by $1$ room. We can show that the assignment is still unique. In the third test case, every fourth guest moves to the right by $1$ room, and the other guests move to the right by $5$ rooms. We can show that the assignment is still unique. In the fourth test case, guests $0$ and $1$ are both assigned to room $3$. In the fifth test case, guests $1$ and $2$ are both assigned to room $2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) l = [int(x) for x in input().split()] vals = [(x + i) % n for i, x in enumerate(l)] print("YES" if len(set(vals)) == n else "NO") ```
{ "language": "python", "test_cases": [ { "input": "6\n1\n14\n2\n1 -1\n4\n5 5 5 1\n3\n3 2 1\n2\n0 1\n5\n-239 -2 -100 -3 -11\n", "output": "YES\nYES\nYES\nNO\nNO\nYES\n", "type": "stdin_stdout" }, { "input": "10\n1\n1000000000\n1\n-1000000000\n2\n1000000000 0\n2\n0 1000000000\n2\n1000000000 1\n2\n1 1000000000\n2\n-1000000000 0\n2\n0 -1000000000\n2\n-1000000000 1\n2\n1 -1000000000\n", "output": "YES\nYES\nYES\nYES\nNO\nNO\nYES\nYES\nNO\nNO\n", "type": "stdin_stdout" }, { "input": "10\n3\n-15 -33 79\n16\n45 -84 19 85 69 -64 93 -70 0 -53 2 -52 -55 66 33 -60\n2\n14 -2\n4\n-65 -76 5 25\n5\n55 -66 63 -66 -35\n5\n-87 59 78 2 -10\n1\n25\n1\n-19\n1\n-8\n12\n32 34 43 -83 57 8 -86 88 -25 96 22 -44\n", "output": "NO\nNO\nYES\nNO\nNO\nNO\nYES\nYES\nYES\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1344/A" }
vfc_6638
apps
verifiable_code
2274
Solve the following coding problem using the programming language python: Allen and Bessie are playing a simple number game. They both know a function $f: \{0, 1\}^n \to \mathbb{R}$, i. e. the function takes $n$ binary arguments and returns a real value. At the start of the game, the variables $x_1, x_2, \dots, x_n$ are all set to $-1$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $i$ such that $x_i = -1$ and either setting $x_i \to 0$ or $x_i \to 1$. After $n$ rounds all variables are set, and the game value resolves to $f(x_1, x_2, \dots, x_n)$. Allen wants to maximize the game value, and Bessie wants to minimize it. Your goal is to help Allen and Bessie find the expected game value! They will play $r+1$ times though, so between each game, exactly one value of $f$ changes. In other words, between rounds $i$ and $i+1$ for $1 \le i \le r$, $f(z_1, \dots, z_n) \to g_i$ for some $(z_1, \dots, z_n) \in \{0, 1\}^n$. You are to find the expected game value in the beginning and after each change. -----Input----- The first line contains two integers $n$ and $r$ ($1 \le n \le 18$, $0 \le r \le 2^{18}$). The next line contains $2^n$ integers $c_0, c_1, \dots, c_{2^n-1}$ ($0 \le c_i \le 10^9$), denoting the initial values of $f$. More specifically, $f(x_0, x_1, \dots, x_{n-1}) = c_x$, if $x = \overline{x_{n-1} \ldots x_0}$ in binary. Each of the next $r$ lines contains two integers $z$ and $g$ ($0 \le z \le 2^n - 1$, $0 \le g \le 10^9$). If $z = \overline{z_{n-1} \dots z_0}$ in binary, then this means to set $f(z_0, \dots, z_{n-1}) \to g$. -----Output----- Print $r+1$ lines, the $i$-th of which denotes the value of the game $f$ during the $i$-th round. Your answer must have absolute or relative error within $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 2 2 0 1 2 3 2 5 0 4 Output 1.500000 2.250000 3.250000 Input 1 0 2 3 Output 2.500000 Input 2 0 1 1 1 1 Output 1.000000 -----Note----- Consider the second test case. If Allen goes first, he will set $x_1 \to 1$, so the final value will be $3$. If Bessie goes first, then she will set $x_1 \to 0$ so the final value will be $2$. Thus the answer is $2.5$. In the third test case, the game value will always be $1$ regardless of Allen and Bessie's play. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, r = [int(x) for x in input().split()] n = 2 ** n xs = [int(x) for x in input().split()] s = sum(xs) res = [0 for _ in range(r+1)] for i in range(r): res[i] = s / n i, val = [int(x) for x in input().split()] s += val - xs[i] xs[i] = val res[r] = s / n print("\n".join(map(str, res))) ```
{ "language": "python", "test_cases": [ { "input": "2 2\n0 1 2 3\n2 5\n0 4\n", "output": "1.500000\n2.250000\n3.250000\n", "type": "stdin_stdout" }, { "input": "1 0\n2 3\n", "output": "2.500000\n", "type": "stdin_stdout" }, { "input": "2 0\n1 1 1 1\n", "output": "1.000000\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/995/D" }
vfc_6642
apps
verifiable_code
2275
Solve the following coding problem using the programming language python: Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced. Formally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$. -----Input----- Input consists of multiple test cases. The first line contains one integer $t$ $(1 \leq t \leq 10^5)$ — the number of test cases. Each test case is described as follows: The first line contains two integers $n$ and $p$ $(1 \leq n, p \leq 10^6)$. The second line contains $n$ integers $k_i$ $(0 \leq k_i \leq 10^6)$. The sum of $n$ over all test cases doesn't exceed $10^6$. -----Output----- Output one integer — the reminder of division the answer by $1\,000\,000\,007$. -----Example----- Input 4 5 2 2 3 4 4 3 3 1 2 10 1000 4 5 0 1 1 100 1 8 89 Output 4 1 146981438 747093407 -----Note----- You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $2$, but there is also a distribution where the difference is $10^9 + 8$, then the answer is $2$, not $1$. In the first test case of the example, there're the following numbers: $4$, $8$, $16$, $16$, and $8$. We can divide them into such two sets: ${4, 8, 16}$ and ${8, 16}$. Then the difference between the sums of numbers in sets would be $4$. 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 MOD = 10 ** 9 + 7 t = int(input()) for _ in range(t): n, p = list(map(int, input().split())) l = list(map(int, input().split())) if p == 1: print(n % 2) else: l.sort(reverse = True) curr = l[0] out = 0 real = True for v in l: if v < curr: diff = curr - v if 10 ** (7/diff) < p and out > 0: real = False out *= pow(p, diff, MOD) if out > 10 ** 7: real = False out %= MOD curr = v if out > 0 or not real: out -= 1 else: out += 1 out %= MOD out *= pow(p, curr, MOD) print(out % MOD) ```
{ "language": "python", "test_cases": [ { "input": "4\n5 2\n2 3 4 4 3\n3 1\n2 10 1000\n4 5\n0 1 1 100\n1 8\n89\n", "output": "4\n1\n146981438\n747093407\n", "type": "stdin_stdout" }, { "input": "1\n1 2\n88\n", "output": "140130951\n", "type": "stdin_stdout" }, { "input": "1\n20 22328\n2572 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", "output": "1000000004\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1361/B" }
vfc_6646
apps
verifiable_code
2276
Solve the following coding problem using the programming language python: This is an easier version of the next problem. The difference is only in constraints. You are given a rectangular $n \times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times. After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $i$-th row it is equal $r_i$. What is the maximal possible value of $r_1+r_2+\ldots+r_n$? -----Input----- The first line contains an integer $t$ ($1 \le t \le 40$), the number of test cases in the input. The first line of each test case contains integers $n$ and $m$ ($1 \le n \le 4$, $1 \le m \le 100$) — the number of rows and the number of columns in the given matrix $a$. Each of the following $n$ lines contains $m$ integers, the elements of $a$ ($1 \le a_{i, j} \le 10^5$). -----Output----- Print $t$ integers: answers for all test cases in the order they are given in the input. -----Example----- Input 2 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 Output 12 29 -----Note----- In the first test case, you can shift the third column down by one, this way there will be $r_1 = 5$ and $r_2 = 7$. In the second case you can don't rotate anything at all, this way there will be $r_1 = r_2 = 10$ and $r_3 = 9$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python rnd_mod = 1234567890133 rnd_x = 987654321098 def rnd(): nonlocal rnd_x rnd_x = rnd_x**2 % rnd_mod return (rnd_x>>5) % (1<<20) def randrange(a): return rnd() % a T = int(input()) for _ in range(T): N, M = list(map(int, input().split())) X = [] for __ in range(N): X.append([int(a) for a in input().split()]) Y = [[X[i][j] for i in range(N)] for j in range(M)] ma = 0 for t in range(577): for i in range(M): a = randrange(N) Y[i] = [Y[i][j-a] for j in range(N)] ma = max(ma, sum([max([Y[i][j] for i in range(M)]) for j in range(N)])) print(ma) ```
{ "language": "python", "test_cases": [ { "input": "2\n2 3\n2 5 7\n4 2 4\n3 6\n4 1 5 2 10 4\n8 6 6 4 9 10\n5 4 9 5 8 7\n", "output": "12\n29\n", "type": "stdin_stdout" }, { "input": "40\n2 2\n5 2\n1 5\n1 1\n3\n1 2\n1 1\n1 2\n1 1\n1 2\n2 3\n2 1\n1\n1\n1 1\n1\n2 1\n1\n1\n1 2\n2 3\n2 2\n1 3\n3 3\n1 1\n1\n2 1\n3\n4\n1 1\n2\n2 2\n1 1\n1 1\n2 2\n1 1\n1 1\n1 1\n1\n2 1\n1\n1\n2 1\n5\n3\n1 1\n2\n1 2\n2 2\n2 1\n1\n1\n2 2\n3 2\n2 4\n1 1\n5\n1 2\n2 1\n1 2\n1 1\n1 2\n1 1\n1 2\n1 1\n1 1\n3\n2 2\n1 2\n2 2\n1 2\n4 3\n1 1\n3\n2 1\n2\n2\n1 2\n3 2\n2 1\n3\n1\n2 1\n1\n1\n2 1\n1\n2\n2 2\n2 1\n2 1\n1 1\n2\n1 2\n3 5\n1 1\n2\n", "output": "10\n3\n1\n1\n3\n2\n1\n2\n3\n6\n1\n7\n2\n2\n2\n1\n2\n8\n2\n2\n2\n7\n5\n2\n1\n1\n1\n3\n4\n4\n3\n4\n3\n4\n2\n3\n4\n2\n5\n2\n", "type": "stdin_stdout" }, { "input": "1\n4 2\n1 1\n2 1\n1 2\n2 2\n", "output": "7\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1209/E1" }
vfc_6650
apps
verifiable_code
2278
Solve the following coding problem using the programming language python: Recently Vasya learned that, given two points with different $x$ coordinates, you can draw through them exactly one parabola with equation of type $y = x^2 + bx + c$, where $b$ and $c$ are reals. Let's call such a parabola an $U$-shaped one. Vasya drew several distinct points with integer coordinates on a plane and then drew an $U$-shaped parabola through each pair of the points that have different $x$ coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya. The internal area of an $U$-shaped parabola is the part of the plane that lies strictly above the parabola when the $y$ axis is directed upwards. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 100\,000$) — the number of points. The next $n$ lines describe the points, the $i$-th of them contains two integers $x_i$ and $y_i$ — the coordinates of the $i$-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed $10^6$ by absolute value. -----Output----- In the only line print a single integer — the number of $U$-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself). -----Examples----- Input 3 -1 0 0 2 1 0 Output 2 Input 5 1 0 1 -1 0 -1 -1 0 -1 -1 Output 1 -----Note----- On the pictures below all $U$-shaped parabolas that pass through at least two given points are drawn for each of the examples. The $U$-shaped parabolas that do not have any given point inside their internal area are drawn in red. [Image] The first example. [Image] The second example. 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()) rows = [input().split() for _ in range(n)] rows = [(int(x),int(y)) for x,y in rows] points = {} for x,y in rows: if x in points: points[x] = max(y, points[x]) else: points[x] = y points = sorted(points.items(),key=lambda point: point[0]) def above(p,p1,p2): """ x1 < x2 y1 = x1^2 + bx1 + c y2 = x2^2 + bx2 + c y >? x^2 + bx + c y2 - y1 = x2^2 - x1^2 + bx2 - bx1 b = (y2 - y1 - x2^2 + x1^2) / (x2 - x1) b * (x2 - x1) = y2 - y1 - x2^2 + x1^2 c = y1 - x1^2 - bx1 c * (x2 - x1) = (y1 - x1^2) * (x2 - x1) - x1 * (y2 - y1 - x2^2 + x1^2) y * (x2 - x1) >? (x^2 + bx + c) * (x2 - x1) y * (x2 - x1) >? x^2 * (x2 - x1) + x * (y2 - y1 - x2^2 + x1^2) + (y1 - x1^2) * (x2 - x1) - x1 * (y2 - y1 - x2^2 + x1^2) """ x,y = p x1,y1 = p1 x2,y2 = p2 x_2 = x**2 x12 = x1**2 x22 = x2**2 x2_x1 = x2 - x1 eq_b = y2 - y1 - x22 + x12 term_y = y * x2_x1 term_x2 = x_2 * x2_x1 term_x = x * eq_b term_c = (y1 - x12) * x2_x1 - (x1 * eq_b) return term_y >= term_x2 + term_x + term_c #print(above(points[2],points[0],points[1])) Us = [] for i, p in enumerate(points): while len(Us) >= 2: p1, p2 = Us[-2:] if above(p,p1,p2): Us.pop() else: break Us.append(p) out = len(Us) - 1 print(out) ```
{ "language": "python", "test_cases": [ { "input": "3\n-1 0\n0 2\n1 0\n", "output": "2\n", "type": "stdin_stdout" }, { "input": "5\n1 0\n1 -1\n0 -1\n-1 0\n-1 -1\n", "output": "1\n", "type": "stdin_stdout" }, { "input": "1\n-751115 -925948\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1142/C" }
vfc_6658
apps
verifiable_code
2279
Solve the following coding problem using the programming language python: In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks. More precisely, two different numbers $a$ and $b$ are friends if $gcd(a,b)$, $\frac{a}{gcd(a,b)}$, $\frac{b}{gcd(a,b)}$ can form sides of a triangle. Three numbers $a$, $b$ and $c$ can form sides of a triangle if $a + b > c$, $b + c > a$ and $c + a > b$. In a group of numbers, a number is lonely if it doesn't have any friends in that group. Given a group of numbers containing all numbers from $1, 2, 3, ..., n$, how many numbers in that group are lonely? -----Input----- The first line contains a single integer $t$ $(1 \leq t \leq 10^6)$ - number of test cases. On next line there are $t$ numbers, $n_i$ $(1 \leq n_i \leq 10^6)$ - meaning that in case $i$ you should solve for numbers $1, 2, 3, ..., n_i$. -----Output----- For each test case, print the answer on separate lines: number of lonely numbers in group $1, 2, 3, ..., n_i$. -----Example----- Input 3 1 5 10 Output 1 3 3 -----Note----- For first test case, $1$ is the only number and therefore lonely. For second test case where $n=5$, numbers $1$, $3$ and $5$ are lonely. For third test case where $n=10$, numbers $1$, $5$ and $7$ are lonely. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") primes = [] prime = [True] * (10 ** 6 +5) prime[0] = False for i in range(2, 10 ** 6): if prime[i]: for j in range(2 * i, 10 ** 6 + 5, i): prime[j] = False pref = [0] for i in range(1, 10 ** 6 + 5): pref.append(pref[-1]) if prime[i]: pref[-1] += 1 s = round(i ** .5) if s * s == i and prime[s] and i != 1: pref[-1] -= 1 n = int(input()) l = list(map(int, input().split())) out = [] for v in l: out.append(pref[v]) print('\n'.join(map(str,out))) ```
{ "language": "python", "test_cases": [ { "input": "3\n1 5 10\n", "output": "1\n3\n3\n", "type": "stdin_stdout" }, { "input": "6\n12 432 21 199 7 1\n", "output": "4\n76\n7\n41\n4\n1\n", "type": "stdin_stdout" }, { "input": "7\n1 10 100 1000 10000 100000 1000000\n", "output": "1\n3\n22\n158\n1205\n9528\n78331\n", "type": "stdin_stdout" }, { "input": "100\n42 486 341 527 189 740 490 388 989 489 711 174 305 844 971 492 998 954 832 442 424 619 906 154 293 395 439 735 738 915 453 748 786 550 871 932 693 326 53 904 732 835 354 364 691 669 157 719 282 875 573 672 695 790 58 872 732 751 557 779 329 39 213 844 289 137 50 951 284 671 474 829 906 736 395 366 22 133 418 552 649 636 109 974 775 852 971 384 945 335 961 472 651 335 543 560 135 85 952 558\n", "output": "11\n85\n62\n92\n37\n123\n86\n69\n156\n86\n119\n35\n56\n137\n154\n87\n158\n153\n137\n78\n75\n106\n145\n32\n56\n70\n78\n122\n122\n147\n80\n124\n129\n93\n141\n149\n117\n60\n13\n145\n121\n137\n65\n65\n117\n113\n33\n120\n55\n141\n97\n113\n117\n130\n13\n141\n121\n125\n94\n129\n60\n10\n42\n137\n55\n29\n12\n152\n56\n113\n84\n137\n145\n122\n70\n65\n7\n28\n73\n93\n110\n107\n26\n154\n129\n137\n154\n69\n151\n61\n152\n84\n110\n61\n92\n94\n28\n20\n152\n94\n", "type": "stdin_stdout" }, { "input": "100\n838 147 644 688 727 940 991 309 705 409 27 774 951 92 277 835 804 589 103 529 11 304 171 655 378 792 679 590 36 65 378 152 958 746 980 434 139 222 26 349 473 300 781 394 960 918 242 768 246 607 429 971 534 44 430 198 901 624 781 657 428 366 652 558 570 490 623 46 606 375 302 867 384 32 601 46 376 223 688 509 290 739 54 2 445 966 907 792 146 468 732 908 673 506 825 424 325 624 836 524\n", "output": "137\n30\n109\n116\n121\n150\n157\n57\n118\n73\n7\n129\n152\n21\n54\n137\n131\n99\n24\n91\n4\n56\n34\n111\n67\n130\n115\n99\n9\n15\n67\n32\n153\n124\n155\n77\n30\n42\n7\n64\n84\n56\n129\n70\n153\n147\n48\n127\n48\n103\n75\n154\n91\n12\n75\n40\n145\n106\n129\n111\n75\n65\n110\n94\n96\n86\n106\n12\n102\n67\n56\n141\n69\n9\n102\n12\n67\n43\n116\n90\n55\n123\n13\n2\n79\n152\n146\n130\n30\n84\n121\n146\n114\n89\n135\n75\n60\n106\n137\n92\n", "type": "stdin_stdout" }, { "input": "100\n324 624 954 469 621 255 536 588 821 334 231 20 850 642 5 735 199 506 97 358 554 589 344 513 456 226 472 625 601 816 813 297 609 819 38 185 493 646 557 305 45 204 209 687 966 198 835 911 176 523 219 637 297 76 349 669 389 891 894 462 899 163 868 418 903 31 333 670 32 705 561 505 920 414 81 723 603 513 25 896 879 703 415 799 271 440 8 596 207 296 116 458 646 781 842 963 174 157 747 207\n", "output": "60\n106\n153\n84\n106\n49\n91\n99\n134\n61\n45\n7\n137\n108\n3\n122\n41\n89\n22\n65\n93\n99\n62\n90\n80\n43\n84\n106\n102\n133\n133\n56\n103\n133\n10\n37\n87\n109\n94\n56\n12\n41\n41\n116\n152\n40\n137\n147\n35\n92\n42\n107\n56\n18\n64\n113\n70\n145\n145\n82\n145\n34\n141\n73\n145\n9\n61\n113\n9\n118\n94\n89\n148\n73\n19\n120\n102\n90\n7\n145\n142\n118\n73\n131\n53\n78\n4\n100\n41\n56\n27\n81\n109\n129\n137\n152\n35\n33\n124\n41\n", "type": "stdin_stdout" }, { "input": "100\n996 361 371 721 447 566 438 566 449 522 176 79 740 757 156 436 296 23 704 542 572 455 886 962 194 219 301 437 315 122 513 299 468 760 133 713 348 692 792 276 318 380 217 74 913 819 834 966 318 784 350 578 670 11 482 149 220 243 137 164 541 471 185 477 57 681 319 466 271 45 181 540 750 670 200 322 479 51 171 33 806 915 976 399 213 629 504 419 324 850 364 900 397 180 845 99 495 326 526 186\n", "output": "157\n65\n66\n120\n79\n95\n77\n95\n80\n91\n35\n19\n123\n126\n32\n77\n56\n8\n118\n92\n97\n80\n144\n152\n39\n42\n56\n77\n59\n26\n90\n56\n84\n126\n28\n119\n63\n117\n130\n53\n60\n68\n42\n18\n147\n133\n137\n152\n60\n129\n64\n98\n113\n4\n85\n31\n42\n48\n29\n34\n92\n84\n37\n84\n13\n115\n60\n83\n53\n12\n37\n91\n124\n113\n41\n60\n85\n12\n34\n9\n131\n147\n154\n71\n42\n106\n89\n74\n60\n137\n65\n145\n71\n36\n137\n22\n87\n60\n92\n37\n", "type": "stdin_stdout" }, { "input": "100\n791 303 765 671 210 999 106 489 243 635 807 104 558 628 545 926 35 3 75 196 35 460 523 621 748 45 501 143 240 318 78 908 207 369 436 6 285 200 236 864 731 786 915 672 293 563 141 708 698 646 48 128 603 716 681 329 389 489 683 616 875 510 20 493 141 176 803 106 92 928 20 762 203 336 586 258 56 781 172 115 890 104 595 491 607 489 628 653 635 960 449 549 909 977 124 621 741 275 206 558\n", "output": "130\n56\n127\n113\n41\n158\n24\n86\n48\n107\n131\n24\n94\n106\n92\n148\n9\n3\n18\n39\n9\n81\n92\n106\n124\n12\n88\n30\n47\n60\n18\n146\n41\n66\n77\n3\n56\n41\n46\n141\n121\n129\n147\n113\n56\n95\n30\n118\n117\n109\n13\n27\n102\n119\n115\n60\n70\n86\n116\n104\n141\n90\n7\n87\n30\n35\n131\n24\n21\n148\n7\n127\n41\n61\n98\n50\n13\n129\n34\n27\n145\n24\n100\n87\n103\n86\n106\n111\n107\n153\n80\n93\n146\n155\n26\n106\n123\n53\n41\n94\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1423/K" }
vfc_6662
apps
verifiable_code
2280
Solve the following coding problem using the programming language python: Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\frac{p_i}{100}$ for all $1 \le i \le n$. Some mirrors are called checkpoints. Initially, only the $1$st mirror is a checkpoint. It remains a checkpoint all the time. Creatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities: The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to $i$. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given $q$ queries, each query is represented by an integer $u$: If the $u$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $u$-th mirror is no longer a checkpoint. After each query, you need to calculate the expected number of days until Creatnx becomes happy. Each of this numbers should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$. -----Input----- The first line contains two integers $n$, $q$ ($2 \leq n, q \le 2 \cdot 10^5$)  — the number of mirrors and queries. The second line contains $n$ integers: $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq 100$). Each of $q$ following lines contains a single integer $u$ ($2 \leq u \leq n$) — next query. -----Output----- Print $q$ numbers – the answers after each query by modulo $998244353$. -----Examples----- Input 2 2 50 50 2 2 Output 4 6 Input 5 5 10 20 30 40 50 2 3 4 5 3 Output 117 665496274 332748143 831870317 499122211 -----Note----- In the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to $\frac{1}{2}$. So, the expected number of days, until one mirror will say, that he is beautiful is equal to $2$ and the answer will be equal to $4 = 2 + 2$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline from itertools import accumulate from collections import Counter from bisect import bisect as br, bisect_left as bl class PMS: #1-indexed def __init__(self, A, B, issum = False): #Aに初期状態の要素をすべて入れる,Bは値域のリスト self.X, self.comp = self.compress(B) self.size = len(self.X) self.tree = [0] * (self.size + 1) self.p = 2**(self.size.bit_length() - 1) self.dep = self.size.bit_length() CA = Counter(A) S = [0] + list(accumulate([CA[self.X[i]] for i in range(self.size)])) for i in range(1, 1+self.size): self.tree[i] = S[i] - S[i - (i&-i)] if issum: self.sumtree = [0] * (self.size + 1) Ssum = [0] + list(accumulate([CA[self.X[i]]*self.X[i] for i in range(self.size)])) for i in range(1, 1+self.size): self.sumtree[i] = Ssum[i] - Ssum[i - (i&-i)] def compress(self, L): #座圧 L2 = list(set(L)) L2.sort() C = {v : k for k, v in enumerate(L2, 1)} # 1-indexed return L2, C def leng(self): #今入っている個数を取得 return self.count(self.X[-1]) def count(self, v): #v(Bの元)以下の個数を取得 i = self.comp[v] s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def less(self, v): #v(Bの元である必要はない)未満の個数を取得 i = bl(self.X, v) s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def leq(self, v): #v(Bの元である必要はない)以下の個数を取得 i = br(self.X, v) s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, v, x): #vをx個入れる,負のxで取り出す,iの個数以上取り出すとエラーを出さずにバグる i = self.comp[v] while i <= self.size: self.tree[i] += x i += i & -i def get(self, i): # i番目の値を取得 if i <= 0: return -1 s = 0 k = self.p for _ in range(self.dep): if s + k <= self.size and self.tree[s+k] < i: s += k i -= self.tree[s] k //= 2 return self.X[s] def gets(self, v): #累積和がv以下となる最大のindexを返す v1 = v s = 0 k = self.p for _ in range(self.dep): if s + k <= self.size and self.sumtree[s+k] < v: s += k v -= self.sumtree[s] k //= 2 if s == self.size: return self.leng() return self.count(self.X[s]) + (v1 - self.countsum(self.X[s]))//self.X[s] def addsum(self, i, x): #sumを扱いたいときにaddの代わりに使う self.add(i, x) x *= i i = self.comp[i] while i <= self.size: self.sumtree[i] += x i += i & -i def countsum(self, v): #v(Bの元)以下のsumを取得 i = self.comp[v] s = 0 while i > 0: s += self.sumtree[i] i -= i & -i return s def getsum(self, i): #i番目までのsumを取得 x = self.get(i) return self.countsum(x) - x*(self.count(x) - i) N, Q = map(int, readline().split()) P = list(map(int, readline().split())) MOD = 998244353 T = [100*pow(pi, MOD-2, MOD)%MOD for pi in P] AT = [None]*N AT[0] = T[0] for i in range(1, N): AT[i] = (AT[i-1]+1)*T[i]%MOD AM = [None]*N AMi = [None]*N AM[0] = T[0] for i in range(1, N): AM[i] = AM[i-1]*T[i]%MOD AMi[N-1] = pow(AM[N-1], MOD-2, MOD) for i in range(N-2, -1, -1): AMi[i] = AMi[i+1]*T[i+1]%MOD AT += [0] AM += [1] AMi += [1] Ans = [None]*Q kk = set([0, N]) PM = PMS([0, N], list(range(N+1))) ans = AT[N-1] for qu in range(Q): f = int(readline()) - 1 if f not in kk: kk.add(f) PM.add(f, 1) fidx = PM.count(f) fm = PM.get(fidx-1) fp = PM.get(fidx+1) am = (AT[f-1] - AM[f-1]*AMi[fm-1]*AT[fm-1])%MOD ap = (AT[fp-1] - AM[fp-1]*AMi[f-1]*AT[f-1])%MOD aa = (AT[fp-1] - AM[fp-1]*AMi[fm-1]*AT[fm-1])%MOD ans = (ans - aa + am + ap)%MOD else: kk.remove(f) fidx = PM.count(f) fm = PM.get(fidx-1) fp = PM.get(fidx+1) PM.add(f, -1) am = (AT[f-1] - AM[f-1]*AMi[fm-1]*AT[fm-1])%MOD ap = (AT[fp-1] - AM[fp-1]*AMi[f-1]*AT[f-1])%MOD aa = (AT[fp-1] - AM[fp-1]*AMi[fm-1]*AT[fm-1])%MOD ans = (ans + aa - am - ap)%MOD Ans[qu] = ans print('\n'.join(map(str, Ans))) ```
{ "language": "python", "test_cases": [ { "input": "2 2\n50 50\n2\n2\n", "output": "4\n6\n", "type": "stdin_stdout" }, { "input": "5 5\n10 20 30 40 50\n2\n3\n4\n5\n3\n", "output": "117\n665496274\n332748143\n831870317\n499122211\n", "type": "stdin_stdout" }, { "input": "2 2\n38 4\n2\n2\n", "output": "262695910\n577931032\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1264/C" }
vfc_6666
apps
verifiable_code
2282
Solve the following coding problem using the programming language python: A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $a \times b$ and $b \times a$ are considered different if $a \neq b$. For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle. Calculate the amount of pairs $(A; B)$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $A$ and $B$. Note that pairs $(A; B)$ and $(B; A)$ are considered different when $A \neq B$. -----Input----- The first line consists of a single integer $n$ ($1 \leq n \leq 2 \cdot 10^{5}$) — amount of different types of rectangles left after cutting the initial rectangle. The next $n$ lines each consist of three integers $w_{i}, h_{i}, c_{i}$ $(1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12})$ — the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type. It is guaranteed that the rectangles of the different types are different. -----Output----- Output one integer — the answer to the problem. -----Examples----- Input 1 1 1 9 Output 3 Input 2 2 3 20 2 4 40 Output 6 Input 2 1 2 5 2 3 5 Output 0 -----Note----- In the first sample there are three suitable pairs: $(1; 9)$, $(3; 3)$ and $(9; 1)$. In the second sample case there are 6 suitable pairs: $(2; 220)$, $(4; 110)$, $(8; 55)$, $(10; 44)$, $(20; 22)$ and $(40; 11)$. Here the sample of cut for $(20; 22)$. [Image] The third sample has no suitable pairs. 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()) w=[] h=[] c=[] cntw={} cnth={} gcdC=0 cntC=0 def insert1(a,b,c): if not a in b : b[a]=c else : b[a]=b[a]+c def gcd(a,b): if a % b == 0 : return b else : return gcd(b,a%b) for i in range(0, n): a,b,d = map(int,input().split()) w.append(a) h.append(b) c.append(d) insert1(a,cntw,d) insert1(b,cnth,d) cntC += d if gcdC == 0 : gcdC = d else : gcdC = gcd(gcdC, d) for i in range(0, n): if cntw[w[i]] * cnth[h[i]] != cntC * c[i]: print (0) return ans = 0 i = 1 while (i * i <= gcdC) : if gcdC % i == 0 : ans += 1 if i * i != gcdC : ans += 1 i += 1 print (ans) ```
{ "language": "python", "test_cases": [ { "input": "1\n1 1 9\n", "output": "3\n", "type": "stdin_stdout" }, { "input": "2\n2 3 20\n2 4 40\n", "output": "6\n", "type": "stdin_stdout" }, { "input": "2\n1 2 5\n2 3 5\n", "output": "0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/963/C" }
vfc_6674
apps
verifiable_code
2283
Solve the following coding problem using the programming language python: Alice and Bob are playing a fun game of tree tag. The game is played on a tree of $n$ vertices numbered from $1$ to $n$. Recall that a tree on $n$ vertices is an undirected, connected graph with $n-1$ edges. Initially, Alice is located at vertex $a$, and Bob at vertex $b$. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most $da$ from the current vertex. And in a move, Bob can jump to a vertex with distance at most $db$ from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most $10^{100}$ moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). Description of the test cases follows. The first line of each test case contains five integers $n,a,b,da,db$ ($2\le n\le 10^5$, $1\le a,b\le n$, $a\ne b$, $1\le da,db\le n-1$)  — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following $n-1$ lines describe the edges of the tree. The $i$-th of these lines contains two integers $u$, $v$ ($1\le u, v\le n, u\ne v$), denoting an edge between vertices $u$ and $v$. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$. -----Output----- For each test case, output a single line containing the winner of the game: "Alice" or "Bob". -----Example----- Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice -----Note----- In the first test case, Alice can win by moving to vertex $1$. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. [Image] In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices $1$ or $6$ is farthest from Alice. [Image] 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 collections import deque def NC_Dij(lis,start): ret = [float("inf")] * len(lis) ret[start] = 0 q = deque([start]) plis = [i for i in range(len(lis))] while len(q) > 0: now = q.popleft() for nex in lis[now]: if ret[nex] > ret[now] + 1: ret[nex] = ret[now] + 1 plis[nex] = now q.append(nex) return ret,plis tt = int(stdin.readline()) for loop in range(tt): n,a,b,da,db = list(map(int,stdin.readline().split())) N = n a -= 1 b -= 1 lis = [ [] for i in range(n)] for i in range(n-1): u,v = list(map(int,stdin.readline().split())) u -= 1 v -= 1 lis[u].append(v) lis[v].append(u) if 2*da >= db: print ("Alice") continue fa,tmp = NC_Dij(lis,a) if fa[b] <= da: print ("Alice") continue mv = 0 for i in range(N): if fa[i] > fa[mv]: mv = i fv,tmp = NC_Dij(lis,mv) if max(fv) <= 2*da: print ("Alice") else: print ("Bob") ```
{ "language": "python", "test_cases": [ { "input": "4\n4 3 2 1 2\n1 2\n1 3\n1 4\n6 6 1 2 5\n1 2\n6 5\n2 3\n3 4\n4 5\n9 3 9 2 5\n1 2\n1 6\n1 9\n1 3\n9 5\n7 9\n4 8\n4 3\n11 8 11 3 3\n1 2\n11 9\n4 9\n6 5\n2 10\n3 2\n5 9\n8 3\n7 4\n7 10\n", "output": "Alice\nBob\nAlice\nAlice\n", "type": "stdin_stdout" }, { "input": "1\n5 5 4 3 4\n1 2\n4 1\n5 1\n5 3\n", "output": "Alice\n", "type": "stdin_stdout" }, { "input": "10\n10 9 10 6 6\n6 1\n7 6\n4 2\n4 10\n5 1\n9 5\n6 8\n3 4\n4 5\n2 1 2 1 1\n2 1\n9 7 4 2 3\n5 1\n2 4\n4 8\n8 6\n8 9\n7 8\n1 8\n1 3\n11 2 11 6 8\n1 10\n6 11\n8 2\n11 3\n1 7\n11 4\n5 8\n11 7\n1 9\n1 8\n5 3 2 1 2\n3 1\n2 1\n4 5\n1 5\n2 1 2 1 1\n2 1\n2 2 1 1 1\n2 1\n2 2 1 1 1\n1 2\n2 2 1 1 1\n2 1\n5 4 5 4 2\n2 1\n1 5\n3 1\n4 1\n", "output": "Alice\nAlice\nAlice\nAlice\nAlice\nAlice\nAlice\nAlice\nAlice\nAlice\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1404/B" }
vfc_6678
apps
verifiable_code
2284
Solve the following coding problem using the programming language python: Let's call two strings $s$ and $t$ anagrams of each other if it is possible to rearrange symbols in the string $s$ to get a string, equal to $t$. Let's consider two strings $s$ and $t$ which are anagrams of each other. We say that $t$ is a reducible anagram of $s$ if there exists an integer $k \ge 2$ and $2k$ non-empty strings $s_1, t_1, s_2, t_2, \dots, s_k, t_k$ that satisfy the following conditions: If we write the strings $s_1, s_2, \dots, s_k$ in order, the resulting string will be equal to $s$; If we write the strings $t_1, t_2, \dots, t_k$ in order, the resulting string will be equal to $t$; For all integers $i$ between $1$ and $k$ inclusive, $s_i$ and $t_i$ are anagrams of each other. If such strings don't exist, then $t$ is said to be an irreducible anagram of $s$. Note that these notions are only defined when $s$ and $t$ are anagrams of each other. For example, consider the string $s = $ "gamegame". Then the string $t = $ "megamage" is a reducible anagram of $s$, we may choose for example $s_1 = $ "game", $s_2 = $ "gam", $s_3 = $ "e" and $t_1 = $ "mega", $t_2 = $ "mag", $t_3 = $ "e": [Image] On the other hand, we can prove that $t = $ "memegaga" is an irreducible anagram of $s$. You will be given a string $s$ and $q$ queries, represented by two integers $1 \le l \le r \le |s|$ (where $|s|$ is equal to the length of the string $s$). For each query, you should find if the substring of $s$ formed by characters from the $l$-th to the $r$-th has at least one irreducible anagram. -----Input----- The first line contains a string $s$, consisting of lowercase English characters ($1 \le |s| \le 2 \cdot 10^5$). The second line contains a single integer $q$ ($1 \le q \le 10^5$)  — the number of queries. Each of the following $q$ lines contain two integers $l$ and $r$ ($1 \le l \le r \le |s|$), representing a query for the substring of $s$ formed by characters from the $l$-th to the $r$-th. -----Output----- For each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise. -----Examples----- Input aaaaa 3 1 1 2 4 5 5 Output Yes No Yes Input aabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 Output No Yes Yes Yes No No -----Note----- In the first sample, in the first and third queries, the substring is "a", which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand, in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose $s_1 = $ "a", $s_2 = $ "aa", $t_1 = $ "a", $t_2 = $ "aa" to show that it is a reducible anagram. In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline S = list([ord(x)-97 for x in readline().strip()]) N = len(S) table = [[0]*26 for _ in range(N)] for i in range(N): table[i][S[i]] = 1 for i in range(1, N): for j in range(26): table[i][j] += table[i-1][j] Q = int(readline()) Ans = [None]*Q for qu in range(Q): l, r = list(map(int, readline().split())) l -= 1 r -= 1 if l == r or S[l] != S[r]: Ans[qu] = True continue K = [table[r][j] - table[l][j] for j in range(26)] if len([k for k in K if k]) <= 2: Ans[qu] = False else: Ans[qu] = True print('\n'.join(['Yes' if s else 'No' for s in Ans])) ```
{ "language": "python", "test_cases": [ { "input": "aaaaa\n3\n1 1\n2 4\n5 5\n", "output": "Yes\nNo\nYes\n", "type": "stdin_stdout" }, { "input": "aabbbbbbc\n6\n1 2\n2 4\n2 2\n1 9\n5 7\n3 5\n", "output": "No\nYes\nYes\nYes\nNo\nNo\n", "type": "stdin_stdout" }, { "input": "f\n1\n1 1\n", "output": "Yes\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1290/B" }
vfc_6682
apps
verifiable_code
2285
Solve the following coding problem using the programming language python: You are given a sequence of $n$ digits $d_1d_2 \dots d_{n}$. You need to paint all the digits in two colors so that: each digit is painted either in the color $1$ or in the color $2$; if you write in a row from left to right all the digits painted in the color $1$, and then after them all the digits painted in the color $2$, then the resulting sequence of $n$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $d=914$ the only valid coloring is $211$ (paint in the color $1$ two last digits, paint in the color $2$ the first digit). But $122$ is not a valid coloring ($9$ concatenated with $14$ is not a non-decreasing sequence). It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions. Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10000$) — the number of test cases in the input. The first line of each test case contains an integer $n$ ($1 \le n \le 2\cdot10^5$) — the length of a given sequence of digits. The next line contains a sequence of $n$ digits $d_1d_2 \dots d_{n}$ ($0 \le d_i \le 9$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values ​​of $n$ for all test cases in the input does not exceed $2\cdot10^5$. -----Output----- Print $t$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $n$ digits $t_1t_2 \dots t_n$ ($1 \le t_i \le 2$), where $t_i$ is the color the $i$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign). -----Example----- Input 5 12 040425524644 1 0 9 123456789 2 98 3 987 Output 121212211211 1 222222222 21 - -----Note----- In the first test case, $d=040425524644$. The output $t=121212211211$ is correct because $0022444$ (painted in $1$) concatenated with $44556$ (painted in $2$) is $002244444556$ which is a sorted sequence of $n$ given digits. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python for __ in range(int(input())): n = int(input()) s = list(map(int, input())) r = [0] * n for i in range(10): left_lim = 0 for j, c in enumerate(s): if c < i: left_lim = j + 1 prv = [-1, -1, -1] flg = True for j, c in enumerate(s): r[j] = 1 if c < i or (c == i and j >= left_lim) else 2 if c < prv[r[j]]: flg = False; break prv[r[j]] = c if flg: print(''.join(map(str, r))) break if not flg: print('-') ```
{ "language": "python", "test_cases": [ { "input": "5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987\n", "output": "121212211211\n1\n222222222\n21\n-\n", "type": "stdin_stdout" }, { "input": "5\n4\n6148\n1\n7\n5\n49522\n3\n882\n2\n51\n", "output": "2112\n2\n-\n221\n21\n", "type": "stdin_stdout" }, { "input": "5\n1\n3\n5\n74730\n1\n4\n5\n49554\n2\n59\n", "output": "2\n-\n2\n-\n22\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1209/C" }
vfc_6686
apps
verifiable_code
2308
Solve the following coding problem using the programming language python: You are given $n$ arrays that can have different sizes. You also have a table with $w$ columns and $n$ rows. The $i$-th array is placed horizontally in the $i$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table. You need to find the maximum sum of the integers in the $j$-th column for each $j$ from $1$ to $w$ independently. [Image] Optimal placements for columns $1$, $2$ and $3$ are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero. -----Input----- The first line contains two integers $n$ ($1 \le n \le 10^{6}$) and $w$ ($1 \le w \le 10^{6}$) — the number of arrays and the width of the table. Each of the next $n$ lines consists of an integer $l_{i}$ ($1 \le l_{i} \le w$), the length of the $i$-th array, followed by $l_{i}$ integers $a_{i1}, a_{i2}, \ldots, a_{il_i}$ ($-10^{9} \le a_{ij} \le 10^{9}$) — the elements of the array. The total length of the arrays does no exceed $10^{6}$. -----Output----- Print $w$ integers, the $i$-th of them should be the maximum sum for column $i$. -----Examples----- Input 3 3 3 2 4 8 2 2 5 2 6 3 Output 10 15 16 Input 2 2 2 7 8 1 -8 Output 7 8 -----Note----- Illustration for the first example is in the statement. 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 from collections import deque def slidemax(X, k): q = deque([]) ret = [] for i in range(len(X)): while q and q[-1][1] <= X[i]: q.pop() deque.append(q, (i+k, X[i])) if q[0][0] == i: deque.popleft(q) if i >= k-1: ret.append(q[0][1]) return ret N, W = list(map(int, input().split())) A = [0] * W s = 0 for _ in range(N): l, *B = list(map(int, input().split())) if l*2 < W: C = slidemax([0]*(l-1)+B+[0]*(l-1), l) m = max(B + [0]) s += m for i in range(l-1): A[i] += C[i] - m A[-i-1] += C[-i-1] - m else: C = slidemax([0]*(W-l)+B+[0]*(W-l), W - l + 1) A = [a+c for a, c in zip(A, C)] print(*[a+s for a in A]) ```
{ "language": "python", "test_cases": [ { "input": "3 3\n3 2 4 8\n2 2 5\n2 6 3\n", "output": "10 15 16 \n", "type": "stdin_stdout" }, { "input": "2 2\n2 7 8\n1 -8\n", "output": "7 8 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1208/E" }
vfc_6778
apps
verifiable_code
2309
Solve the following coding problem using the programming language python: Masha and Grisha like studying sets of positive integers. One day Grisha has written a set A containing n different integers a_{i} on a blackboard. Now he asks Masha to create a set B containing n different integers b_{j} such that all n^2 integers that can be obtained by summing up a_{i} and b_{j} for all possible pairs of i and j are different. Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 10^6, and all numbers in B must also be in the same range. Help Masha to create the set B that satisfies Grisha's requirement. -----Input----- Input data contains multiple test cases. The first line contains an integer t — the number of test cases (1 ≤ t ≤ 100). Each test case is described in the following way: the first line of the description contains one integer n — the number of elements in A (1 ≤ n ≤ 100). The second line contains n integers a_{i} — the elements of A (1 ≤ a_{i} ≤ 10^6). -----Output----- For each test first print the answer: NO, if Masha's task is impossible to solve, there is no way to create the required set B. YES, if there is the way to create the required set. In this case the second line must contain n different positive integers b_{j} — elements of B (1 ≤ b_{j} ≤ 10^6). If there are several possible sets, output any of them. -----Example----- Input 3 3 1 10 100 1 1 2 2 4 Output YES 1 2 3 YES 1 YES 1 2 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python d = [-1] * 1000001 for t in range(int(input())): n, a = int(input()), list(map(int, input().split())) a.sort() for i in range(n): for j in range(i + 1, n): d[a[j] - a[i]] = t i = 1 while any(d[i * j] == t for j in range(1, n)): i += 1 print("YES\n" + ' '.join(str(j * i + 1) for j in range(n))) ```
{ "language": "python", "test_cases": [ { "input": "3\n3\n1 10 100\n1\n1\n2\n2 4\n", "output": "YES\n1 2 3 \nYES\n1 \nYES\n1 2 \n", "type": "stdin_stdout" }, { "input": "1\n100\n74 14 24 45 22 9 49 78 79 20 60 1 31 91 32 39 90 5 42 57 30 58 64 68 12 11 86 8 3 38 76 17 98 26 85 92 56 65 89 66 36 87 23 67 13 48 15 47 81 73 63 50 34 93 82 44 77 69 96 100 41 19 35 16 88 27 99 40 62 95 70 18 46 21 53 59 37 6 61 71 2 4 52 28 97 25 29 51 7 33 80 83 72 10 75 94 43 84 54 55\n", "output": "YES\n1 101 201 301 401 501 601 701 801 901 1001 1101 1201 1301 1401 1501 1601 1701 1801 1901 2001 2101 2201 2301 2401 2501 2601 2701 2801 2901 3001 3101 3201 3301 3401 3501 3601 3701 3801 3901 4001 4101 4201 4301 4401 4501 4601 4701 4801 4901 5001 5101 5201 5301 5401 5501 5601 5701 5801 5901 6001 6101 6201 6301 6401 6501 6601 6701 6801 6901 7001 7101 7201 7301 7401 7501 7601 7701 7801 7901 8001 8101 8201 8301 8401 8501 8601 8701 8801 8901 9001 9101 9201 9301 9401 9501 9601 9701 9801 9901 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/856/A" }
vfc_6782
apps
verifiable_code
2310
Solve the following coding problem using the programming language python: Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test. You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The sound of clashing rocks will awaken the door! Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks: '^': this rock moves upwards; '<': this rock moves leftwards; '>': this rock moves rightwards; 'v': this rock moves downwards. To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 10^7 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated. If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds. The following picture illustrates the four possible scenarios of moving rocks. Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated. [Image] Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end. [Image] Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced. [Image] Does not move because the wall is in the way. No sounds are produced and the movements end. [Image] Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door! -----Input----- The first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem: n = 5, x = 5; n = 3, x = 2; n = 100, x = 10^5. All of these testcases are in pretest. -----Output----- Output n lines. Each line consists of n characters — the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these: '^', '<', '>', or 'v': a rock as described in the problem statement. '.': an empty tile. Then, output two integers r and c (1 ≤ r, c ≤ n) on the next line — this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell. If there are multiple solutions, you may output any of them. -----Examples----- Input 5 5 Output >...v v.<.. ..^.. >.... ..^.< 1 1 Input 3 2 Output >vv ^<. ^.< 1 3 -----Note----- Here's a simulation of the first example, accompanied with the number of sounds produced so far. $8$ 0 sound [Image] 1 sound $8$ 2 sounds $8$ 3 sounds $8$ 4 sounds $8$ still 4 sounds In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound. [Image] 5 sounds At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens. [Image] 6 sounds [Image] 7 sounds [Image] still 7 sounds [Image] 8 sounds And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound. Here's a simulation of the second example: [Image] 0 sound [Image] 1 sound [Image] 2 sounds Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 10^7 limit, after which the movement will cease. [Image] In total, it produced exactly 2 sounds, so the solution is correct. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python r, c = list(map(int, input().split())) if r == 3: print('>vv') print('^<.') print('^.<') print('1 3') elif r == 5: print('>...v') print('v.<..') print('..^..') print('>....') print('..^.<') print('1 1') elif r == 100: for i in range(25): print('>'*50+'.>'*24+'.v') print('^'+'<.'*25+'<'*49) print('v.'+'<.'*24+'<'*50) print('>'*49+'.>'*25+'^') print('1 1') else: d = [] d[1] = 1 ```
{ "language": "python", "test_cases": [ { "input": "5 5\n", "output": ">...v\nv.<..\n..^..\n>....\n..^.<\n1 1\n", "type": "stdin_stdout" }, { "input": "3 2\n", "output": ">vv\n^<.\n^.<\n1 3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/329/D" }
vfc_6786
apps
verifiable_code
2311
Solve the following coding problem using the programming language python: Let us define two functions f and g on positive integer numbers. $f(n) = \text{product of non-zero digits of} n$ $g(n) = \left\{\begin{array}{ll}{n} & {\text{if} n < 10} \\{g(f(n))} & {\text{otherwise}} \end{array} \right.$ You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x) = k. -----Input----- The first line of the input contains an integer Q (1 ≤ Q ≤ 2 × 10^5) representing the number of queries. Q lines follow, each of which contains 3 integers l, r and k (1 ≤ l ≤ r ≤ 10^6, 1 ≤ k ≤ 9). -----Output----- For each query, print a single line containing the answer for that query. -----Examples----- Input 4 22 73 9 45 64 6 47 55 7 2 62 4 Output 1 4 0 8 Input 4 82 94 6 56 67 4 28 59 9 39 74 4 Output 3 1 1 5 -----Note----- In the first example: g(33) = 9 as g(33) = g(3 × 3) = g(9) = 9 g(47) = g(48) = g(60) = g(61) = 6 There are no such integers between 47 and 55. g(4) = g(14) = g(22) = g(27) = g(39) = g(40) = g(41) = g(58) = 4 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 sys input = sys.stdin.readline def main(): MAX_N = int(1e6) + 1 dp = [0 for i in range(MAX_N)] vals = [[] for i in range(10)] for i in range(10): dp[i] = i vals[i].append(i) for i in range(10, MAX_N): prod = 1 for j in str(i): if j != '0': prod *= int(j) dp[i] = dp[prod] vals[dp[prod]].append(i) q = int(input()) for i in range(len(vals)): vals[i] = sorted(vals[i]) for i in range(q): l,r, k = [int(x) for x in input().split(' ')] posl = -1 posr = -1 for j in range(25, -1, -1): jump = 2**j if posl + jump < len(vals[k]) and vals[k][posl+jump] < l: posl += jump if posr + jump < len(vals[k]) and vals[k][posr+jump] <= r: posr += jump print(posr - posl) def __starting_point(): main() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "4\n22 73 9\n45 64 6\n47 55 7\n2 62 4\n", "output": "1\n4\n0\n8\n", "type": "stdin_stdout" }, { "input": "4\n82 94 6\n56 67 4\n28 59 9\n39 74 4\n", "output": "3\n1\n1\n5\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/932/B" }
vfc_6790
apps
verifiable_code
2312
Solve the following coding problem using the programming language python: Toad Pimple has an array of integers $a_1, a_2, \ldots, a_n$. We say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \ldots < p_k=y$, and $a_{p_i}\, \&\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \leq i < k$. Here $\&$ denotes the bitwise AND operation. You are given $q$ pairs of indices, check reachability for each of them. -----Input----- The first line contains two integers $n$ and $q$ ($2 \leq n \leq 300\,000$, $1 \leq q \leq 300\,000$) — the number of integers in the array and the number of queries you need to answer. The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 300\,000$) — the given array. The next $q$ lines contain two integers each. The $i$-th of them contains two space-separated integers $x_i$ and $y_i$ ($1 \leq x_i < y_i \leq n$). You need to check if $y_i$ is reachable from $x_i$. -----Output----- Output $q$ lines. In the $i$-th of them print "Shi" if $y_i$ is reachable from $x_i$, otherwise, print "Fou". -----Example----- Input 5 3 1 3 0 2 1 1 3 2 4 1 4 Output Fou Shi Shi -----Note----- In the first example, $a_3 = 0$. You can't reach it, because AND with it is always zero. $a_2\, \&\, a_4 > 0$, so $4$ is reachable from $2$, and to go from $1$ to $4$ you can use $p = [1, 2, 4]$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop,heapify import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline from itertools import accumulate from functools import lru_cache M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] n, q = li() queue = [-1] * 20 ans = [[-1] * 20 for i in range(n + 1)] l = li() for i, curr in enumerate(l): for j in range(20): if curr >> j & 1: for k in range(20): ans[i][k] = max(ans[i][k], ans[queue[j]][k]) ans[i][j] = i for j in range(20):queue[j] = max(queue[j], ans[i][j]) queries = [] for i in range(q):queries.append(li()) for i in range(q): a, b = queries[i] a -= 1 b -= 1 currans = 0 for j in range(20): if (l[a] >> j) & 1 and ans[b][j] >= a: currans = 1 break print('Shi' if currans else 'Fou') ```
{ "language": "python", "test_cases": [ { "input": "5 3\n1 3 0 2 1\n1 3\n2 4\n1 4\n", "output": "Fou\nShi\nShi\n", "type": "stdin_stdout" }, { "input": "2 1\n300000 300000\n1 2\n", "output": "Shi\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1168/C" }
vfc_6794
apps
verifiable_code
2313
Solve the following coding problem using the programming language python: Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a_1, a_2, ..., a_{n}. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height a_{i} in the beginning), then the cost of charging the chain saw would be b_{i}. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, a_{i} < a_{j} and b_{i} > b_{j} and also b_{n} = 0 and a_1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you? -----Input----- The first line of input contains an integer n (1 ≤ n ≤ 10^5). The second line of input contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). The third line of input contains n integers b_1, b_2, ..., b_{n} (0 ≤ b_{i} ≤ 10^9). It's guaranteed that a_1 = 1, b_{n} = 0, a_1 < a_2 < ... < a_{n} and b_1 > b_2 > ... > b_{n}. -----Output----- The only line of output must contain the minimum cost of cutting all the trees completely. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Examples----- Input 5 1 2 3 4 5 5 4 3 2 0 Output 25 Input 6 1 2 3 10 20 30 6 5 4 3 2 0 Output 138 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 = [0] * n stk = [0] for i in range(1, n): while len(stk) > 1 and c[stk[1]] - c[stk[0]] <= a[i] * (b[stk[0]] - b[stk[1]]): del stk[0] c[i] = c[stk[0]] + a[i] * b[stk[0]] while len(stk) > 1 and ((c[stk[-1]] - c[stk[-2]]) * (b[stk[-1]] - b[i]) > (b[stk[-2]] - b[stk[-1]]) * (c[i] - c[stk[-1]])): del stk[-1] stk.append(i) print(c[n - 1]) ```
{ "language": "python", "test_cases": [ { "input": "5\n1 2 3 4 5\n5 4 3 2 0\n", "output": "25\n", "type": "stdin_stdout" }, { "input": "6\n1 2 3 10 20 30\n6 5 4 3 2 0\n", "output": "138\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/319/C" }
vfc_6798
apps
verifiable_code
2314
Solve the following coding problem using the programming language python: For an array $b$ of length $m$ we define the function $f$ as $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $ where $\oplus$ is bitwise exclusive OR. For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$ You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 5000$) — the length of $a$. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$) — the elements of the array. The third line contains a single integer $q$ ($1 \le q \le 100\,000$) — the number of queries. Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$). -----Output----- Print $q$ lines — the answers for the queries. -----Examples----- Input 3 8 4 1 2 2 3 1 2 Output 5 12 Input 6 1 2 4 8 16 32 4 1 6 2 5 3 4 1 2 Output 60 30 12 3 -----Note----- In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment. In second sample, optimal segment for first query are $[3,6]$, for second query — $[2,5]$, for third — $[3,4]$, for fourth — $[1,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()) *a, = map(int, input().split()) dp = [[0 for i in range(n + 1)] for j in range(n + 1)] for i in range(n): dp[0][i] = a[i] for i in range(1, n): for j in range(n - i + 1): dp[i][j] = dp[i - 1][j] ^ dp[i - 1][j + 1] for i in range(1, n): for j in range(n - i): dp[i][j] = max(dp[i][j], dp[i - 1][j], dp[i - 1][j + 1]) for i in range(int(input())): l, r = map(int, input().split()) print(dp[r - l][l - 1]) ```
{ "language": "python", "test_cases": [ { "input": "3\n8 4 1\n2\n2 3\n1 2\n", "output": "5\n12\n", "type": "stdin_stdout" }, { "input": "6\n1 2 4 8 16 32\n4\n1 6\n2 5\n3 4\n1 2\n", "output": "60\n30\n12\n3\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/983/B" }
vfc_6802
apps
verifiable_code
2315
Solve the following coding problem using the programming language python: Vasya has written some permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, so for all $1 \leq i \leq n$ it is true that $1 \leq p_i \leq n$ and all $p_1, p_2, \ldots, p_n$ are different. After that he wrote $n$ numbers $next_1, next_2, \ldots, next_n$. The number $next_i$ is equal to the minimal index $i < j \leq n$, such that $p_j > p_i$. If there is no such $j$ let's let's define as $next_i = n + 1$. In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values $next_i$ are completely lost! If for some $i$ the value $next_i$ is lost, let's say that $next_i = -1$. You are given numbers $next_1, next_2, \ldots, next_n$ (maybe some of them are equal to $-1$). Help Vasya to find such permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, that he can write it to the notebook and all numbers $next_i$, which are not equal to $-1$, will be correct. -----Input----- The first line contains one integer $t$ — the number of test cases ($1 \leq t \leq 100\,000$). Next $2 \cdot t$ lines contains the description of test cases,two lines for each. The first line contains one integer $n$ — the length of the permutation, written by Vasya ($1 \leq n \leq 500\,000$). The second line contains $n$ integers $next_1, next_2, \ldots, next_n$, separated by spaces ($next_i = -1$ or $i < next_i \leq n + 1$). It is guaranteed, that the sum of $n$ in all test cases doesn't exceed $500\,000$. In hacks you can only use one test case, so $T = 1$. -----Output----- Print $T$ lines, in $i$-th of them answer to the $i$-th test case. If there is no such permutations $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$, that Vasya could write, print the only number $-1$. In the other case print $n$ different integers $p_1, p_2, \ldots, p_n$, separated by spaces ($1 \leq p_i \leq n$). All defined values of $next_i$ which are not equal to $-1$ should be computed correctly $p_1, p_2, \ldots, p_n$ using defenition given in the statement of the problem. If there exists more than one solution you can find any of them. -----Example----- Input 6 3 2 3 4 2 3 3 3 -1 -1 -1 3 3 4 -1 1 2 4 4 -1 4 5 Output 1 2 3 2 1 2 1 3 -1 1 3 2 1 4 -----Note----- In the first test case for permutation $p = [1, 2, 3]$ Vasya should write $next = [2, 3, 4]$, because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation. In the third test case, any permutation can be the answer because all numbers $next_i$ are lost. In the fourth test case, there is no satisfying permutation, so the answer is $-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 input = sys.stdin.readline T = int(input()) for _ in range(T): n = int(input()) l = list(map(int, input().split())) stack = [] out = [-1] * n curr = 0 works = True for i in range(n): while stack and stack[-1][0] == i: _, j = stack.pop() curr += 1 out[j] = curr nex = l[i] - 1 if nex == -2: curr += 1 out[i] = curr else: if stack and nex > stack[-1][0]: works = False else: stack.append((nex, i)) while stack: _, j = stack.pop() curr += 1 out[j] = curr if works: print(*out) else: print(-1) ```
{ "language": "python", "test_cases": [ { "input": "6\n3\n2 3 4\n2\n3 3\n3\n-1 -1 -1\n3\n3 4 -1\n1\n2\n4\n4 -1 4 5\n", "output": "1 2 3 \n2 1 \n1 2 3 \n-1\n1 \n3 1 2 4 \n", "type": "stdin_stdout" }, { "input": "10\n4\n2 4 4 5\n4\n2 -1 4 -1\n4\n4 5 5 5\n4\n2 3 4 5\n4\n2 3 4 5\n4\n-1 3 4 5\n4\n-1 3 4 5\n4\n3 3 4 5\n4\n3 5 5 5\n4\n5 4 5 5\n", "output": "2 3 1 4 \n1 2 3 4 \n-1\n1 2 3 4 \n1 2 3 4 \n1 2 3 4 \n1 2 3 4 \n2 1 3 4 \n-1\n-1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1158/C" }
vfc_6806
apps
verifiable_code
2316
Solve the following coding problem using the programming language python: Koa the Koala and her best friend want to play a game. The game starts with an array $a$ of length $n$ consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to $0$. Koa starts. Let's describe a move in the game: During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player. More formally: if the current score of the player is $x$ and the chosen element is $y$, his new score will be $x \oplus y$. Here $\oplus$ denotes bitwise XOR operation. Note that after a move element $y$ is removed from $a$. The game ends when the array is empty. At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw. If both players play optimally find out whether Koa will win, lose or draw the game. -----Input----- Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows. The first line of each test case contains the integer $n$ ($1 \le n \le 10^5$) — the length of $a$. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — elements of $a$. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case print: WIN if Koa will win the game. LOSE if Koa will lose the game. DRAW if the game ends in a draw. -----Examples----- Input 3 3 1 2 2 3 2 2 3 5 0 0 0 2 2 Output WIN LOSE DRAW Input 4 5 4 1 5 1 3 4 1 0 1 6 1 0 2 5 4 Output WIN WIN DRAW WIN -----Note----- In testcase $1$ of the first sample we have: $a = [1, 2, 2]$. Here Koa chooses $1$, other player has to choose $2$, Koa chooses another $2$. Score for Koa is $1 \oplus 2 = 3$ and score for other player is $2$ so Koa wins. 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 = lambda: sys.stdin.readline().rstrip() T = int(input()) for _ in range(T): N = int(input()) A = [int(a) for a in input().split()] X = [0] * 30 for a in A: for i in range(30): if a & (1 << i): X[i] += 1 for i in range(30)[::-1]: if X[i] % 2: if X[i] == 1: print("WIN") elif N % 2 == 0: print("WIN") elif X[i] % 4 == 1: print("WIN") else: print("LOSE") break else: print("DRAW") ```
{ "language": "python", "test_cases": [ { "input": "3\n3\n1 2 2\n3\n2 2 3\n5\n0 0 0 2 2\n", "output": "WIN\nLOSE\nDRAW\n", "type": "stdin_stdout" }, { "input": "4\n5\n4 1 5 1 3\n4\n1 0 1 6\n1\n0\n2\n5 4\n", "output": "WIN\nWIN\nDRAW\nWIN\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1383/B" }
vfc_6810
apps
verifiable_code
2317
Solve the following coding problem using the programming language python: You have an array $a$ of length $n$. For every positive integer $x$ you are going to perform the following operation during the $x$-th second: Select some distinct indices $i_{1}, i_{2}, \ldots, i_{k}$ which are between $1$ and $n$ inclusive, and add $2^{x-1}$ to each corresponding position of $a$. Formally, $a_{i_{j}} := a_{i_{j}} + 2^{x-1}$ for $j = 1, 2, \ldots, k$. Note that you are allowed to not select any indices at all. You have to make $a$ nondecreasing as fast as possible. Find the smallest number $T$ such that you can make the array nondecreasing after at most $T$ seconds. Array $a$ is nondecreasing if and only if $a_{1} \le a_{2} \le \ldots \le a_{n}$. You have to answer $t$ independent test cases. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^{4}$) — the number of test cases. The first line of each test case contains single integer $n$ ($1 \le n \le 10^{5}$) — the length of array $a$. It is guaranteed that the sum of values of $n$ over all test cases in the input does not exceed $10^{5}$. The second line of each test case contains $n$ integers $a_{1}, a_{2}, \ldots, a_{n}$ ($-10^{9} \le a_{i} \le 10^{9}$). -----Output----- For each test case, print the minimum number of seconds in which you can make $a$ nondecreasing. -----Example----- Input 3 4 1 7 6 5 5 1 2 3 4 5 2 0 -4 Output 2 0 3 -----Note----- In the first test case, if you select indices $3, 4$ at the $1$-st second and $4$ at the $2$-nd second, then $a$ will become $[1, 7, 7, 8]$. There are some other possible ways to make $a$ nondecreasing in $2$ seconds, but you can't do it faster. In the second test case, $a$ is already nondecreasing, so answer is $0$. In the third test case, if you do nothing at first $2$ seconds and select index $2$ at the $3$-rd second, $a$ will become $[0, 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 input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): diff = a[i] - a[i + 1] if diff <= 0: continue else: ans = max(len(bin(diff)) - 2, ans) a[i + 1] = a[i] print(ans) ```
{ "language": "python", "test_cases": [ { "input": "3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n", "output": "2\n0\n3\n", "type": "stdin_stdout" }, { "input": "6\n3\n1000000000 0 -1000000000\n1\n6\n2\n-1000000000 1000000000\n2\n1000000000 -1000000000\n2\n1000000000 1000000000\n2\n-1000000000 -1000000000\n", "output": "31\n0\n0\n31\n0\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1338/A" }
vfc_6814
apps
verifiable_code
2318
Solve the following coding problem using the programming language python: During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a_1, the second place participant has rating a_2, ..., the n-th place participant has rating a_{n}. Then changing the rating on the Codesecrof site is calculated by the formula $d_{i} = \sum_{j = 1}^{i - 1}(a_{j} \cdot(j - 1) -(n - i) \cdot a_{i})$. After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant d_{i} < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table. We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who d_{i} < k. We also know that the applications for exclusion from rating were submitted by all participants. Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement. -----Input----- The first line contains two integers n, k (1 ≤ n ≤ 2·10^5, - 10^9 ≤ k ≤ 0). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — ratings of the participants in the initial table. -----Output----- Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table. -----Examples----- Input 5 0 5 3 4 1 2 Output 2 3 4 Input 10 -10 5 5 1 7 5 1 2 4 9 2 Output 2 4 5 7 8 9 -----Note----- Consider the first test sample. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered. Thus, you should print 2, 3, 4. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, k = list(map(int, input().split())) c, m, l, r = 0, 0, [], 0 for e in [int(i) for i in input().split()]: d = m - c * (n - c - 1) * e r+= 1 if d < k: n -= 1 l += [r] else: m += c * e c += 1 l.sort() for e in l: print(e) ```
{ "language": "python", "test_cases": [ { "input": "5 0\n5 3 4 1 2\n", "output": "2\n3\n4\n", "type": "stdin_stdout" }, { "input": "10 -10\n5 5 1 7 5 1 2 4 9 2\n", "output": "2\n4\n5\n7\n8\n9\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/314/A" }
vfc_6818
apps
verifiable_code
2319
Solve the following coding problem using the programming language python: We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times. On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \ldots, a_n$ to the left in order to fill in the empty space. You are given the initial permutation $a_1, a_2, \ldots, a_n$ and the resulting array $b_1, b_2, \ldots, b_k$. All elements of an array $b$ are distinct. Calculate the number of possible sequences of indices $t_1, t_2, \ldots, t_k$ modulo $998\,244\,353$. -----Input----- Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100\,000$), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers $n, k$ ($1 \le k < n \le 200\,000$): sizes of arrays $a$ and $b$. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): elements of $a$. All elements of $a$ are distinct. The third line of each test case contains $k$ integers $b_1, b_2, \ldots, b_k$ ($1 \le b_i \le n$): elements of $b$. All elements of $b$ are distinct. The sum of all $n$ among all test cases is guaranteed to not exceed $200\,000$. -----Output----- For each test case print one integer: the number of possible sequences modulo $998\,244\,353$. -----Example----- Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 -----Note----- $\require{cancel}$ Let's denote as $a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$ an operation over an element with index $i$: removal of element $a_i$ from array $a$ and appending element $a_{i+1}$ to array $b$. In the first example test, the following two options can be used to produce the given array $b$: $1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$; $(t_1, t_2, t_3) = (4, 3, 2)$; $1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$; $(t_1, t_2, t_3) = (4, 1, 2)$. In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $4$, namely number $3$, which means that it couldn't be added to array $b$ on the second step. In the third example test, there are four options to achieve the given array $b$: $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$; $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 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 readline = sys.stdin.readline T = int(readline()) MOD = 998244353 Ans = [None]*T for qu in range(T): N, K = map(int, readline().split()) A = [0] + list(map(int, readline().split())) + [0] B = list(map(int, readline().split())) C = [None]*(N+1) for i in range(1, N+1): C[A[i]] = i ans = 1 for b in B[::-1]: bi = C[b] res = 0 if A[bi-1]: res += 1 if A[bi+1]: res += 1 A[bi] = 0 ans = ans*res%MOD Ans[qu] = ans print('\n'.join(map(str, Ans))) ```
{ "language": "python", "test_cases": [ { "input": "3\n5 3\n1 2 3 4 5\n3 2 5\n4 3\n4 3 2 1\n4 3 1\n7 4\n1 4 7 3 6 2 5\n3 2 4 5\n", "output": "2\n0\n4\n", "type": "stdin_stdout" }, { "input": "6\n2 1\n2 1\n1\n3 2\n1 3 2\n1 3\n4 2\n4 1 3 2\n1 2\n5 3\n4 3 2 5 1\n1 4 5\n6 3\n2 4 5 6 1 3\n2 4 5\n7 3\n7 6 4 3 2 1 5\n1 2 6\n", "output": "1\n0\n2\n0\n0\n4\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1442/B" }
vfc_6822
apps
verifiable_code
2320
Solve the following coding problem using the programming language python: Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets. But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition A_{i} ≥ B_{j} holds. Help Leha rearrange the numbers in the array A so that the sum $\sum_{i = 1}^{m} F(A_{i}^{\prime}, B_{i})$ is maximally possible, where A' is already rearranged array. -----Input----- First line of input data contains single integer m (1 ≤ m ≤ 2·10^5) — length of arrays A and B. Next line contains m integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — array A. Next line contains m integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 10^9) — array B. -----Output----- Output m integers a'_1, a'_2, ..., a'_{m} — array A' which is permutation of the array A. -----Examples----- Input 5 7 3 5 3 4 2 1 3 2 3 Output 4 7 3 5 3 Input 7 4 6 5 8 8 2 6 2 1 2 2 1 1 2 Output 2 6 4 5 8 8 6 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ Author : Arif Ahmad Date : Algo : Difficulty : """ from sys import stdin, stdout, setrecursionlimit import threading def main(): m = int(stdin.readline().strip()) a = [int(_) for _ in stdin.readline().strip().split()] b = [int(_) for _ in stdin.readline().strip().split()] c = [] for i, v in enumerate(b): c.append((v, i)) a = sorted(a, reverse=True) c = sorted(c) ans = [0 for i in range(m)] j = 0 for v, i in c: ans[i] = a[j] j += 1 stdout.write(' '.join(str(_) for _ in ans)) def __starting_point(): # the following 4 lines of code are required to increase # the recursion limit and stack size # * if is cause any problem, comment out the lines, # * and just call main() setrecursionlimit(10**6) threading.stack_size(134217728) # 128MB thread = threading.Thread(target=main) thread.start() __starting_point() ```
{ "language": "python", "test_cases": [ { "input": "5\n7 3 5 3 4\n2 1 3 2 3\n", "output": "4 7 3 5 3\n", "type": "stdin_stdout" }, { "input": "7\n4 6 5 8 8 2 6\n2 1 2 2 1 1 2\n", "output": "2 6 4 5 8 8 6\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/840/A" }
vfc_6826
apps
verifiable_code
2322
Solve the following coding problem using the programming language python: You are working for the Gryzzl company, headquartered in Pawnee, Indiana. The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be $n$ antennas located somewhere in the park. When someone would like to know their current location, their Gryzzl hologram phone will communicate with antennas and obtain distances from a user's current location to all antennas. Knowing those distances and antennas locations it should be easy to recover a user's location... Right? Well, almost. The only issue is that there is no way to distinguish antennas, so you don't know, which distance corresponds to each antenna. Your task is to find a user's location given as little as all antennas location and an unordered multiset of distances. -----Input----- The first line of input contains a single integer $n$ ($2 \leq n \leq 10^5$) which is the number of antennas. The following $n$ lines contain coordinates of antennas, $i$-th line contain two integers $x_i$ and $y_i$ ($0 \leq x_i,y_i \leq 10^8$). It is guaranteed that no two antennas coincide. The next line of input contains integer $m$ ($1 \leq n \cdot m \leq 10^5$), which is the number of queries to determine the location of the user. Following $m$ lines contain $n$ integers $0 \leq d_1 \leq d_2 \leq \dots \leq d_n \leq 2 \cdot 10^{16}$ each. These integers form a multiset of squared distances from unknown user's location $(x;y)$ to antennas. For all test cases except the examples it is guaranteed that all user's locations $(x;y)$ were chosen uniformly at random, independently from each other among all possible integer locations having $0 \leq x, y \leq 10^8$. -----Output----- For each query output $k$, the number of possible a user's locations matching the given input and then output the list of these locations in lexicographic order. It is guaranteed that the sum of all $k$ over all points does not exceed $10^6$. -----Examples----- Input 3 0 0 0 1 1 0 1 1 1 2 Output 1 1 1 Input 4 0 0 0 1 1 0 1 1 2 0 1 1 2 2 5 5 8 Output 4 0 0 0 1 1 0 1 1 4 -1 -1 -1 2 2 -1 2 2 -----Note----- As you see in the second example, although initially a user's location is picked to have non-negative coordinates, you have to output all possible integer locations. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys import math n = int(input()) x = [0]*n y = [0]*n for i in range(n): x[i], y[i] = list(map(int, input().split())) sx = sum(x) sy = sum(y) for i in range(n): x[i] = n * x[i] - sx y[i] = n * y[i] - sy m = int(input()) d = [0]*n e = [0]*n HD = 0 def check(a, b): nonlocal HD HE = 0 for i in range(n): HE ^= hash((a-x[i])*(a-x[i])+(b-y[i])*(b-y[i])) return HD == HE def sqrt(x): nn = int(x) if nn == 0: return 0 fa, fb = divmod(nn.bit_length(), 2) x = 2**(fa+fb) while True: y = (x + nn//x)//2 if y >= x: return x x = y def hash(x): return x * 9991 + 43 pans = [] def solve(): nonlocal d d = list(map(int, input().split())) c = 0 d = [p * n * n for p in d] for i in range(n): c += d[i] - x[i] * x[i] - y[i] * y[i] assert(c % n == 0) c //= n ans = [] ax = x[0] ay = y[0] if ax is 0 and ay is 0: ax = x[1] ay = y[1] rev = 0 if ay == 0: ay = ax ax = 0 rev = 1 d.sort() nonlocal HD HD = 0 for p in d: HD ^= hash(p) old = -1 for p in d: if (p == old): continue old = p a = c + ax * ax + ay * ay - p if (a % 2 != 0): continue a //= 2 A = ax * ax + ay * ay B = a * ax C = a * a - ay * ay * c D = B * B - A * C if (D < 0): continue sD = sqrt(D) if D != sD * sD: continue if (B + sD) % A == 0: qx = (B + sD) // A qy = (a - ax * qx) // ay if rev: t = qx qx = qy qy = t if ((qx + sx) % n == 0 and (qy + sy) % n == 0 and check(qx, qy)): qx = (qx + sx) // n qy = (qy + sy) // n ans.append([qx, qy]) if sD == 0: continue if (B - sD) % A == 0: qx = (B - sD) // A qy = (a - ax * qx) // ay if rev: t = qx qx = qy qy = t if ((qx + sx) % n == 0 and (qy + sy) % n == 0 and check(qx, qy)): qx = (qx + sx) // n qy = (qy + sy) // n ans.append([qx, qy]) ans.sort() buf=[] buf.append(len(ans)) for p in ans: buf.append(p[0]) buf.append(p[1]) nonlocal pans pans.append(" ".join(map(str,buf))) while m > 0: m -= 1 solve() sys.stdout.write("\n".join(pans)) ```
{ "language": "python", "test_cases": [ { "input": "3\n0 0\n0 1\n1 0\n1\n1 1 2\n", "output": "1 1 1 \n", "type": "stdin_stdout" }, { "input": "4\n0 0\n0 1\n1 0\n1 1\n2\n0 1 1 2\n2 5 5 8\n", "output": "4 0 0 0 1 1 0 1 1 \n4 -1 -1 -1 2 2 -1 2 2 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1220/G" }
vfc_6834
apps
verifiable_code
2328
Solve the following coding problem using the programming language python: When Misha hits his favorite gym, he comes across an interesting problem with the barbell. In the gym, someone always leaves the weight plates in the strangest places you can imagine and sometime it's difficult to equip the barbell the way you want. Let's imagine that you have N weight plates placed in any order (remember that any gym has no more than K different types of weight plates and all weights are square-free). As a preliminary step towards solving this problem, Misha wants to simulate a simple gym, and for this purpose you have to deal with some queries: - [1 I X] Set the weight of the ith weight plate to value X. - [2 L R] Reverse the sequence of weight plates in the interval from L to R, where 1 ≤ L ≤ R ≤ N. - [3 L R W] Check the interval from L to R to find out if you can make the weight W using only weight plates on this interval. (Note: this type of query will appear no more than P times) Please help Misha in solving this problem. -----Input----- First line of input contains the number of weight plates N, and number of queries Q. Next line contains N integers w1, w2, ..., wN, where wi is the weight of the ith weight plate. Next Q lines contain some queries described above. -----Output----- For all queries of the third type: print "Yes" if your check returns a positive outcome, and "No" otherwise. -----Constraints----- - 1 ≤ N, W, Q ≤ 105 - K ≤ 10 - P ≤ 1000 - All numbers in the input are positive integers and ≤ 105. - All the weights are square-free. -----Subtasks----- - Subtask 1: 1 ≤ N ≤ 103, 1 ≤ W ≤ 103, Q = 1 - 10 pts. - Subtask 2: 1 ≤ N ≤ 103, 1 ≤ W ≤ 103, 1 ≤ Q ≤ 103, P ≤ 100 - 15 pts - Subtask 3: 1 ≤ N ≤ 104, 1 ≤ W ≤ 104, 1 ≤ Q ≤ 104, P ≤ 300 - 25 pts. - Subtask 4: 1 ≤ N ≤ 105, 1 ≤ W ≤ 105, 1 ≤ Q ≤ 105, K ≤ 2 - 20 pts. - Subtask 5: Original constraints - 30 pts. -----Example-----First Input:5 10 1 2 3 5 6 3 2 3 3 3 2 3 4 3 2 3 5 2 2 5 3 2 4 8 1 2 1 3 2 4 8 2 1 4 3 2 4 3 3 1 5 7 Output:Yes No Yes Yes Yes No YesSecond Input:3 4 2013 2015 2017 3 1 3 4030 1 1 111 3 1 3 4030 3 1 2 111 Output:Yes No Yes -----Explanation:-----First test explanation (step by step) 1 2 3 5 6 3 2 3 3 ([2, 3] 3=3 => Yes) 3 2 3 4 ([2, 3] can't make 4 => No) 3 2 3 5 ([2, 3] 2+3=5 => Yes) 2 2 5 (Reverse: [1, 6, 5, 3, 2]) 3 2 4 8 ([6, 5, 3] 5+3=8 => Yes) 1 2 1 (Set: [1, 1, 5, 3, 2]) 3 2 4 8 ([1, 5, 3] 5+3=8 => Yes) 2 1 4 (Reverse: [3, 5, 1, 1, 2]) 3 2 4 3 ([5, 1, 1] can't make 3 => No) 3 1 5 7 ([3, 5, 1, 1, 2] 2+1+1+3=7 => Yes) The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def fx(s,n,xsum): sub=[[None for x in range(n+2)]for y in range(xsum+2)] for i in range(n+1): sub[0][i]=True for i in range(1,xsum+1): sub[i][0]=False for i in range(1,xsum+1): for j in range(1,n+1): sub[i][j]=sub[i][j-1] if i>=s[j-1]: sub[i][j]=sub[i][j] or sub[i-s[j-1]][j-1] if sub[xsum][n]: print('Yes') else: print('No') n,t=list(map(int,input().split())) a=list(map(int,input().split())) for _ in range(t): q=list(map(int,input().split())) if q[0]==1: a[q[1]-1]=q[2] continue if q[0]==2: w=a[q[1]-1:q[2]] a[q[1]-1:q[2]]=w[::-1] continue if q[0]==3: e=a[q[1]-1:q[2]] if q[3]<min(e) or q[3]>sum(e): print('No') continue if q[3] in e: print('Yes') continue fx(e,len(e),q[3]) ```
{ "language": "python", "test_cases": [ { "input": "5 10\n1 2 3 5 6\n3 2 3 3\n3 2 3 4\n3 2 3 5\n2 2 5\n3 2 4 8\n1 2 1\n3 2 4 8\n2 1 4 \n3 2 4 3 \n3 1 5 7 \n", "output": "Yes\nNo\nYes\nYes\nYes\nNo\nYes\n", "type": "stdin_stdout" }, { "input": "3 4\n2013 2015 2017\n3 1 3 4030\n1 1 111\n3 1 3 4030\n3 1 2 111\n", "output": "Yes\nNo\nYes\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://www.codechef.com/OCT15/problems/MGCHGYM" }
vfc_6858
apps
verifiable_code
2329
Solve the following coding problem using the programming language python: You are given an array A, consisting of N integers and an array B, consisting of M integers. The subsequence of A is the array that can be obtained by picking the elements at the arbitrary sorted set of positions from A. Your task is to count the number of such subsequences C of A that: - C contains exactly M elements. - The array (C+B) is non-decreasing. Here by + operation, we mean element-wise sum. For example, the array (4, 8, 5) plus the array (10, 20, 30) is (14, 28, 35). Formally, (C+B) is an array of size M such that (C+B)i = Ci + Bi. In case some subsequence appears more that once, you should counts it as many times as it appears. Formally, two subarrays of an array a, (ai_1, ai_2, ... ,ai_n) and (aj_1, aj_2, ... ,aj_m) will be considered different if either their lengths are different i.e. n != m or there exists an index k such that such that i_k != j_k. Since the answer can be very large, we ask you to calculate it, modulo 109+7. -----Input----- The first line of input contains a pair of space separated integers N and M, denoting the number of elements in the array A and the number of elements in the array B. The second line contains N space-separated integers Ai, denoting the array A. The third line contains M space-separated integers Bj, denoting the array B. -----Output----- Output a single line containing the number of subsequences C as asked in the problem, modulo 109+7. -----Constraints----- - 1 ≤ Ai, Bi ≤ 109 - 1 ≤ M ≤ N -----Subtasks----- - Subtask #1 (33 points): 1 ≤ N ≤ 50, 1 ≤ M ≤ 5 - Subtask #2 (33 points): 1 ≤ N ≤ 500, 1 ≤ M ≤ 50 - Subtask #3 (34 points): 1 ≤ N ≤ 2000, 1 ≤ M ≤ 1000 -----Example----- Input #1: 5 3 1 5 2 4 7 7 9 6 Output #1: 4 Input #2: 4 2 7 7 7 7 3 4 Output #2: 6 -----Explanation----- Example case 1. The suitable subsequences are (1, 2, 7), (1, 4, 7), (5, 4, 7), (2, 4, 7). Example case 2. The suitable subsequence is (7, 7), and it appears 6 times: - at indices (1, 2) - at indices (1, 3) - at indices (1, 4) - at indices (2, 3) - at indices (2, 4) - at indices (3, 4) So, the answer is 6. 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 n,m = list(map(int,input().split())) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] dp = [] for i in range(n): dp += [[0]*m] dp[-1][-1]=1 for i in range(n-2,-1,-1): dp[i][-1]=1 for j in range(m-1): x = (a[i]+b[j])-(b[j+1]) temp = 0 for k in range(i+1,n): if(a[k]>=x): temp += dp[k][j+1] dp[i][j]=temp ans = 0 for i in range(n): ans += dp[i][0] print(ans%mod) ```
{ "language": "python", "test_cases": [ { "input": "5 3\n1 5 2 4 7\n7 9 6\n\n\n", "output": "4\n", "type": "stdin_stdout" }, { "input": "4 2\n7 7 7 7\n3 4\n\n\n", "output": "6\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://www.codechef.com/LTIME34/problems/ARRAYSUM" }
vfc_6862
apps
verifiable_code
2334
Solve the following coding problem using the programming language python: Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA $\to$ AABBA $\to$ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? -----Input----- Each test contains multiple test cases. The first line contains a single integer $t$ $(1 \leq t \leq 20000)$  — the number of test cases. The description of the test cases follows. Each of the next $t$ lines contains a single test case each, consisting of a non-empty string $s$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $s$ are either 'A' or 'B'. It is guaranteed that the sum of $|s|$ (length of $s$) among all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case, print a single integer: the length of the shortest string that Zookeeper can make. -----Example----- Input 3 AAA BABA AABBBABBBB Output 3 2 0 -----Note----- For the first test case, you can't make any moves, so the answer is $3$. For the second test case, one optimal sequence of moves is BABA $\to$ BA. So, the answer is $2$. For the third test case, one optimal sequence of moves is AABBBABBBB $\to$ AABBBABB $\to$ AABBBB $\to$ ABBB $\to$ AB $\to$ (empty string). So, 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 import sys readline = sys.stdin.readline T = int(readline()) Ans = [None]*T for qu in range(T): S = [1 if s == 'A' else 0 for s in readline().strip()] stack = [] for s in S: if s: stack.append(s) else: if stack and stack[-1] == 1: stack.pop() else: stack.append(s) stack2 = [] for s in stack: if s: stack2.append(s) else: if stack2 and stack2[-1] == 0: stack2.pop() else: stack2.append(s) Ans[qu] = len(stack2) print('\n'.join(map(str, Ans))) ```
{ "language": "python", "test_cases": [ { "input": "3\nAAA\nBABA\nAABBBABBBB\n", "output": "3\n2\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1428/C" }
vfc_6882
apps
verifiable_code
2335
Solve the following coding problem using the programming language python: Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck. When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $n$ steps. At the $i$-th step, a place is chosen for the number $i$ $(1 \leq i \leq n)$. The position for the number $i$ is defined as follows: For all $j$ from $1$ to $n$, we calculate $r_j$  — the minimum index such that $j \leq r_j \leq n$, and the position $r_j$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $r_j$ is not defined. For all $t$ from $1$ to $n$, we calculate $count_t$  — the number of positions $1 \leq j \leq n$ such that $r_j$ is defined and $r_j = t$. Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $count$ array is maximum. The generator selects one of these positions for the number $i$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example: [Image] Let $n = 5$ and the algorithm has already arranged the numbers $1, 2, 3$ in the permutation. Consider how the generator will choose a position for the number $4$: The values of $r$ will be $r = [3, 3, 3, 4, \times]$, where $\times$ means an indefinite value. Then the $count$ values will be $count = [0, 0, 3, 1, 0]$. There are only two unoccupied positions in the permutation: $3$ and $4$. The value in the $count$ array for position $3$ is $3$, for position $4$ it is $1$. The maximum value is reached only for position $3$, so the algorithm will uniquely select this position for number $4$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $p_1, p_2, \ldots, p_n$ and decided to find out if it could be obtained as a result of the generator. Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs. -----Input----- The first line contains a single integer $t$ $(1 \leq t \leq 10^5)$  — the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $n$ $(1 \leq n \leq 10^5)$  — the size of the permutation. The second line of the test case contains $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq n$)  — the permutation written by Denis. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No". All letters can be displayed in any case. -----Example----- Input 5 5 2 3 4 5 1 1 1 3 1 3 2 4 4 2 3 1 5 1 5 2 4 3 Output Yes Yes No Yes No -----Note----- Let's simulate the operation of the generator in the first test. At the $1$ step, $r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$. The maximum value is reached in any free position, so the generator can choose a random position from $1$ to $5$. In our example, it chose $5$. At the $2$ step, $r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$. The maximum value is reached in positions from $1$ to $4$, so the generator can choose a random position among them. In our example, it chose $1$. At the $3$ step, $r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$. The maximum value is $2$ and is reached only at the $2$ position, so the generator will choose this position. At the $4$ step, $r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$. The maximum value is $3$ and is reached only at the $3$ position, so the generator will choose this position. At the $5$ step, $r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$. The maximum value is $4$ and is reached only at the $4$ position, so the generator will choose this position. In total, we got a permutation of $2, 3, 4, 5, 1$, that is, a generator could generate it. 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()) out = [] for _ in range(t): n = int(input()) l = list(map(int,input().split())) smol = l[0] works = True for i in range(1, n): if l[i] == l[i-1] + 1: pass else: if l[i] > smol: works = False break smol = min(smol, l[i]) if works: out.append('Yes') else: out.append('No') print('\n'.join(out)) ```
{ "language": "python", "test_cases": [ { "input": "5\n5\n2 3 4 5 1\n1\n1\n3\n1 3 2\n4\n4 2 3 1\n5\n1 5 2 4 3\n", "output": "Yes\nYes\nNo\nYes\nNo\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1340/A" }
vfc_6886
apps
verifiable_code
2336
Solve the following coding problem using the programming language python: Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?! You somehow get a test from one of these problems and now you want to know from which one. -----Input----- In the first line of input there is one integer $n$ ($10^{3} \le n \le 10^{6}$). In the second line there are $n$ distinct integers between $1$ and $n$ — the permutation of size $n$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $n$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method. -----Output----- If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes). -----Example----- Input 5 2 4 5 1 3 Output Petr -----Note----- Please note that the sample is not a valid test (because of limitations for $n$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC. Due to randomness of input hacks in this problem are forbidden. 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) - 1 for x in input().split()] parity = 0 explore = set(l) while len(explore) > 0: x = explore.pop() tmp = x found = [x] while l[tmp] != x: tmp = l[tmp] found.append(tmp) for i in found[1:]: explore.remove(i) parity ^= (len(found) - 1) % 2 if parity == n % 2: print("Petr") else: print("Um_nik") ```
{ "language": "python", "test_cases": [ { "input": "5\n2 4 5 1 3\n", "output": "Petr\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/986/B" }
vfc_6890
apps
verifiable_code
2338
Solve the following coding problem using the programming language python: This is the hard version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix. For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$. Your task is to transform the string $a$ into $b$ in at most $2n$ operations. It can be proved that it is always possible. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$)  — the length of the binary strings. The next two lines contain two binary strings $a$ and $b$ of length $n$. It is guaranteed that the sum of $n$ across all test cases does not exceed $10^5$. -----Output----- For each test case, output an integer $k$ ($0\le k\le 2n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation. -----Example----- Input 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 Output 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1 -----Note----- In the first test case, we have $01\to 11\to 00\to 10$. In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$. In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged. 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 from collections import deque t=int(input()) for tests in range(t): n=int(input()) a=input().strip() b=input().strip() Q=deque(a) L=[] while Q: L.append(Q.popleft()) if Q: L.append(Q.pop()) ANS=[] for i in range(n): if i%2==0: if L[i]==b[-1-i]: ANS.append(1) else: if L[i]!=b[-1-i]: ANS.append(1) ANS.append(n-i) print(len(ANS),*ANS) ```
{ "language": "python", "test_cases": [ { "input": "5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n", "output": "3 1 2 1 \n8 1 5 1 4 1 3 2 1 \n3 2 1 1 \n19 1 10 1 9 1 8 1 7 1 6 1 5 1 4 1 3 1 2 1 \n1 1 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1381/A2" }
vfc_6898
apps
verifiable_code
2339
Solve the following coding problem using the programming language python: This is the easy version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix. For example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$. Your task is to transform the string $a$ into $b$ in at most $3n$ operations. It can be proved that it is always possible. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $3t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 1000$)  — the length of the binary strings. The next two lines contain two binary strings $a$ and $b$ of length $n$. It is guaranteed that the sum of $n$ across all test cases does not exceed $1000$. -----Output----- For each test case, output an integer $k$ ($0\le k\le 3n$), followed by $k$ integers $p_1,\ldots,p_k$ ($1\le p_i\le n$). Here $k$ is the number of operations you use and $p_i$ is the length of the prefix you flip in the $i$-th operation. -----Example----- Input 5 2 01 10 5 01011 11100 2 01 01 10 0110011011 1000110100 1 0 1 Output 3 1 2 1 6 5 2 5 3 1 2 0 9 4 1 2 10 4 1 2 1 5 1 1 -----Note----- In the first test case, we have $01\to 11\to 00\to 10$. In the second test case, we have $01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$. In the third test case, the strings are already the same. Another solution is to flip the prefix of length $2$, which will leave $a$ unchanged. 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 from collections import deque t=int(input()) for tests in range(t): n=int(input()) a=input().strip() b=input().strip() Q=deque(a) L=[] while Q: L.append(Q.popleft()) if Q: L.append(Q.pop()) ANS=[] for i in range(n): if i%2==0: if L[i]==b[-1-i]: ANS.append(1) else: if L[i]!=b[-1-i]: ANS.append(1) ANS.append(n-i) print(len(ANS),*ANS) ```
{ "language": "python", "test_cases": [ { "input": "5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n", "output": "3 1 2 1 \n8 1 5 1 4 1 3 2 1 \n3 2 1 1 \n19 1 10 1 9 1 8 1 7 1 6 1 5 1 4 1 3 1 2 1 \n1 1 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1381/A1" }
vfc_6902
apps
verifiable_code
2340
Solve the following coding problem using the programming language python: Let $a$ and $b$ be two arrays of lengths $n$ and $m$, respectively, with no elements in common. We can define a new array $\mathrm{merge}(a,b)$ of length $n+m$ recursively as follows: If one of the arrays is empty, the result is the other array. That is, $\mathrm{merge}(\emptyset,b)=b$ and $\mathrm{merge}(a,\emptyset)=a$. In particular, $\mathrm{merge}(\emptyset,\emptyset)=\emptyset$. If both arrays are non-empty, and $a_1<b_1$, then $\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$. That is, we delete the first element $a_1$ of $a$, merge the remaining arrays, then add $a_1$ to the beginning of the result. If both arrays are non-empty, and $a_1>b_1$, then $\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$. That is, we delete the first element $b_1$ of $b$, merge the remaining arrays, then add $b_1$ to the beginning of the result. This algorithm has the nice property that if $a$ and $b$ are sorted, then $\mathrm{merge}(a,b)$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $a=[3,1]$ and $b=[2,4]$, then $\mathrm{merge}(a,b)=[2,3,1,4]$. A permutation 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). There is a permutation $p$ of length $2n$. Determine if there exist two arrays $a$ and $b$, each of length $n$ and with no elements in common, so that $p=\mathrm{merge}(a,b)$. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $2t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 2000$). The second line of each test case contains $2n$ integers $p_1,\ldots,p_{2n}$ ($1\le p_i\le 2n$). It is guaranteed that $p$ is a permutation. It is guaranteed that the sum of $n$ across all test cases does not exceed $2000$. -----Output----- For each test case, output "YES" if there exist arrays $a$, $b$, each of length $n$ and with no common elements, so that $p=\mathrm{merge}(a,b)$. Otherwise, output "NO". -----Example----- Input 6 2 2 3 1 4 2 3 1 2 4 4 3 2 6 1 5 7 8 4 3 1 2 3 4 5 6 4 6 1 3 7 4 5 8 2 6 4 3 2 5 1 11 9 12 8 6 10 7 Output YES NO YES YES NO NO -----Note----- In the first test case, $[2,3,1,4]=\mathrm{merge}([3,1],[2,4])$. In the second test case, we can show that $[3,1,2,4]$ is not the merge of two arrays of length $2$. In the third test case, $[3,2,6,1,5,7,8,4]=\mathrm{merge}([3,2,8,4],[6,1,5,7])$. In the fourth test case, $[1,2,3,4,5,6]=\mathrm{merge}([1,3,6],[2,4,5])$, for example. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): n = int(input()) l = [int(x) for x in input().split()] cur = l[0] cll = 1 blocks = [] for x in l[1:]: if x > cur: blocks.append(cll) cur = x cll = 1 else: cll += 1 blocks.append(cll) poss = [[False]*(n+1) for _ in range(len(blocks) + 1)] poss[0][0] = True for i, b in enumerate(blocks): for j in range(n+1): poss[i+1][j] = poss[i][j] if b <= j: poss[i+1][j] |= poss[i][j-b] # print() # print(blocks) # for r in poss: # print(r) print("YES" if poss[len(blocks)][n] else "NO") ```
{ "language": "python", "test_cases": [ { "input": "6\n2\n2 3 1 4\n2\n3 1 2 4\n4\n3 2 6 1 5 7 8 4\n3\n1 2 3 4 5 6\n4\n6 1 3 7 4 5 8 2\n6\n4 3 2 5 1 11 9 12 8 6 10 7\n", "output": "YES\nNO\nYES\nYES\nNO\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1381/B" }
vfc_6906
apps
verifiable_code
2341
Solve the following coding problem using the programming language python: You and your $n - 1$ friends have found an array of integers $a_1, a_2, \dots, a_n$. You have decided to share it in the following way: All $n$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process. You are standing in the $m$-th position in the line. Before the process starts, you may choose up to $k$ different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded. Suppose that you're doing your choices optimally. What is the greatest integer $x$ such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to $x$? Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available. -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains three space-separated integers $n$, $m$ and $k$ ($1 \le m \le n \le 3500$, $0 \le k \le n - 1$)  — the number of elements in the array, your position in line and the number of people whose choices you can fix. The second line of each test case contains $n$ positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$)  — elements of the array. It is guaranteed that the sum of $n$ over all test cases does not exceed $3500$. -----Output----- For each test case, print the largest integer $x$ such that you can guarantee to obtain at least $x$. -----Example----- Input 4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 Output 8 4 1 1 -----Note----- In the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element ($5$) because he or she was forced by you to take the last element. After this turn the remaining array will be $[2, 9, 2, 3, 8]$; the second person will take the first element ($2$) because he or she was forced by you to take the first element. After this turn the remaining array will be $[9, 2, 3, 8]$; if the third person will choose to take the first element ($9$), at your turn the remaining array will be $[2, 3, 8]$ and you will take $8$ (the last element); if the third person will choose to take the last element ($8$), at your turn the remaining array will be $[9, 2, 3]$ and you will take $9$ (the first element). Thus, this strategy guarantees to end up with at least $8$. We can prove that there is no strategy that guarantees to end up with at least $9$. Hence, the answer is $8$. In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with $4$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import sys readline = sys.stdin.readline class Segtree: def __init__(self, A, intv, initialize = True, segf = max): self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv self.segf = segf if initialize: self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N) for i in range(self.N0-1, 0, -1): self.data[i] = self.segf(self.data[2*i], self.data[2*i+1]) else: self.data = [intv]*(2*self.N0) def update(self, k, x): k += self.N0 self.data[k] = x while k > 0 : k = k >> 1 self.data[k] = self.segf(self.data[2*k], self.data[2*k+1]) def query(self, l, r): L, R = l+self.N0, r+self.N0 s = self.intv while L < R: if R & 1: R -= 1 s = self.segf(s, self.data[R]) if L & 1: s = self.segf(s, self.data[L]) L += 1 L >>= 1 R >>= 1 return s def binsearch(self, l, r, check, reverse = False): L, R = l+self.N0, r+self.N0 SL, SR = [], [] while L < R: if R & 1: R -= 1 SR.append(R) if L & 1: SL.append(L) L += 1 L >>= 1 R >>= 1 if reverse: for idx in (SR + SL[::-1]): if check(self.data[idx]): break else: return -1 while idx < self.N0: if check(self.data[2*idx+1]): idx = 2*idx + 1 else: idx = 2*idx return idx - self.N0 else: for idx in (SL + SR[::-1]): if check(self.data[idx]): break else: return -1 while idx < self.N0: if check(self.data[2*idx]): idx = 2*idx else: idx = 2*idx + 1 return idx - self.N0 Tc = int(readline()) Ans = [None]*Tc for qu in range(Tc): N, M, K = list(map(int, readline().split())) A = list(map(int, readline().split())) Ai = A[::-1] table = [None]*M for i in range(M): j = (M-1)-i table[i] = max(A[i], Ai[j]) inf = 10**9+7 T = Segtree(table, inf, initialize = True, segf = min) ans = min(table) K = min(K, M-1) R = M-1-K for ki in range(K+1): ans = max(ans, T.query(ki, ki+R+1)) Ans[qu] = ans print('\n'.join(map(str, Ans))) ```
{ "language": "python", "test_cases": [ { "input": "4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\n", "output": "8\n4\n1\n1\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1290/A" }
vfc_6910
apps
verifiable_code
2342
Solve the following coding problem using the programming language python: You are given an array $a$ of $n$ positive integers. You can use the following operation as many times as you like: select any integer $1 \le k \le n$ and do one of two things: decrement by one $k$ of the first elements of the array. decrement by one $k$ of the last elements of the array. For example, if $n=5$ and $a=[3,2,2,1,4]$, then you can apply one of the following operations to it (not all possible options are listed below): decrement from the first two elements of the array. After this operation $a=[2, 1, 2, 1, 4]$; decrement from the last three elements of the array. After this operation $a=[3, 2, 1, 0, 3]$; decrement from the first five elements of the array. After this operation $a=[2, 1, 1, 0, 3]$; Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations. -----Input----- The first line contains one positive integer $t$ ($1 \le t \le 30000$) — the number of test cases. Then $t$ test cases follow. Each test case begins with a line containing one integer $n$ ($1 \le n \le 30000$) — the number of elements in the array. The second line of each test case contains $n$ integers $a_1 \ldots a_n$ ($1 \le a_i \le 10^6$). The sum of $n$ over all test cases does not exceed $30000$. -----Output----- For each test case, output on a separate line: YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations. NO, otherwise. The letters in the words YES and NO can be outputed in any case. -----Example----- Input 4 3 1 2 1 5 11 7 9 6 8 5 1 3 1 3 1 4 5 2 1 10 Output YES YES NO YES 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 for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) for i in range(n-1,0,-1): a[i] -= a[i-1] minus = 0 for i in range(1,n): if a[i]<0: minus -= a[i] if a[0] - minus >=0: print("YES") else: print("NO") ```
{ "language": "python", "test_cases": [ { "input": "4\n3\n1 2 1\n5\n11 7 9 6 8\n5\n1 3 1 3 1\n4\n5 2 1 10\n", "output": "YES\nYES\nNO\nYES\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1442/A" }
vfc_6914
apps
verifiable_code
2343
Solve the following coding problem using the programming language python: Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers $d, m$, find the number of arrays $a$, satisfying the following constraints: The length of $a$ is $n$, $n \ge 1$ $1 \le a_1 < a_2 < \dots < a_n \le d$ Define an array $b$ of length $n$ as follows: $b_1 = a_1$, $\forall i > 1, b_i = b_{i - 1} \oplus a_i$, where $\oplus$ is the bitwise exclusive-or (xor). After constructing an array $b$, the constraint $b_1 < b_2 < \dots < b_{n - 1} < b_n$ should hold. Since the number of possible arrays may be too large, you need to find the answer modulo $m$. -----Input----- The first line contains an integer $t$ ($1 \leq t \leq 100$) denoting the number of test cases in the input. Each of the next $t$ lines contains two integers $d, m$ ($1 \leq d, m \leq 10^9$). Note that $m$ is not necessary the prime! -----Output----- For each test case, print the number of arrays $a$, satisfying all given constrains, modulo $m$. -----Example----- Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python t = int(input()) for _ in range(t): d, m = list(map(int, input().split())) d += 1 out = 1 curr = 2 while curr < d: out *= (curr // 2) + 1 out %= m curr *= 2 out *= (d - curr // 2 + 1) print((out - 1) % m) ```
{ "language": "python", "test_cases": [ { "input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1\n", "output": "1\n3\n5\n11\n17\n23\n29\n59\n89\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1329/B" }
vfc_6918
apps
verifiable_code
2346
Solve the following coding problem using the programming language python: The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $i$ and $j$ ($1 \le i, j \le n$) such that $|i-j|=1$ and $a_i>0$ and apply $a_i = a_i - 1$, $a_j = a_j + 1$. She may also decide to not do anything on some days because she is lazy. Bessie wants to maximize the number of haybales in pile $1$ (i.e. to maximize $a_1$), and she only has $d$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $1$ if she acts optimally! -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$)  — the number of test cases. Next $2t$ lines contain a description of test cases  — two lines per test case. The first line of each test case contains integers $n$ and $d$ ($1 \le n,d \le 100$) — the number of haybale piles and the number of days, respectively. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 100$)  — the number of haybales in each pile. -----Output----- For each test case, output one integer: the maximum number of haybales that may be in pile $1$ after $d$ days if Bessie acts optimally. -----Example----- Input 3 4 5 1 0 3 2 2 2 100 1 1 8 0 Output 3 101 0 -----Note----- In the first test case of the sample, this is one possible way Bessie can end up with $3$ haybales in pile $1$: On day one, move a haybale from pile $3$ to pile $2$ On day two, move a haybale from pile $3$ to pile $2$ On day three, move a haybale from pile $2$ to pile $1$ On day four, move a haybale from pile $2$ to pile $1$ On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $2$ to pile $1$ on the second day. 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.stdin=open("data.txt") input=sys.stdin.readline mii=lambda:list(map(int,input().split())) for _ in range(int(input())): n,d=mii() a=list(mii()) ans=0 for i in range(n): while d>=i and a[i]: a[i]-=1 ans+=1 d-=i print(ans) ```
{ "language": "python", "test_cases": [ { "input": "3\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0\n", "output": "3\n101\n0\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1307/A" }
vfc_6930
apps
verifiable_code
2347
Solve the following coding problem using the programming language python: A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $k$-balanced if every substring of size $k$ of this bitstring has an equal amount of 0 and 1 characters ($\frac{k}{2}$ of each). You are given an integer $k$ and a string $s$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $k$-balanced bitstring by replacing every ? characters in $s$ with either 0 or 1. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). Description of the test cases follows. The first line of each test case contains two integers $n$ and $k$ ($2 \le k \le n \le 3 \cdot 10^5$, $k$ is even)  — the length of the string and the parameter for a balanced bitstring. The next line contains the string $s$ ($|s| = n$). It is given that $s$ consists of only 0, 1, and ?. It is guaranteed that the sum of $n$ over all test cases does not exceed $3 \cdot 10^5$. -----Output----- For each test case, print YES if we can replace every ? in $s$ with 0 or 1 such that the resulting bitstring is $k$-balanced, or NO if it is not possible. -----Example----- Input 9 6 4 100110 3 2 1?1 3 2 1?0 4 4 ???? 7 4 1?0??1? 10 10 11??11??11 4 2 1??1 4 4 ?0?0 6 2 ????00 Output YES YES NO YES YES NO NO YES NO -----Note----- For the first test case, the string is already a $4$-balanced bitstring. For the second test case, the string can be transformed into 101. For the fourth test case, the string can be transformed into 0110. For the fifth test case, the string can be transformed into 1100110. 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 _ in range(t): n, k = list(map(int, input().split())) s = input() l = ['']*k works = True for i in range(n): c = s[i] if c != '?': if l[i%k] == c or l[i%k] == '': l[i%k] = c else: works = False break if works: smol = 0 big = k for c in l: if c == '0': big -= 1 elif c == '1': smol += 1 goal = k//2 if smol <= goal <= big: print('YES') else: print('NO') else: print('NO') ```
{ "language": "python", "test_cases": [ { "input": "9\n6 4\n100110\n3 2\n1?1\n3 2\n1?0\n4 4\n????\n7 4\n1?0??1?\n10 10\n11??11??11\n4 2\n1??1\n4 4\n?0?0\n6 2\n????00\n", "output": "YES\nYES\nNO\nYES\nYES\nNO\nNO\nYES\nNO\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/1404/A" }
vfc_6934
apps
verifiable_code
2349
Solve the following coding problem using the programming language python: The Chef has one long loaf of bread of length 1. He wants to cut it into as many little loaves as he can. But he wants to adhere to the following rule: At any moment, the length of the longest loaf which he possesses may not be larger than the length of shortest one, times some constant factor. Every time, he is only allowed to cut exactly one loaf into two shorter ones. -----Input----- One floating-point number, 1 ≤ k ≤ 1.999, meaning the stated constant factor. The number will have at most 3 digits after the decimal point. -----Output----- First, you should output one number n, the maximal achievable number of loaves for the given value of the constant factor. Then, you should output any proof that this number of loaves is in fact achievable: n-1 descriptions of cutting, using the following notation. At each step, you print two numbers: first, the index of the loaf that you want to cut into two parts; second, the length of the newly created loaf (cut off from the original one). It is assumed that the starting loaf has index 0. Each newly created loaf will be given the lowest possible free integer index (so, at the ith step this will be i). Each time, the size of size of the original loaf will be decreased by the size of the newly created loaf. -----Example----- Input: 1.5 Output: 4 0 0.4 0 0.3 1 0.2 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 math import log k = float(sys.stdin.readline()) answer = int(log(2.0, 2.0/k)) print(2*answer) m = 2 ** (1.0/answer) # m = 2.0/k thesum = 0 for i in range(answer): thesum += m**i # print [m**i/thesum for i in xrange(answer)] loaves = [1] def maxIndex(list): max = -1 mi = -1 for i, x in enumerate(list): if x > max: max = x mi = i return mi desired = [m**i/thesum for i in range(answer)] desired.reverse() # print desired cuts = [] while len(desired) > 1: cuts.append(desired[-1]) lastsum = desired[-1] + desired[-2] del desired[-2:] desired[0:0] = [lastsum] # print cuts while cuts: length = cuts.pop() i = maxIndex(loaves) print(i, length) loaves[i] -= length loaves.append(length) # print loaves # print loaves for i in range(answer): i = maxIndex(loaves[:answer]) x = loaves[i]/2.0 print(i, x) loaves.append(x) loaves[i] -= x # print loaves ```
{ "language": "python", "test_cases": [ { "input": "1.5\n", "output": "4\n0 0.4\n0 0.3\n1 0.2\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://www.codechef.com/AUG09/problems/F6" }
vfc_6942
apps
verifiable_code
2350
Solve the following coding problem using the programming language python: A hypergraph is a generalization of a graph, where an edge can connect any number of vertices. A k-uniform hypergraph is a hypergraph such that all its hyperedges have size k. For more information, see Wikipedia. Let's call a particular hypergraph a hypertree if it is connected (that is, you can move from any vertex to any other vertex using only its hyperedges) and removing any of its hyperedges makes the hypergraph disconnected (note that this definition of hypertrees differs from the standard one). Given just one integer N, find the number of 3-uniform hypertrees on N vertices. Two 3-uniform hypertrees are considered different if a hyperedge (u, v, w) exists such that it is present in exactly one of these hypertrees (note that the order of vertices in the hyperedge doesn't matter, and neither does the order of hyperedges in the hypertree). -----Input----- The first line of the input contains an integer T -- the number of test cases (at most 15). Then T lines follow, each contains an integer N (3 ≤ N ≤ 17). Important! Please include all code used in solving this problem in your solution. -----Output----- For each test case output one line containing the requested number. It's guaranteed that this number won't exceed 263-1. -----Examples----- Input: 4 3 4 5 8 Output: 1 6 25 93268 Explanation: There is just one 3-uniform hypertree on 3 vertices: {(1,2,3)}. There are six of them on 4 vertices: {(1,2,3), (1,2,4)}, {(1,2,3), (1,3,4)}, {(1,2,3), (2,3,4)}, {(1,2,4), (1,3,4)}, {(1,2,4), (2,3,4)}, {(1,3,4), (2,3,4)}. Two of the 25 possible hypertrees on 5 vertices are {(1,2,3), (3,4,5)} and {(1,2,3), (1,2,4), (1,2,5)}. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python """ #this code is a precomputation part. #it takes about 2 hours. class Graph: def __init__(self,n): self.edge=[[0 for j in xrange(n)] for i in xrange(n)] self.n=n def addedge(self,i,j,m=1): assert i!=j and 0<=i<self.n and 0<=j<self.n self.edge[i][j]+=m self.edge[j][i]+=m def deledge(self,i,j,m=1): assert i!=j and 0<=i<self.n and 0<=j<self.n self.edge[i][j]-=m self.edge[j][i]-=m def strongconnect(self): ret = True n=self.n for i in xrange(n): for j in xrange(i+1,n): if self.edge[i][j]: self.deledge(i,j) ret=self.connect() self.addedge(i,j) if ret==False:return ret return True def connect(self): n=self.n edge=self.edge z=[0 for _ in xrange(n)] def f(i): assert 0<=i<n if z[i]==1:return z[i]=1 for j in xrange(n): if edge[i][j]:f(j) f(0) return sum(z)==n def Nconnect(self): n=self.n edge=self.edge z=[0 for _ in xrange(n)] def f(i): assert 0<=i<n if z[i]==1:return z[i]=1 for j in xrange(n): if edge[i][j]:f(j) ret=0 for ver in xrange(n): if z[ver]==0: ret+=1 f(ver) return ret def search(nv,ne): graph=Graph(nv) init=( graph, (0,0), ne) def f(state): ret=0 g,(i,j),e=state if e==0: if g.strongconnect(): return fact(ne) else:return 0 if e<g.Nconnect(): return 0 for i2 in xrange(nv): for j2 in xrange(i2+1,nv): if (i2,j2)>(i,j): for k in xrange(1,e+1): g.addedge(i2,j2,k) ret += f((g,(i2,j2),e-k)) / fact(k) g.deledge(i2,j2,k) return ret return f(init) def fact(n): assert n>=0 ret=1 for i in xrange(n):ret*=i+1 return ret def comb(a,b): return fact(a+b)/fact(a)/fact(b) pass nnn=17 sve=dict( ( (v,e),search(v,e) ) for v in xrange(nnn+1) for e in xrange(nnn+1) if e>=v and e+v<=nnn) sve[(1,0)]=1 print sve """ output=""" {(6, 9): 10559808000, (0, 7): 0, (1, 6): 0, (0, 10): 0, (3, 7): 2142, (2, 5): 1, (1, 11): 0, (5, 8): 48094200, (6, 7): 6350400, (5, 5): 1440, (6, 10): 247973140800, (0, 17): 0, (0, 4): 0, (1, 1): 0, (4, 10): 57808440, (2, 6): 1, (5, 11): 84587745000, (4, 5): 2160, (0, 1): 0, (3, 12): 531366, (1, 12): 0, (2, 11): 1, (7, 8): 482630400, (0, 14): 0, (3, 11): 177078, (1, 15): 0, (8, 9): 45113241600, (4, 12): 2148847272, (2, 12): 1, (1, 16): 0, (1, 5): 0, (0, 11): 0, (3, 6): 690, (2, 2): 1, (1, 10): 0, (6, 11): 4928158065600, (0, 5): 0, (1, 0): 1, (0, 8): 0, (4, 11): 354158640, (3, 5): 210, (2, 7): 1, (5, 10): 7639380000, (4, 6): 25560, (5, 7): 2835000, (0, 2): 0, (1, 3): 0, (4, 8): 1433544, (2, 8): 1, (0, 15): 0, (3, 10): 58986, (1, 14): 0, (4, 13): 12970756656, (2, 13): 1, (1, 4): 0, (0, 12): 0, (3, 9): 19626, (2, 3): 1, (1, 9): 0, (2, 14): 1, (6, 8): 336268800, (0, 6): 0, (1, 7): 0, (0, 9): 0, (3, 4): 54, (2, 4): 1, (5, 9): 644550480, (4, 7): 206640, (6, 6): 43200, (5, 6): 104400, (7, 7): 1814400, (0, 16): 0, (0, 3): 0, (3, 14): 4782882, (1, 2): 0, (4, 9): 9265200, (3, 3): 6, (2, 9): 1, (5, 12): 900380296200, (4, 4): 72, (7, 10): 2379856852800, (0, 0): 1, (3, 13): 1594242, (1, 13): 0, (2, 10): 1, (7, 9): 44808422400, (0, 13): 0, (3, 8): 6510, (1, 8): 0, (8, 8): 101606400, (2, 15): 1} """ sve=eval( "".join( output.split("\n") ) ) def fact(n): assert n>=0 ret=1 for i in range(n):ret*=i+1 return ret def comb(a,b): return fact(a+b)/fact(a)/fact(b) pass "python 2.5 cannot use fractions." "I used fractions for local computation." #import fractions #fr=fractions.Fraction(1) memo_ff={} def powpoly(x,t): ret=[1]+[0]*( len(x)-1 ) n=len(x) for _ in range(t): ret2=[0 for _ in range(n)] for i in range(n): for j in range(n): if i+j<n: ret2[i+j]+=ret[i]*x[j] ret=ret2 return ret def ing(x): n=len(x) assert x[0]==0 ret=[0 for _ in range(n)] for t in range(0,n): ret2=powpoly(x,t) for i in range(n): ret[i]+=fr*ret2[i]/fact(t) return ret def ff(Y): if Y in memo_ff: return memo_ff[Y] t=Y[0] if t==0: n=Y[1] ret=0 for (v,e) in sve: if v+e>n or v==0:continue val=sve[(v,e)] for l1 in range(n-v+1): l2=n-v-l1 p1=ff((2,l1,e)) p2=ff((3,l2,v)) a = fr * val * fact(n-1) / fact(v-1) / fact(l1) / fact(l2) * p1 * p2 / fact(e) ret += a elif t==1: n=Y[1] ret=0 for (v,e) in sve: val=sve[(v,e)] e-=1 if e==-1 or v+e>n or v==0:continue for l1 in range(n-v+1): l2=n-v-l1 p1=ff((2,l1,e)) p2=ff((3,l2,v)) ret += fr * val * fact(n) / fact(v) / fact(l1) / fact(l2) * p1 * p2 / fact(e) elif t==2: n=Y[1] e=Y[2] F=[ fr*i*ff((0,i))/fact(i) for i in range(n+1) ] Fa=powpoly(F,e) ret=Fa[n]*fact(n) elif t==3: n=Y[1] v=Y[2] G=[v*fr*ff((1,i))/fact(i) for i in range(n+1)] Ga=ing(G) ret = Ga[n]*fact(n) memo_ff[Y]=ret return ret memo={} def g(Y): if Y in memo: return memo[Y] k,c=Y if c==0: return ff((0,k)) if 2*c>=k:return 0 ret=0 for k1 in range(1,18): for k2 in range(1,18): k3=k-k1-k2 if k3<=0:break for c1 in range(18): if 2*c1>=k1:break for c2 in range(18): if 2*c2>=k2:break c3=c-1-c1-c2 if 2*c3>=k3:continue ret += g((k1,c1)) * g((k2,c2)) * g((k3,c3)) * fact(k1+k2+k3)/fact(k1)/fact(k2)/fact(k3)*k1*k2*k3 r=ret/(6*c) memo[Y]=r return r def ans(n): return sum(g((n,i)) for i in range(n)) def brute(n): m=[(i1,i2,i3) for i1 in range(n) for i2 in range(i1+1,n) for i3 in range(i2+1,n)] init=[] memob={} def f(vs): ret=0 if vs: g=Graph(n) for v in vs: i1,i2,i3=v g.addedge(i1,i2) g.addedge(i1,i3) a=g.Nconnect() for notv in vs: g=Graph(n) for v in vs: if v==notv:continue i1,i2,i3=v g.addedge(i1,i2) g.addedge(i1,i3) if g.Nconnect()==a: return 0 if a==1:return 1 ret = 0 for v in m: if len(vs)==0 or v>vs[-1]: ret += f(vs+[v]) return ret return f(init) def brute2(n): m=[(i1,i2,i3) for i1 in range(n) for i2 in range(i1+1,n) for i3 in range(i2+1,n)] init=[] def f(vs): ret=0 if vs: g=Graph(n) for v in vs: i1,i2,i3=v g.addedge(i1,i2) g.addedge(i1,i3) a=g.Nconnect() for notv in vs: g=Graph(n) for v in vs: if v==notv:continue i1,i2,i3=v g.addedge(i1,i2) g.addedge(i1,i3) if g.Nconnect()==a or ( a==1 and g.Nconnect()==3): return 0 if a==1: return 1 ret = 0 for v in m: if len(vs)==0 or v>vs[-1]: ret += f(vs+[v]) return ret return f(init) def main(): t=eval(input()) #z=[int(ans(i)) for i in xrange(18)] it takes about 10 seconds z=[0, 1, 0, 1, 6, 25, 495, 5586, 93268, 2052513, 43258365, 1167393700, 34010847486, 1078391538159, 38595111963499, 1476893151785520, 61479081902937000, 2761923686066698561] for _ in range(t): print(z[eval(input())]) #test() main() ```
{ "language": "python", "test_cases": [ { "input": "4\n3\n4\n5\n8\n\n\n", "output": "1\n6\n25\n93268\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://www.codechef.com/DEC11/problems/HYPER" }
vfc_6946
apps
verifiable_code
2351
Solve the following coding problem using the programming language python: The Chef has been kidnapped by aliens ( they want to utilize his excellent cooking skills :P ) and has been transported to the alien planet "ZX532". Interestingly, "ZX532" uses a different time scale which has Y AlienHours on the face of a clock (instead of the 12 hours that we have). They also have 'X*Y' AlienMinutes (instead of the 60 that we have). X is defined as the number of minute divisions between each hour (the earth clock has X=5). The Chef has been forced to cook a lot of dishes by the aliens. He is short of ingredients and hence needs to go out to the market to get them. However when he returns, he makes an interesting observation. The hands of AlienClock have exactly swapped position from the time he left (the big hand and the little hand have switched)! Given the times between which The Chef might have left and the times between which The Chef may have returned, you are supposed to find out the actual time when he left. If there is more than one possibility, print the one that maximizes the amount of time that The Chef is out.Details of the Clock The AlienClock is circular and has exactly 2 hands : the hour hand and the minute hand. The whole circumference of the AlienClock is divided into Y divisions , each of which is further divided into X subdivisions [ X and Y are both positive integers ]. The clock is not discrete but continuous (the hands move continuously instead of moving at certain intervals such as every second, etc.... ). -----Input----- First line of input contains t (1≤ t ≤ 100) - the number of test cases. Each test case contains 2 lines each. The first line contains 2 space separated integers , X and Y (same as those specified in the problem statement; X ≤ 109 and Y ≤ 109 ). The next line contains 8 space separated integers (a,b,c,d,e,f,g,h; 0 ≤ a ≤ c < Y; 0 ≤ e ≤ g < Y; a ≤ e; 0 ≤ b,d,f,h < X*Y ): specifying the times between which The Chef might have left (a:b => a hours and b minutes TO c:d => c hours and d minutes) and the times between which The Chef may have returned (The Chef returns sometime between e:f and g:h). The interval at which The Chef re-enters the kitchen will never start prior to the interval at which he first leaves the kitchen to purchase the ingredients. -----Output----- The output should contain one line for each test case specifying the time when The Chef left the kitchen. This should be in the form (h:m => h hours and m minutes). h will be an integer, and m should be rounded to 2 decimal places. In case, there is no solution possible, output -1 for that test case. -----Example----- Input: 3 5 12 1 0 2 0 4 0 5 0 5 12 3 30 4 0 5 0 6 0 5 12 3 0 4 0 5 0 6 0 Output: 1:20.56 -1 3:26.43 Note: Be careful with precision. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python import decimal; from decimal import *; def solve(a, b, min1, min2, min3, min4, x, y): if a > b: return []; solMin1 = (a/y+b)/(y-1/y); solMin2 = (b/y+a)/(y-1/y); solMin1 *= (x*y); solMin2 *= (x*y); if solMin1 >= min1 and solMin1 <= min2 and solMin2 >= min3 and solMin2 <= min4: # Solution found return [a, solMin1, b, solMin2]; return []; def integerPart(x): return Decimal(str(x).split(".")[0]); def fractionalPart(x): t = str(x).split("."); if len(t) > 0: return "." + t[1]; return 0; getcontext().prec = 30; for i in range(eval(input())): (x,y) = input().split(); (a,b,c,d,e,f,g,h) = input().split(); x=Decimal(x);y=Decimal(y);a=Decimal(a);b=Decimal(b);c=Decimal(c);d=Decimal(d);e=Decimal(e);f=Decimal(f);g=Decimal(g);h=Decimal(h); if a > g or (a == g and b > h): print("-1"); continue; solutionh = Decimal("-1"); solutionm = Decimal("-1"); diff = Decimal("-10000000000000000"); solution1 = [];solution2=[];solution3=[];solution4=[];solution5=[];solution6=[];solution7=[];solution8=[];solution9=[]; solution10 = [];solution11=[];solution12=[];solution13=[];solution14=[]; l1 = 0; if g == e: l1 = f; solution1 = solve(a+0,g+0,b,x*y,l1,h,x,y); if a < y - 1 and len(solution1) == 0: solution2 = solve(a+1,g+0,0,x*y,l1,h,x,y); if g >= 1 and len(solution1) == 0 and len(solution2) == 0: solution4 = solve(a+0,g-1,b,x*y,0,x*y,x,y); if g-e >= 2 and c-a>=2 : solution5 = solve(a+1,g-1,0,x*y,0,x*y,x,y); if len(solution1) == 0 and len(solution2) == 0 and len(solution4) == 0: solution10 = solve(a, e, 0, x*y, 0, x*y, x, y); solution11 = solve(c, e, 0, x*y, 0, x*y, x, y); solution12 = solve(c, g, 0, x*y, 0, x*y, x, y); if a < y - 1 and len(solution1) == 0 and len(solution2) == 0 and len(solution4) == 0 and c - a >= 2: solution13 = solve(a + 1, e, 0, x*y, 0, x*y, x, y); if g >= 1 and len(solution1) == 0 and len(solution2) == 0 and len(solution4) == 0 and g - e >= 2: solution14 = solve(c, g - 1, 0, x*y, 0, x*y, x, y); if len(solution1) > 0: if solution1[0] < c or (solution1[0] == c and solution1[1] <= d): if solution1[2] > e or (solution1[2] == e and solution1[3] >= f): t = (solution1[2]-solution1[0])*x*y + (solution1[3]-solution1[1]); if t > diff: diff = t; solutionh = solution1[0]; solutionm = solution1[1]; if len(solution2) > 0: if solution2[0] < c or (solution2[0] == c and solution2[1] <= d): if solution2[2] > e or (solution2[2] == e and solution2[3] >= f): t = (solution2[2]-solution2[0])*x*y + (solution2[3]-solution2[1]); if t > diff: diff = t; solutionh = solution2[0]; solutionm = solution2[1]; if len(solution4) > 0: if solution4[0] < c or (solution4[0] == c and solution4[1] <= d): if solution4[2] > e or (solution4[2] == e and solution4[3] >= f): t = (solution4[2]-solution4[0])*x*y + (solution4[3]-solution4[1]); if t > diff: diff = t; solutionh = solution4[0]; solutionm = solution4[1]; if len(solution5) > 0: if solution5[0] < c or (solution5[0] == c and solution5[1] <= d): if solution5[2] > e or (solution5[2] == e and solution5[3] >= f): t = (solution5[2]-solution5[0])*x*y + (solution5[3]-solution5[1]); if t > diff: diff = t; solutionh = solution5[0]; solutionm = solution5[1]; if len(solution10) > 0: if solution10[0] > a or (solution10[0] == a and solution10[1] >= b): if solution10[0] < c or (solution10[0] == c and solution10[1] <= d): if solution10[2] > e or (solution10[2] == e and solution10[3] >= f): if solution10[2] < g or (solution10[2] == g and solution10[3] <= h): t = (solution10[2]-solution10[0])*x*y + (solution10[3]-solution10[1]); if t > diff: diff = t; solutionh = solution10[0]; solutionm = solution10[1]; if len(solution11) > 0: if solution11[0] > a or (solution11[0] == a and solution11[1] >= b): if solution11[0] < c or (solution11[0] == c and solution11[1] <= d): if solution11[2] > e or (solution11[2] == e and solution11[3] >= f): if solution11[2] < g or (solution11[2] == g and solution11[3] <= h): t = (solution11[2]-solution11[0])*x*y + (solution11[3]-solution11[1]); if t > diff: diff = t; solutionh = solution11[0]; solutionm = solution11[1]; if len(solution12) > 0: if solution12[0] > a or (solution12[0] == a and solution12[1] >= b): if solution12[0] < c or (solution12[0] == c and solution12[1] <= d): if solution12[2] > e or (solution12[2] == e and solution12[3] >= f): if solution12[2] < g or (solution12[2] == g and solution12[3] <= h): t = (solution12[2]-solution12[0])*x*y + (solution12[3]-solution12[1]); if t > diff: diff = t; solutionh = solution12[0]; solutionm = solution12[1]; if len(solution13) > 0: if solution13[0] > a or (solution13[0] == a and solution13[1] >= b): if solution13[0] < c or (solution13[0] == c and solution13[1] <= d): if solution13[2] > e or (solution13[2] == e and solution13[3] >= f): if solution13[2] < g or (solution13[2] == g and solution13[3] <= h): t = (solution13[2]-solution13[0])*x*y + (solution13[3]-solution13[1]); if t > diff: diff = t; solutionh = solution13[0]; solutionm = solution13[1]; if len(solution14) > 0: if solution14[0] > a or (solution14[0] == a and solution14[1] >= b): if solution14[0] < c or (solution14[0] == c and solution14[1] <= d): if solution14[2] > e or (solution14[2] == e and solution14[3] >= f): if solution14[2] < g or (solution14[2] == g and solution14[3] <= h): t = (solution14[2]-solution14[0])*x*y + (solution14[3]-solution14[1]); if t > diff: diff = t; solutionh = solution14[0]; solutionm = solution14[1]; limit1 = (y-1/y)*(f/(x*y))-e/y; if limit1 <= a + 1: limit1 = a + 1; limit1 = Decimal(str(int(limit1))); limit2 = (y-1/y)*(d/(x*y))-c/y; if limit2 >= g-1: limit2=g-1; limit2 = Decimal(str(int(limit2))); if limit1 >= a + 1 and limit1 <= c-1: solutionNew = solve(limit1, e, 0, x*y, 0, x*y, x, y); if len(solutionNew) > 0: if solutionNew[0] > a or (solutionNew[0] == a and solutionNew[1] >= b): if solutionNew[0] < c or (solutionNew[0] == c and solutionNew[1] <= d): if solutionNew[2] > e or (solutionNew[2] == e and solutionNew[3] >= f): if solutionNew[2] < g or (solutionNew[2] == g and solutionNew[3] <= h): t = (solutionNew[2]-solutionNew[0])*x*y + (solutionNew[3]-solutionNew[1]); if t > diff: diff = t; solutionh = solutionNew[0]; solutionm = solutionNew[1]; if limit1 + 1 >= a + 1 and limit1 + 1 <= c-1: solutionNew = solve(limit1 + 1, e, 0, x*y, 0, x*y, x, y); if len(solutionNew) > 0: if solutionNew[0] > a or (solutionNew[0] == a and solutionNew[1] >= b): if solutionNew[0] < c or (solutionNew[0] == c and solutionNew[1] <= d): if solutionNew[2] > e or (solutionNew[2] == e and solutionNew[3] >= f): if solutionNew[2] < g or (solutionNew[2] == g and solutionNew[3] <= h): t = (solutionNew[2]-solutionNew[0])*x*y + (solutionNew[3]-solutionNew[1]); if t > diff: diff = t; solutionh = solutionNew[0]; solutionm = solutionNew[1]; if limit2 >= e + 1 and limit2 <= g-1: solutionNew = solve(c, limit2, 0, x*y, 0, x*y, x, y); if len(solutionNew) > 0: if solutionNew[0] > a or (solutionNew[0] == a and solutionNew[1] >= b): if solutionNew[0] < c or (solutionNew[0] == c and solutionNew[1] <= d): if solutionNew[2] > e or (solutionNew[2] == e and solutionNew[3] >= f): if solutionNew[2] < g or (solutionNew[2] == g and solutionNew[3] <= h): t = (solutionNew[2]-solutionNew[0])*x*y + (solutionNew[3]-solutionNew[1]); if t > diff: diff = t; solutionh = solutionNew[0]; solutionm = solutionNew[1]; if limit1 - 1 >= e + 1 and limit2 - 1 <= g-1: solutionNew = solve(c, limit2 - 1, 0, x*y, 0, x*y, x, y); if len(solutionNew) > 0: if solutionNew[0] > a or (solutionNew[0] == a and solutionNew[1] >= b): if solutionNew[0] < c or (solutionNew[0] == c and solutionNew[1] <= d): if solutionNew[2] > e or (solutionNew[2] == e and solutionNew[3] >= f): if solutionNew[2] < g or (solutionNew[2] == g and solutionNew[3] <= h): t = (solutionNew[2]-solutionNew[0])*x*y + (solutionNew[3]-solutionNew[1]); if t > diff: diff = t; solutionh = solutionNew[0]; solutionm = solutionNew[1]; if solutionh == -1 or diff < 0: print("-1"); else: tz = solutionm; solutionm *= 100; try: r1 = integerPart(solutionm); r1 = str(r1); r1 = Decimal(r1); r2 = solutionm - r1; if r2 >= Decimal(".5"): r1 += Decimal("1"); t1 = (r1 - r1%100)/100; t2 = r1%100; t1 = int(t1); if t2 == 0: t2 = "00"; elif t2 < 10: t2 = "0" + str(t2); else: t2 = str(t2); except: exit(0); #print str(solutionh)+":%.2f"%(solutionm); print(str(solutionh)+":%d.%s"%(t1, t2)); ```
{ "language": "python", "test_cases": [ { "input": "3\n5 12\n1 0 2 0 4 0 5 0\n5 12\n3 30 4 0 5 0 6 0\n5 12\n3 0 4 0 5 0 6 0\n\n\n", "output": "1:20.56\n-1\n3:26.43\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://www.codechef.com/JUNE09/problems/D7" }
vfc_6950
apps
verifiable_code
2352
Solve the following coding problem using the programming language python: Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), <domain> is a non-empty string, consisting of lowercase English letters, the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters. If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context). When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".". Help Vasya to restore the possible address of the recorded Internet resource. -----Input----- The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only. It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above. -----Output----- Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them. -----Examples----- Input httpsunrux Output http://sun.ru/x Input ftphttprururu Output ftp://http.ru/ruru -----Note----- In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru". The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s="" L=[] s=input() k=0 r=0 c=0 if s[0]=='h': L.append('http://') c=4 s=s[c:] elif s[0]=='f': L.append('ftp://') c=3 s=s[c:] r=s.find('ru',1) L.append(s[:r]) L.append('.ru') k=r+2 if k<len(s): L.append('/') L.append(s[k:]) print(''.join(L)) ```
{ "language": "python", "test_cases": [ { "input": "httpsunrux\n", "output": "http://sun.ru/x\n", "type": "stdin_stdout" }, { "input": "ftphttprururu\n", "output": "ftp://http.ru/ruru\n", "type": "stdin_stdout" }, { "input": "httpuururrururruruurururrrrrurrurrurruruuruuu\n", "output": "http://uu.ru/rrururruruurururrrrrurrurrurruruuruuu\n", "type": "stdin_stdout" }, { "input": "httpabuaruauabbaruru\n", "output": "http://abua.ru/auabbaruru\n", "type": "stdin_stdout" }, { "input": "httpuurrruurruuruuruuurrrurururuurruuuuuuruurr\n", "output": "http://uurr.ru/urruuruuruuurrrurururuurruuuuuuruurr\n", "type": "stdin_stdout" }, { "input": "httpruhhphhhpuhruruhhpruhhphruhhru\n", "output": "http://ruhhphhhpuh.ru/ruhhpruhhphruhhru\n", "type": "stdin_stdout" }, { "input": "httpftprftprutprururftruruftptp\n", "output": "http://ftprftp.ru/tprururftruruftptp\n", "type": "stdin_stdout" }, { "input": "httpfttpftpfttftpftpftppfrurururu\n", "output": "http://fttpftpfttftpftpftppf.ru/rururu\n", "type": "stdin_stdout" }, { "input": "httpruhttttpruhttprupruhttpruhtturuhttphtruuru\n", "output": "http://ruhttttp.ru/httprupruhttpruhtturuhttphtruuru\n", "type": "stdin_stdout" }, { "input": "httpsjkazaaghasjkasjkabruru\n", "output": "http://sjkazaaghasjkasjkab.ru/ru\n", "type": "stdin_stdout" }, { "input": "httpftphttptphttphrururuhpftphtpftphtpftphtptpft\n", "output": "http://ftphttptphttph.ru/ruruhpftphtpftphtpftphtptpft\n", "type": "stdin_stdout" }, { "input": "httpppppru\n", "output": "http://pppp.ru\n", "type": "stdin_stdout" }, { "input": "ftprrurururrurururuurrururruuru\n", "output": "ftp://r.ru/rururrurururuurrururruuru\n", "type": "stdin_stdout" }, { "input": "ftpabaruru\n", "output": "ftp://aba.ru/ru\n", "type": "stdin_stdout" }, { "input": "ftpruurruurururururuuruuur\n", "output": "ftp://ruur.ru/urururururuuruuur\n", "type": "stdin_stdout" }, { "input": "ftphhphruhhpruhhpuhhpuruhhphruhhruhhpuhhru\n", "output": "ftp://hhph.ru/hhpruhhpuhhpuruhhphruhhruhhpuhhru\n", "type": "stdin_stdout" }, { "input": "ftparua\n", "output": "ftp://a.ru/a\n", "type": "stdin_stdout" }, { "input": "httpzru\n", "output": "http://z.ru\n", "type": "stdin_stdout" }, { "input": "httprrur\n", "output": "http://r.ru/r\n", "type": "stdin_stdout" }, { "input": "ftprru\n", "output": "ftp://r.ru\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/245/B" }
vfc_6954
apps
verifiable_code
2353
Solve the following coding problem using the programming language python: You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x_1, x_2, ..., x_{k}} (1 ≤ x_{i} ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. $\sum_{i = 1}^{k} a_{x_{i}} \neq \sum_{i = 1}^{k} b_{x_{i}}$ -----Input----- The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array. The second line contains n space-separated distinct integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the elements of the array. -----Output----- If there is no such array b, print -1. Otherwise in the only line print n space-separated integers b_1, b_2, ..., b_{n}. Note that b must be a permutation of a. If there are multiple answers, print any of them. -----Examples----- Input 2 1 2 Output 2 1 Input 4 1000 100 10 1 Output 100 1 1000 10 -----Note----- An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x. Note that the empty subset and the subset containing all indices are not counted. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python n, a = int(input()), [int(i) for i in input().split()] b, m = a[:], dict() b.sort() for i in range(len(b) - 1): m[b[i]] = b[i + 1] m[b[-1]] = b[0] for i in range(len(a)): a[i] = m[a[i]] if len(set(b)) == n: print(*a) else: print(-1) ```
{ "language": "python", "test_cases": [ { "input": "2\n1 2\n", "output": "2 1 \n", "type": "stdin_stdout" }, { "input": "4\n1000 100 10 1\n", "output": "100 1 1000 10\n", "type": "stdin_stdout" }, { "input": "5\n1 3 4 5 2\n", "output": "5 2 3 4 1 \n", "type": "stdin_stdout" }, { "input": "1\n10000000\n", "output": "10000000 \n", "type": "stdin_stdout" }, { "input": "4\n1 5 8 4\n", "output": "8 4 5 1 \n", "type": "stdin_stdout" }, { "input": "3\n1 3 2\n", "output": "3 2 1 \n", "type": "stdin_stdout" }, { "input": "4\n3 1 2 4\n", "output": "2 4 1 3 \n", "type": "stdin_stdout" }, { "input": "12\n7 1 62 12 3 5 8 9 10 22 23 0\n", "output": "5 0 23 10 1 3 7 8 9 12 22 62 \n", "type": "stdin_stdout" }, { "input": "17\n1 3 2 5 4 6 7 8 10 9 13 11 12 14 15 16 18\n", "output": "18 2 1 4 3 5 6 7 9 8 12 10 11 13 14 15 16 \n", "type": "stdin_stdout" }, { "input": "22\n1 3 5 7 22 2 4 6 8 9 10 11 12 13 15 14 17 18 16 20 19 23\n", "output": "23 2 4 6 20 1 3 5 7 8 9 10 11 12 14 13 16 17 15 19 18 22 \n", "type": "stdin_stdout" }, { "input": "22\n17 6 1 22 9 23 38 40 10 20 29 11 12 39 3 32 26 4 13 36 14 35\n", "output": "14 4 40 20 6 22 36 39 9 17 26 10 11 38 1 29 23 3 12 35 13 32 \n", "type": "stdin_stdout" }, { "input": "22\n27 21 12 14 8 40 47 45 24 49 36 37 17 32 42 13 35 10 18 2 5 30\n", "output": "24 18 10 13 5 37 45 42 21 47 35 36 14 30 40 12 32 8 17 49 2 27 \n", "type": "stdin_stdout" }, { "input": "22\n33 2 19 26 18 13 27 9 25 35 6 24 20 22 11 5 1 30 17 15 7 29\n", "output": "30 1 18 25 17 11 26 7 24 33 5 22 19 20 9 2 35 29 15 13 6 27 \n", "type": "stdin_stdout" }, { "input": "22\n18 37 15 33 35 5 14 1 0 27 22 11 40 20 13 2 30 21 8 25 32 16\n", "output": "16 35 14 32 33 2 13 0 40 25 21 8 37 18 11 1 27 20 5 22 30 15 \n", "type": "stdin_stdout" }, { "input": "22\n4 24 22 18 28 3 17 8 29 20 11 15 13 2 19 26 5 36 33 14 30 25\n", "output": "3 22 20 17 26 2 15 5 28 19 8 14 11 36 18 25 4 33 30 13 29 24 \n", "type": "stdin_stdout" }, { "input": "22\n28 40 5 38 29 12 21 24 2 33 35 17 30 11 16 0 8 27 34 14 19 36\n", "output": "27 38 2 36 28 11 19 21 0 30 34 16 29 8 14 40 5 24 33 12 17 35 \n", "type": "stdin_stdout" }, { "input": "22\n25 12 38 5 6 20 30 27 4 19 8 18 10 17 26 32 43 14 40 35 1 22\n", "output": "22 10 35 4 5 19 27 26 1 18 6 17 8 14 25 30 40 12 38 32 43 20 \n", "type": "stdin_stdout" }, { "input": "22\n2 22 21 19 3 25 28 11 10 9 14 37 18 38 15 23 20 34 7 30 31 4\n", "output": "38 21 20 18 2 23 25 10 9 7 11 34 15 37 14 22 19 31 4 28 30 3 \n", "type": "stdin_stdout" }, { "input": "22\n7 0 23 37 20 18 46 26 2 24 44 13 47 15 32 5 35 30 39 41 27 10\n", "output": "5 47 20 35 18 15 44 24 0 23 41 10 46 13 30 2 32 27 37 39 26 7 \n", "type": "stdin_stdout" }, { "input": "22\n36 5 7 22 33 30 14 8 25 24 28 12 19 29 37 2 20 15 10 17 13 21\n", "output": "33 2 5 21 30 29 13 7 24 22 25 10 17 28 36 37 19 14 8 15 12 20 \n", "type": "stdin_stdout" }, { "input": "22\n23 32 13 39 29 41 40 6 21 10 38 42 4 8 20 35 31 26 15 2 17 5\n", "output": "21 31 10 38 26 40 39 5 20 8 35 41 2 6 17 32 29 23 13 42 15 4 \n", "type": "stdin_stdout" }, { "input": "22\n41 12 14 36 16 21 0 2 18 22 39 29 40 31 37 25 28 9 4 34 6 43\n", "output": "40 9 12 34 14 18 43 0 16 21 37 28 39 29 36 22 25 6 2 31 4 41 \n", "type": "stdin_stdout" }, { "input": "22\n32 43 3 37 29 42 40 12 28 1 14 25 34 46 8 35 5 17 2 23 20 9\n", "output": "29 42 2 35 28 40 37 9 25 46 12 23 32 43 5 34 3 14 1 20 17 8 \n", "type": "stdin_stdout" }, { "input": "22\n17 10 24 44 41 33 48 6 30 27 38 19 16 46 22 8 35 13 5 9 4 1\n", "output": "16 9 22 41 38 30 46 5 27 24 35 17 13 44 19 6 33 10 4 8 1 48 \n", "type": "stdin_stdout" }, { "input": "22\n16 11 29 30 12 5 3 2 13 6 17 15 9 24 25 35 1 27 0 23 20 33\n", "output": "15 9 27 29 11 3 2 1 12 5 16 13 6 23 24 33 0 25 35 20 17 30 \n", "type": "stdin_stdout" }, { "input": "22\n12 38 6 37 14 26 2 0 9 17 28 33 3 11 15 8 31 21 29 34 18 24\n", "output": "11 37 3 34 12 24 0 38 8 15 26 31 2 9 14 6 29 18 28 33 17 21 \n", "type": "stdin_stdout" }, { "input": "22\n20 38 26 32 36 8 44 0 40 41 35 21 11 17 29 33 1 42 24 14 5 3\n", "output": "17 36 24 29 35 5 42 44 38 40 33 20 8 14 26 32 0 41 21 11 3 1 \n", "type": "stdin_stdout" }, { "input": "22\n7 10 1 25 42 8 39 35 6 19 31 24 16 0 21 32 11 28 13 4 37 22\n", "output": "6 8 0 24 39 7 37 32 4 16 28 22 13 42 19 31 10 25 11 1 35 21 \n", "type": "stdin_stdout" }, { "input": "22\n9 13 7 20 38 40 27 12 31 25 1 23 46 35 45 29 19 16 33 4 42 39\n", "output": "7 12 4 19 35 39 25 9 29 23 46 20 45 33 42 27 16 13 31 1 40 38 \n", "type": "stdin_stdout" }, { "input": "22\n13 2 10 25 5 34 19 18 16 9 7 22 28 20 31 38 36 35 1 26 6 23\n", "output": "10 1 9 23 2 31 18 16 13 7 6 20 26 19 28 36 35 34 38 25 5 22 \n", "type": "stdin_stdout" }, { "input": "22\n106855341 41953605 16663229 140358177 145011760 49391214 42672526 1000000000 173686818 18529133 155326121 177597841 65855243 125680752 111261017 47020618 35558283 100881772 149421816 84207033 181739589 185082482\n", "output": "100881772 35558283 1000000000 125680752 140358177 47020618 41953605 185082482 155326121 16663229 149421816 173686818 49391214 111261017 106855341 42672526 18529133 84207033 145011760 65855243 177597841 181739589 \n", "type": "stdin_stdout" }, { "input": "22\n177663922 168256855 139197944 78700101 93490895 127229611 46317725 84284513 48674853 66142856 29224095 1000000000 138390832 117500569 98525700 100418194 44827621 151960474 43225995 16918107 53307514 48861499\n", "output": "168256855 151960474 138390832 66142856 84284513 117500569 44827621 78700101 46317725 53307514 16918107 177663922 127229611 100418194 93490895 98525700 43225995 139197944 29224095 1000000000 48861499 48674853 \n", "type": "stdin_stdout" }, { "input": "22\n83255567 39959119 124812899 157774437 12694468 89732189 102545715 67019496 110206980 98186415 63181429 141617294 177406424 195504716 158928060 64956133 67949891 31436243 155002729 1000000000 128745406 52504492\n", "output": "67949891 31436243 110206980 155002729 1000000000 83255567 98186415 64956133 102545715 89732189 52504492 128745406 158928060 177406424 157774437 63181429 67019496 12694468 141617294 195504716 124812899 39959119 \n", "type": "stdin_stdout" }, { "input": "22\n138499935 195582510 159774498 12295611 37071371 91641202 167958938 119995178 19438466 182405139 207729895 56797798 79876605 152841775 1000000000 149079380 158867321 154637978 72179187 75460169 145092927 103227705\n", "output": "119995178 182405139 158867321 1000000000 19438466 79876605 159774498 103227705 12295611 167958938 195582510 37071371 75460169 149079380 207729895 145092927 154637978 152841775 56797798 72179187 138499935 91641202 \n", "type": "stdin_stdout" }, { "input": "22\n133295371 188010892 71730560 209842234 193069109 184556873 87395258 234247052 230809052 211444018 148989732 17810977 158722706 11753932 100093528 1000000000 43672080 61357581 171830832 13873487 34865589 114340079\n", "output": "114340079 184556873 61357581 193069109 188010892 171830832 71730560 230809052 211444018 209842234 133295371 13873487 148989732 1000000000 87395258 234247052 34865589 43672080 158722706 11753932 17810977 100093528 \n", "type": "stdin_stdout" }, { "input": "22\n94506085 195061283 78884975 27418524 41348358 185397891 151515774 66605535 170723638 212843258 218566729 7450050 21809921 1000000000 146101141 132453297 228865386 240705035 57636433 114219677 158240908 228428432\n", "output": "78884975 185397891 66605535 21809921 27418524 170723638 146101141 57636433 158240908 195061283 212843258 1000000000 7450050 240705035 132453297 114219677 228428432 228865386 41348358 94506085 151515774 218566729 \n", "type": "stdin_stdout" }, { "input": "22\n116213533 171312666 76695399 60099180 30779320 43431323 146620629 15321904 71245898 94843310 56549974 104020167 84091716 134384095 24383373 83975332 1000000000 101710173 188076412 199811222 153566780 115893674\n", "output": "115893674 153566780 71245898 56549974 24383373 30779320 134384095 1000000000 60099180 84091716 43431323 101710173 83975332 116213533 15321904 76695399 199811222 94843310 171312666 188076412 146620629 104020167 \n", "type": "stdin_stdout" }, { "input": "22\n79749952 42551386 1000000000 60427603 50702468 16899307 85913428 116634789 151569595 100251788 152378664 96284924 60769416 136345503 59995727 88224321 29257228 64921932 77805288 126026727 103477637 115959196\n", "output": "77805288 29257228 152378664 59995727 42551386 1000000000 79749952 115959196 136345503 96284924 151569595 88224321 60427603 126026727 50702468 85913428 16899307 60769416 64921932 116634789 100251788 103477637 \n", "type": "stdin_stdout" }, { "input": "22\n32119698 129510003 107370317 182795872 160438101 17245069 117836566 141016185 196664039 215252245 170450315 18866624 68629021 47385728 77249092 89835593 132769095 95649030 48749357 126701972 40219294 1000000000\n", "output": "18866624 126701972 95649030 170450315 141016185 1000000000 107370317 132769095 182795872 196664039 160438101 17245069 48749357 40219294 68629021 77249092 129510003 89835593 47385728 117836566 32119698 215252245 \n", "type": "stdin_stdout" }, { "input": "22\n148671024 180468173 99388811 78666746 187172484 157360521 112604605 2988530 60271244 163263697 27469084 166381131 1000000000 125847469 137766458 198740424 88387613 15152912 200315776 149201551 45997250 36252057\n", "output": "137766458 166381131 88387613 60271244 180468173 149201551 99388811 1000000000 45997250 157360521 15152912 163263697 200315776 112604605 125847469 187172484 78666746 2988530 198740424 148671024 36252057 27469084 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/891/B" }
vfc_6958
apps
verifiable_code
2354
Solve the following coding problem using the programming language python: As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. -----Input----- The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. -----Output----- Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). -----Examples----- Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES -----Note----- In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python s = input() n = int(input()) a = [input() for i in range(n)] for i in range(n): for j in range(n): if a[i] == s or a[i][1] + a[j][0] == s: print("YES") return print("NO") ```
{ "language": "python", "test_cases": [ { "input": "ya\n4\nah\noy\nto\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "hp\n2\nht\ntp\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ah\n1\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "bb\n4\nba\nab\naa\nbb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "bc\n4\nca\nba\nbb\ncc\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ba\n4\ncd\nad\ncc\ncb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "pg\n4\nzl\nxs\ndi\nxn\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "bn\n100\ndf\nyb\nze\nml\nyr\nof\nnw\nfm\ndw\nlv\nzr\nhu\nzt\nlw\nld\nmo\nxz\ntp\nmr\nou\nme\npx\nvp\nes\nxi\nnr\nbx\nqc\ngm\njs\nkn\ntw\nrq\nkz\nuc\nvc\nqr\nab\nna\nro\nya\nqy\ngu\nvk\nqk\ngs\nyq\nop\nhw\nrj\neo\nlz\nbh\nkr\nkb\nma\nrd\nza\nuf\nhq\nmc\nmn\nti\nwn\nsh\nax\nsi\nnd\ntz\ndu\nfj\nkl\nws\now\nnf\nvr\nye\nzc\niw\nfv\nkv\noo\nsm\nbc\nrs\nau\nuz\nuv\ngh\nsu\njn\ndz\nrl\nwj\nbk\nzl\nas\nms\nit\nwu\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "bb\n1\naa\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "qm\n25\nqw\nwe\ner\nrt\nty\nyu\nui\nio\nop\npa\nas\nsd\ndf\nfg\ngh\nhj\njk\nkl\nlz\nzx\nxc\ncv\nvb\nbn\nnm\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "mq\n25\nqw\nwe\ner\nrt\nty\nyu\nui\nio\nop\npa\nas\nsd\ndf\nfg\ngh\nhj\njk\nkl\nlz\nzx\nxc\ncv\nvb\nbn\nnm\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "aa\n1\naa\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "bb\n1\nbb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ba\n1\ncc\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ha\n1\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "aa\n1\naa\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ez\n1\njl\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "aa\n2\nab\nba\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "aa\n2\nca\ncc\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "dd\n2\nac\ndc\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "qc\n2\nyc\nkr\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "aa\n3\nba\nbb\nab\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ca\n3\naa\nbb\nab\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ca\n3\nbc\nbd\nca\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "dd\n3\nmt\nrg\nxl\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "be\n20\nad\ncd\ncb\ndb\ndd\naa\nab\nca\nae\ned\ndc\nbb\nba\nda\nee\nea\ncc\nac\nec\neb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "fc\n20\nca\nbb\nce\nfd\nde\nfa\ncc\nec\nfb\nfc\nff\nbe\ncf\nba\ndb\ned\naf\nae\nda\nef\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ca\n20\ndc\naf\ndf\neg\naa\nbc\nea\nbd\nab\ndb\ngc\nfb\nba\nbe\nee\ngf\ncf\nag\nga\nca\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ke\n20\nzk\nra\nbq\nqz\nwt\nzg\nmz\nuk\nge\nuv\nud\nfd\neh\ndm\nsk\nki\nfv\ntp\nat\nfb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "hh\n50\nag\nhg\ndg\nfh\neg\ngh\ngd\nda\nbh\nab\nhf\ndc\nhb\nfe\nad\nec\nac\nfd\nca\naf\ncg\nhd\neb\nce\nhe\nha\ngb\nea\nae\nfb\nff\nbe\nch\nhh\nee\nde\nge\ngf\naa\ngg\neh\ned\nbf\nfc\nah\nga\nbd\ncb\nbg\nbc\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "id\n50\nhi\ndc\nfg\nee\ngi\nhc\nac\nih\ndg\nfc\nde\ned\nie\neb\nic\ncf\nib\nfa\ngc\nba\nbe\nga\nha\nhg\nia\ndf\nab\nei\neh\nad\nii\nci\ndh\nec\nif\ndi\nbg\nag\nhe\neg\nca\nae\ndb\naa\nid\nfh\nhh\ncc\nfb\ngb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "fe\n50\nje\nbi\nbg\ngc\nfb\nig\ndf\nji\ndg\nfe\nfc\ncf\ngf\nai\nhe\nac\nch\nja\ngh\njf\nge\ncb\nij\ngb\ncg\naf\neh\nee\nhd\njd\njb\nii\nca\nci\nga\nab\nhi\nag\nfj\nej\nfi\nie\ndj\nfg\nef\njc\njg\njh\nhf\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "rn\n50\nba\nec\nwg\nao\nlk\nmz\njj\ncf\nfa\njk\ndy\nsz\njs\nzr\nqv\ntx\nwv\nrd\nqw\nls\nrr\nvt\nrx\nkc\neh\nnj\niq\nyi\nkh\nue\nnv\nkz\nrn\nes\nua\nzf\nvu\nll\neg\nmj\ncz\nzj\nxz\net\neb\nci\nih\nig\nam\nvd\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ee\n100\nah\nfb\ncd\nbi\nii\nai\nid\nag\nie\nha\ndi\nec\nae\nce\njb\ndg\njg\ngd\ngf\nda\nih\nbd\nhj\ngg\nhb\ndf\ned\nfh\naf\nja\nci\nfc\nic\nji\nac\nhi\nfj\nch\nbc\njd\naa\nff\nad\ngj\nej\nde\nee\nhe\ncf\nga\nia\ncg\nbb\nhc\nbe\ngi\njf\nbg\naj\njj\nbh\nfe\ndj\nef\ngb\nge\ndb\nig\ncj\ndc\nij\njh\nei\ndd\nib\nhf\neg\nbf\nfg\nab\ngc\nfd\nhd\ngh\neh\njc\neb\nhh\nca\nje\nbj\nif\nea\nhg\nfa\ncc\nba\ndh\ncb\nfi\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "if\n100\njd\nbc\nje\nhi\nga\nde\nkb\nfc\ncd\ngd\naj\ncb\nei\nbf\ncf\ndk\ndb\ncg\nki\ngg\nkg\nfa\nkj\nii\njf\njg\ngb\nbh\nbg\neh\nhj\nhb\ndg\ndj\njc\njb\nce\ndi\nig\nci\ndf\nji\nhc\nfk\naf\nac\ngk\nhd\nae\nkd\nec\nkc\neb\nfh\nij\nie\nca\nhh\nkf\nha\ndd\nif\nef\nih\nhg\nej\nfe\njk\nea\nib\nck\nhf\nak\ngi\nch\ndc\nba\nke\nad\nka\neg\njh\nja\ngc\nfd\ncc\nab\ngj\nik\nfg\nbj\nhe\nfj\nge\ngh\nhk\nbk\ned\nid\nfi\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "kd\n100\nek\nea\nha\nkf\nkj\ngh\ndl\nfj\nal\nga\nlj\nik\ngd\nid\ncb\nfh\ndk\nif\nbh\nkb\nhc\nej\nhk\ngc\ngb\nef\nkk\nll\nlf\nkh\ncl\nlh\njj\nil\nhh\nci\ndb\ndf\ngk\njg\nch\nbd\ncg\nfg\nda\neb\nlg\ndg\nbk\nje\nbg\nbl\njl\ncj\nhb\nei\naa\ngl\nka\nfa\nfi\naf\nkc\nla\ngi\nij\nib\nle\ndi\nck\nag\nlc\nca\nge\nie\nlb\nke\nii\nae\nig\nic\nhe\ncf\nhd\nak\nfb\nhi\ngf\nad\nba\nhg\nbi\nkl\nac\ngg\ngj\nbe\nlk\nld\naj\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n1\nab\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ya\n1\nya\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ay\n1\nyb\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ax\n2\nii\nxa\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "hi\n1\nhi\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ag\n1\nag\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "th\n1\nth\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "sb\n1\nsb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "hp\n1\nhp\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ah\n1\nah\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ta\n1\nta\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "tb\n1\ntb\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n5\nca\nda\nea\nfa\nka\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ac\n1\nac\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ha\n2\nha\nzz\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ok\n1\nok\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "bc\n1\nbc\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "az\n1\nzz\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ab\n2\nba\ntt\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ah\n2\nap\nhp\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "sh\n1\nsh\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "az\n1\nby\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "as\n1\nas\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n2\nab\ncd\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n2\nxa\nza\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ab\n2\net\nab\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n1\naa\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ab\n2\nab\nde\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ah\n2\nba\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ha\n3\ndd\ncc\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "oo\n1\nox\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ab\n2\nax\nbx\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ww\n4\nuw\now\npo\nko\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ay\n1\nay\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "yo\n1\nyo\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ba\n1\nba\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "qw\n1\nqw\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "la\n1\nla\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n2\nbb\nbc\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "aa\n2\nab\nac\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ah\n2\nbb\nha\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ya\n42\nab\nac\nad\nae\naf\nag\nah\nai\nak\naj\nba\nbc\nbd\nbe\nbf\nbg\nbh\nbi\nbk\nbj\ncb\nca\ncd\nce\ncf\ncg\nch\nci\nck\ncj\ndb\ndc\nda\nde\ndf\ndg\ndh\ndi\ndk\ndj\nef\nek\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "ab\n3\nab\nxx\nyy\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n2\nab\ncc\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "sa\n2\nxx\nas\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ma\n1\nma\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ba\n1\nbb\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "bc\n1\nab\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "fa\n1\nfa\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ap\n1\nap\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n1\nbb\n", "output": "NO\n", "type": "stdin_stdout" }, { "input": "bk\n1\nbk\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "xy\n2\nxy\naa\n", "output": "YES\n", "type": "stdin_stdout" }, { "input": "ab\n2\nza\nbz\n", "output": "YES\n", "type": "stdin_stdout" } ] }
{ "difficulty": "competition", "problem_url": "https://codeforces.com/problemset/problem/868/A" }
vfc_6962
apps
verifiable_code
2361
Solve the following coding problem using the programming language python: You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $[l; r]$. If $r-l+1$ is odd (not divisible by $2$) then assign (set) $a[\frac{l+r}{2}] := i$ (where $i$ is the number of the current action), otherwise (if $r-l+1$ is even) assign (set) $a[\frac{l+r-1}{2}] := i$. Consider the array $a$ of length $5$ (initially $a=[0, 0, 0, 0, 0]$). Then it changes as follows: Firstly, we choose the segment $[1; 5]$ and assign $a[3] := 1$, so $a$ becomes $[0, 0, 1, 0, 0]$; then we choose the segment $[1; 2]$ and assign $a[1] := 2$, so $a$ becomes $[2, 0, 1, 0, 0]$; then we choose the segment $[4; 5]$ and assign $a[4] := 3$, so $a$ becomes $[2, 0, 1, 3, 0]$; then we choose the segment $[2; 2]$ and assign $a[2] := 4$, so $a$ becomes $[2, 4, 1, 3, 0]$; and at last we choose the segment $[5; 5]$ and assign $a[5] := 5$, so $a$ becomes $[2, 4, 1, 3, 5]$. Your task is to find the array $a$ of length $n$ after performing all $n$ actions. Note that the answer exists and unique. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The only line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $a$. It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer — the array $a$ of length $n$ after performing $n$ actions described in the problem statement. Note that the answer exists and unique. -----Example----- Input 6 1 2 3 4 5 6 Output 1 1 2 2 1 3 3 1 2 4 2 4 1 3 5 3 4 1 5 2 6 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 as dd from collections import deque import bisect import heapq def ri(): return int(input()) def rl(): return list(map(int, input().split())) def solve(): n = ri() output = [0] * (n) Q = [(-n, 0 ,n - 1)] for i in range(1, n + 1): prev = heapq.heappop(Q) lo, hi = prev[1], prev[2] mid = (lo + hi) // 2 output[mid] = i if mid > lo: heapq.heappush(Q, (-(mid - 1 - lo), lo, mid - 1)) if hi > mid: heapq.heappush(Q, (-(hi - 1 - mid), mid + 1, hi)) print(*output) mode = 'T' if mode == 'T': t = ri() for i in range(t): solve() else: solve() ```
{ "language": "python", "test_cases": [ { "input": "6\n1\n2\n3\n4\n5\n6\n", "output": "1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "introductory", "problem_url": "https://codeforces.com/problemset/problem/1353/D" }
vfc_6990
apps
verifiable_code
2362
Solve the following coding problem using the programming language python: $n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $i$-th robot is currently located at the point having coordinates ($x_i$, $y_i$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $X$ and $Y$, and when each robot receives this command, it starts moving towards the point having coordinates ($X$, $Y$). The robot stops its movement in two cases: either it reaches ($X$, $Y$); or it cannot get any closer to ($X$, $Y$). Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($x_c$, $y_c$). Then the movement system allows it to move to any of the four adjacent points: the first action allows it to move from ($x_c$, $y_c$) to ($x_c - 1$, $y_c$); the second action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c + 1$); the third action allows it to move from ($x_c$, $y_c$) to ($x_c + 1$, $y_c$); the fourth action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c - 1$). Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform. You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $X$ and $Y$ so that each robot can reach the point ($X$, $Y$). Is it possible to find such a point? -----Input----- The first line contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries. Then $q$ queries follow. Each query begins with one line containing one integer $n$ ($1 \le n \le 10^5$) — the number of robots in the query. Then $n$ lines follow, the $i$-th of these lines describes the $i$-th robot in the current query: it contains six integer numbers $x_i$, $y_i$, $f_{i, 1}$, $f_{i, 2}$, $f_{i, 3}$ and $f_{i, 4}$ ($-10^5 \le x_i, y_i \le 10^5$, $0 \le f_{i, j} \le 1$). The first two numbers describe the initial location of the $i$-th robot, and the following four numbers describe which actions the $i$-th robot can use to move ($f_{i, j} = 1$ if the $i$-th robot can use the $j$-th action, and $f_{i, j} = 0$ if it cannot use the $j$-th action). It is guaranteed that the total number of robots over all queries does not exceed $10^5$. -----Output----- You should answer each query independently, in the order these queries appear in the input. To answer a query, you should do one of the following: if it is impossible to find a point that is reachable by all $n$ robots, print one number $0$ on a separate line; if it is possible to find a point that is reachable by all $n$ robots, print three space-separated integers on the same line: $1$ $X$ $Y$, where $X$ and $Y$ are the coordinates of the point reachable by all $n$ robots. Both $X$ and $Y$ should not exceed $10^5$ by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding $10^5$ by absolute value. -----Example----- Input 4 2 -1 -2 0 0 0 0 -1 -2 0 0 0 0 3 1 5 1 1 1 1 2 5 0 1 0 1 3 5 1 0 0 0 2 1337 1337 0 1 1 1 1336 1337 1 1 0 1 1 3 5 1 1 1 1 Output 1 -1 -2 1 2 5 0 1 -100000 -100000 The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python def main(): import sys input = sys.stdin.readline def solve(): n = int(input()) maxx = 10**5 minx = -10**5 maxy = 10**5 miny = -10**5 for _ in range(n): x, y, f1, f2, f3, f4 = map(int, input().split()) if not f1: minx = max(minx, x) if not f2: maxy = min(maxy, y) if not f3: maxx = min(maxx, x) if not f4: miny = max(miny, y) if minx > maxx or miny > maxy: print(0) else: print(1, minx, miny) for _ in range(int(input())): solve() return 0 main() ```
{ "language": "python", "test_cases": [ { "input": "4\n2\n-1 -2 0 0 0 0\n-1 -2 0 0 0 0\n3\n1 5 1 1 1 1\n2 5 0 1 0 1\n3 5 1 0 0 0\n2\n1337 1337 0 1 1 1\n1336 1337 1 1 0 1\n1\n3 5 1 1 1 1\n", "output": "1 -1 -2\n1 2 5\n0\n1 -100000 -100000\n", "type": "stdin_stdout" } ] }
{ "difficulty": "introductory", "problem_url": "https://codeforces.com/problemset/problem/1196/C" }
vfc_6994
apps
verifiable_code
2363
Solve the following coding problem using the programming language python: There are $n$ athletes in front of you. Athletes are numbered from $1$ to $n$ from left to right. You know the strength of each athlete — the athlete number $i$ has the strength $s_i$. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $A$ and $B$ so that the value $|\max(A) - \min(B)|$ is as small as possible, where $\max(A)$ is the maximum strength of an athlete from team $A$, and $\min(B)$ is the minimum strength of an athlete from team $B$. For example, if $n=5$ and the strength of the athletes is $s=[3, 1, 2, 6, 4]$, then one of the possible split into teams is: first team: $A = [1, 2, 4]$, second team: $B = [3, 6]$. In this case, the value $|\max(A) - \min(B)|$ will be equal to $|4-3|=1$. This example illustrates one of the ways of optimal split into two teams. Print the minimum value $|\max(A) - \min(B)|$. -----Input----- The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases in the input. Then $t$ test cases follow. Each test case consists of two lines. The first line contains positive integer $n$ ($2 \le n \le 50$) — number of athletes. The second line contains $n$ positive integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 1000$), where $s_i$ — is the strength of the $i$-th athlete. Please note that $s$ values may not be distinct. -----Output----- For each test case print one integer — the minimum value of $|\max(A) - \min(B)|$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams. -----Example----- Input 5 5 3 1 2 6 4 6 2 1 3 2 4 3 4 7 9 3 1 2 1 1000 3 100 150 200 Output 1 0 2 999 50 -----Note----- The first test case was explained in the statement. In the second test case, one of the optimal splits is $A=[2, 1]$, $B=[3, 2, 4, 3]$, so the answer is $|2-2|=0$. The input will be stdin and you should print your solution to stdout Now solve the problem and return the code.
```python T = int(input()) for _ in range(T): a = int(input()) hh = sorted(map(int, input().split())) ans = 10**10 for h1, h2 in zip(hh[:-1], hh[1:]): ans = min(ans, h2 - h1) print(ans) ```
{ "language": "python", "test_cases": [ { "input": "5\n5\n3 1 2 6 4\n6\n2 1 3 2 4 3\n4\n7 9 3 1\n2\n1 1000\n3\n100 150 200\n", "output": "1\n0\n2\n999\n50\n", "type": "stdin_stdout" } ] }
{ "difficulty": "introductory", "problem_url": "https://codeforces.com/problemset/problem/1360/B" }
vfc_6998
apps
verifiable_code
2364
Solve the following coding problem using the programming language python: You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts). Mike has planned a trip from the vertex (district) $a$ to the vertex (district) $b$ and then from the vertex (district) $b$ to the vertex (district) $c$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $p$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road. You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains five integers $n, m, a, b$ and $c$ ($2 \le n \le 2 \cdot 10^5$, $n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$, $1 \le a, b, c \le n$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $m$ integers $p_1, p_2, \dots, p_m$ ($1 \le p_i \le 10^9$), where $p_i$ is the $i$-th price from the array. The following $m$ lines of the test case denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($v_i, u_i$) there are no other pairs ($v_i, u_i$) or ($u_i, v_i$) in the array of edges, and for each pair $(v_i, u_i)$ the condition $v_i \ne u_i$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $n$ (as well as the sum of $m$) does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$, $\sum m \le 2 \cdot 10^5$). -----Output----- For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally. -----Example----- Input 2 4 3 2 3 4 1 2 3 1 2 1 3 1 4 7 9 1 5 7 2 10 4 8 5 6 7 3 3 1 2 1 3 1 4 3 2 3 5 4 2 5 6 1 7 6 7 Output 7 12 -----Note----- One of the possible solution to the first test case of the example: [Image] One of the possible solution to the second test case of the example: [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 from collections import deque input = sys.stdin.readline t = int(input()) for _ in range(t): n, m, a, b, c = list(map(int,input().split())) p = list(map(int, input().split())) p.sort() pref = [0] curr = 0 for i in range(m): curr += p[i] pref.append(curr) adj = [[] for i in range(n)] for _ in range(m): u, v = list(map(int,input().split())) adj[u - 1].append(v - 1) adj[v - 1].append(u - 1) aD = [-1] * n bD = [-1] * n cD = [-1] * n for i in range(3): q = deque() q.append(([a,b,c][i]-1,0)) l = [aD,bD,cD][i] l[q[0][0]] = 0 while q: v, d = q.popleft() for nex in adj[v]: if l[nex] == -1: l[nex] = d + 1 q.append((nex,d+1)) poss = [] for i in range(n): if aD[i] + bD[i] + cD[i] <= m: poss.append(pref[aD[i] + bD[i] + cD[i]] + pref[bD[i]]) print(min(poss)) ```
{ "language": "python", "test_cases": [ { "input": "2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7\n", "output": "7\n12\n", "type": "stdin_stdout" } ] }
{ "difficulty": "introductory", "problem_url": "https://codeforces.com/problemset/problem/1343/E" }
vfc_7002
apps
verifiable_code
2365
Solve the following coding problem using the programming language python: We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you. For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \dots, p_r$ in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be: $[2, 5, 6]$ $[4, 6]$ $[1, 3, 4]$ $[1, 3]$ $[1, 2, 4, 6]$ Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow. The first line of the test case contains one integer $n$ ($2 \le n \le 200$) — the length of the permutation. The next $n-1$ lines describe given segments. The $i$-th line contains the description of the $i$-th segment. The line starts with the integer $k_i$ ($2 \le k_i \le n$) — the length of the $i$-th segment. Then $k_i$ integers follow. All integers in a line are distinct, sorted in ascending order, between $1$ and $n$, inclusive. It is guaranteed that the required $p$ exists for each test case. It is also guaranteed that the sum of $n$ over all test cases does not exceed $200$ ($\sum n \le 200$). -----Output----- For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). -----Example----- Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 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 input = sys.stdin.readline def dfs(x,S): #print(x,S) for i in range(len(S)): if x in S[i]: S[i].remove(x) #print(x,S) LEN1=0 for s in S: if len(s)==1: LEN1+=1 ne=list(s)[0] if LEN1==2: return [-1] if LEN1==1: return [ne]+dfs(ne,S) else: return [-1] import copy t=int(input()) for tests in range(t): n=int(input()) A=tuple(set(list(map(int,input().split()))[1:]) for i in range(n-1)) for i in range(1,n+1): ANS=[i]+dfs(i,copy.deepcopy(A)) #print(i,ANS) if -1 in ANS[:n]: continue else: #print(ANS[:n]) USE=[0]*(n-1) flag=1 for i in range(n-1,0,-1): SET=set() for j in range(i,-1,-1): SET.add(ANS[j]) if SET in A: break else: flag=0 break if flag: print(*ANS[:n]) break ```
{ "language": "python", "test_cases": [ { "input": "5\n6\n3 2 5 6\n2 4 6\n3 1 3 4\n2 1 3\n4 1 2 4 6\n5\n2 2 3\n2 1 2\n2 1 4\n2 4 5\n7\n3 1 2 6\n4 1 3 5 6\n2 1 2\n3 4 5 7\n6 1 2 3 4 5 6\n3 1 3 6\n2\n2 1 2\n5\n2 2 5\n3 2 3 5\n4 2 3 4 5\n5 1 2 3 4 5\n", "output": "3 1 4 6 2 5 \n3 2 1 4 5 \n2 1 6 3 5 4 7 \n1 2 \n2 5 3 4 1 \n", "type": "stdin_stdout" } ] }
{ "difficulty": "introductory", "problem_url": "https://codeforces.com/problemset/problem/1343/F" }
vfc_7006