source
stringclasses 4
values | task_type
stringclasses 1
value | in_source_id
stringlengths 0
138
| problem
stringlengths 219
13.2k
| gold_standard_solution
stringlengths 0
413k
| problem_id
stringlengths 5
10
| metadata
dict | verification_info
dict |
---|---|---|---|---|---|---|---|
apps | verifiable_code | 1391 | Solve the following coding problem using the programming language python:
A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.
The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs p_{j} rubles.
In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has b_{i} personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.
Each boy can rent at most one bike, one cannot give his bike to somebody else.
What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?
-----Input-----
The first line of the input contains three integers n, m and a (1 ≤ n, m ≤ 10^5; 0 ≤ a ≤ 10^9). The second line contains the sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^4), where b_{i} is the amount of the i-th boy's personal money. The third line contains the sequence of integers p_1, p_2, ..., p_{m} (1 ≤ p_{j} ≤ 10^9), where p_{j} is the price for renting the j-th bike.
-----Output-----
Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.
-----Examples-----
Input
2 2 10
5 5
7 6
Output
2 3
Input
4 5 2
8 1 1 2
6 3 7 5 2
Output
3 8
-----Note-----
In the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
3
def readln(): return tuple(map(int, input().split()))
n, m, a = readln()
b = list(sorted(readln()))
p = list(sorted(readln()))
l = ost = 0
r = min(m, n) + 1
while r - l > 1:
k = (r + l) // 2
s = d = 0
for x, y in zip(b[-k:], p[:k]):
if x < y:
d += y - x
s += y
if d <= a:
l = k
ost = max(0, s - a)
else:
r = k
print(l, ost)
``` | vfc_15318 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/363/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2 10\n5 5\n7 6\n",
"output": "2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5 2\n8 1 1 2\n6 3 7 5 2\n",
"output": "3 8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 2\n1\n2\n",
"output": "1 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1 1\n3 2 3 2\n3\n",
"output": "1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 4 1\n3\n2 4 5 5\n",
"output": "1 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1392 | Solve the following coding problem using the programming language python:
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).
-----Input-----
The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th of the following n lines contains integer a_{i} without leading zeroes (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print a single integer — the number of k-good numbers in a.
-----Examples-----
Input
10 6
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
1234560
Output
10
Input
2 1
1
10
Output
1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def check(s,k):
for i in range(k+1):
if chr(ord('0')+i) not in s:
return False
return True
n, k = map(int,input().split())
ans = 0
for i in range(n):
ss = input()
if check(ss,k):
ans +=1
print(ans)
``` | vfc_15322 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/365/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 6\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n1234560\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1\n10\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1394 | Solve the following coding problem using the programming language python:
Bob has a string $s$ consisting of lowercase English letters. He defines $s'$ to be the string after removing all "a" characters from $s$ (keeping all other characters in the same order). He then generates a new string $t$ by concatenating $s$ and $s'$. In other words, $t=s+s'$ (look at notes for an example).
You are given a string $t$. Your task is to find some $s$ that Bob could have used to generate $t$. It can be shown that if an answer exists, it will be unique.
-----Input-----
The first line of input contains a string $t$ ($1 \leq |t| \leq 10^5$) consisting of lowercase English letters.
-----Output-----
Print a string $s$ that could have generated $t$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).
-----Examples-----
Input
aaaaa
Output
aaaaa
Input
aacaababc
Output
:(
Input
ababacacbbcc
Output
ababacac
Input
baba
Output
:(
-----Note-----
In the first example, we have $s = $ "aaaaa", and $s' = $ "".
In the second example, no such $s$ can work that will generate the given $t$.
In the third example, we have $s = $ "ababacac", and $s' = $ "bbcc", and $t = s + s' = $ "ababacacbbcc".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t = input()
z = t.count('a')
q = (len(t) - z) // 2
s = t[:q + z]
ss = t[q + z:]
p = ''.join([i for i in s if i != 'a'])
if p == ss:
print(s)
else:
print(':(')
``` | vfc_15330 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1146/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "aaaaa\n",
"output": "aaaaa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aacaababc\n",
"output": ":(\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ababacacbbcc\n",
"output": "ababacac\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "baba\n",
"output": ":(\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "keke\n",
"output": "ke\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1395 | Solve the following coding problem using the programming language python:
Stepan has a very big positive integer.
Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.
Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m.
-----Input-----
The first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200 000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.
The second line contains the integer m (2 ≤ m ≤ 10^8) — the number by which Stepan divides good shifts of his integer.
-----Output-----
Print the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number m.
-----Examples-----
Input
521
3
Output
2
Input
1001
5
Output
0
Input
5678901234567890123456789
10000
Output
123
-----Note-----
In the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.
In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
m = int(input())
mn = m
ttt = 0
t = 0
ttt = 1
for i in range(1,len(s)):
ttt = (ttt * 10) % m
for i in range(0,len(s)):
t = (t * 10 + ord(s[i]) - ord('0')) % m
for i in range(0,len(s)):
if s[i] != '0':
mn = min(mn,t)
t = t - (((ord(s[i])- ord('0')) * ttt) % m)
if t < 0:
t = t + m
t = (t * 10 + (ord(s[i])- ord('0'))) % m
print(mn)
``` | vfc_15334 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/774/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "521\n3\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1001\n5\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5678901234567890123456789\n10000\n",
"output": "123\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "552352155\n13\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11533077525260\n193983\n",
"output": "22331\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\n19\n",
"output": "13\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1396 | Solve the following coding problem using the programming language python:
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?
There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.
For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.
Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.
-----Input-----
The first line of input contains three integers: n (1 ≤ n ≤ 100), k (1 ≤ k ≤ 100) and x (1 ≤ x ≤ k). The next line contains n space-separated integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ k). Number c_{i} means that the i-th ball in the row has color c_{i}.
It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color.
-----Output-----
Print a single integer — the maximum number of balls Iahub can destroy.
-----Examples-----
Input
6 2 2
1 1 2 2 1 1
Output
6
Input
1 1 1
1
Output
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import copy
n, k, x = map(int, input().split())
c = list(map(int, input().split()))
for i in range(n):
c[i] = (c[i],0)
ans = 0
for i in range(n + 1):
c2 = copy.deepcopy(c)
c2.insert(i, (x,1))
while True:
dq = False
for i in range(len(c2) - 2):
if c2[i][0] == c2[i + 1][0] == c2[i + 2][0]:
le = i
re = i
while re < len(c2) and c2[re][0] == c2[le][0]:
re += 1
c2 = c2[:le] + c2[re:]
dq = True
break
if not dq:
break
cntdel = 0
for a,b in c2:
if b==0:
cntdel+=1
ans = max(ans, n - cntdel)
print(ans)
``` | vfc_15338 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/430/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2 2\n1 1 2 2 1 1\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 2 1\n2 1 2 2 1 2 2 1 1 2\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50 2 1\n1 1 2 2 1 2 1 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2 2 1 2 1 2 1 2 2 1 1 2 2 1 1 2 2 1 2 1 1 2 1 1 2 2 1 1 2\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "75 5 5\n1 1 5 5 3 5 2 3 3 2 2 1 1 5 4 4 3 4 5 4 3 3 1 2 2 1 2 1 2 5 5 2 1 3 2 2 3 1 2 1 1 5 5 1 1 2 1 1 2 2 5 2 2 1 1 2 1 2 1 1 3 3 5 4 4 3 3 4 4 5 5 1 1 2 2\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1397 | Solve the following coding problem using the programming language python:
A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.
Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
-----Input-----
The first line consists of two integers n and m $(1 \leq n \leq 10^{3}, 0 \leq m < \frac{n}{2})$.
Then m lines follow, each consisting of two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), which means that it is not possible to construct a road connecting cities a_{i} and b_{i}. Consider the cities are numbered from 1 to n.
It is guaranteed that every pair of cities will appear at most once in the input.
-----Output-----
You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}), which means that a road should be constructed between cities a_{i} and b_{i}.
If there are several solutions, you may print any of them.
-----Examples-----
Input
4 1
1 3
Output
3
1 2
4 2
2 3
-----Note-----
This is one possible solution of the example: [Image]
These are examples of wrong solutions: [Image] The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. [Image] The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads. [Image] Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = list(map(int, input().split()))
table = [False] * (n + 1)
for _ in range(m):
a, b = list(map(int, input().split()))
table[a] = table[b] = True
print(n - 1)
for i in range(1, n + 1):
if not table[i]:
for j in range(1, n + 1):
if i != j:
print(i, j)
break
``` | vfc_15342 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/330/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 1\n1 3\n",
"output": "3\n1 2\n4 2\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "34 7\n10 28\n10 19\n10 13\n24 10\n10 29\n20 10\n10 26\n",
"output": "33\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 13\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n1 24\n1 25\n1 26\n1 27\n1 28\n1 29\n1 30\n1 31\n1 32\n1 33\n1 34\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "84 3\n39 19\n55 73\n42 43\n",
"output": "83\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 13\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n1 24\n1 25\n1 26\n1 27\n1 28\n1 29\n1 30\n1 31\n1 32\n1 33\n1 34\n1 35\n1 36\n1 37\n1 38\n1 39\n1 40\n1 41\n1 42\n1 43\n1 44\n1 45\n1 46\n1 47\n1 48\n1 49\n1 50\n1 51\n1 52\n1 53\n1 54\n1 55\n1 56\n1 57\n1 58\n1 59\n1 60\n1 61\n1 62\n1 63\n1 64\n1 65\n1 66\n1 67\n1 68\n1 69\n1 70\n1 71\n1 72\n1 73\n1 74\n1 75\n1 76\n1 77\n1 78\n1 79\n1 80\n1 81\n1 82\n1 83\n1 84\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "84 0\n",
"output": "83\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 13\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n1 24\n1 25\n1 26\n1 27\n1 28\n1 29\n1 30\n1 31\n1 32\n1 33\n1 34\n1 35\n1 36\n1 37\n1 38\n1 39\n1 40\n1 41\n1 42\n1 43\n1 44\n1 45\n1 46\n1 47\n1 48\n1 49\n1 50\n1 51\n1 52\n1 53\n1 54\n1 55\n1 56\n1 57\n1 58\n1 59\n1 60\n1 61\n1 62\n1 63\n1 64\n1 65\n1 66\n1 67\n1 68\n1 69\n1 70\n1 71\n1 72\n1 73\n1 74\n1 75\n1 76\n1 77\n1 78\n1 79\n1 80\n1 81\n1 82\n1 83\n1 84\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "34 7\n11 32\n33 29\n17 16\n15 5\n13 25\n8 19\n20 4\n",
"output": "33\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 13\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n1 24\n1 25\n1 26\n1 27\n1 28\n1 29\n1 30\n1 31\n1 32\n1 33\n1 34\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "43 21\n38 19\n43 8\n40 31\n3 14\n24 21\n12 17\n1 9\n5 27\n25 37\n11 6\n13 26\n16 22\n10 32\n36 7\n30 29\n42 35\n20 33\n4 23\n18 15\n41 34\n2 28\n",
"output": "42\n39 1\n39 2\n39 3\n39 4\n39 5\n39 6\n39 7\n39 8\n39 9\n39 10\n39 11\n39 12\n39 13\n39 14\n39 15\n39 16\n39 17\n39 18\n39 19\n39 20\n39 21\n39 22\n39 23\n39 24\n39 25\n39 26\n39 27\n39 28\n39 29\n39 30\n39 31\n39 32\n39 33\n39 34\n39 35\n39 36\n39 37\n39 38\n39 40\n39 41\n39 42\n39 43\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1398 | Solve the following coding problem using the programming language python:
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y ≤ 2·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.
Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.
-----Input-----
The first line contains integer n (2 ≤ n ≤ 10^5) — the number of measurements Vasya made. The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 5000) — the results of the measurements. The numbers on the second line are separated by single spaces.
-----Output-----
Print a single integer — the minimum number of results Vasya will have to remove.
-----Examples-----
Input
6
4 5 3 8 3 7
Output
2
Input
4
4 3 2 4
Output
0
-----Note-----
In the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will 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
from bisect import *
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
ans=n=int(input())
a=sorted(map(int,sys.stdin.readline().split()))
for i in range(n):ans=min(ans,n-bisect_right(a,a[i]*2)+i)
print(ans)
``` | vfc_15346 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/253/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n4 5 3 8 3 7\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 3 2 4\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n5 6 4 9 4 8\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1399 | Solve the following coding problem using the programming language python:
You are given $n$ segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.
Count the number of distinct points with integer coordinates, which are covered by at least one segment.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 1000$) — the number of segments.
Each of the next $n$ lines contains four integers $Ax_i, Ay_i, Bx_i, By_i$ ($-10^6 \le Ax_i, Ay_i, Bx_i, By_i \le 10^6$) — the coordinates of the endpoints $A$, $B$ ($A \ne B$) of the $i$-th segment.
It is guaranteed that no two segments lie on the same line.
-----Output-----
Print a single integer — the number of distinct points with integer coordinates, which are covered by at least one segment.
-----Examples-----
Input
9
0 0 4 4
-1 5 4 0
4 0 4 4
5 2 11 2
6 1 6 7
5 6 11 6
10 1 10 7
7 0 9 8
10 -1 11 -1
Output
42
Input
4
-1 2 1 2
-1 0 1 0
-1 0 0 3
0 3 1 0
Output
7
-----Note-----
The image for the first example: [Image]
Several key points are marked blue, the answer contains some non-marked points as well.
The image for the second 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
def getIntList():
return list(map(int, input().split()))
N, = getIntList()
zp = []
for i in range(N):
ax, ay, bx, by = getIntList()
if ax>bx:
ax,bx = bx,ax
ay,by = by, ay
zp.append( (ax,ay, bx,by))
res = 0
def gcd(a,b):
if b==0:return a
return gcd(b, a%b)
zgcd = []
for i in range(N):
ax, ay, bx, by = zp[i]
tx = abs(bx-ax)
ty = abs(by - ay)
g = gcd(tx, ty)
res += g+1
zgcd .append(g)
"""
ax + k1 dax = bx + k2 dbx
ay + k1 day = by + k2 dby
"""
for i in range(N):
ax = zp[i][0]
dax = (zp[i][2] - ax) // zgcd[i]
ay = zp[i][1]
day = (zp[i][3] - ay) // zgcd[i]
cross = []
for j in range(i+1, N):
#dprint('node',i,j)
bx = zp[j][0]
dbx = (zp[j][2] - bx) // zgcd[j]
by = zp[j][1]
dby = (zp[j][3] - by) // zgcd[j]
#dprint(ax,dax,ay,day)
#dprint(bx,dbx,by,dby)
t1 = ax * day - ay * dax - bx * day + by * dax
t2 = dbx *day - dby * dax
#dprint(t1,t2)
if t2==0:
continue
if t1%t2!=0:
continue
k2 = t1 // t2
if k2 <0 or k2 > zgcd[j]:
continue
if dax!=0:
t3 = k2*dbx + bx - ax
if t3%dax!=0:
continue
k1 = t3//dax
else:
t3 = k2* dby + by - ay
if t3%day !=0:
continue
k1 = t3//day
if k1<0 or k1 > zgcd[i]:
continue
#dprint(ax + k1 * dax, ay+k1 * day)
cross.append(k1)
if not cross: continue
cross.sort()
d = 1
for j in range(1, len(cross)):
if cross[j]!=cross[j-1]:
d+=1
res-=d
print(res)
``` | vfc_15350 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1036/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9\n0 0 4 4\n-1 5 4 0\n4 0 4 4\n5 2 11 2\n6 1 6 7\n5 6 11 6\n10 1 10 7\n7 0 9 8\n10 -1 11 -1\n",
"output": "42\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1400 | Solve the following coding problem using the programming language python:
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $T$ seconds after coming.
Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $n$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $t_i$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).
Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $t_i$ seconds or $t_i + 1$ seconds to solve the $i$-th crossword, equiprobably (with probability $\frac{1}{2}$ he solves the crossword in exactly $t_i$ seconds, and with probability $\frac{1}{2}$ he has to spend an additional second to finish the crossword). All these events are independent.
After $T$ seconds pass (or after solving the last crossword, if he manages to do it in less than $T$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $E$ — the expected number of crosswords he will be able to solve completely. Can you calculate it?
Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $E = \sum \limits_{i = 0}^{n} i p_i$, where $p_i$ is the probability that Adilbek will solve exactly $i$ crosswords.
We can represent $E$ as rational fraction $\frac{P}{Q}$ with $Q > 0$. To give the answer, you should print $P \cdot Q^{-1} \bmod (10^9 + 7)$.
-----Input-----
The first line contains two integers $n$ and $T$ ($1 \le n \le 2 \cdot 10^5$, $1 \le T \le 2 \cdot 10^{14}$) — the number of crosswords and the time Adilbek has to spend, respectively.
The second line contains $n$ integers $t_1, t_2, \dots, t_n$ ($1 \le t_i \le 10^9$), where $t_i$ is the time it takes a crossword expert to solve the $i$-th crossword.
Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
-----Output-----
Print one integer — the expected value of the number of crosswords Adilbek solves in $T$ seconds, expressed in the form of $P \cdot Q^{-1} \bmod (10^9 + 7)$.
-----Examples-----
Input
3 5
2 2 2
Output
750000007
Input
3 5
2 1 2
Output
125000003
-----Note-----
The answer for the first sample is equal to $\frac{14}{8}$.
The answer for the second sample is equal to $\frac{17}{8}$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import stdin, stdout, exit
mod = 10**9 + 7
def modinv(x):
return pow(x, mod-2, mod)
N = 2*10**5 + 10
facts = [1]*N
for i in range(1,N):
facts[i] = facts[i-1] * i
facts[i] %= mod
def binom(n, k):
ans = modinv(facts[k]) * modinv(facts[n-k])
ans %= mod
ans *= facts[n]
ans %= mod
return ans
#print("Finished preprocess")
n, T = list(map(int, stdin.readline().split()))
ts = list(map(int, stdin.readline().split()))
ans = 0
total = sum(ts)
running = total
last_idx = n-1
while running > T:
running -= ts[last_idx]
last_idx -= 1
#print(last_idx+1)
last_bd = -1
last_sum = 0
idx = last_idx
while running + idx + 1 > T:
bd = T - running
# print("time remaining for", idx+1, "flips is", bd)
cur_sum = last_sum + (binom(idx+1, last_bd) if last_bd >= 0 else 0)
cur_sum *= modinv(2)
cur_sum %= mod
for fresh in range(last_bd+1, bd+1):
cur_sum += binom(idx+1, fresh)
cur_sum %= mod
# print("pr of", idx+1, "flips is", cur_sum, cur_sum / (2**(idx+1)))
ans += cur_sum * modinv(pow(2, idx+1, mod))
ans %= mod
running -= ts[idx]
last_bd = bd
last_sum = cur_sum
idx -= 1
#print(idx+1, "freebies")
ans += idx+1
ans %= mod
print(ans)
``` | vfc_15354 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1194/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n2 2 2\n",
"output": "750000007\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1401 | Solve the following coding problem using the programming language python:
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.
The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > a_{u}, where a_{u} is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.
Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.
Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?
-----Input-----
In the first line of the input integer n (1 ≤ n ≤ 10^5) is given — the number of vertices in the tree.
In the second line the sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) is given, where a_{i} is the number written on vertex i.
The next n - 1 lines describe tree edges: i^{th} of them consists of two integers p_{i} and c_{i} (1 ≤ p_{i} ≤ n, - 10^9 ≤ c_{i} ≤ 10^9), meaning that there is an edge connecting vertices i + 1 and p_{i} with number c_{i} written on it.
-----Output-----
Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.
-----Example-----
Input
9
88 22 83 14 95 91 98 53 11
3 24
7 -8
1 67
1 64
9 65
5 12
6 -80
3 8
Output
5
-----Note-----
The following image represents possible process of removing leaves from the tree: [Image]
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()))
maxDist = [0] * n
G = [[] for _ in range(n)]
for v in range(1, n):
u, d = tuple(map(int, input().split()))
u -= 1
G[v].append((u, d))
G[u].append((v, d))
seen = [False] * n
seen[0] = True
q = [0]
to_remove = []
while q:
v = q.pop();
for u, dist in G[v]:
if not seen[u]:
seen[u] = True
maxDist[u] = max(dist, maxDist[v] + dist)
if maxDist[u] > A[u]:
to_remove.append(u)
else:
q.append(u)
count = 0
while to_remove:
v = to_remove.pop()
count += 1
for u, _ in G[v]:
if not seen[u]:
seen[u] = True
to_remove.append(u)
print(count)
``` | vfc_15358 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/682/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8\n",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1402 | Solve the following coding problem using the programming language python:
Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≤ i, j ≤ n), such that s_{i} > w_{i} and s_{j} < w_{j}. Here sign s_{i} represents the i-th digit of string s, similarly, w_{j} represents the j-th digit of string w.
A string's template is a string that consists of digits and question marks ("?").
Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers.
Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (10^9 + 7).
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5) — the length of both templates. The second line contains the first template — a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format.
-----Output-----
In a single line print the remainder after dividing the answer to the problem by number 1000000007 (10^9 + 7).
-----Examples-----
Input
2
90
09
Output
1
Input
2
11
55
Output
0
Input
5
?????
?????
Output
993531194
-----Note-----
The first test contains no question marks and both strings are incomparable, so the answer is 1.
The second test has no question marks, but the given strings are comparable, 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
n, s = int(input()), 0
s1, s2 = str(input()), str(input())
b1, b2 = False, False
for i in range(n):
if s1[i] != '?' and s2[i] != '?':
if ord(s1[i]) < ord(s2[i]):
b1 = True
if ord(s1[i]) > ord(s2[i]):
b2 = True
s += (s1[i] == '?') + (s2[i] == '?')
ans1, ans2, ans3 = 1, 1, 1
for i in range(n):
if s1[i] == '?' and s2[i] == '?':
ans1 = (ans1 * 55) % 1000000007
ans2 = (ans2 * 55) % 1000000007
ans3 = (ans3 * 10) % 1000000007
elif s1[i] == '?':
ans1 = (ans1 * (ord(s2[i]) - ord('0') + 1)) % 1000000007
ans2 = (ans2 * (10 - ord(s2[i]) + ord('0'))) % 1000000007
elif s2[i] == '?':
ans1 = (ans1 * (10 - ord(s1[i]) + ord('0'))) % 1000000007
ans2 = (ans2 * (ord(s1[i]) - ord('0') + 1)) % 1000000007
print((10 ** s - (not b2) * ans1 - (not b1) * ans2 + (not b1 and not b2) * ans3) % 1000000007)
``` | vfc_15362 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/296/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n90\n09\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n11\n55\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n?????\n?????\n",
"output": "993531194\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1403 | Solve the following coding problem using the programming language python:
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$.
The $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \le a_j + K$. The swallow operations go one after another.
For example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \underline{101}, 55, 54]$ $\to$ $[101, \underline{53}, 42, 102, 55, 54]$ $\to$ $[\underline{101}, 42, 102, 55, 54]$ $\to$ $[42, 102, 55, \underline{54}]$ $\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish.
Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.
-----Input-----
The first line contains two space separated positive integers $n$ and $K$ ($1 \le n \le 2 \cdot 10^5$, $1 \le K \le 10^6$) — number of bacteria and intergalactic constant $K$.
The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — sizes of bacteria you have.
-----Output-----
Print the only integer — minimal possible number of bacteria can remain.
-----Examples-----
Input
7 1
101 53 42 102 101 55 54
Output
3
Input
6 5
20 15 10 15 20 25
Output
1
Input
7 1000000
1 1 1 1 1 1 1
Output
7
-----Note-----
The first example is clarified in the problem statement.
In the second example an optimal possible sequence of swallows is: $[20, 15, 10, 15, \underline{20}, 25]$ $\to$ $[20, 15, 10, \underline{15}, 25]$ $\to$ $[20, 15, \underline{10}, 25]$ $\to$ $[20, \underline{15}, 25]$ $\to$ $[\underline{20}, 25]$ $\to$ $[25]$.
In the third example no bacteria can swallow any other bacteria.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n , k = input().split()
n , k = int(n), int(k)
d = {}
arr = list(map(int, input().split()))
for i in arr:
if i in d:
d[i] += 1
else:
d[i] = 1;
arr = list(set(arr))
arr.sort()
cnt = 0
for i in range(len(arr)-1):
if (arr[i] + k >= arr[i+1]):
cnt += d[arr[i]]
print(n - cnt)
``` | vfc_15366 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/990/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 1\n101 53 42 102 101 55 54\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5\n20 15 10 15 20 25\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 1000000\n1 1 1 1 1 1 1\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1404 | Solve the following coding problem using the programming language python:
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $n$ numbers from $1$ to $200$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:
$a_{1} \le a_{2}$,
$a_{n} \le a_{n-1}$ and
$a_{i} \le max(a_{i-1}, \,\, a_{i+1})$ for all $i$ from $2$ to $n-1$.
Ivan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from $1$ to $200$. Since the number of ways can be big, print it modulo $998244353$.
-----Input-----
First line of input contains one integer $n$ ($2 \le n \le 10^{5}$) — size of the array.
Second line of input contains $n$ integers $a_{i}$ — elements of array. Either $a_{i} = -1$ or $1 \le a_{i} \le 200$. $a_{i} = -1$ means that $i$-th element can't be read.
-----Output-----
Print number of ways to restore the array modulo $998244353$.
-----Examples-----
Input
3
1 -1 2
Output
1
Input
2
-1 -1
Output
200
-----Note-----
In the first example, only possible value of $a_{2}$ is $2$.
In the second example, $a_{1} = a_{2}$ so there are $200$ different values because all restored elements should be integers between $1$ and $200$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MOD = 998244353.0
float_prec = 1801439850948198.4
float_mod = lambda x: x if -float_prec < x < float_prec else x % MOD
n = int(input())
a = [int(i) for i in input().split()]
f0, f1 = [1.0] * 201, [0.0] * 201
for i in range(n):
nf0, nf1 = [0.0] * 201, [0.0] * 201
if a[i] == -1:
for j in range(200):
nf0[j + 1] = float_mod(nf0[j] + f0[j] + f1[j])
nf1[j + 1] = float_mod(nf1[j] - f0[j] + f0[j + 1] - f1[j] + f1[200])
else:
for j in range(200):
nf0[j + 1], nf1[j + 1] = nf0[j], nf1[j]
if j + 1 == a[i]:
nf0[j + 1] = float_mod(nf0[j] + f0[j] + f1[j])
nf1[j + 1] = float_mod(nf1[j] - f0[j] + f0[j + 1] - f1[j] + f1[200])
f0, f1 = nf0, nf1
print(int(f1[200] % MOD))
``` | vfc_15370 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1068/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 -1 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n-1 -1\n",
"output": "200\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n-1 -1 -1\n",
"output": "40000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 -1 -1 4 4\n",
"output": "206\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 3 4 1 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 -1 -1 -1 -1 7 6\n",
"output": "5117500\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1405 | Solve the following coding problem using the programming language python:
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f_0 and f_1 are arbitrary f_{n} + 2 = f_{n} + 1 + f_{n} for all n ≥ 0.
You are given some sequence of integers a_1, a_2, ..., a_{n}. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
-----Input-----
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence a_{i}.
The second line contains n integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10^9).
-----Output-----
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
-----Examples-----
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
-----Note-----
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence a_{i} would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is $7$, $14$, $21$, $35$, 28.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
n = int(input())
a = [int(x) for x in input().split()]
sorted_a = sorted(a)
dict_a = {}
for x in a:
if not x in dict_a:
dict_a[x] = 1
else:
dict_a[x] += 1
sorted_uniq_a = sorted(dict_a.keys())
max_fib_prefix = [a[0], a[1]]
for i in range(0, len(sorted_uniq_a)):
for j in range(0, len(sorted_uniq_a)):
if i != j or dict_a[sorted_uniq_a[i]] > 1:
if sorted_uniq_a[i] + sorted_uniq_a[j] > sorted_uniq_a[-1]:
break
fib_prefix = [sorted_uniq_a[i], sorted_uniq_a[j]]
dict_a[sorted_uniq_a[i]] -= 1
dict_a[sorted_uniq_a[j]] -= 1
while True:
next_fib = fib_prefix[-1] + fib_prefix[-2]
if not next_fib in dict_a or dict_a[next_fib] == 0:
break
fib_prefix.append(next_fib)
dict_a[next_fib] -= 1
for x in fib_prefix:
dict_a[x] += 1
if len(fib_prefix) > len(max_fib_prefix):
max_fib_prefix = fib_prefix
print(len(max_fib_prefix))
``` | vfc_15374 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/633/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 -1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n28 35 7 14 21\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11\n-9 -1 -10 9 7 -4 0 -8 -3 3 5\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n-4 -8 -8 8 -9 0 -7 9 1 0\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 -1 0 -2\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1406 | Solve the following coding problem using the programming language python:
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.
Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.
-----Input-----
The first line of input contains three space-separated integers n, k, d (1 ≤ n, d ≤ 1000; 1 ≤ k ≤ 10^9).
-----Output-----
If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.
-----Examples-----
Input
3 2 2
Output
1 1 2
1 2 1
Input
3 2 1
Output
-1
-----Note-----
Note that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
3
import sys
# 1 <= n, d <= 1000, 1 <= k <= 10**9
n, k, d = list(map(int, sys.stdin.readline().split()))
no_sol = False
solution = [[1 for j in range(n)] for i in range(d)]
def schedule(i, j, level):
nonlocal no_sol
if level >= d:
no_sol = True
return
count = j - i
chunk = count // k
extra = count % k
r = i
for t in range(min(k, count)):
size = chunk + (1 if t < extra else 0)
for z in range(size):
solution[level][r+z] = t+1
if size > 1:
schedule(r, r + size, level + 1)
r += size
if k == 1:
if n > 1:
no_sol = True
else:
schedule(0, n, 0)
if no_sol:
print(-1)
else:
for l in solution:
print(' '.join(str(x) for x in l))
``` | vfc_15378 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/459/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2 2\n",
"output": "1 1 2 \n1 2 1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1407 | Solve the following coding problem using the programming language python:
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.
You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.
A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only;
Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
-----Input-----
The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly.
Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 10^5.
The numbers in the lines are separated by single spaces.
-----Output-----
Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
-----Examples-----
Input
3 3
1 2 3
5 6 1
4 4 1
Output
1
Input
2 3
4 8 8
9 2 9
Output
3
Input
2 2
1 3
4 2
Output
0
-----Note-----
In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.
In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.
In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
maxn = 100100
ar = [1 for i in range(maxn)]
ar[0], ar[1] = 0, 0
for i in range(2, maxn):
if ar[i]:
for j in range(i, (maxn - 1) // i + 1):
ar[i * j] = 0
dst = maxn
d = [dst for i in range(maxn)]
for i in reversed(list(range(maxn))):
if ar[i]: dst = 0
d[i] = min(d[i], dst)
dst += 1
n, m = list(map(int, input().split()))
g = [[int(x) for x in input().split()] for _ in range(n)]
g = [[d[x] for x in y] for y in g]
tmpsharon = min([sum(x) for x in g] + [sum(x) for x in zip(*g)])
print(tmpsharon)
``` | vfc_15382 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/271/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n1 2 3\n5 6 1\n4 4 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1408 | Solve the following coding problem using the programming language python:
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is t_{i} and its pages' width is equal to w_{i}. The thickness of each book is either 1 or 2. All books have the same page heights. $1$
Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. [Image]
Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
-----Input-----
The first line of the input contains an integer n, (1 ≤ n ≤ 100). Each of the next n lines contains two integers t_{i} and w_{i} denoting the thickness and width of the i-th book correspondingly, (1 ≤ t_{i} ≤ 2, 1 ≤ w_{i} ≤ 100).
-----Output-----
On the only line of the output print the minimum total thickness of the vertical books that we can achieve.
-----Examples-----
Input
5
1 12
1 3
2 15
2 5
2 1
Output
5
Input
3
1 10
2 1
2 4
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
3
n = int(input())
books = [[], []]
for _ in range(n):
t, w = tuple(map(int, input().split()))
books[t - 1].append(w)
for _ in range(2):
books[_].sort()
#print(books)
ans = 10**9
for i in range(len(books[0]) + 1):
for j in range(len(books[1]) + 1):
hor = sum(books[0][:i]) + sum(books[1][:j])
ver = len(books[0]) - i + 2 * (len(books[1]) - j)
if hor <= ver and ver < ans:
ans = ver
#print(i, j, hor, ver, ans)
print(ans)
``` | vfc_15386 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/294/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 12\n1 3\n2 15\n2 5\n2 1\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 10\n2 1\n2 4\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1409 | Solve the following coding problem using the programming language python:
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?
-----Input-----
The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y_1, y_2, ..., y_{n} (0 ≤ y_{i} ≤ 5), where y_{i} shows the number of times the i-th person participated in the ACM ICPC world championship.
-----Output-----
Print a single number — the answer to the problem.
-----Examples-----
Input
5 2
0 4 5 1 0
Output
1
Input
6 4
0 1 2 3 4 5
Output
0
Input
6 5
0 0 0 0 0 0
Output
2
-----Note-----
In the first sample only one team could be made: the first, the fourth and the fifth participants.
In the second sample no teams could be created.
In the third sample two teams could be created. Any partition into two teams fits.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
for i in a:
if 5 - i >= k:
ans += 1
print(ans // 3)
``` | vfc_15390 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/432/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\n0 4 5 1 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 4\n0 1 2 3 4 5\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5\n0 0 0 0 0 0\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 4\n0 1 0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1410 | Solve the following coding problem using the programming language python:
You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph. [Image] Example of a tree.
You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.
You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $(x, y, z)$ such that $x \neq y, y \neq z, x \neq z$, $x$ is connected by an edge with $y$, and $y$ is connected by an edge with $z$. The colours of $x$, $y$ and $z$ should be pairwise distinct. Let's call a painting which meets this condition good.
You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.
-----Input-----
The first line contains one integer $n$ $(3 \le n \le 100\,000)$ — the number of vertices.
The second line contains a sequence of integers $c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$ $(1 \le c_{1, i} \le 10^{9})$, where $c_{1, i}$ is the cost of painting the $i$-th vertex into the first color.
The third line contains a sequence of integers $c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$ $(1 \le c_{2, i} \le 10^{9})$, where $c_{2, i}$ is the cost of painting the $i$-th vertex into the second color.
The fourth line contains a sequence of integers $c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$ $(1 \le c_{3, i} \le 10^{9})$, where $c_{3, i}$ is the cost of painting the $i$-th vertex into the third color.
Then $(n - 1)$ lines follow, each containing two integers $u_j$ and $v_j$ $(1 \le u_j, v_j \le n, u_j \neq v_j)$ — the numbers of vertices connected by the $j$-th undirected edge. It is guaranteed that these edges denote a tree.
-----Output-----
If there is no good painting, print $-1$.
Otherwise, print the minimum cost of a good painting in the first line. In the second line print $n$ integers $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 3)$, where the $i$-th integer should denote the color of the $i$-th vertex. If there are multiple good paintings with minimum cost, print any of them.
-----Examples-----
Input
3
3 2 3
4 3 2
3 1 3
1 2
2 3
Output
6
1 3 2
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 3
Output
-1
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 4
Output
9
1 3 2 1 3
-----Note-----
All vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color $1$, the second vertex — into color $3$, and the third vertex — into color $2$. The cost of this painting is $3 + 2 + 1 = 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 deque
import sys
input = sys.stdin.readline
n = int(input())
cost = [list(map(int, input().split())) for i in range(3)]
info = [list(map(int, input().split())) for i in range(n-1)]
graph = [[] for i in range(n)]
for i in range(n-1):
a, b = info[i]
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
for i in graph:
if len(i) >= 3:
print(-1)
return
for i, j in enumerate(graph):
if len(j) == 1:
start = i
break
visited = [-1]*n
visited[start] = 0
q = deque([start])
while q:
pos = q.popleft()
for next_pos in graph[pos]:
if visited[next_pos] != -1:
continue
visited[next_pos] = (visited[pos] + 1) % 3
q.append(next_pos)
ans = float("inf")
ind = [0, 1, 2]
for ptn in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]:
tmp_ans = 0
for i in range(n):
tmp_ans += cost[ptn[visited[i]]][i]
if tmp_ans < ans:
ans = tmp_ans
ind = ptn[0:]
print(ans)
new_ans = [0]*n
for i in range(n):
new_ans[i] = ind[visited[i]] + 1
print(*new_ans)
``` | vfc_15394 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1244/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 2 3\n4 3 2\n3 1 3\n1 2\n2 3\n",
"output": "6\n1 3 2 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1411 | Solve the following coding problem using the programming language python:
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat s_{i} slices of pizza, and gain a_{i} happiness for each slice of type 1 pizza they eat, and b_{i} happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
-----Input-----
The first line of input will contain integers N and S (1 ≤ N ≤ 10^5, 1 ≤ S ≤ 10^5), the number of contestants and the number of slices per pizza, respectively. N lines follow.
The i-th such line contains integers s_{i}, a_{i}, and b_{i} (1 ≤ s_{i} ≤ 10^5, 1 ≤ a_{i} ≤ 10^5, 1 ≤ b_{i} ≤ 10^5), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.
-----Output-----
Print the maximum total happiness that can be achieved.
-----Examples-----
Input
3 12
3 5 7
4 6 7
5 9 5
Output
84
Input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6
Output
314
-----Note-----
In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def bins(sortedlist,x):
n=len(sortedlist)
start = 0
end = n - 1
while(start <= end):
mid =int( (start + end)/2)
if (x == sortedlist[mid][0]):
return mid
elif(x < sortedlist[mid][0]):
end = mid - 1
else:
start = mid + 1
if(sortedlist[mid][0]<=x):
return mid
else:
return mid-1
n,s=list(map(int,input().split()))
hap=[]
for i in range(n):
hap.append(list(map(int,input().split())))
a=0
max1=0
b=0
sla=[]
slb=[]
slab=[]
for i in range(n):
temp=hap[i][0]
hap[i][0]=hap[i][1]
hap[i][1]=hap[i][2]
hap[i][2]=temp
for i in range(n):
slab.append([hap[i][0]-hap[i][1],hap[i][2]])
happi=0
for i in range(n):
if(hap[i][0]>hap[i][1]):
a+=hap[i][2]
happi+=hap[i][2]*hap[i][0]
else:
b+=hap[i][2]
happi+=hap[i][2]*hap[i][1]
sla.sort()
slb.sort()
slab.sort()
if((a%s + b%s)>s):
print(happi)
else:
loc=bins(slab,0)
happia=happi
count=0
#print(a,b)
b=b%s
a=a%s
left=b%s
while(left>0):
if(slab[loc+count][1]<left):
happia+=slab[loc+count][0]*slab[loc+count][1]
left-=slab[loc+count][1]
else:
happia+=slab[loc+count][0]*left
break
count-=1
left=a%s
count=0
happib=happi
while(loc<n and slab[loc][0]<=0):
loc+=1
#print(slab[loc][0])
while(left>0):
if(slab[loc+count][1]<left):
happib-=slab[loc+count][0]*slab[loc+count][1]
left-=slab[loc+count][1]
else:
happib-=slab[loc+count][0]*left
break
count+=1
#print(happia,happib,happi)
print(max(happia,happib))
``` | vfc_15398 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/865/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 12\n3 5 7\n4 6 7\n5 9 5\n",
"output": "84\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 10\n7 4 7\n5 8 8\n12 5 8\n6 11 6\n3 3 7\n5 9 6\n",
"output": "314\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1412 | Solve the following coding problem using the programming language python:
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.
The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from l_{i} to r_{i}, inclusive. Today Fedor wants to take exactly k coupons with him.
Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
-----Input-----
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·10^5) — the number of coupons Fedor has, and the number of coupons he wants to choose.
Each of the next n lines contains two integers l_{i} and r_{i} ( - 10^9 ≤ l_{i} ≤ r_{i} ≤ 10^9) — the description of the i-th coupon. The coupons can be equal.
-----Output-----
In the first line print single integer — the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted.
In the second line print k distinct integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — the ids of the coupons which Fedor should choose.
If there are multiple answers, print any of them.
-----Examples-----
Input
4 2
1 100
40 70
120 130
125 180
Output
31
1 2
Input
3 2
1 12
15 20
25 30
Output
0
1 2
Input
5 2
1 10
5 15
14 50
30 70
99 100
Output
21
3 4
-----Note-----
In the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total.
In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from heapq import heappop, heappush
n, k = [int(x) for x in input().split()]
cs = []
for i in range(n):
l, r = [int(x) for x in input().split()]
cs.append((l, r, i+1))
cs.sort()
h = []
lcs = set()
for i in range(k-1):
heappush(h, [cs[i][1], cs[i][2]])
lcs.add(cs[i][2])
l = -1
poped = []
push_i = k-1
for i in range(k-1, n):
heappush(h, [cs[i][1], cs[i][2]])
d = h[0][0] - cs[i][0]
if d > l:
l = d
for j in range(push_i, i+1):
lcs.add(cs[j][2])
for e in poped:
lcs.remove(e)
push_i = i+1
poped = []
poped.append(heappop(h)[1])
print(l+1)
if l == -1:
for i in range(1, k+1):
print(i, end=' ')
else:
for i in lcs:
print(i, end=' ')
``` | vfc_15402 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/754/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\n1 100\n40 70\n120 130\n125 180\n",
"output": "31\n1 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n1 12\n15 20\n25 30\n",
"output": "0\n1 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n1 10\n5 15\n14 50\n30 70\n99 100\n",
"output": "21\n3 4 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1413 | Solve the following coding problem using the programming language python:
You are given a string $s=s_1s_2\dots s_n$ of length $n$, which only contains digits $1$, $2$, ..., $9$.
A substring $s[l \dots r]$ of $s$ is a string $s_l s_{l + 1} s_{l + 2} \ldots s_r$. A substring $s[l \dots r]$ of $s$ is called even if the number represented by it is even.
Find the number of even substrings of $s$. Note, that even if some substrings are equal as strings, but have different $l$ and $r$, they are counted as different substrings.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 65000$) — the length of the string $s$.
The second line contains a string $s$ of length $n$. The string $s$ consists only of digits $1$, $2$, ..., $9$.
-----Output-----
Print the number of even substrings of $s$.
-----Examples-----
Input
4
1234
Output
6
Input
4
2244
Output
10
-----Note-----
In the first example, the $[l, r]$ pairs corresponding to even substrings are: $s[1 \dots 2]$
$s[2 \dots 2]$
$s[1 \dots 4]$
$s[2 \dots 4]$
$s[3 \dots 4]$
$s[4 \dots 4]$
In the second example, all $10$ substrings of $s$ are even substrings. Note, that while substrings $s[1 \dots 1]$ and $s[2 \dots 2]$ both define the substring "2", they are still counted as different substrings.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
s = input()
r = 0
for i in range(n):
if s[i] in '2468':
r += i + 1
print(r)
``` | vfc_15406 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1139/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1234\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2244\n",
"output": "10",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n6\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n9572683145\n",
"output": "24",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n13\n",
"output": "0",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1414 | Solve the following coding problem using the programming language python:
Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".
Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:
initially, Inna chooses some cell of the table where letter "D" is written; then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D".
Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 10^3).
Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A".
Note that it is not guaranteed that the table contains at least one letter "D".
-----Output-----
If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer — the maximum number of times Inna can go through name DIMA.
-----Examples-----
Input
1 2
DI
Output
Poor Dima!
Input
2 2
MA
ID
Output
Poor Inna!
Input
5 5
DIMAD
DIMAI
DIMAM
DDMAA
AAMID
Output
4
-----Note-----
Notes to the samples:
In the first test sample, Inna cannot go through name DIMA a single time.
In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.
In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
m += 1
q = {'I': 0, 'M': 1, 'A': 2, 'D': 3}
t = []
for i in range(n):
t += map(q.get, input())
t.append(-7)
t += [-7] * m
p = [[] for q in t]
c = [0] * len(t)
for a in range(n * m):
for b in (a - m, a + m, a - 1, a + 1):
if abs(t[b] - t[a] + 1) == 2:
p[a].append(b)
c[b] += 1
s = [i for i, q in enumerate(c) if not q]
while s:
a = s.pop()
for b in p[a]:
t[b] = max(t[b], t[a] + 1)
c[b] -= 1
if c[b] == 0: s.append(b)
k = max(t) - 2 >> 2
print('Poor Inna!' if any(c) else k if k > 0 else 'Poor Dima!')
``` | vfc_15410 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/374/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 2\nDI\n",
"output": "Poor Dima!\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\nMA\nID\n",
"output": "Poor Inna!\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1415 | Solve the following coding problem using the programming language python:
The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x_0, y_0) of a rectangular squared field of size x × y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x·y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.
After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.
Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.
The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.
-----Input-----
The first line of the input contains four integers x, y, x_0, y_0 (1 ≤ x, y ≤ 500, 1 ≤ x_0 ≤ x, 1 ≤ y_0 ≤ y) — the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right.
The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100 000 characters and only consists of characters 'L', 'R', 'U', 'D'.
-----Output-----
Print the sequence consisting of (length(s) + 1) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up.
-----Examples-----
Input
3 4 2 2
UURDRDRL
Output
1 1 0 1 1 1 1 0 6
Input
2 2 2 2
ULD
Output
1 1 1 1
-----Note-----
In the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: $(2,2) \rightarrow(1,2) \rightarrow(1,2) \rightarrow(1,3) \rightarrow(2,3) \rightarrow(2,4) \rightarrow(3,4) \rightarrow(3,4) \rightarrow(3,3)$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a, b, x, y = map(int, input().split())
s = input()
p = []
for i in range(a + 1):
p.append([0] * (b + 1))
sum = 0
for i in range(len(s)):
if p[x][y] == 0:
p[x][y] = 1
print(1, end = ' ')
sum += 1
else:
print(0, end = ' ')
if s[i] == 'U' and x != 1:
x -= 1
if s[i] == 'D' and x != a:
x += 1
if s[i] == 'L' and y != 1:
y -= 1
if s[i] == 'R' and y != b:
y += 1
print(a * b - sum)
``` | vfc_15414 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/606/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4 2 2\nUURDRDRL\n",
"output": "1 1 0 1 1 1 1 0 6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1417 | Solve the following coding problem using the programming language python:
Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $P$. For example, if $n = 3$, then $P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence is $n \cdot n!$.
Let $1 \leq i \leq j \leq n \cdot n!$ be a pair of indices. We call the sequence $(P_i, P_{i+1}, \dots, P_{j-1}, P_j)$ a subarray of $P$.
You are given $n$. Find the number of distinct subarrays of $P$. Since this number may be large, output it modulo $998244353$ (a prime number).
-----Input-----
The only line contains one integer $n$ ($1 \leq n \leq 10^6$), as described in the problem statement.
-----Output-----
Output a single integer — the number of distinct subarrays, modulo $998244353$.
-----Examples-----
Input
2
Output
8
Input
10
Output
19210869
-----Note-----
In the first example, the sequence $P = [1, 2, 2, 1]$. It has eight distinct subarrays: $[1]$, $[2]$, $[1, 2]$, $[2, 1]$, $[2, 2]$, $[1, 2, 2]$, $[2, 2, 1]$ and $[1, 2, 2, 1]$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
'''
// There are n! / (i+1)! * i permutations with decreasing seq length i (i+1 changes) for i <= n!
// There are n! / (i+1)! permutations for each 1 <= j <= i of position of moved one
// All nonempty things
+ n*n! * (n*n! + 1) / 2
// Subtract off everything inside one of them
- n! * n * (n+1) / 2
// Subtract off everything that doesn't include the min-incr
- sum_{perm i,j} n * (n-i)
// We're left with all words that include at least last of prv -> min-incr, which all have at least one match
// No matches
+ sum_{i=1..n} n!/(n-i)!
// First match is dist N, doesn't include anything
// aaa....aaa -> middle part can't all be decreasing
+ sum_{i=1..n} n! - n!/(n-i)!
// First match is dist N, includes subst
// aaabxyc aaac
// Everything decreasing xycb
+ sum_{i=1..n-1} n!/(i+1)! * (n-i-1)
// First match is dist N, includes min-incr -> is unique, already counted
// First match is < N -> either came from min-incr or from subst
// You can distinguish because match..match includes everything smaller or everything smaller minus one of them
// Ending at min-incr gives unique thing
// How many distinct things end at subst?
// Ending at subst: (b ijk ) lmn c xyz ... c such that zyxbcnmlkji are sorted leftovers
or b ijk lmn c xyz .... c
// Might as well not include xyz
+ sum_{i=1..n-1} n!/(i+1)! * (i+1)
// Simplified claim:
if it includes min-incr, then it's always unique;
if it includes subst, only count if it came from the end (j = 1) (in which case it always matches)
otherwise, it's just some delta-N match or it's all distinct
n*n! * (n*n! + 1) / 2
- n! * n * (n+1) / 2
- sum_{i=1..n-1} n! / (i+1)! * i * n * (n-i)
+ sum_{i=1..n} n! / (n-i)!
+ sum_{i=1..n} n! - n! / (n-i)!
+ sum_{i=1..n-1} n! / (i+1)! * n
= n*n! * (n*n! + 1) / 2
- n! * n * (n+1) / 2
- sum_{i=1..n-1} n! / (i+1)! * n * (i * (n-i) - 1)
+ n * n!
= n*n! * (n*n! - n + 2) / 2
- sum_{i=1..n-1} n! / (i+1)! * n * (i * (n-i) - 1)
'''
def fact(n):
res = 1
for i in range(1,n+1):
res *= i
return res
def f(n):
l = fact(n) * n
ans = l * (l-n+2) // 2
for i in range(1,n):
ans -= fact(n) // fact(i+1) * n * (i * (n-i) - 1)
return ans
#print(f(int(input())) % 998244353)
def g(n):
M = 998244353
p = n
a = 0
for i in range(n,1,-1):
a=(a+p*(i-1)*(n-i+1)-p)%M
p=p*i%M
a=(p*(p-n+2)-a-a)%M
if a&1:a+=M
return a//2
print(g(int(input())))
``` | vfc_15422 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1266/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n",
"output": "19210869\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000\n",
"output": "739718215\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "17\n",
"output": "466150679\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "141\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1418 | Solve the following coding problem using the programming language python:
You're given an integer $n$. For every integer $i$ from $2$ to $n$, assign a positive integer $a_i$ such that the following conditions hold: For any pair of integers $(i,j)$, if $i$ and $j$ are coprime, $a_i \neq a_j$. The maximal value of all $a_i$ should be minimized (that is, as small as possible).
A pair of integers is called coprime if their greatest common divisor is $1$.
-----Input-----
The only line contains the integer $n$ ($2 \le n \le 10^5$).
-----Output-----
Print $n-1$ integers, $a_2$, $a_3$, $\ldots$, $a_n$ ($1 \leq a_i \leq n$).
If there are multiple solutions, print any of them.
-----Examples-----
Input
4
Output
1 2 1
Input
3
Output
2 1
-----Note-----
In the first example, notice that $3$ and $4$ are coprime, so $a_3 \neq a_4$. Also, notice that $a=[1,2,3]$ satisfies the first condition, but it's not a correct answer because its maximal value is $3$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def isPrime(n):
# a prime(except 2 or 3) is of the form 6k-1 or 6k+1
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
w = 2
sqN = int(pow(n, .5))
while i <= sqN:
if n % i == 0:
return False
i += w
w = 6 - w
return True
n = int(input().strip())
arr = [0]*(n+1)
c = 1
for i in range(2, n+1):
if isPrime(i):
arr[i] = c
for j in range(i+i, n+1, i):
if not arr[j]:
arr[j] = c
c += 1
print(*arr[2:])
``` | vfc_15426 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1174/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n",
"output": "1 2 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "2 1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "1 2 1 3 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n",
"output": "1 2 1 3 2 4 1 2 3 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1419 | Solve the following coding problem using the programming language python:
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen.
It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word.
When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.
The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.
You should write a program that will find minimal width of the ad.
-----Input-----
The first line contains number k (1 ≤ k ≤ 10^5).
The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 10^6 characters.
-----Output-----
Output minimal width of the ad.
-----Examples-----
Input
4
garage for sa-le
Output
7
Input
4
Edu-ca-tion-al Ro-unds are so fun
Output
10
-----Note-----
Here all spaces are replaced with dots.
In the first example one of possible results after all word wraps looks like this:
garage.
for.
sa-
le
The second example:
Edu-ca-
tion-al.
Ro-unds.
are.so.fun
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
inf = 1 << 30
def solve():
def check(mid):
tot = 1
line = 0
buf = 0
for ch in s:
buf += 1
if ch == ' ' or ch == '-':
if line + buf > mid:
tot += 1
if tot > k or buf > mid:
return False
line = buf
buf = 0
else:
line += buf
buf = 0
if line + buf > mid:
tot += 1
if tot > k or buf > mid:
return False
return True
k = int(input())
s = input()
# binary-search
top = len(s)
btm = 0
while top - btm > 1:
mid = (top + btm) // 2
if check(mid):
top = mid
else:
btm = mid
ans = top
print(ans)
def __starting_point():
solve()
__starting_point()
``` | vfc_15430 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/803/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\ngarage for sa-le\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\nEdu-ca-tion-al Ro-unds are so fun\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nj\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\nb\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nQGVsfZevMD\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\nqUOYCytbKgoGRgaqhjrohVRxKTKjjOUPPnEjiXJWlvpCyqiRzbnpyNqDylWverSTrcgZpEoDKhJCrOOvsuXHzkPtbXeKCKMwUTVk\n",
"output": "100\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1421 | Solve the following coding problem using the programming language python:
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes.
They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer a_{i} — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.
The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.
Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.
Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of gifts.
The next line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the pleasantness of the gifts.
The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the description of the tree's edges. It means that gifts with numbers u_{i} and v_{i} are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: v_{i} hangs on u_{i} or u_{i} hangs on v_{i}.
It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
-----Output-----
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together.
Otherwise print Impossible.
-----Examples-----
Input
8
0 5 -1 4 3 2 6 5
1 2
2 4
2 5
1 3
3 6
6 7
6 8
Output
25
Input
4
1 -5 1 1
1 2
1 4
2 3
Output
2
Input
1
-1
Output
Impossible
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
input = sys.stdin.readline
oo = 10**20
n = int(input())
a = list(map(int, input().split()))
adj = [[] for _ in range(n)]
for _ in range(n-1):
u, v = [int(i) - 1 for i in input().split()]
adj[u].append(v)
adj[v].append(u)
sm = [0] * n
mx = [-oo] * n
best = [-oo] * n
def dfs(start):
stack = [(start, -1)]
visit = [False] * n
while stack:
u, p = stack[-1]
if not visit[u]:
for v in adj[u]:
if v != p:
stack.append((v, u))
visit[u] = True
else:
x = [-oo] * 3
for v in adj[u]:
if v != p:
sm[u] += sm[v]
mx[u] = max(mx[u], mx[v])
best[u] = max(best[u], best[v])
x[0] = mx[v]
x.sort()
sm[u] += a[u]
mx[u] = max(mx[u], sm[u])
if x[1] > -oo and x[2] > -oo:
cur = x[1] + x[2]
best[u] = max(best[u], cur)
stack.pop()
dfs(0)
ans = max(best)
if ans <= -oo:
print('Impossible')
else:
print(ans)
``` | vfc_15438 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/743/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8\n",
"output": "25",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 -5 1 1\n1 2\n1 4\n2 3\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n-1\n",
"output": "Impossible",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3 2 -4 2 0 3 3 3 3 4\n10 8\n4 2\n4 9\n3 5\n5 2\n7 4\n2 6\n1 8\n10 9\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n-1 2 -2 -3 -1 -1 0 -4 -5 -4\n4 6\n6 9\n1 2\n6 2\n7 8\n7 9\n5 10\n6 3\n10 1\n",
"output": "-3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n4 -4 2 5 -1 3 -1 1 4 5\n1 8\n7 1\n4 1\n9 6\n1 2\n5 10\n10 1\n9 3\n1 9\n",
"output": "14",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1422 | Solve the following coding problem using the programming language python:
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.
Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.
You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on the scales or to say that it can't be done.
-----Input-----
The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i ≥ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≤ m ≤ 1000).
-----Output-----
In the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers — the weights' weights in the order you put them on the scales.
If there are multiple solutions, you can print any of them.
-----Examples-----
Input
0000000101
3
Output
YES
8 10 8
Input
1000000000
2
Output
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
p, m = [i for i, x in enumerate(input(), 1) if x == '1'], int(input())
r, q = [(-1, 0, 0, [])], 'NO'
while r:
x, d, s, t = r.pop()
if s == m:
q = 'YES\n' + ' '.join(map(str, t))
break
for y in p:
if y != x and y > d: r.append((y, y - d, s + 1, t + [y]))
print(q)
``` | vfc_15442 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/339/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "0000000101\n3\n",
"output": "YES\n8 10 8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000\n2\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000\n1\n",
"output": "YES\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1001100000\n11\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1423 | Solve the following coding problem using the programming language python:
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: c_{i} = b_{i} - a_{i}.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l ≤ a_{i} ≤ r and l ≤ b_{i} ≤ r. About sequence c we know that all its elements are distinct.
[Image]
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that p_{i} equals to the number of integers which are less than or equal to c_{i} in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
-----Input-----
The first line contains three integers n, l, r (1 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a_1, a_2, ..., a_{n} (l ≤ a_{i} ≤ r) — the elements of the sequence a.
The next line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the compressed sequence of the sequence c.
-----Output-----
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers — the elements of any suitable sequence b.
-----Examples-----
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1 4
Output
2 2 2 9
Input
6 1 5
1 1 1 1 1 1
2 3 5 4 1 6
Output
-1
-----Note-----
Sequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1, - 2, - 6, 0] (note that c_{i} = b_{i} - a_{i}) has compressed sequence equals to p = [3, 2, 1, 4].
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, l, r = list(map(int, input().split()))
read = lambda: list(map(int, input().split()))
a = list(read())
p = list(read())
d = [(a[i], p[i], i) for i in range(n)]
d.sort(key = lambda x: x[1])
cur = l - d[0][0]
b = [0] * n
for i in range(n):
ind = d[i][2]
b[ind] = a[ind] + cur
if b[ind] < l:
cur = l - a[ind]
b[ind] = l
cur += 1
if max(b) > r:
print(-1)
return
print(' '.join(map(str, b)))
``` | vfc_15446 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/761/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 1 5\n1 1 1 1 1\n3 1 5 4 2\n",
"output": "3 1 5 4 2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1424 | Solve the following coding problem using the programming language python:
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».
The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer x_{i}. Consider binary representation of x_{i}: if the j-th bit of number x_{i} equal to one, then the army of the i-th player has soldiers of the j-th type.
Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.
-----Input-----
The first line contains three integers n, m, k (1 ≤ k ≤ n ≤ 20; 1 ≤ m ≤ 1000).
The i-th of the next (m + 1) lines contains a single integer x_{i} (1 ≤ x_{i} ≤ 2^{n} - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.
-----Output-----
Print a single integer — the number of Fedor's potential friends.
-----Examples-----
Input
7 3 1
8
5
111
17
Output
0
Input
3 3 3
1
2
3
4
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def check(i):
x, counter = armies[i] ^ armies[-1], 0
while x:
counter += x & 1
x >>= 1
return counter <= k
n, m, k = list(map(int, input().split()))
armies = [int(input()) for x in range(m + 1)]
print(sum(map(check, list(range(m)))))
``` | vfc_15450 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/467/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 3 1\n8\n5\n111\n17\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 3\n1\n2\n3\n4\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2 2\n5\n6\n7\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 7 4\n9\n10\n5\n12\n4\n12\n7\n10\n",
"output": "7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1425 | Solve the following coding problem using the programming language python:
You are given $n$ numbers $a_1, a_2, \ldots, a_n$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?
For example, for the array $[1, 4, 5, 6, 7, 8]$, the arrangement on the left is valid, while arrangement on the right is not, as $5\ge 4 + 1$ and $8> 1 + 6$. [Image]
-----Input-----
The first line contains a single integer $n$ ($3\le n \le 10^5$) — the number of numbers.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \le 10^9$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).
-----Output-----
If there is no solution, output "NO" in the first line.
If there is a solution, output "YES" in the first line. In the second line output $n$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.
-----Examples-----
Input
3
2 4 3
Output
YES
4 2 3
Input
5
1 2 3 4 4
Output
YES
4 4 2 1 3
Input
3
13 8 5
Output
NO
Input
4
1 10 100 1000
Output
NO
-----Note-----
One of the possible arrangements is shown in the first example:
$4< 2 + 3$;
$2 < 4 + 3$;
$3< 4 + 2$.
One of the possible arrangements is shown in the second example.
No matter how we arrange $13, 8, 5$ in a circle in the third example, $13$ will have $8$ and $5$ as neighbors, but $13\ge 8 + 5$.
There is no solution in the fourth 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())
l1=list(map(int,input().split()))
l1.sort()
l1=l1[::-1]
ans=[-1]*n
i=0
y=n-1
for j in range(n):
if j%2==0:
ans[i]=l1[j]
i+=1
else :
ans[y]=l1[j]
y-=1
flag=0
for i in range(n):
if ans[i]>=ans[i-1]+ans[(i+1)%n]:
flag=1
break
if flag==0:
print("YES")
print(' '.join(str(x) for x in ans))
else :
print("NO")
``` | vfc_15454 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1189/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 4 3\n",
"output": "YES\n4 2 3 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1434 | Solve the following coding problem using the programming language python:
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degree_{v} and s_{v}, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degree_{v} and s_{v} left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 2^16), the number of vertices in the graph.
The i-th of the next lines contains numbers degree_{i} and s_{i} (0 ≤ degree_{i} ≤ n - 1, 0 ≤ s_{i} < 2^16), separated by a space.
-----Output-----
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
-----Examples-----
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
-----Note-----
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from heapq import heappush, heappop
queue = []
degree = []
s = []
ans = []
n = int(input())
used = [False for i in range(n)]
for i in range(n):
a, b = list(map(int, input().split()))
degree.append(a)
s.append(b)
heappush(queue, (a, i))
while queue:
el = heappop(queue)
vert = el[1]
if used[vert]:
continue
used[vert] = True
if degree[vert] == 0:
continue
other = s[vert]
ans.append((vert, other))
s[other] ^= vert
degree[other] -= 1
heappush(queue, (degree[other], other))
print(len(ans))
for el in ans:
print(el[0], el[1])
``` | vfc_15490 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/501/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 3\n1 0\n1 0\n",
"output": "2\n1 0\n2 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1435 | Solve the following coding problem using the programming language python:
Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.
Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.
For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.
Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.
-----Input-----
The first line of the input contains integer a (1 ≤ a ≤ 10^100000). Number a doesn't have any zeroes.
-----Output-----
In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 2^63 - 1.
Please, do not use 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
369727
Output
2
Input
123456789987654321
Output
1
Input
1
Output
1
-----Note-----
Notes to the samples
In the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.
In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s=input()
ans=0
i=1
past=int(s[0])
c=1
ans=1
while(i<len(s)):
if(int(s[i])+past==9):
c+=1
past=int(s[i])
else:
if(c%2==1 and c!=1):
ans*=(c//2+1)
c=1
past=int(s[i])
i+=1
if(c!=1 and c%2==1):
ans*=(c//2+1)
print(ans)
``` | vfc_15494 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/374/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "369727\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "123456789987654321\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3636363636363454545454543636363636454545452727272727218181818181999111777\n",
"output": "1512\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1437 | Solve the following coding problem using the programming language python:
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 10^9 + 7.
To represent the string as a number in numeral system with base 64 Vanya uses the following rules: digits from '0' to '9' correspond to integers from 0 to 9; letters from 'A' to 'Z' correspond to integers from 10 to 35; letters from 'a' to 'z' correspond to integers from 36 to 61; letter '-' correspond to integer 62; letter '_' correspond to integer 63.
-----Input-----
The only line of the input contains a single word s (1 ≤ |s| ≤ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.
-----Output-----
Print a single integer — the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 10^9 + 7.
-----Examples-----
Input
z
Output
3
Input
V_V
Output
9
Input
Codeforces
Output
130653412
-----Note-----
For a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.
In the first sample, there are 3 possible solutions: z&_ = 61&63 = 61 = z _&z = 63&61 = 61 = z z&z = 61&61 = 61 = z
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MOD = 1000000007
def main():
opts = [0] * 64
for i in range(64):
for j in range(64):
opts[i & j] += 1
s = input()
n = len(s)
ans = 1
for c in s:
if '0' <= c <= '9':
ans *= opts[ord(c) - ord('0')]
ans %= MOD
elif 'A' <= c <= 'Z':
ans *= opts[ord(c) - ord('A') + 10]
ans %= MOD
elif 'a' <= c <= 'z':
ans *= opts[ord(c) - ord('a') + 36]
ans %= MOD
elif c == '-':
ans *= opts[62]
ans %= MOD
else:
ans *= opts[63]
ans %= MOD
print(ans)
main()
``` | vfc_15502 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/677/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "z\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "V_V\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1438 | Solve the following coding problem using the programming language python:
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.
Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value a_{i} — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.
Apollinaria has b_{i} gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.
Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.
-----Input-----
The first line of the input contains two positive integers n and k (1 ≤ n, k ≤ 1000) — the number of ingredients and the number of grams of the magic powder.
The second line contains the sequence a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie.
The third line contains the sequence b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.
-----Output-----
Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.
-----Examples-----
Input
3 1
2 1 4
11 3 16
Output
4
Input
4 3
4 3 5 6
11 12 14 20
Output
3
-----Note-----
In the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.
In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer.
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()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
r = 0
ok = 1
while ok:
L = [0 for _ in range(n)]
for i in range(n):
B[i] = B[i] - A[i]
if B[i] < 0:
L[i] = -B[i]
B[i] = 0
if sum(L) <= k:
r += 1
k = k - sum(L)
else:
ok = 0
print(r)
``` | vfc_15506 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/670/D1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1\n2 1 4\n11 3 16\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n4 3 5 6\n11 12 14 20\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 926\n5 6 8 1 2 5 1 8 4 4\n351 739 998 725 953 970 906 691 707 1000\n",
"output": "137\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 925\n7 3 1 2 1 3 1 3 1 2 3 1 5 8 1 3 7 3 4 2\n837 898 965 807 786 670 626 873 968 745 878 359 760 781 829 882 777 740 907 779\n",
"output": "150\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "30 300\n1 4 2 1 2 5 6 4 1 3 2 1 1 1 1 1 2 3 1 3 4 2 2 3 2 2 2 1 1 1\n997 817 767 860 835 809 817 565 630 804 586 953 977 356 905 890 958 916 740 583 902 945 313 956 871 729 976 707 516 788\n",
"output": "164\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1439 | Solve the following coding problem using the programming language python:
You are given a sequence of numbers a_1, a_2, ..., a_{n}, and a number m.
Check if it is possible to choose a non-empty subsequence a_{i}_{j} such that the sum of numbers in this subsequence is divisible by m.
-----Input-----
The first line contains two numbers, n and m (1 ≤ n ≤ 10^6, 2 ≤ m ≤ 10^3) — the size of the original sequence and the number such that sum should be divisible by it.
The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9).
-----Output-----
In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.
-----Examples-----
Input
3 5
1 2 3
Output
YES
Input
1 6
5
Output
NO
Input
4 6
3 1 1 3
Output
YES
Input
6 6
5 5 5 5 5 5
Output
YES
-----Note-----
In the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.
In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.
In the third sample test you need to choose two numbers 3 on the ends.
In the fourth sample test you can take the whole subsequence.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
__author__ = 'User'
n, m = list(map(int, input().split()))
arr = list(map(int, input().split()))
for i in range(n):
arr[i] = arr[i] % m
d = [0] * m
for e in arr:
t = [0] * m
t[e] = 1
for i in range(m):
if d[i] == 1:
#print("T", i + e)
t[(i + e) % m] = 1
for i in range(m):
if t[i] == 1:
d[i] = 1
#print(d)
if d[0] == 1:
break
if d[0] == 1:
print("YES")
else:
print("NO")
#print(d)
#print(arr)
``` | vfc_15510 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/577/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n1 2 3\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 6\n5\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 6\n3 1 1 3\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 6\n5 5 5 5 5 5\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1440 | Solve the following coding problem using the programming language python:
Pavel has several sticks with lengths equal to powers of two.
He has $a_0$ sticks of length $2^0 = 1$, $a_1$ sticks of length $2^1 = 2$, ..., $a_{n-1}$ sticks of length $2^{n-1}$.
Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.
It is forbidden to break sticks, and each triangle should consist of exactly three sticks.
Find the maximum possible number of triangles.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 300\,000$) — the number of different lengths of sticks.
The second line contains $n$ integers $a_0$, $a_1$, ..., $a_{n-1}$ ($1 \leq a_i \leq 10^9$), where $a_i$ is the number of sticks with the length equal to $2^i$.
-----Output-----
Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.
-----Examples-----
Input
5
1 2 2 2 2
Output
3
Input
3
1 1 1
Output
0
Input
3
3 3 3
Output
3
-----Note-----
In the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $(2^0, 2^4, 2^4)$, $(2^1, 2^3, 2^3)$, $(2^1, 2^2, 2^2)$.
In the second example, Pavel cannot make a single triangle.
In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $(2^0, 2^0, 2^0)$, $(2^1, 2^1, 2^1)$, $(2^2, 2^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
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [tuple(map(int, l.split())) for l in sys.stdin]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n = I()
a = LI()
r = 0
ai = 0
for i in range(n):
if a[i] < 2:
continue
while ai < i:
if a[ai] < 1:
ai += 1
continue
if a[i] < 2:
break
r += 1
a[ai] -= 1
a[i] -= 2
r += a[i] // 3
a[i] %= 3
return r
print(main())
``` | vfc_15514 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1119/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 2 2 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1441 | Solve the following coding problem using the programming language python:
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). [Image] Figure 1. The initial position for n = 5.
After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. [Image] Figure 2. The example of a throw.
In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.
Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.
-----Input-----
The first line contains a single number n — the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.
The input limits for scoring 30 points are (subproblem D1): 1 ≤ n ≤ 10.
The input limits for scoring 70 points are (subproblems D1+D2): 1 ≤ n ≤ 500.
The input limits for scoring 100 points are (subproblems D1+D2+D3): 1 ≤ n ≤ 1000000.
-----Output-----
The output should contain a single integer — the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
5
1 2 2 1 2
Output
120
Input
8
1 2 2 1 2 1 1 2
Output
16800
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
m = 1000000007
n = int(input())
a = map(int, input().split())
t1, t2 = 0, 0
for i in a:
if i == 1:
t1 += 1
else:
t2 += 1
a = [1, 2]
for i in range(3, t1+1):
a = a[::-1]
a[1] = (a[0]+(i-1)*a[1])%m
if not t1 or t1 == 1:
a[1] = 1
for i in range(t1+1, n+1):
a[1] = a[1]*i%m
print(a[1])
``` | vfc_15518 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/316/D3",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 2 2 1 2\n",
"output": "120\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n1 2 2 1 2 1 1 2\n",
"output": "16800\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1442 | Solve the following coding problem using the programming language python:
In this task you need to process a set of stock exchange orders and use them to create order book.
An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price p_{i}, direction d_{i} — buy or sell, and integer q_{i}. This means that the participant is ready to buy or sell q_{i} stocks at price p_{i} for one stock. A value q_{i} is also known as a volume of an order.
All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.
An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.
An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.
You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
-----Input-----
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth.
Next n lines contains a letter d_{i} (either 'B' or 'S'), an integer p_{i} (0 ≤ p_{i} ≤ 10^5) and an integer q_{i} (1 ≤ q_{i} ≤ 10^4) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
-----Output-----
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
-----Examples-----
Input
6 2
B 10 3
S 50 2
S 40 1
S 50 6
B 20 4
B 25 10
Output
S 50 8
S 40 1
B 25 10
B 20 4
-----Note-----
Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.
You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
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
import collections
n, s = list(map(int, input().split()))
buy_orders = collections.defaultdict(int)
sell_orders = collections.defaultdict(int)
for i in range(n):
d, p, q = input().split()
p, q = int(p), int(q)
if d == 'B':
buy_orders[p] += q
else:
sell_orders[p] += q
buy_orders = sorted(list(buy_orders.items()), reverse=True)
sell_orders = sorted(list(sell_orders.items()), reverse=True)
for order in sell_orders[-s:]:
print('S', order[0], order[1])
for order in buy_orders[:s]:
print('B', order[0], order[1])
``` | vfc_15522 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/572/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10\n",
"output": "S 50 8\nS 40 1\nB 25 10\nB 20 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\nB 7523 5589\nS 69799 1711\n",
"output": "S 69799 1711\nB 7523 5589\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\nB 48259 991\n",
"output": "B 48259 991\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1443 | Solve the following coding problem using the programming language python:
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! [Image] Duck is the ultimate animal! (Image courtesy of See Bang)
The journey can be represented as a straight line, consisting of $n$ segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last segment. Each segment has a length in meters, and also terrain type: grass, water or lava.
Bob has three movement types: swimming, walking and flying. He can switch between them or change his direction at any point in time (even when he is located at a non-integer coordinate), and doing so doesn't require any extra time. Bob can swim only on the water, walk only on the grass and fly over any terrain. Flying one meter takes $1$ second, swimming one meter takes $3$ seconds, and finally walking one meter takes $5$ seconds.
Bob has a finite amount of energy, called stamina. Swimming and walking is relaxing for him, so he gains $1$ stamina for every meter he walks or swims. On the other hand, flying is quite tiring, and he spends $1$ stamina for every meter flown. Staying in place does not influence his stamina at all. Of course, his stamina can never become negative. Initially, his stamina is zero.
What is the shortest possible time in which he can reach Alice's nest?
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of segments of terrain.
The second line contains $n$ integers $l_1, l_2, \dots, l_n$ ($1 \leq l_i \leq 10^{12}$). The $l_i$ represents the length of the $i$-th terrain segment in meters.
The third line contains a string $s$ consisting of $n$ characters "G", "W", "L", representing Grass, Water and Lava, respectively.
It is guaranteed that the first segment is not Lava.
-----Output-----
Output a single integer $t$ — the minimum time Bob needs to reach Alice.
-----Examples-----
Input
1
10
G
Output
30
Input
2
10 10
WL
Output
40
Input
2
1 2
WL
Output
8
Input
3
10 10 10
GLW
Output
80
-----Note-----
In the first sample, Bob first walks $5$ meters in $25$ seconds. Then he flies the remaining $5$ meters in $5$ seconds.
In the second sample, Bob first swims $10$ meters in $30$ seconds. Then he flies over the patch of lava for $10$ seconds.
In the third sample, the water pond is much smaller. Bob first swims over the water pond, taking him $3$ seconds. However, he cannot fly over the lava just yet, as he only has one stamina while he needs two. So he swims back for half a meter, and then half a meter forward, taking him $3$ seconds in total. Now he has $2$ stamina, so he can spend $2$ seconds flying over the lava.
In the fourth sample, he walks for $50$ seconds, flies for $10$ seconds, swims for $15$ seconds, and finally flies for $5$ seconds.
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=list(map(int,input().split()))
s=input()
water=0
grass=0
cgrass=0
time=0
seen=False
for i in range(n):
if s[i]=="G":
dist=l[i]
if water>=dist:
water-=dist
time+=2*dist
cgrass+=dist
else:
dist-=water
time+=2*water
cgrass+=water
water=0
time+=3*dist
grass+=dist
elif s[i]=="W":
water+=l[i]
time+=2*l[i]
seen=True
else:
dist=l[i]
if water>=dist:
water-=dist
time+=2*dist
else:
dist-=water
time+=2*water
water=0
if cgrass>=dist:
cgrass-=dist
grass+=dist
time+=3*dist
else:
dist-=cgrass
grass+=cgrass
time+=3*cgrass
cgrass=0
if grass>=dist:
grass-=dist
time+=3*dist
else:
dist-=grass
time+=3*grass
grass=0
if seen:
time+=4*dist
else:
time+=6*dist
print(time)
``` | vfc_15526 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1091/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n10\nG\n",
"output": "30\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n10 10\nWL\n",
"output": "40\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\nWL\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n10 10 10\nGLW\n",
"output": "80\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 10\nGL\n",
"output": "60\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1444 | Solve the following coding problem using the programming language python:
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!
The President of Berland was forced to leave only k of the currently existing n subway stations.
The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate x_{i}. In such case the distance between stations i and j is calculated by a simple formula |x_{i} - x_{j}|.
Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!
Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is $\frac{n \cdot(n - 1)}{2}$) and divided by the speed of the train.
Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
-----Input-----
The first line of the input contains integer n (3 ≤ n ≤ 3·10^5) — the number of the stations before the innovation. The second line contains the coordinates of the stations x_1, x_2, ..., x_{n} ( - 10^8 ≤ x_{i} ≤ 10^8). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation.
The station coordinates are distinct and not necessarily sorted.
-----Output-----
Print a sequence of k distinct integers t_1, t_2, ..., t_{k} (1 ≤ t_{j} ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
-----Examples-----
Input
3
1 100 101
2
Output
2 3
-----Note-----
In the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
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
n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
a = sorted([(a[x],str(x+1)) for x in range(n)])
k = int(stdin.readline())
sums = [0]
for x in a:
sums.append(sums[-1]+x[0])
total = 0
s = 0
for x in range(k):
total += a[x][0]*x-s
s += a[x][0]
low = total
lowInd = 0
#print(total)
for x in range(n-k):
s -= a[x][0]
total -= s-a[x][0]*(k-1)
total += a[x+k][0]*(k-1)-s
s += a[x+k][0]
if total < low:
low = total
lowInd = x+1
out = []
for x in range(lowInd,lowInd+k):
out.append(a[x][1])
print(' '.join(out))
``` | vfc_15530 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/371/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 100 101\n2\n",
"output": "2 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n11 21 30 40 50\n3\n",
"output": "1 2 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n0 -4 -3\n2\n",
"output": "2 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n5 -7 8 1\n2\n",
"output": "1 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n-4 -2 10 -9 -10\n2\n",
"output": "5 4 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1445 | Solve the following coding problem using the programming language python:
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number a_{i}, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 2·10^5) — the number of cubes.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9), where a_{i} is the number written on the i-th cube after Dima has changed their order.
-----Output-----
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
-----Examples-----
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
-----Note-----
Consider the first sample. At the begining row was [2, 3, 9, 6, 7, 1, 4]. After first operation row was [4, 1, 7, 6, 9, 3, 2]. After second operation row was [4, 3, 9, 6, 7, 1, 2]. After third operation row was [4, 3, 7, 6, 9, 1, 2]. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
i = 1
while i <= n - i + 1:
if i % 2:
a[i - 1], a[-i] = a[-i], a[i - 1]
i += 1
print(*a)
``` | vfc_15534 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/764/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n4 3 7 6 9 1 2\n",
"output": "2 3 9 6 7 1 4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n6 1 4 2 5 6 9 2\n",
"output": "2 1 6 2 5 4 9 6",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1446 | Solve the following coding problem using the programming language python:
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals c_{i}. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type c_{i} are numbered from $(\sum_{k = 1}^{i - 1} c_{k}) + 1$ to $\sum_{k = 1}^{i} c_{k}$.
With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers u_{i}, v_{i} and x_{i} mean that this way allows moving energy from bacteria with number u_{i} to bacteria with number v_{i} or vice versa for x_{i} dollars.
Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.
As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k × k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.
-----Input-----
The first line contains three integers n, m, k (1 ≤ n ≤ 10^5; 0 ≤ m ≤ 10^5; 1 ≤ k ≤ 500). The next line contains k integers c_1, c_2, ..., c_{k} (1 ≤ c_{i} ≤ n). Each of the next m lines contains three integers u_{i}, v_{i}, x_{i} (1 ≤ u_{i}, v_{i} ≤ 10^5; 0 ≤ x_{i} ≤ 10^4). It is guaranteed that $\sum_{i = 1}^{k} c_{i} = n$.
-----Output-----
If Dima's type-distribution is correct, print string «Yes», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print «No».
-----Examples-----
Input
4 4 2
1 3
2 3 0
3 4 0
2 4 1
2 1 2
Output
Yes
0 2
2 0
Input
3 1 2
2 1
1 2 0
Output
Yes
0 -1
-1 0
Input
3 2 2
2 1
1 2 0
2 3 1
Output
Yes
0 1
1 0
Input
3 0 2
1 2
Output
No
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 sys import stdin
from bisect import bisect_left, bisect_right
INF = int(1e9)
def find(par, a):
if par[a] == a:
return a
par[a] = find(par, par[a])
return par[a]
def union(par, rnk, a, b):
a = find(par,a)
b = find(par,b)
if a==b:
return
if rnk[a]<rnk[b]:
par[a] = b
else:
par[b] = a
if rnk[a]==rnk[b]:
rnk[a] += 1
def solve():
n, m, k = map(int, stdin.readline().split())
cnts = list(map(int, stdin.readline().split()))
for i in range(1,k):
cnts[i] += cnts[i-1]
group = list(range(n))
rnk = [0 for i in range(n)]
adj = [[INF for j in range(k)] for i in range(k)]
for i in range(m):
u, v, x = map(int, stdin.readline().split())
if x==0:
union(group, rnk, u-1, v-1)
tu = bisect_left(cnts, u)
tv = bisect_left(cnts, v)
adj[tu][tv] = min(adj[tu][tv], x)
adj[tv][tu] = min(adj[tv][tu], x)
p = 0
for i in range(k):
cur = group[p]
while p<cnts[i]:
if group[p]!=cur:
print("No")
return
p += 1
print("Yes")
for p in range(k):
for i in range(k):
for j in range(k):
adj[i][j] = min(adj[i][j], adj[i][p]+adj[p][j])
for i in range(k):
adj[i][i] = 0
for j in range(k):
if adj[i][j] == INF:
adj[i][j] = -1
for i in range(k):
print(' '.join(map(lambda x: str(x), adj[i])))
solve()
``` | vfc_15538 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/400/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4 2\n1 3\n2 3 0\n3 4 0\n2 4 1\n2 1 2\n",
"output": "Yes\n0 2\n2 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1447 | Solve the following coding problem using the programming language python:
Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.
The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.
You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.
-----Input-----
First line of the input consists of two integers n and m (1 ≤ n, m ≤ 1000), separated by space — number of cards in each deck, and number of decks.
-----Output-----
On the only line of the output print one floating point number – probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10^{ - 6}.
-----Examples-----
Input
2 2
Output
0.6666666666666666
Input
4 4
Output
0.4000000000000000
Input
1 2
Output
1.0000000000000000
-----Note-----
In the first sample, with probability $\frac{1}{3}$ Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed.
With the remaining $\frac{2}{3}$ probability he took two different cards, and the probability of pulling off the trick is $\frac{1}{2}$.
The resulting probability is $\frac{1}{3} \times 1 + \frac{2}{3} \times \frac{1}{2} = \frac{2}{3}$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
if n == 1:
print(1)
else:
print('{:9}'.format((n-1)/n * (m - 1) / (n*m - 1) + 1 / n))
``` | vfc_15542 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/452/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n",
"output": "0.6666666666666666\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n",
"output": "0.4000000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n",
"output": "1.0000000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n",
"output": "0.5000000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n",
"output": "0.1818181818181818\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1448 | Solve the following coding problem using the programming language python:
Vasya owns a cornfield which can be defined with two integers $n$ and $d$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $(0, d), (d, 0), (n, n - d)$ and $(n - d, n)$.
[Image] An example of a cornfield with $n = 7$ and $d = 2$.
Vasya also knows that there are $m$ grasshoppers near the field (maybe even inside it). The $i$-th grasshopper is at the point $(x_i, y_i)$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
-----Input-----
The first line contains two integers $n$ and $d$ ($1 \le d < n \le 100$).
The second line contains a single integer $m$ ($1 \le m \le 100$) — the number of grasshoppers.
The $i$-th of the next $m$ lines contains two integers $x_i$ and $y_i$ ($0 \le x_i, y_i \le n$) — position of the $i$-th grasshopper.
-----Output-----
Print $m$ lines. The $i$-th line should contain "YES" if the position of the $i$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $i$-th line should contain "NO".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
-----Note-----
The cornfield from the first example is pictured above. Grasshoppers with indices $1$ (coordinates $(2, 4)$) and $4$ (coordinates $(4, 5)$) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices $1$ (coordinates $(4, 4)$), $3$ (coordinates $(8, 1)$) and $4$ (coordinates $(6, 1)$) are inside the cornfield. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, d = list(map(int, input().split()))
for i in range(int(input())):
x, y = list(map(int, input().split()))
print(('YES' if x+y in range(d, n + n - d + 1) and x-y in range(-d, d + 1) else 'NO'));
``` | vfc_15546 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1030/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 2\n4\n2 4\n4 1\n6 3\n4 5\n",
"output": "YES\nNO\nNO\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 7\n4\n4 4\n2 8\n8 1\n6 1\n",
"output": "YES\nNO\nYES\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n13\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2\n0 0\n0 0\n2 2\n2 2\n",
"output": "NO\nYES\nNO\nYES\nYES\nYES\nNO\nYES\nNO\nNO\nNO\nNO\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 1\n32\n0 1\n1 0\n100 99\n99 100\n96 94\n96 95\n96 96\n96 97\n96 98\n30 27\n30 28\n30 29\n30 30\n30 31\n30 32\n30 33\n37 40\n38 40\n39 40\n40 40\n41 40\n42 40\n43 40\n59 62\n60 62\n61 62\n62 62\n63 62\n64 62\n65 62\n100 0\n0 100\n",
"output": "YES\nYES\nYES\nYES\nNO\nYES\nYES\nYES\nNO\nNO\nNO\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nYES\nYES\nYES\nNO\nNO\nNO\nNO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1449 | Solve the following coding problem using the programming language python:
You are given a non-decreasing array of non-negative integers $a_1, a_2, \ldots, a_n$. Also you are given a positive integer $k$.
You want to find $m$ non-decreasing arrays of non-negative integers $b_1, b_2, \ldots, b_m$, such that: The size of $b_i$ is equal to $n$ for all $1 \leq i \leq m$. For all $1 \leq j \leq n$, $a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$. In the other word, array $a$ is the sum of arrays $b_i$. The number of different elements in the array $b_i$ is at most $k$ for all $1 \leq i \leq m$.
Find the minimum possible value of $m$, or report that there is no possible $m$.
-----Input-----
The first line contains one integer $t$ ($1 \leq t \leq 100$): the number of test cases.
The first line of each test case contains two integers $n$, $k$ ($1 \leq n \leq 100$, $1 \leq k \leq n$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$, $a_n > 0$).
-----Output-----
For each test case print a single integer: the minimum possible value of $m$. If there is no such $m$, print $-1$.
-----Example-----
Input
6
4 1
0 0 0 1
3 1
3 3 3
11 3
0 1 2 2 3 3 3 4 4 4 4
5 3
1 2 3 4 5
9 4
2 2 3 5 7 11 13 13 17
10 7
0 1 1 2 3 3 4 5 5 6
Output
-1
1
2
2
2
1
-----Note-----
In the first test case, there is no possible $m$, because all elements of all arrays should be equal to $0$. But in this case, it is impossible to get $a_4 = 1$ as the sum of zeros.
In the second test case, we can take $b_1 = [3, 3, 3]$. $1$ is the smallest possible value of $m$.
In the third test case, we can take $b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$ and $b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$. It's easy to see, that $a_i = b_{1, i} + b_{2, i}$ for all $i$ and the number of different elements in $b_1$ and in $b_2$ is equal to $3$ (so it is at most $3$). It can be proven that $2$ is the smallest possible value of $m$.
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 nbt in range(t):
n,k=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
nbc=len(set(a))-1
if k==1:
if nbc:
print(-1)
else:
print(1)
else:
print(1+max(0,(nbc-1)//(k-1)))
``` | vfc_15550 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1408/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n4 1\n0 0 0 1\n3 1\n3 3 3\n11 3\n0 1 2 2 3 3 3 4 4 4 4\n5 3\n1 2 3 4 5\n9 4\n2 2 3 5 7 11 13 13 17\n10 7\n0 1 1 2 3 3 4 5 5 6\n",
"output": "-1\n1\n2\n2\n2\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4 4\n1 1 1 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 2\n2 2 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 3\n1 1 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2 2\n1 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1450 | Solve the following coding problem using the programming language python:
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves: "010210" $\rightarrow$ "100210"; "010210" $\rightarrow$ "001210"; "010210" $\rightarrow$ "010120"; "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
-----Input-----
The first line of the input contains the string $s$ consisting only of characters '0', '1' and '2', its length is between $1$ and $10^5$ (inclusive).
-----Output-----
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
-----Examples-----
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
pref = []
cnt1 = s.count('1')
s = s.replace('1', '')
i = 0
while i < len(s) and s[i] != '2':
i += 1
end = ''
if i != len(s):
end = s[i:]
s = s[:i] + '1' * cnt1 + end
print(s)
``` | vfc_15554 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1009/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "100210\n",
"output": "001120\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11222121\n",
"output": "11112222\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20\n",
"output": "20\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1002\n",
"output": "0012\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n",
"output": "01\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "000021\n",
"output": "000012\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1451 | Solve the following coding problem using the programming language python:
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.
Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.
-----Input-----
The first line contains two integers n, k (1 ≤ n, k ≤ 100). The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the numbers that Roma has.
The numbers in the lines are separated by single spaces.
-----Output-----
In a single line print a single integer — the answer to the problem.
-----Examples-----
Input
3 4
1 2 4
Output
3
Input
3 2
447 44 77
Output
2
-----Note-----
In the first sample all numbers contain at most four lucky digits, so the answer is 3.
In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = list(map(int, input().split()))
print(sum(s.count('4')+s.count('7')<=k for s in input().split()))
``` | vfc_15558 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/262/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n1 2 4\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1452 | Solve the following coding problem using the programming language python:
Suppose there is a $h \times w$ grid consisting of empty or full cells. Let's make some definitions:
$r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \le i \le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty. $c_{j}$ is the number of consecutive full cells connected to the top end in the $j$-th column ($1 \le j \le w$). In particular, $c_j=0$ if the topmost cell of the $j$-th column is empty.
In other words, the $i$-th row starts exactly with $r_i$ full cells. Similarly, the $j$-th column starts exactly with $c_j$ full cells.
[Image] These are the $r$ and $c$ values of some $3 \times 4$ grid. Black cells are full and white cells are empty.
You have values of $r$ and $c$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $r$ and $c$. Since the answer can be very large, find the answer modulo $1000000007\,(10^{9} + 7)$. In other words, find the remainder after division of the answer by $1000000007\,(10^{9} + 7)$.
-----Input-----
The first line contains two integers $h$ and $w$ ($1 \le h, w \le 10^{3}$) — the height and width of the grid.
The second line contains $h$ integers $r_{1}, r_{2}, \ldots, r_{h}$ ($0 \le r_{i} \le w$) — the values of $r$.
The third line contains $w$ integers $c_{1}, c_{2}, \ldots, c_{w}$ ($0 \le c_{j} \le h$) — the values of $c$.
-----Output-----
Print the answer modulo $1000000007\,(10^{9} + 7)$.
-----Examples-----
Input
3 4
0 3 1
0 2 3 0
Output
2
Input
1 1
0
1
Output
0
Input
19 16
16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12
6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4
Output
797922655
-----Note-----
In the first example, this is the other possible case.
[Image]
In the second example, it's impossible to make a grid to satisfy such $r$, $c$ values.
In the third example, make sure to print answer modulo $(10^9 + 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 defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
H,W = inpl()
rr = inpl()
cc = inpl()
MAP = [[-1]*W for _ in range(H)]
for x,c in enumerate(cc):
for y in range(c):
MAP[y][x] = 1
if c < H:
MAP[c][x] = 0
for y,r in enumerate(rr):
for x in range(r):
if MAP[y][x] == 0:
print(0)
return
MAP[y][x] = 1
if r < W:
if MAP[y][r] == 1:
print(0)
return
MAP[y][r] = 0
cnt = 0
for y in range(H):
for x in range(W):
if MAP[y][x] == -1:
cnt += 1
print(pow(2,cnt,mod))
``` | vfc_15562 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1228/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n0 3 1\n0 2 3 0\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n0\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "19 16\n16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12\n6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4\n",
"output": "797922655\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n2 0 3 1\n1 3 0 3\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 6\n0 0 0\n0 0 0 0 0 0\n",
"output": "1024\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1453 | Solve the following coding problem using the programming language python:
Tsumugi brought $n$ delicious sweets to the Light Music Club. They are numbered from $1$ to $n$, where the $i$-th sweet has a sugar concentration described by an integer $a_i$.
Yui loves sweets, but she can eat at most $m$ sweets each day for health reasons.
Days are $1$-indexed (numbered $1, 2, 3, \ldots$). Eating the sweet $i$ at the $d$-th day will cause a sugar penalty of $(d \cdot a_i)$, as sweets become more sugary with time. A sweet can be eaten at most once.
The total sugar penalty will be the sum of the individual penalties of each sweet eaten.
Suppose that Yui chooses exactly $k$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?
Since Yui is an undecided girl, she wants you to answer this question for every value of $k$ between $1$ and $n$.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le m \le n \le 200\ 000$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 200\ 000$).
-----Output-----
You have to output $n$ integers $x_1, x_2, \ldots, x_n$ on a single line, separed by spaces, where $x_k$ is the minimum total sugar penalty Yui can get if she eats exactly $k$ sweets.
-----Examples-----
Input
9 2
6 19 3 4 4 2 6 7 8
Output
2 5 11 18 30 43 62 83 121
Input
1 1
7
Output
7
-----Note-----
Let's analyze the answer for $k = 5$ in the first example. Here is one of the possible ways to eat $5$ sweets that minimize total sugar penalty: Day $1$: sweets $1$ and $4$ Day $2$: sweets $5$ and $3$ Day $3$ : sweet $6$
Total penalty is $1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $5$ sweets, hence $x_5 = 30$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
ans = [0] * n
prefsum = [0] * m
prefsum[0] = A[0]
ans[0] = A[0]
for i in range(1, n):
ans[i] = ans[i - 1] + prefsum[i % m] + A[i]
prefsum[i % m] += A[i]
print(*ans)
``` | vfc_15566 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1253/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9 2\n6 19 3 4 4 2 6 7 8\n",
"output": "2 5 11 18 30 43 62 83 121\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1454 | Solve the following coding problem using the programming language python:
In this problem, a $n \times m$ rectangular matrix $a$ is called increasing if, for each row of $i$, when go from left to right, the values strictly increase (that is, $a_{i,1}<a_{i,2}<\dots<a_{i,m}$) and for each column $j$, when go from top to bottom, the values strictly increase (that is, $a_{1,j}<a_{2,j}<\dots<a_{n,j}$).
In a given matrix of non-negative integers, it is necessary to replace each value of $0$ with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.
It is guaranteed that in a given value matrix all values of $0$ are contained only in internal cells (that is, not in the first or last row and not in the first or last column).
-----Input-----
The first line contains integers $n$ and $m$ ($3 \le n, m \le 500$) — the number of rows and columns in the given matrix $a$.
The following lines contain $m$ each of non-negative integers — the values in the corresponding row of the given matrix: $a_{i,1}, a_{i,2}, \dots, a_{i,m}$ ($0 \le a_{i,j} \le 8000$).
It is guaranteed that for all $a_{i,j}=0$, $1 < i < n$ and $1 < j < m$ are true.
-----Output-----
If it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1.
-----Examples-----
Input
4 5
1 3 5 6 7
3 0 7 0 9
5 0 0 0 10
8 9 10 11 12
Output
144
Input
3 3
1 2 3
2 0 4
4 5 6
Output
30
Input
3 3
1 2 3
3 0 4
4 5 6
Output
-1
Input
3 3
1 2 3
2 3 4
3 4 2
Output
-1
-----Note-----
In the first example, the resulting matrix is as follows:
1 3 5 6 7
3 6 7 8 9
5 7 8 9 10
8 9 10 11 12
In the second example, the value $3$ must be put in the middle cell.
In the third example, the desired resultant matrix does not exist.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
matr = [list(map(int, input().split())) for _ in range(n)]
for i, st in enumerate(matr):
for j, elem in enumerate(st):
if matr[~i][~j] == 0:
matr[~i][~j] = min(matr[~i + 1][~j], matr[~i][~j + 1]) - 1
# print(*matr, sep='\n')
for i, st in enumerate(matr):
for j, elem in enumerate(st):
if i != 0 and j != 0:
if matr[i][j] <= max(matr[i - 1][j], matr[i][j - 1]):
print('-1')
return
elif i == 0 and j != 0:
if matr[i][j] <= matr[i][j - 1]:
print('-1')
return
elif i != 0 and j == 0:
if matr[i][j] <= matr[i - 1][j]:
print('-1')
return
print(sum(sum(l) for l in matr))
``` | vfc_15570 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1231/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 5\n1 3 5 6 7\n3 0 7 0 9\n5 0 0 0 10\n8 9 10 11 12\n",
"output": "144\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 2 3\n2 0 4\n4 5 6\n",
"output": "30\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1455 | Solve the following coding problem using the programming language python:
Nauuo is a girl who loves playing chess.
One day she invented a game by herself which needs $n$ chess pieces to play on a $m\times m$ chessboard. The rows and columns are numbered from $1$ to $m$. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.
The game's goal is to place $n$ chess pieces numbered from $1$ to $n$ on the chessboard, the $i$-th piece lies on $(r_i,\,c_i)$, while the following rule is satisfied: for all pairs of pieces $i$ and $j$, $|r_i-r_j|+|c_i-c_j|\ge|i-j|$. Here $|x|$ means the absolute value of $x$.
However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.
She wants to find the smallest chessboard on which she can put $n$ pieces according to the rules.
She also wonders how to place the pieces on such a chessboard. Can you help her?
-----Input-----
The only line contains a single integer $n$ ($1\le n\le 1000$) — the number of chess pieces for the game.
-----Output-----
The first line contains a single integer — the minimum value of $m$, where $m$ is the length of sides of the suitable chessboard.
The $i$-th of the next $n$ lines contains two integers $r_i$ and $c_i$ ($1\le r_i,c_i\le m$) — the coordinates of the $i$-th chess piece.
If there are multiple answers, print any.
-----Examples-----
Input
2
Output
2
1 1
1 2
Input
4
Output
3
1 1
1 3
3 1
3 3
-----Note-----
In the first example, you can't place the two pieces on a $1\times1$ chessboard without breaking the rule. But you can place two pieces on a $2\times2$ chessboard like this:
[Image]
In the second example, you can't place four pieces on a $2\times2$ chessboard without breaking the rule. For example, if you place the pieces like this:
[Image]
then $|r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1$, $|1-3|=2$, $1<2$; and $|r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2$, $|1-4|=3$, $2<3$. It doesn't satisfy the rule.
However, on a $3\times3$ chessboard, you can place four pieces like this:
[Image]
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())
m = (n + 2) // 2
d = [0, 1]
print(m)
for i in range(1, n + 1):
if d[0] < m:
d[0] += 1
print(*d)
else:
d[1] += 1
print(*d)
``` | vfc_15574 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1173/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n",
"output": "2\n1 1\n2 1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "3\n1 1\n2 1\n3 1\n3 2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "1\n1 1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "2\n1 1\n2 1\n2 2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "3\n1 1\n2 1\n3 1\n3 2\n3 3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n",
"output": "4\n1 1\n2 1\n3 1\n4 1\n4 2\n4 3",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1456 | Solve the following coding problem using the programming language python:
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.
Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.
Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).
Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 50).
The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: o — in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; x — in this case field (i, j) is attacked by some piece; . — in this case field (i, j) isn't attacked by any piece.
It is guaranteed that there is at least one piece on the board.
-----Output-----
If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n - 1) × (2n - 1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them.
If a valid set of moves does not exist, print a single word 'NO'.
-----Examples-----
Input
5
oxxxx
x...x
x...x
x...x
xxxxo
Output
YES
....x....
....x....
....x....
....x....
xxxxoxxxx
....x....
....x....
....x....
....x....
Input
6
.x.x..
x.x.x.
.xo..x
x..ox.
.x.x.x
..x.x.
Output
YES
...........
...........
...........
....x.x....
...x...x...
.....o.....
...x...x...
....x.x....
...........
...........
...........
Input
3
o.x
oxx
o.x
Output
NO
-----Note-----
In the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.
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(input())
s = [input() for i in range(n)]
a = [[1] * (2 * n) for i in range(2 * n)]
for i in range(n):
for j in range(n):
if s[i][j] != 'o':
continue
for x in range(n):
for y in range(n):
if s[x][y] == '.':
a[n + x - i][n + y - j] = 0
for i in range(n):
for j in range(n):
if s[i][j] != 'x':
continue
c = 0
for x in range(n):
for y in range(n):
if s[x][y] == 'o' and a[n + i - x][n + j - y] == 1:
c = 1
break
if c == 1:
break
if c == 0:
print('NO')
return
print('YES')
for i in range(1, 2 * n):
for j in range(1, 2 * n):
if i == n and j == n:
print('o', end='')
elif a[i][j] == 1:
print('x', end='')
else:
print('.', end='')
print('')
``` | vfc_15578 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/538/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\noxxxx\nx...x\nx...x\nx...x\nxxxxo\n",
"output": "YES\nxxxxxxxxx\nx...xxxxx\nx...xxxxx\nx...xxxxx\nxxxxoxxxx\nxxxxx...x\nxxxxx...x\nxxxxx...x\nxxxxxxxxx\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n.x.x..\nx.x.x.\n.xo..x\nx..ox.\n.x.x.x\n..x.x.\n",
"output": "YES\nxxxxxxxxxxx\nxxxxxxxxxxx\nxx.x.x..xxx\nxxx.x.x..xx\nxx.x...x.xx\nxxx..o..xxx\nxx.x...x.xx\nxx..x.x.xxx\nxxx..x.x.xx\nxxxxxxxxxxx\nxxxxxxxxxxx\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\no.x\noxx\no.x\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\no\n",
"output": "YES\no\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nox\n.o\n",
"output": "YES\nxxx\n.ox\nx.x\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n.xxo.\n..oxo\nx.oxo\no..xo\noooox\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1457 | Solve the following coding problem using the programming language python:
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.
This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.
Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.
Substring is a continuous subsequence of a string.
-----Input-----
The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.
-----Output-----
Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.
-----Examples-----
Input
intellect
tell
Output
1
Input
google
apple
Output
0
Input
sirisiri
sir
Output
2
-----Note-----
In the first sample AI's name may be replaced with "int#llect".
In the second sample Gogol can just keep things as they are.
In the third sample one of the new possible names of AI may be "s#ris#ri".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
a = str(input())
b = str(input())
print(a.count(b))
def __starting_point():
main()
__starting_point()
``` | vfc_15582 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/625/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "intellect\ntell\n",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "google\napple\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "sirisiri\nsir\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "sirisiri\nsiri\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaaaaaa\naaaa\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1458 | Solve the following coding problem using the programming language python:
You are given a string $s$ consisting of $n$ lowercase Latin letters.
Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $3$ and ends in position $6$), but "aa" or "d" aren't substrings of this string. So the substring of the string $s$ from position $l$ to position $r$ is $s[l; r] = s_l s_{l + 1} \dots s_r$.
You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $s[l; r] = s_r s_{r - 1} \dots s_l$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.
If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.
String $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x \ne y$), or there exists such $i$ ($1 \le i \le min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \le j < i$) $x_j = y_j$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the length of $s$.
The second line of the input contains the string $s$ of length $n$ consisting only of lowercase Latin letters.
-----Output-----
If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $l$ and $r$ ($1 \le l < r \le n$) denoting the substring you have to reverse. If there are multiple answers, you can print any.
-----Examples-----
Input
7
abacaba
Output
YES
2 5
Input
6
aabcfg
Output
NO
-----Note-----
In the first testcase the resulting string is "aacabba".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
s = input()
for i in range(len(s) - 1):
if s[i] > s[i + 1]:
print("YES")
print(i + 1, i + 2)
return
print("NO")
``` | vfc_15586 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1155/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\nabacaba\n",
"output": "YES\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\naabcfg\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "12\nparapapapaaa\n",
"output": "YES\n1 2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1459 | Solve the following coding problem using the programming language python:
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
d_1 is the distance between the 1-st and the 2-nd station;
d_2 is the distance between the 2-nd and the 3-rd station;
...
d_{n} - 1 is the distance between the n - 1-th and the n-th station;
d_{n} is the distance between the n-th and the 1-st station.
The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.
-----Input-----
The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d_1, d_2, ..., d_{n} (1 ≤ d_{i} ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same.
The numbers in the lines are separated by single spaces.
-----Output-----
Print a single number — the length of the shortest path between stations number s and t.
-----Examples-----
Input
4
2 3 4 9
1 3
Output
5
Input
4
5 8 2 100
4 1
Output
15
Input
3
1 1 1
3 1
Output
1
Input
3
31 41 59
1 1
Output
0
-----Note-----
In the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.
In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.
In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.
In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def calc_shortest(N, D, s1, s2):
#D[1:3] = D[1]+D[2] = d_2+d_3 = distance between Station 2 and Station 4
if s1 == s2:
return 0
elif s1 < s2:
s1_index = s1-1
s2_index = s2-1
else:
s1_index = s2-1
s2_index = s1-1
#print("s1:"+str(s1_index)+" s2:"+str(s2_index))
path1 = sum(D[s1_index:s2_index])
path2 = sum(D)-path1
if path1 < path2:
return path1
else:
return path2
N = [int(i) for i in input().strip().split()][0]
D = [int(i) for i in input().strip().split()]
s1, s2 = [int(i) for i in input().strip().split()]
print(calc_shortest(N, D, s1, s2))
return
``` | vfc_15590 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/278/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n2 3 4 9\n1 3\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n5 8 2 100\n4 1\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 1 1\n3 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n31 41 59\n1 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n16 13 10 30 15\n4 2\n",
"output": "23\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1460 | Solve the following coding problem using the programming language python:
Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.
To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied:
The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side).
Each gray cell has an even number of gray neighbours.
There are exactly $n$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).
Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $n$. Help him, and provide any example of a beautiful picture.
To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $(0, 0)$, axes $0x$ and $0y$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.
-----Input-----
The only line contains a single integer $n$ ($1 \leq n \leq 500$) — the number of gray cells with all gray neighbours in a beautiful picture.
-----Output-----
In the first line, print a single integer $k$ — the number of gray cells in your picture. For technical reasons, $k$ should not exceed $5 \cdot 10^5$.
Each of the following $k$ lines should contain two integers — coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $10^9$ by absolute value.
One can show that there exists an answer satisfying all requirements with a small enough $k$.
-----Example-----
Input
4
Output
12
1 0
2 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
1 3
2 3
-----Note-----
The answer for the sample is pictured below:
[Image]
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())
print(n*3+4)
print(0, 0)
print(1, 0)
for i in range(n):
for j in range(3):
print(i+j, i+1)
print(n, n+1)
print(n+1, n+1)
``` | vfc_15594 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1368/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n",
"output": "16\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n2 3\n3 2\n3 3\n3 4\n4 3\n4 4\n4 5\n5 4\n5 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "7\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "10\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n2 3\n3 2\n3 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "13\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n2 3\n3 2\n3 3\n3 4\n4 3\n4 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "19\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n2 3\n3 2\n3 3\n3 4\n4 3\n4 4\n4 5\n5 4\n5 5\n5 6\n6 5\n6 6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "17\n",
"output": "55\n0 0\n0 1\n1 0\n1 1\n1 2\n2 1\n2 2\n2 3\n3 2\n3 3\n3 4\n4 3\n4 4\n4 5\n5 4\n5 5\n5 6\n6 5\n6 6\n6 7\n7 6\n7 7\n7 8\n8 7\n8 8\n8 9\n9 8\n9 9\n9 10\n10 9\n10 10\n10 11\n11 10\n11 11\n11 12\n12 11\n12 12\n12 13\n13 12\n13 13\n13 14\n14 13\n14 14\n14 15\n15 14\n15 15\n15 16\n16 15\n16 16\n16 17\n17 16\n17 17\n17 18\n18 17\n18 18\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1461 | Solve the following coding problem using the programming language python:
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f_0, f_1, ..., f_{n} - 1, where f_{i} — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w_0, w_1, ..., w_{n} - 1, where w_{i} — the arc weight from i to f_{i}. [Image] The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers s_{i} and m_{i}, where: s_{i} — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i; m_{i} — the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
-----Input-----
The first line contains two integers n, k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^10). The second line contains the sequence f_0, f_1, ..., f_{n} - 1 (0 ≤ f_{i} < n) and the third — the sequence w_0, w_1, ..., w_{n} - 1 (0 ≤ w_{i} ≤ 10^8).
-----Output-----
Print n lines, the pair of integers s_{i}, m_{i} in each line.
-----Examples-----
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
g = {}
def push(u, v, w):
g[u] = [v, w]
n, pos = list(map(int, input().split()))
V = list(map(int, input().split()))
W = list(map(int, input().split()))
for _ in range(n):
push(_, V[_], W[_])
max_log = 35
next_n = [[-1] * n for _ in range(max_log)]
next_m = [[float('inf')] * n for _ in range(max_log)]
next_s = [[0] * n for _ in range(max_log)]
for u in range(n):
v, w = g[u]
next_n[0][u] = v
next_m[0][u] = w
next_s[0][u] = w
for k in range(1, max_log):
for u in range(n):
v = next_n[k-1][u]
m = next_m[k-1][u]
s = next_s[k-1][u]
next_n[k][u] = next_n[k-1][v]
next_m[k][u] = min(next_m[k-1][v], m)
next_s[k][u] = next_s[k-1][v] + s
m_arr = [float('inf')] * n
s_arr = [0] * n
for _ in range(n):
s, m = 0, float('inf')
v = _
cur = 1<<max_log
i = max_log
while cur > 0:
if cur & pos:
m = min(m, next_m[i][v])
s = s + next_s[i][v]
v = next_n[i][v]
cur >>= 1
i -= 1
m_arr[_] = m
s_arr[_] = s
arr = [str(x) + ' ' + str(y) for x, y in zip(s_arr, m_arr)]
print('\n'.join([x for x in arr]))
``` | vfc_15598 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/702/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 3\n1 2 3 4 3 2 6\n6 3 1 4 2 2 3\n",
"output": "10 1\n8 1\n7 1\n10 2\n8 2\n7 1\n9 3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1462 | Solve the following coding problem using the programming language python:
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.
Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
-----Input-----
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 10^5). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.
-----Output-----
Print a single integer – the answer to the problem.
-----Examples-----
Input
15 10
DZFDFZDFDDDDDDF
Output
82
Input
6 4
YJSNPI
Output
4
-----Note-----
In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
arr = [0] * 26
s = input()
aux = ord('A')
for i in range(len(s)):
arr[ord(s[i]) - aux] += 1
arr.sort(reverse = True)
i = 0
sum = 0
while k > 0:
if arr[i] >= k:
sum += k ** 2
k = 0
else:
k -= arr[i]
sum += arr[i] ** 2
i += 1
print(sum)
``` | vfc_15602 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/462/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "15 10\nDZFDFZDFDDDDDDF\n",
"output": "82\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 4\nYJSNPI\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\nAOWBY\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\nV\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\nWT\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\nBL\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1463 | Solve the following coding problem using the programming language python:
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every x, y such that 1 ≤ x, y ≤ n and a_{x}, y ≠ 1, there should exist two indices s and t so that a_{x}, y = a_{x}, s + a_{t}, y, where a_{i}, j denotes the integer in i-th row and j-th column.
Help Okabe determine whether a given lab is good!
-----Input-----
The first line of input contains the integer n (1 ≤ n ≤ 50) — the size of the lab.
The next n lines contain n space-separated integers denoting a row of the grid. The j-th integer in the i-th row is a_{i}, j (1 ≤ a_{i}, j ≤ 10^5).
-----Output-----
Print "Yes" if the given lab is good and "No" otherwise.
You can output each letter in upper or lower case.
-----Examples-----
Input
3
1 1 2
2 3 1
6 4 1
Output
Yes
Input
3
1 5 2
1 1 1
1 2 3
Output
No
-----Note-----
In the first sample test, the 6 in the bottom left corner is valid because it is the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this table, so the answer is "Yes".
In the second sample test, the 5 cannot be formed as the sum of an integer in the same row and an integer in the same column. Thus the answer is "No".
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())
table = []
for i in range(N):
table.append(list(map(int, input().split())))
for i in range(N):
for j in range(N):
if table[i][j] == 1:
continue
flg = False
for s in range(N):
for t in range(N):
if table[i][j] == table[i][s] + table[t][j]:
flg = True
break
if not flg:
print("No")
return
print("Yes")
``` | vfc_15606 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/821/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 1 2\n2 3 1\n6 4 1\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 5 2\n1 1 1\n1 2 3\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "Yes\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1464 | Solve the following coding problem using the programming language python:
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems.
You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s_1s_2... s_{|}s| (where |s| is the length of string s) is string s_{l}s_{l} + 1... s_{r}.
String x = x_1x_2... x_{p} is lexicographically smaller than string y = y_1y_2... y_{q}, if either p < q and x_1 = y_1, x_2 = y_2, ... , x_{p} = y_{p}, or there exists such number r (r < p, r < q), that x_1 = y_1, x_2 = y_2, ... , x_{r} = y_{r} and x_{r} + 1 < y_{r} + 1. The string characters are compared by their ASCII codes.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 30) — the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.
-----Output-----
Print a string, consisting of lowercase English letters — the lexicographically minimum shortest original title.
-----Examples-----
Input
5
threehorses
goodsubstrings
secret
primematrix
beautifulyear
Output
j
Input
4
aa
bdefghijklmn
opqrstuvwxyz
c
Output
ab
-----Note-----
In the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.
In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import re
import itertools
from collections import Counter
class Task:
strings = []
answer = ""
def getData(self):
numberOfStrings = int(input())
for i in range(0, numberOfStrings):
self.strings += [input()]
def solve(self):
badStrings = set()
for current in self.strings:
for left in range(0, len(current)):
for right in range(left + 1, len(current) + 1):
badStrings.add(current[left : right])
alphabet = []
for character in range(ord('a'), ord('z') + 1):
alphabet += [chr(character)]
for answerLength in range(1, 21 + 1):
for p in itertools.product(alphabet, repeat = answerLength):
string = re.sub("[^\w]", "", str(p));
if string not in badStrings:
self.answer = string
return
def printAnswer(self):
print(self.answer)
task = Task();
task.getData();
task.solve();
task.printAnswer();
``` | vfc_15610 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/278/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear\n",
"output": "j\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1465 | Solve the following coding problem using the programming language python:
There are $n$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number $n$, the initial arrangement of children and the number $k$. You have to find a way for the children to act if they want to finish the process in exactly $k$ seconds. More formally, for each of the $k$ moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and $k = 2$ children can do the following steps: [Image] At the beginning, two pairs make move: $(1, 2)$ and $(3, 4)$. After that, we receive the following configuration: [Image] At the second move pair $(2, 3)$ makes the move. The final configuration is reached. Good job. [Image]
It is guaranteed that if the solution exists, it takes not more than $n^2$ "headturns".
-----Input-----
The first line of input contains two integers $n$ and $k$ ($2 \le n \le 3000$, $1 \le k \le 3000000$) — the number of children and required number of moves.
The next line contains a string of length $n$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
-----Output-----
If there is no solution, print a single line with number $-1$.
Otherwise, output $k$ lines. Each line has to start with a number $n_i$ ($1\le n_i \le \frac{n}{2}$) — the number of pairs of children, who turn at this move. After that print $n_i$ distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
-----Examples-----
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
-----Note-----
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in $k>0$ moves.
The third configuration is described 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
n,k=map(int,input().split())
a=list(input())
ans,cnt=list(list()),0
while True :
cur=list()
for i in range(n-1) :
if a[i]=='R' and a[i+1]=='L' :
cur.append(i)
cnt+=1
if len(cur)>0:
ans.append(cur.copy())
for i in cur :
a[i],a[i+1]=a[i+1],a[i]
else :
break
if len(ans)>k or cnt<k:
print(-1)
else :
lst=list()
dumb=k-len(ans)
w,p=0,0
while dumb>0 :
lst.append("1 "+str(ans[w][p]+1)+"\n")
dumb-=1
p+=1
if p==len(ans[w]) :
p=0
w+=1
dumb+=1
while w<len(ans) :
lst.append(str(len(ans[w])-p)+" ")
while p<len(ans[w]) :
lst.append(str(ans[w][p]+1)+" ")
p+=1
lst.append("\n")
w+=1
p=0
print("".join(lst))
``` | vfc_15614 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1333/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 1\nRL\n",
"output": "1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\nLR\n",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\nRLRL\n",
"output": "2 1 3 \n1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\nRRL\n",
"output": "1 2 \n1 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1466 | Solve the following coding problem using the programming language python:
You are given an undirected connected weighted graph consisting of $n$ vertices and $m$ edges. Let's denote the length of the shortest path from vertex $1$ to vertex $i$ as $d_i$.
You have to erase some edges of the graph so that at most $k$ edges remain. Let's call a vertex $i$ good if there still exists a path from $1$ to $i$ with length $d_i$ after erasing the edges.
Your goal is to erase the edges in such a way that the number of good vertices is maximized.
-----Input-----
The first line contains three integers $n$, $m$ and $k$ ($2 \le n \le 3 \cdot 10^5$, $1 \le m \le 3 \cdot 10^5$, $n - 1 \le m$, $0 \le k \le m$) — the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively.
Then $m$ lines follow, each containing three integers $x$, $y$, $w$ ($1 \le x, y \le n$, $x \ne y$, $1 \le w \le 10^9$), denoting an edge connecting vertices $x$ and $y$ and having weight $w$.
The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).
-----Output-----
In the first line print $e$ — the number of edges that should remain in the graph ($0 \le e \le k$).
In the second line print $e$ distinct integers from $1$ to $m$ — the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.
-----Examples-----
Input
3 3 2
1 2 1
3 2 1
1 3 3
Output
2
1 2
Input
4 5 2
4 1 8
2 4 1
2 1 3
3 4 9
3 1 5
Output
2
3 2
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, defaultdict
import heapq
from sys import stdin, stdout
raw_input = stdin.readline
xrange=range
n,m,k=list(map(int,input().split()))
k=min(n-1,k)
p=[0]*(n+1)
vis = [0]*(n+1)
d=[[] for i in range(n+1)]
ans=[]
dp={}
for i in range(m):
u,v,w=list(map(int,input().split()))
d[u].append((v,w))
d[v].append((u,w))
dp[(u,v)]=i+1
dp[(v,u)]=i+1
q=[(0,1,1)]
c=0
while q:
wt,x,par=heapq.heappop(q)
if vis[x]:
continue
vis[x]=1
c+=1
if par!=x:
ans.append(str(dp[(par,x)]))
if c>k:
break
for i,w in d[x]:
if not vis[i]:
heapq.heappush(q,(wt+w,i,x))
print(len(ans))
print(' '.join(ans))
``` | vfc_15618 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1076/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3 2\n1 2 1\n3 2 1\n1 3 3\n",
"output": "2\n1 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5 2\n4 1 8\n2 4 1\n2 1 3\n3 4 9\n3 1 5\n",
"output": "2\n3 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 4\n1 2 999999999\n2 3 999999999\n3 4 999999999\n1 5 999999999\n5 4 999999999\n",
"output": "4\n1 4 2 5 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5 0\n4 1 8\n2 4 1\n2 1 3\n3 4 9\n3 1 5\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1467 | Solve the following coding problem using the programming language python:
You are given an array $a_1, a_2, \dots, a_n$ of integer numbers.
Your task is to divide the array into the maximum number of segments in such a way that:
each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $0$.
Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the array.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$).
-----Output-----
Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists.
-----Examples-----
Input
4
5 5 7 2
Output
2
Input
3
1 2 3
Output
-1
Input
3
3 1 10
Output
3
-----Note-----
In the first example $2$ is the maximum number. If you divide the array into $\{[5], [5, 7, 2]\}$, the XOR value of the subset of only the second segment is $5 \oplus 7 \oplus 2 = 0$. $\{[5, 5], [7, 2]\}$ has the value of the subset of only the first segment being $5 \oplus 5 = 0$. However, $\{[5, 5, 7], [2]\}$ will lead to subsets $\{[5, 5, 7]\}$ of XOR $7$, $\{[2]\}$ of XOR $2$ and $\{[5, 5, 7], [2]\}$ of XOR $5 \oplus 5 \oplus 7 \oplus 2 = 5$.
Let's take a look at some division on $3$ segments — $\{[5], [5, 7], [2]\}$. It will produce subsets:
$\{[5]\}$, XOR $5$; $\{[5, 7]\}$, XOR $2$; $\{[5], [5, 7]\}$, XOR $7$; $\{[2]\}$, XOR $2$; $\{[5], [2]\}$, XOR $7$; $\{[5, 7], [2]\}$, XOR $0$; $\{[5], [5, 7], [2]\}$, XOR $5$;
As you can see, subset $\{[5, 7], [2]\}$ has its XOR equal to $0$, which is unacceptable. You can check that for other divisions of size $3$ or $4$, non-empty subset with $0$ XOR always exists.
The second example has no suitable divisions.
The third example array can be divided into $\{[3], [1], [10]\}$. No subset of these segments has its XOR equal to $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
from math import *
from fractions import gcd
readints=lambda:list(map(int, input().strip('\n').split()))
n=int(input())
arr = list(readints())
pref=0
basis=[]
for v in arr:
pref = pref^v
for b in basis:
v = min(v, v^b)
if v>0:
basis.append(v)
if pref==0:
print(-1)
else:
print(len(basis))
``` | vfc_15622 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1101/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n5 5 7 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1468 | Solve the following coding problem using the programming language python:
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.
The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).
Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now.
Each of the next n lines contains exactly one hashtag of positive length.
It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.
-----Output-----
Print the resulting hashtags in any of the optimal solutions.
-----Examples-----
Input
3
#book
#bigtown
#big
Output
#b
#big
#big
Input
3
#book
#cool
#cold
Output
#book
#co
#cold
Input
4
#car
#cart
#art
#at
Output
#
#
#art
#at
Input
3
#apple
#apple
#fruit
Output
#apple
#apple
#fruit
-----Note-----
Word a_1, a_2, ..., a_{m} of length m is lexicographically not greater than word b_1, b_2, ..., b_{k} of length k, if one of two conditions hold: at first position i, such that a_{i} ≠ b_{i}, the character a_{i} goes earlier in the alphabet than character b_{i}, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal.
The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.
For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.
According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def sortHashtags(htags):
def shorten(j, i):
s = 0
while s < len(htags[i]) and htags[i][s] == htags[j][s]:
s += 1
htags[j] = htags[j][:s]
n = len(htags)
for i in range(n-1, 0, -1):
if htags[i-1] > htags[i]:
shorten(i-1, i)
return '\n'.join(htags)
n = int(input())
tags = []
for i in range(n):
tags.append(input())
print(sortHashtags(tags))
``` | vfc_15626 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/777/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n#book\n#bigtown\n#big\n",
"output": "#b\n#big\n#big\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n#book\n#cool\n#cold\n",
"output": "#book\n#co\n#cold\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n#car\n#cart\n#art\n#at\n",
"output": "#\n#\n#art\n#at\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n#apple\n#apple\n#fruit\n",
"output": "#apple\n#apple\n#fruit\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n#h\n",
"output": "#h\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1473 | Solve the following coding problem using the programming language python:
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
-----Input-----
The first line contains integer n (2 ≤ n ≤ 2·10^5) — the number of students in the queue.
Then n lines follow, i-th line contains the pair of integers a_{i}, b_{i} (0 ≤ a_{i}, b_{i} ≤ 10^6), where a_{i} is the ID number of a person in front of a student and b_{i} is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.
The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.
-----Output-----
Print a sequence of n integers x_1, x_2, ..., x_{n} — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.
-----Examples-----
Input
4
92 31
0 7
31 0
7 141
Output
92 7 31 141
-----Note-----
The picture illustrates the queue for the first sample. [Image]
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())
d={}
d1={}
for i in range(n):
a,b=list(map(int,input().split()))
d[a]=b
d1[b]=a
r=[0]*n
front=0
i=1
while i<n:
r[i] = d.get(front)
front = r[i]
i += 2
for f in list(d.keys()):
if d1.get(f) == None:
front = f
break
r[0]=front
i=2
while i<n:
r[i] = d.get(front)
front = r[i]
i += 2
print(*r)
``` | vfc_15646 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/490/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n92 31\n0 7\n31 0\n7 141\n",
"output": "92 7 31 141 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1474 | Solve the following coding problem using the programming language python:
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is h_{i}.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (10^9 + 7).
-----Input-----
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.
The second line contains n space-separated numbers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9), where h_{i} equals the height of the i-th board to the left.
-----Output-----
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
-----Examples-----
Input
2
1 1
Output
0
Input
3
3 4 2
Output
13
-----Note-----
From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.
All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part): [Image]
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 = int(input())
h = list([int(x) - 1 for x in input().split()])
ans = x = 0
for i in range(n):
ans += h[i] + min(h[i], h[i - 1]) * x
if i < n - 1:
x *= min(h[i - 1], h[i], h[i + 1])
x += min(h[i], h[i + 1])
ans %= mod
x %= mod
print(ans)
``` | vfc_15650 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/659/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3 4 2\n",
"output": "13\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1475 | Solve the following coding problem using the programming language python:
There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second block, he gets the integer 12.
Wet Shark then takes this number modulo x. Please, tell him how many ways he can choose one digit from each block so that he gets exactly k as the final result. As this number may be too large, print it modulo 10^9 + 7.
Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are 3 ways to choose digit 5 from block 3 5 6 7 8 9 5 1 1 1 1 5.
-----Input-----
The first line of the input contains four space-separated integers, n, b, k and x (2 ≤ n ≤ 50 000, 1 ≤ b ≤ 10^9, 0 ≤ k < x ≤ 100, x ≥ 2) — the number of digits in one block, the number of blocks, interesting remainder modulo x and modulo x itself.
The next line contains n space separated integers a_{i} (1 ≤ a_{i} ≤ 9), that give the digits contained in each block.
-----Output-----
Print the number of ways to pick exactly one digit from each blocks, such that the resulting integer equals k modulo x.
-----Examples-----
Input
12 1 5 10
3 5 6 7 8 9 5 1 1 1 1 5
Output
3
Input
3 2 1 2
6 2 2
Output
0
Input
3 2 1 2
3 1 2
Output
6
-----Note-----
In the second sample possible integers are 22, 26, 62 and 66. None of them gives the remainder 1 modulo 2.
In the third sample integers 11, 13, 21, 23, 31 and 33 have remainder 1 modulo 2. There is exactly one way to obtain each of these integers, so the total 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
p = 10 ** 9 + 7
n, b, k, x = [int(s) for s in input().split()]
block = [int(s) for s in input().split()]
D = [0 for i in range(10)]
for s in block:
D[s] += 1
A = [[0 for t in range(x)]]
pows = [pow(10, 1<<j, x) for j in range(b.bit_length())]
for i in range(10):
A[0][i%x] += D[i]
for j in range(b.bit_length()-1):
B = A[-1]
C = [sum(B[i]*B[(t - i*pows[j])%x] for i in range(x)) % p for t in range(x)]
A.append(C)
ans = None
for j in range(b.bit_length()):
if (b>>j)&1:
if ans is None:
ans = A[j][:]
else:
ans = [sum(A[j][(t - i*pows[j])%x]*ans[i] for i in range(x)) % p for t in range(x)]
print(ans[k])
``` | vfc_15654 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/621/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "12 1 5 10\n3 5 6 7 8 9 5 1 1 1 1 5\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 1 2\n6 2 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 1 2\n3 1 2\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 1 2\n6 3 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 1 2\n3 6 3\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 0 2\n3 3 9\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1476 | Solve the following coding problem using the programming language python:
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
-----Input-----
A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.
-----Output-----
In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.
In the second line print k distinct integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ n), where a_{i} is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |a_{i} - a_{i} + 1| ≠ 1 for all i from 1 to k - 1.
If there are several possible answers, output any of them.
-----Examples-----
Input
6
Output
6
1 5 3 6 2 4
Input
3
Output
2
1 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
if n >= 5:
print(n)
for i in range(1, n + 1, 2):
print(i, end = ' ')
for i in range(2, n + 1, 2):
print(i, end = ' ')
elif n == 4:
print(4)
print(3, 1, 4, 2)
elif n == 3:
print(2)
print(1, 3)
else:
print(1)
print(1)
``` | vfc_15658 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/534/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n",
"output": "6\n5 3 1 6 4 2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "2\n1 3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "1\n1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "1\n1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "4\n3 1 4 2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1477 | Solve the following coding problem using the programming language python:
You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.
Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.
Find the minimal number of coprocessor calls which are necessary to execute the given program.
-----Input-----
The first line contains two space-separated integers N (1 ≤ N ≤ 10^5) — the total number of tasks given, and M (0 ≤ M ≤ 10^5) — the total number of dependencies between tasks.
The next line contains N space-separated integers $E_{i} \in \{0,1 \}$. If E_{i} = 0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor.
The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T_1 and T_2 and means that task T_1 depends on task T_2 (T_1 ≠ T_2). Tasks are indexed from 0 to N - 1. All M pairs (T_1, T_2) are distinct. It is guaranteed that there are no circular dependencies between tasks.
-----Output-----
Output one line containing an integer — the minimal number of coprocessor calls necessary to execute the program.
-----Examples-----
Input
4 3
0 1 0 1
0 1
1 2
2 3
Output
2
Input
4 3
1 1 1 0
0 1
0 2
3 0
Output
1
-----Note-----
In the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -> 2 -> 1 -> 0. You have to call coprocessor twice: first you call it for task 3, then you execute task 2 on the main processor, then you call it for for task 1, and finally you execute task 0 on the main processor.
In the second test, tasks 0, 1 and 2 can only be executed on the coprocessor. Tasks 1 and 2 have no dependencies, and task 0 depends on tasks 1 and 2, so all three tasks 0, 1 and 2 can be sent in one coprocessor call. After that task 3 is executed on the main processor.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = (int(x) for x in input().strip().split())
coproc = [int(x) for x in input().strip().split()]
edges = []
for _ in range(m):
edges.append((int(x) for x in input().strip().split()))
inorder = [0] * n
adj = [[] for _ in range(n)]
for u, v in edges:
adj[v].append(u)
inorder[u] += 1
queue0 = [u for u in range(n) if inorder[u]==0 and not coproc[u]]
queue1 = [u for u in range(n) if inorder[u]==0 and coproc[u]]
res = 0
while len(queue0)>0 or len(queue1)>0:
while queue0:
next0 = []
for u in queue0:
for v in adj[u]:
inorder[v] -= 1
if inorder[v] == 0:
if coproc[v]:
queue1.append(v)
else:
next0.append(v)
queue0 = next0
if queue1:
res += 1 # coproc call
while queue1:
next1 = []
for u in queue1:
for v in adj[u]:
inorder[v] -= 1
if inorder[v] == 0:
if coproc[v]:
next1.append(v)
else:
queue0.append(v)
queue1 = next1
print(res)
``` | vfc_15662 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/909/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n0 1 0 1\n0 1\n1 2\n2 3\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n1 1 1 0\n0 1\n0 2\n3 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 39\n0 1 0 1 0 1 1 0 1 1\n0 1\n0 2\n0 3\n0 4\n0 5\n0 6\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n3 4\n3 6\n3 7\n3 8\n3 9\n4 5\n4 6\n4 7\n4 9\n5 6\n5 7\n5 8\n5 9\n6 8\n6 9\n7 8\n7 9\n8 9\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 16\n0 1 1 0 0 1 1 0 0 1\n0 2\n0 3\n1 2\n1 3\n2 4\n2 5\n3 4\n3 5\n4 6\n4 7\n5 6\n5 7\n6 8\n6 9\n7 8\n7 9\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\n0\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1478 | Solve the following coding problem using the programming language python:
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.
Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.
When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: at first, the text of the comment is written; after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). All elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma.
For example, if the comments look like: [Image]
then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: at first, print a integer d — the maximum depth of nesting comments; after that print d lines, the i-th of them corresponds to nesting level i; for the i-th row print comments of nesting level i in the order of their appearance in the Policarp's comments feed, separated by space.
-----Input-----
The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas.
It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros.
The length of the whole string does not exceed 10^6. It is guaranteed that given structure of comments is valid.
-----Output-----
Print comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input.
-----Examples-----
Input
hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0
Output
3
hello test one
ok bye two
a b
Input
a,5,A,0,a,0,A,0,a,0,A,0
Output
2
a
A a A a A
Input
A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0
Output
4
A K M
B F H L N O
C D G I P
E J
-----Note-----
The first example is explained in the statements.
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
stuff=input().split(",")
n=len(stuff)
comm=[[] for _ in range(1000001)]
st=[1000001]
for i in range(0,n,2):
while st[-1]==0: st.pop(-1)
comm[len(st)].append(stuff[i])
st[-1]-=1
st.append(int(stuff[i+1]))
maxd=0
for i in range(1000000,0,-1):
if len(comm[i]):
maxd=i
break
print(maxd)
for i in range(1,maxd+1):
print(" ".join(comm[i]))
``` | vfc_15666 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/747/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\n",
"output": "3\nhello test one \nok bye two \na b \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a,5,A,0,a,0,A,0,a,0,A,0\n",
"output": "2\na \nA a A a A \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1479 | Solve the following coding problem using the programming language python:
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. [Image]
The park can be represented as a rectangular n × m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.
Om Nom isn't yet sure where to start his walk from but he definitely wants: to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).
We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.
Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.
-----Input-----
The first line contains three integers n, m, k (2 ≤ n, m ≤ 2000; 0 ≤ k ≤ m(n - 1)).
Each of the next n lines contains m characters — the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down).
It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders.
-----Output-----
Print m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right.
-----Examples-----
Input
3 3 4
...
R.L
R.U
Output
0 2 2
Input
2 2 2
..
RL
Output
1 1
Input
2 2 2
..
LR
Output
0 0
Input
3 4 8
....
RRLL
UUUU
Output
1 3 3 1
Input
2 2 2
..
UU
Output
0 0
-----Note-----
Consider the first sample. The notes below show how the spider arrangement changes on the field over time:
... ... ..U ...
R.L -> .*U -> L.R -> ...
R.U .R. ..R ...
Character "*" represents a cell that contains two spiders at the same time. If Om Nom starts from the first cell of the first row, he won't see any spiders. If he starts from the second cell, he will see two spiders at time 1. If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m, k = list(map(int, str.split(input())))
f = tuple([str.strip(input()) for _ in range(n)])
r = []
for x in range(m):
cr = sum([f[y][x] == "U" for y in range(0, n, 2)])
for cx in range(max(0, x + 1 - n), x):
cr += f[x - cx][cx] == "R"
for cx in range(x + 1, min(m, n + x)):
cr += f[cx - x][cx] == "L"
r.append(cr)
print(str.join(" ", list(map(str, r))))
``` | vfc_15670 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/436/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3 4\n...\nR.L\nR.U\n",
"output": "0 2 2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1480 | Solve the following coding problem using the programming language python:
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out a_{i} people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.
For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and a_{i} = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.
You have to write a program which prints the number of the child to be eliminated on every step.
-----Input-----
The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1).
The next line contains k integer numbers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.
-----Examples-----
Input
7 5
10 4 11 4 1
Output
4 2 5 6 1
Input
3 2
2 5
Output
3 2
-----Note-----
Let's consider first example: In the first step child 4 is eliminated, child 5 becomes the leader. In the second step child 2 is eliminated, child 3 becomes the leader. In the third step child 5 is eliminated, child 6 becomes the leader. In the fourth step child 6 is eliminated, child 7 becomes the leader. In the final step child 1 is eliminated, child 3 becomes the leader.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
aa = [int(x) for x in input().split()]
nxt = [(i + 1) % n for i in range(n)]
prv = [(i - 1 + n) % n for i in range(n)]
cur = 0
for z in range(k):
a = aa[z]
a %= n
for i in range(a):
cur = nxt[cur]
nxt[prv[cur]] = nxt[cur]
prv[nxt[cur]] = prv[cur]
print(cur + 1, end=' ')
cur = nxt[cur]
n -= 1
``` | vfc_15674 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/792/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 5\n10 4 11 4 1\n",
"output": "4 2 5 6 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n2 5\n",
"output": "3 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1\n",
"output": "2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n2\n",
"output": "1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1481 | Solve the following coding problem using the programming language python:
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
-----Output-----
Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
-----Examples-----
Input
3
xxo
xox
oxx
Output
YES
Input
4
xxxo
xoxo
oxox
xxxx
Output
NO
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 = []
for i in range(n):
s.append(input())
new = [[0] * n for i in range(n)]
for i in range(n):
for j in range(n):
if s[i][j] == 'o':
new[i][j] = 1
flag = True
for i in range(n):
for j in range(n):
s = 0
if i > 0 and new[i - 1][j] == 1:
s += 1
if i < n - 1 and new[i + 1][j] == 1:
s += 1
if j > 0 and new[i][j - 1] == 1:
s += 1
if j < n - 1 and new[i][j + 1] == 1:
s += 1
if s % 2 == 1:
flag = False
break
if flag:
print("YES")
else:
print("NO")
``` | vfc_15678 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/462/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\nxxo\nxox\noxx\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1482 | Solve the following coding problem using the programming language python:
One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k.
There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number a_{i} (1 ≤ a_{i} ≤ n·k). All numbers a_{i} accidentally turned out to be different.
Now the children wonder, how to divide the orange so as to meet these conditions: each child gets exactly n orange segments; the i-th child gets the segment with number a_{i} for sure; no segment goes to two children simultaneously.
Help the children, divide the orange and fulfill the requirements, described above.
-----Input-----
The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ n·k), where a_{i} is the number of the orange segment that the i-th child would like to get.
It is guaranteed that all numbers a_{i} are distinct.
-----Output-----
Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.
You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.
-----Examples-----
Input
2 2
4 1
Output
2 4
1 3
Input
3 1
2
Output
3 2 1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#CF Round 150. Div II Prob. A - Dividing Orange
import sys
In = sys.stdin
n, k = [int(x) for x in In.readline().split()]
arr, s, cnt = [int(x) for x in In.readline().split()], set(), 1;
s.update(arr)
for i in range(k):
c = [arr[i]]
for j in range(n - 1):
while (cnt in s):
cnt += 1;
c.append(cnt)
cnt += 1;
sep = ' '
print (sep.join(map(str, c)))
``` | vfc_15682 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/244/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n4 1\n",
"output": "2 4 \n1 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n2\n",
"output": "3 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n25 24 23 22 21\n",
"output": "2 3 1 25 4 \n7 6 8 5 24 \n10 12 9 23 11 \n13 15 14 16 22 \n19 21 20 17 18 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1483 | Solve the following coding problem using the programming language python:
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $n$ students doing yet another trick.
Let's assume that all these students are numbered from $1$ to $n$. The teacher came to student $a$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $p_a$.
After that, the teacher came to student $p_a$ and made a hole in his badge as well. The student in reply said that the main culprit was student $p_{p_a}$.
This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.
After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.
You don't know the first student who was caught by the teacher. However, you know all the numbers $p_i$. Your task is to find out for every student $a$, who would be the student with two holes in the badge if the first caught student was $a$.
-----Input-----
The first line of the input contains the only integer $n$ ($1 \le n \le 1000$) — the number of the naughty students.
The second line contains $n$ integers $p_1$, ..., $p_n$ ($1 \le p_i \le n$), where $p_i$ indicates the student who was reported to the teacher by student $i$.
-----Output-----
For every student $a$ from $1$ to $n$ print which student would receive two holes in the badge, if $a$ was the first student caught by the teacher.
-----Examples-----
Input
3
2 3 2
Output
2 2 3
Input
3
1 2 3
Output
1 2 3
-----Note-----
The picture corresponds to the first example test case.
$8$
When $a = 1$, the teacher comes to students $1$, $2$, $3$, $2$, in this order, and the student $2$ is the one who receives a second hole in his badge.
When $a = 2$, the teacher comes to students $2$, $3$, $2$, and the student $2$ gets a second hole in his badge. When $a = 3$, the teacher will visit students $3$, $2$, $3$ with student $3$ getting a second hole in his badge.
For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.
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()]
for i in range(n):
tmp = [0] * n
j = i
while tmp[j] != 1:
tmp[j] = 1
j = p[j] - 1
print(j + 1, end = " ")
``` | vfc_15686 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1020/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 3 2\n",
"output": "2 2 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "1 2 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 3 1\n",
"output": "1 2 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "1 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1484 | Solve the following coding problem using the programming language python:
Let's denote that some array $b$ is bad if it contains a subarray $b_l, b_{l+1}, \dots, b_{r}$ of odd length more than $1$ ($l < r$ and $r - l + 1$ is odd) such that $\forall i \in \{0, 1, \dots, r - l\}$ $b_{l + i} = b_{r - i}$.
If an array is not bad, it is good.
Now you are given an array $a_1, a_2, \dots, a_n$. Some elements are replaced by $-1$. Calculate the number of good arrays you can obtain by replacing each $-1$ with some integer from $1$ to $k$.
Since the answer can be large, print it modulo $998244353$.
-----Input-----
The first line contains two integers $n$ and $k$ ($2 \le n, k \le 2 \cdot 10^5$) — the length of array $a$ and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace $-1$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($a_i = -1$ or $1 \le a_i \le k$) — the array $a$.
-----Output-----
Print one integer — the number of good arrays you can get, modulo $998244353$.
-----Examples-----
Input
2 3
-1 -1
Output
9
Input
5 2
1 -1 -1 1 2
Output
0
Input
5 3
1 -1 -1 1 2
Output
2
Input
4 200000
-1 -1 12345 -1
Output
735945883
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from functools import lru_cache
N, K = list(map(int, input().split()))
P = 998244353
A = [K+100] + [int(a) for a in input().split()] + [K+j for j in range(1, 10)]
# A = [K+100] + [1, 2] + [-1 for a in range(N-4)] + [3,4]+ [K+j for j in range(1, 10)]
X = [[0,0] for _ in range(N//2+5)]
X[0][0] = 1
for i in range(1, N//2+2):
X[i][0] = X[i-1][1]
X[i][1] = (X[i-1][0] * (K-1) + X[i-1][1] * (K-2)) % P
Y = [[0,0] for _ in range(N//2+5)]
Y[0][1] = 1
for i in range(1, N//2+2):
Y[i][0] = Y[i-1][1]
Y[i][1] = (Y[i-1][0] * (K-1) + Y[i-1][1] * (K-2)) % P
def calc(l, a, b):
if a > K and b > K:
return (K * pow(K-1, l-1, P)) % P
if a > K or b > K:
return pow(K-1, l, P)
if a == b:
return X[l+1][0]
else:
return Y[l+1][0]
l = 0
ans = 1
for j in range(2):
pre = K + 50 + j
for i in range(j, N+5, 2):
if A[i] == -1:
l += 1
elif l > 0:
ans *= calc(l, pre, A[i])
ans %= P
pre = A[i]
l = 0
elif pre == A[i]:
# print(A)
ans = 0
break
else:
pre = A[i]
print(ans%P)
``` | vfc_15690 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1140/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n-1 -1\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n1 -1 -1 1 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\n1 -1 -1 1 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 200000\n-1 -1 12345 -1\n",
"output": "735945883\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1485 | Solve the following coding problem using the programming language python:
There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b).
Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new $(\frac{a}{2}, \frac{b}{2})$ card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card.
Polycarpus really wants to get n special cards (1, a_1), (1, a_2), ..., (1, a_{n}). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?
Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires.
-----Input-----
The first line contains two integers n, m (1 ≤ n ≤ 10^5, 2 ≤ m ≤ 10^9). The second line contains the sequence of integers a_1, a_2, ..., a_{n} (2 ≤ a_{i} ≤ 10^9). Note, that the numbers in the sequence can coincide.
The numbers in the lines are separated by single spaces.
-----Output-----
Print a single integer — the answer to the problem.
Please, do not use 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
1 6
2
Output
11
Input
1 6
7
Output
14
Input
2 10
13 7
Output
36
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# written with help of editorial
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
def gcd(x, y):
while y:
x, y = y, x % y
return x
g = 0
for x in a:
g = gcd(g, x - 1)
answer = 0
def process(x):
nonlocal answer
if x % 2 == 0:
return 0
for i in range(30):
v = 2 ** i * x
if v > m:
break
answer += m - v
for i in range(1, g + 1):
if i * i > g:
break
if g % i:
continue
process(i)
if i * i != g:
process(g // i)
print(answer)
``` | vfc_15694 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/271/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 6\n2\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 6\n7\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 10\n13 7\n",
"output": "36\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n9 3 6 6 3 3 6 3 6 9\n",
"output": "25\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1486 | Solve the following coding problem using the programming language python:
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position x_{i} — a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).
Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.
For each city calculate two values min_{i} and max_{i}, where min_{i} is the minimum cost of sending a letter from the i-th city to some other city, and max_{i} is the the maximum cost of sending a letter from the i-th city to some other city
-----Input-----
The first line of the input contains integer n (2 ≤ n ≤ 10^5) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x_1, x_2, ..., x_{n} ( - 10^9 ≤ x_{i} ≤ 10^9), where x_{i} is the x-coordinate of the i-th city. All the x_{i}'s are distinct and follow in ascending order.
-----Output-----
Print n lines, the i-th line must contain two integers min_{i}, max_{i}, separated by a space, where min_{i} is the minimum cost of sending a letter from the i-th city, and max_{i} is the maximum cost of sending a letter from the i-th city.
-----Examples-----
Input
4
-5 -2 2 7
Output
3 12
3 9
4 7
5 12
Input
2
-1 1
Output
2 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 = int(input())
a = list(map(int, input().split()))
for i in range(n):
if i == 0:
print(a[1] - a[0], a[-1] - a[0])
elif i == n - 1:
print(a[i] - a[i - 1], a[i] - a[0])
else:
print(min(a[i + 1] - a[i], a[i] - a[i - 1]), max(a[-1] - a[i], a[i] - a[0]))
``` | vfc_15698 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/567/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n-5 -2 2 7\n",
"output": "3 12\n3 9\n4 7\n5 12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n-1 1\n",
"output": "2 2\n2 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n-1 0 1\n",
"output": "1 2\n1 1\n1 2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1488 | Solve the following coding problem using the programming language python:
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a_1, a_2, ..., a_{n}. The number a_{k} represents that the kth destination is at distance a_{k} kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
-----Input-----
The first line contains integer n (2 ≤ n ≤ 10^5). Next line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7).
-----Output-----
Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.
-----Examples-----
Input
3
2 3 5
Output
22 3
-----Note-----
Consider 6 possible routes: [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8.
The average travel distance is $\frac{1}{6} \cdot(5 + 7 + 7 + 8 + 9 + 8)$ = $\frac{44}{6}$ = $\frac{22}{3}$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from fractions import *
def solve():
n = int(input())
a = list(map(int,input().split()))
a.sort()
ans1 = 0
pres = a[0]
for i in range(1,n):
ans1+=i*a[i] -pres
pres+=a[i]
ans1 *= 2;
tmp = pres+ans1
tmp1 = n
s = Fraction(tmp,tmp1)
print(s.numerator,s.denominator)
solve()
``` | vfc_15706 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/340/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 3 5\n",
"output": "22 3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 5 77 2\n",
"output": "547 4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3 3842 288 199 334\n",
"output": "35918 5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 2 3 40 52 33 86\n",
"output": "255 1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1490 | Solve the following coding problem using the programming language python:
In Berland recently a new collection of toys went on sale. This collection consists of 10^9 types of toys, numbered with integers from 1 to 10^9. A toy from the new collection of the i-th type costs i bourles.
Tania has managed to collect n different types of toys a_1, a_2, ..., a_{n} from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.
Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.
-----Input-----
The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 10^9) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys.
The next line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the types of toys that Tanya already has.
-----Output-----
In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m.
In the second line print k distinct space-separated integers t_1, t_2, ..., t_{k} (1 ≤ t_{i} ≤ 10^9) — the types of toys that Tanya should choose.
If there are multiple answers, you may print any of them. Values of t_{i} can be printed in any order.
-----Examples-----
Input
3 7
1 3 4
Output
2
2 5
Input
4 14
4 6 12 8
Output
4
7 2 3 1
-----Note-----
In the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
s = 0
count = 1
i = 0
answer = []
while i < len(a) and s <= m:
if a[i] == count:
i += 1
count += 1
else:
s += count
answer.append(count)
count += 1
if s > m:
s = s - count + 1
print(len(answer) - 1)
for i in range(len(answer) - 1):
print(answer[i], end = ' ')
elif s == m:
print(len(answer))
for i in range(len(answer)):
print(answer[i], end = ' ')
else:
while s <= m:
s += count
answer.append(count)
count += 1
if s == m:
print(len(answer))
for i in range(len(answer)):
print(answer[i], end = ' ')
else:
s = s - count + 1
print(len(answer) - 1)
for i in range(len(answer) - 1):
print(answer[i], end = ' ')
``` | vfc_15714 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/659/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 7\n1 3 4\n",
"output": "2\n2 5 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1491 | Solve the following coding problem using the programming language python:
Ann and Borya have n piles with candies and n is even number. There are a_{i} candies in pile with number i.
Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).
Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.
-----Input-----
First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies.
Second line contains sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — amounts of candies in each pile.
-----Output-----
Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.
-----Examples-----
Input
4
12 14 30 4
Output
2
Input
6
0 0 0 0 0 0
Output
6
Input
6
120 110 23 34 25 45
Output
3
Input
10
121 56 78 81 45 100 1 0 54 78
Output
0
-----Note-----
In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).
In second example you should add two candies to any three piles.
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())
candies = list(map(int, input().strip().split()))
def intkoren(n):
k = int(n**0.5)
while (k+1)*(k+1) <= n:
k += 1
while k*k > n:
k -= 1
return k
cnt1 = 0
cnt2 = 0
new = []
for e in candies:
u = intkoren(e)
if e == 0:
new.append((2,1))
cnt1 += 1
elif u*u == e:
new.append((1,1))
cnt1 += 1
else:
mini = min(e - u*u, (u+1)*(u+1)-e)
new.append((mini, -1))
cnt2 += 1
new.sort()
#print(new, cnt1,cnt2)
count = 0
if cnt1 >= cnt2:
todo = (cnt1 - cnt2)//2
for steps, v in new:
if todo == 0:
break
if v == 1:
count += steps
todo -= 1
else:
todo = (cnt2 - cnt1)//2
for steps,v in new:
if todo == 0:
break
if v == -1:
count += steps
todo -= 1
print(count)
``` | vfc_15718 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/898/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n12 14 30 4\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n0 0 0 0 0 0\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n120 110 23 34 25 45\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1492 | Solve the following coding problem using the programming language python:
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.
A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $n \times m$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.
The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $0$) some trees were set on fire. At the beginning of minute $0$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $8$ neighboring trees. At the beginning of minute $T$, the fire was extinguished.
The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $T$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $T$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.
Note that you'd like to maximize value $T$ but the set of trees can be arbitrary.
-----Input-----
The first line contains two integer $n$ and $m$ ($1 \le n, m \le 10^6$, $1 \le n \cdot m \le 10^6$) — the sizes of the map.
Next $n$ lines contain the map. The $i$-th line corresponds to the $i$-th row of the map and contains $m$-character string. The $j$-th character of the $i$-th string is "X" if the corresponding tree is burnt and "." otherwise.
It's guaranteed that the map contains at least one "X".
-----Output-----
In the first line print the single integer $T$ — the maximum time the Forest was on fire. In the next $n$ lines print the certificate: the map ($n \times m$ rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".".
-----Examples-----
Input
3 6
XXXXXX
XXXXXX
XXXXXX
Output
1
......
.X.XX.
......
Input
10 10
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXX...
.XXXXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
...XXXXXX.
..........
Output
2
..........
..........
...XX.....
..........
..........
..........
.....XX...
..........
..........
..........
Input
4 5
X....
..XXX
..XXX
..XXX
Output
0
X....
..XXX
..XXX
..XXX
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()
h,w=map(int,input().split())
d=w+2
b=[0]*(w+2)
for i in range(h):
b+=([0]+[int(j=="X") for j in input()]+[0])
b+=([0]*(w+2))
co=sum(b)
t=10**10
for i in range(1,h+1):
f=0
for j in range(w+2):
f+=b[i*d+j]
if b[i*d+j]==0 and f:
t=min(t,(f-1)//2)
f=0
for j in range(1,w+1):
f=0
for i in range(h+2):
f+=b[i*d+j]
if b[i*d+j]==0 and f:
t=min(t,(f-1)//2)
f=0
coo=0
ans=[-1]*(w+2)*(h+2)
stack=[]
for i in range(h+2):
for j in range(w+2):
if b[i*d+j]==0:
stack.append(i*d+j)
ans[i*d+j]=0
dij=[(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
for ij in stack:
i,j=divmod(ij,d)
for x,y in dij:
if 0<=i+x<h+2 and 0<=j+y<w+2:
if ans[(i+x)*d+j+y]==-1:
ans[(i+x)*d+j+y]=ans[i*d+j]+1
if ans[(i+x)*d+j+y]>t:
coo+=1
stack.append((i+x)*d+(j+y))
if coo*6<co and t==1:
t-=1
print(t)
for i in range(1,h+1):
print("".join([".X"[int(t<j)]for j in ans[i*d+1:i*d+w+1]]))
``` | vfc_15722 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1262/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 6\nXXXXXX\nXXXXXX\nXXXXXX\n",
"output": "1\n......\n.XXXX.\n......\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n.XXXXXX...\n.XXXXXX...\n.XXXXXX...\n.XXXXXX...\n.XXXXXXXX.\n...XXXXXX.\n...XXXXXX.\n...XXXXXX.\n...XXXXXX.\n..........\n",
"output": "2\n..........\n..........\n...XX.....\n..........\n..........\n..........\n.....XX...\n..........\n..........\n..........\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 5\nX....\n..XXX\n..XXX\n..XXX\n",
"output": "0\nX....\n..XXX\n..XXX\n..XXX\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\nX\n",
"output": "0\nX\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 12\n...X..X..XX.\n.....X......\n..X.........\n...X..XX...X\n.......X.X..\n....X...X.X.\n..........X.\n......XXX...\n......X..X..\n..X....XX..X\n",
"output": "0\n...X..X..XX.\n.....X......\n..X.........\n...X..XX...X\n.......X.X..\n....X...X.X.\n..........X.\n......XXX...\n......X..X..\n..X....XX..X\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1493 | Solve the following coding problem using the programming language python:
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.
You task is to find any suitable placement of chessmen on the given chessboard.
-----Input-----
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100).
Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.
-----Output-----
Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.
If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.
-----Examples-----
Input
1 1
.
Output
B
Input
2 2
..
..
Output
BW
WB
Input
3 3
.-.
---
--.
Output
B-B
---
--B
-----Note-----
In the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.
In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.
In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
fin = [list(input().strip()) for i in range(n)]
ans = [['-' for i in range(m)] for j in range(n)]
for y in range(n):
for x in range(m):
if fin[y][x] == '-':
continue
elif y % 2 == x % 2:
ans[y][x] = 'B'
else:
ans[y][x] = 'W'
for row in ans:
print(''.join(row))
``` | vfc_15726 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/445/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1\n.\n",
"output": "B\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1494 | Solve the following coding problem using the programming language python:
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates $\operatorname{occ}(s^{\prime}, p)$ that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define $\operatorname{ans}(x)$ as maximum value of $\operatorname{occ}(s^{\prime}, p)$ over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know $\operatorname{ans}(x)$ for all x from 0 to |s| where |s| denotes the length of string s.
-----Input-----
The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).
The second line of the input contains the string p (1 ≤ |p| ≤ 500).
Both strings will only consist of lower case English letters.
-----Output-----
Print |s| + 1 space-separated integers in a single line representing the $\operatorname{ans}(x)$ for all x from 0 to |s|.
-----Examples-----
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
-----Note-----
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
i, j = x, m
while i and j:
j -= s[i - 1] == p[j - 1]
i -= 1
if not j:
for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
for y in range(x): d[x][y] = max(d[x][y], d[x - 1][y])
print(*d[-1])
``` | vfc_15730 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/476/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "aaaaa\naa\n",
"output": "2 2 1 1 0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "axbaxxb\nab\n",
"output": "0 1 1 2 1 1 0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aabb\nab\n",
"output": "1 1 1 0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaaaaaaaaaaaaaa\na\n",
"output": "15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaaaaaaaaaa\nb\n",
"output": "0 0 0 0 0 0 0 0 0 0 0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ababababababababa\naba\n",
"output": "4 4 4 4 4 4 3 3 3 2 2 2 1 1 1 0 0 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1496 | Solve the following coding problem using the programming language python:
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.
Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.
Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.
-----Input-----
First line contains four integers n, m, k, s (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ m ≤ 2·10^5, 1 ≤ s ≤ 10^9) — number of days, total number and required number of gadgets, number of burles Nura has.
Second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6) — the cost of one dollar in burles on i-th day.
Third line contains n integers b_{i} (1 ≤ b_{i} ≤ 10^6) — the cost of one pound in burles on i-th day.
Each of the next m lines contains two integers t_{i}, c_{i} (1 ≤ t_{i} ≤ 2, 1 ≤ c_{i} ≤ 10^6) — type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.
-----Output-----
If Nura can't buy k gadgets print the only line with the number -1.
Otherwise the first line should contain integer d — the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers q_{i}, d_{i} — the number of gadget and the day gadget should be bought. All values q_{i} should be different, but the values d_{i} can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.
In case there are multiple possible solutions, print any of them.
-----Examples-----
Input
5 4 2 2
1 2 3 2 1
3 2 1 2 3
1 1
2 1
1 2
2 2
Output
3
1 1
2 3
Input
4 3 2 200
69 70 71 72
104 105 106 107
1 1
2 2
1 2
Output
-1
Input
4 3 1 1000000000
900000 910000 940000 990000
990000 999000 999900 999990
1 87654
2 76543
1 65432
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from itertools import accumulate
import sys
def solve(f, g):
n, m, k, s = [int(x) for x in f.readline().split()]
a_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
b_price = [(int(x), i+1) for i, x in enumerate(f.readline().split())]
a_gadgets = []
b_gadgets = []
for i, line in enumerate(f):
t, price = [int(x) for x in line.split()]
if t == 1:
a_gadgets.append((price, i + 1))
else:
b_gadgets.append((price, i + 1))
a_gadgets.sort()
b_gadgets.sort()
prefix_a = [0] + list(accumulate(gadget[0] for gadget in a_gadgets))
prefix_b = [0] + list(accumulate(gadget[0] for gadget in b_gadgets))
la = min(k, len(a_gadgets))
lb = min(k, len(b_gadgets))
min_price_for_k = [(prefix_a[i], prefix_b[k - i], i) for i in range(k-lb, la+1)]
for i in range(1, n):
a_price[i] = min(a_price[i], a_price[i-1])
b_price[i] = min(b_price[i], b_price[i-1])
def expence(day):
return lambda x: a_price[day][0]*x[0] + b_price[day][0]*x[1]
x, y = 0, n-1
while x <= y-1:
day = (x + y) // 2
min_cost = min(min_price_for_k, key = expence(day))
if expence(day)(min_cost) > s:
x = day+1
else:
y = day
min_cost = min(min_price_for_k, key = expence(x))
if expence(x)(min_cost) > s:
g.write('-1\n')
else:
g.write(str(x+1) + '\n')
i1 = min_cost[-1]
A, B = ' ' + str(a_price[x][1]) + '\n', ' ' + str(b_price[x][1]) + '\n'
for i in range(i1):
g.write(str(a_gadgets[i][1]) + A)
for i in range(k - i1):
g.write(str(b_gadgets[i][1]) + B)
solve(sys.stdin, sys.stdout)
``` | vfc_15738 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/609/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4 2 2\n1 2 3 2 1\n3 2 1 2 3\n1 1\n2 1\n1 2\n2 2\n",
"output": "3\n1 1\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 2 200\n69 70 71 72\n104 105 106 107\n1 1\n2 2\n1 2\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 1 1000000000\n900000 910000 940000 990000\n990000 999000 999900 999990\n1 87654\n2 76543\n1 65432\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 3 1000000\n921 853 547 187 164\n711 462 437 307 246\n2 94\n2 230\n1 373\n1 476\n2 880\n",
"output": "1\n1 1\n2 1\n5 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1497 | Solve the following coding problem using the programming language python:
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.
Return the maximum number of rows that she can make completely clean.
-----Input-----
The first line of input will be a single integer n (1 ≤ n ≤ 100).
The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.
-----Output-----
The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.
-----Examples-----
Input
4
0101
1000
1111
0101
Output
2
Input
3
111
111
111
Output
3
-----Note-----
In the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.
In the second sample, everything is already clean, so Ohana doesn't need to do anything.
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())
d = {}
for i in range(n):
s = input()
if s in d:
d[s] += 1
else:
d[s] = 1
print(d[max(d,key=d.get)])
``` | vfc_15742 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/554/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0101\n1000\n1111\n0101\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n111\n111\n111\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1498 | Solve the following coding problem using the programming language python:
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.
It is known that during the day q tasks will come, the i-th of them is characterized with three integers: t_{i} — the moment in seconds in which the task will come, k_{i} — the number of servers needed to perform it, and d_{i} — the time needed to perform this task in seconds. All t_{i} are distinct.
To perform the i-th task you need k_{i} servers which are unoccupied in the second t_{i}. After the servers begin to perform the task, each of them will be busy over the next d_{i} seconds. Thus, they will be busy in seconds t_{i}, t_{i} + 1, ..., t_{i} + d_{i} - 1. For performing the task, k_{i} servers with the smallest ids will be chosen from all the unoccupied servers. If in the second t_{i} there are not enough unoccupied servers, the task is ignored.
Write the program that determines which tasks will be performed and which will be ignored.
-----Input-----
The first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 10^5) — the number of servers and the number of tasks.
Next q lines contains three integers each, the i-th line contains integers t_{i}, k_{i} and d_{i} (1 ≤ t_{i} ≤ 10^6, 1 ≤ k_{i} ≤ n, 1 ≤ d_{i} ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds.
-----Output-----
Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.
-----Examples-----
Input
4 3
1 3 2
2 2 1
3 4 3
Output
6
-1
10
Input
3 2
3 2 3
5 1 2
Output
3
3
Input
8 6
1 3 20
4 2 1
6 5 5
10 1 1
15 3 6
21 8 8
Output
6
9
30
-1
15
36
-----Note-----
In the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).
In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, q = list(map(int, input().split()))
servers = [0] * n
for _ in range(q):
t, k, d = list(map(int, input().split()))
# free = [i for i, x in enumerate(servers) if x < t]
free = []
for sn in range(n):
if servers[sn] < t:
free.append(sn)
if len(free) == k:
break
if len(free) < k:
print(-1)
else:
for sn in free:
servers[sn] = t + d - 1
print(sum([x + 1 for x in free]))
``` | vfc_15746 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/747/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 3\n1 3 2\n2 2 1\n3 4 3\n",
"output": "6\n-1\n10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n3 2 3\n5 1 2\n",
"output": "3\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 6\n1 3 20\n4 2 1\n6 5 5\n10 1 1\n15 3 6\n21 8 8\n",
"output": "6\n9\n30\n-1\n15\n36\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n6 1 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10\n4 1 1\n9 1 1\n10 1 1\n12 1 1\n13 1 1\n15 1 1\n16 1 1\n18 1 1\n19 1 1\n20 1 1\n",
"output": "1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1499 | Solve the following coding problem using the programming language python:
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.
Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:
1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.
After occupying all the window seats (for m > 2n) the non-window seats are occupied:
1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.
All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.
1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. [Image] The seating for n = 9 and m = 36.
You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.
-----Input-----
The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers.
-----Output-----
Print m distinct integers from 1 to m — the order in which the passengers will get off the bus.
-----Examples-----
Input
2 7
Output
5 1 6 2 7 3 4
Input
9 36
Output
19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18
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
OUT = (1, 0, 2, 3)
try:
while True:
n, m = map(int, input().split())
bus = [[None] * 4 for i in range(n)]
cur = 1
for row in range(n << 1):
if row >= n:
i = row - n
k = b = 1
else:
i = row
k = 3
b = 0
for j in range(2):
if cur <= m:
bus[i][k * j + b] = cur
cur += 1
for i in range(n):
for j in range(4):
if bus[i][OUT[j]] is not None:
print(bus[i][OUT[j]], end=' ')
print()
except EOFError:
pass
``` | vfc_15750 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/660/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 7\n",
"output": "5 1 6 2 7 3 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 36\n",
"output": "19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 4\n",
"output": "3 1 4 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n",
"output": "1 2 3 4 5 6 7 8 9 10\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1500 | Solve the following coding problem using the programming language python:
Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.
Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x_1 километров вдоль улицы, второй — в точке x_2 и так далее, n-й велопрокат находится в точке x_{n}. Школа Аркадия находится в точке x_1 (то есть там же, где и первый велопрокат), а дом — в точке x_{n} (то есть там же, где и n-й велопрокат). Известно, что x_{i} < x_{i} + 1 для всех 1 ≤ i < n.
Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.
За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы.
Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.
-----Входные данные-----
В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде.
В следующей строке следует последовательность целых чисел x_1, x_2, ..., x_{n} (0 ≤ x_1 < x_2 < ... < x_{n} ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.
-----Выходные данные-----
Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.
-----Примеры-----
Входные данные
4 4
3 6 8 10
Выходные данные
2
Входные данные
2 9
10 20
Выходные данные
-1
Входные данные
12 3
4 6 7 9 10 11 13 15 17 18 20 21
Выходные данные
6
-----Примечание-----
В первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.
Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.
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()))
x = list(map(int, input().split()))
ro = list(x[i] - x[i - 1] for i in range(1, n))
if max(x[i] - x[i - 1] for i in range(1, n)) > k:
print(-1)
else:
ans = 1
r = 0
for el in ro:
r += el
if r > k:
ans += 1
r = el
print(ans)
``` | vfc_15754 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/929/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4\n3 6 8 10\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 9\n10 20\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "12 3\n4 6 7 9 10 11 13 15 17 18 20 21\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1501 | Solve the following coding problem using the programming language python:
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. [Image]
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x_1 < x_2 < ... < x_{k} where p matches s. More formally, for each x_{i} (1 ≤ i ≤ k) he condition s_{x}_{i}s_{x}_{i} + 1... s_{x}_{i} + |p| - 1 = p is fullfilled.
Then Malekas wrote down one of subsequences of x_1, x_2, ... x_{k} (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).
After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.
Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.
Answer can be very large, so Tavas wants you to print the answer modulo 10^9 + 7.
-----Input-----
The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1 ≤ n ≤ 10^6 and 0 ≤ m ≤ n - |p| + 1).
The second line contains string p (1 ≤ |p| ≤ n).
The next line contains m space separated integers y_1, y_2, ..., y_{m}, Malekas' subsequence (1 ≤ y_1 < y_2 < ... < y_{m} ≤ n - |p| + 1).
-----Output-----
In a single line print the answer modulo 1000 000 007.
-----Examples-----
Input
6 2
ioi
1 3
Output
26
Input
5 2
ioi
1 2
Output
0
-----Note-----
In the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.
Here |x| denotes the length of string x.
Please note that it's possible that there is no such string (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
# -*- coding: utf-8 -*-
def solve():
mod = 10**9 + 7
n, m = map(int, input().split())
p = input()
if m == 0:
return powmod(n)
delta = len(p) - 1
ys = map(int, input().split())
answer = 1
tail = 0
for y in ys:
if y > tail:
answer *= powmod(y - tail - 1)
answer %= mod
elif not is_consistent(p, tail - y + 1):
return 0
tail = y + delta
answer *= powmod(n - tail)
return answer % mod
ok_set = set()
def is_consistent(p, margin):
nonlocal ok_set
if margin in ok_set:
return True
elif p[:margin] == p[-margin:]:
ok_set.add(margin)
return True
else:
return False
def powmod(p):
mod = 10**9 + 7
pbin = bin(p)[2:][-1::-1]
result = 26 if pbin[0] == '1' else 1
tmp = 26
for bit in pbin[1:]:
tmp *= tmp
tmp %= mod
if bit == '1':
result *= tmp
result %= mod
return result
print(solve())
``` | vfc_15758 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/535/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 2\nioi\n1 3\n",
"output": "26\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\nioi\n1 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "173700 6\nbcabcbcbcbaaacaccaacaccaabacabaacbcacbbccaccbcacbabcaccccccaacacabbbbbacabbaaacbcbbaccaccabbbbaabbacacbabccaabcabbbcacaaccbabbcaaaaaabccbbcabcacbcbcabcbcbbaabacaaccccabacaaaccacaaabbacacabbcccacbaabcacacbbaaaccaccbaccccccbccaabcacaacabaccababacabcccbcbbacbabacbcbabacbbaccaabcabcbbbaaabbacbbbcacccbaaacacbaccbbcccccabaaa\n110876 118837 169880 171013 172546 173196\n",
"output": "375252451\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "35324 4\nrpcshyyhtvyylyxcqrqonzvlrghvjdejzdtovqichwiavbxztdrtrczhcxtzojlisqwwzvnwrhimmfopazliutcgjslcmyddvxtwueqqzlsgrgjflyihwzncyikncikiutscfbmylgbkoinyvvqsthzmkwehrgliyoxafstviahfiyfwoeahynfhbdjkrlzabuvshcczucihqvtsuzqbyjdwzwv\n2944 22229 25532 34932\n",
"output": "318083188\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1502 | Solve the following coding problem using the programming language python:
[Image]
-----Input-----
The input contains a single integer $a$ ($0 \le a \le 15$).
-----Output-----
Output a single integer.
-----Example-----
Input
3
Output
13
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
f=lambda a:(a+1)%2
n=int(input())
a=list(map(int, bin(n)[2:].zfill(4)[::-1]))
a[3]=f(a[3])
if (a[3]): a[2]=f(a[2])
if a[3] and a[2]: a[1]=f(a[1])
if a[3] and a[2] and a[1]: a[0]=f(a[0])
print (int("".join(map(str, a))[::-1], 2))
``` | vfc_15762 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1145/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "8\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1503 | Solve the following coding problem using the programming language python:
Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $m$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $1$ to $n$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.
However, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" — thinks Gawry — "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.
In how many ways he can do it? Two ways are called different if the remaining common part is different.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 100\,000$, $1 \le m \le 10$) — the number of suspects and the number of asked neighbors.
Each of the next $m$ lines contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). It is guaranteed that these integers form a correct permutation (that is, each number from $1$ to $n$ appears exactly once).
-----Output-----
Output a single integer denoting the number of ways to delete some prefix and some suffix of each permutation (possibly empty), such that the remaining parts will be equal and non-empty.
-----Examples-----
Input
3 2
1 2 3
2 3 1
Output
4
Input
5 6
1 2 3 4 5
2 3 1 4 5
3 4 5 1 2
3 5 4 2 1
2 3 5 4 1
1 2 3 4 5
Output
5
Input
2 2
1 2
2 1
Output
2
-----Note-----
In the first example, all possible common parts are $[1]$, $[2]$, $[3]$ and $[2, 3]$.
In the second and third examples, you can only leave common parts of length $1$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#
import collections, atexit, math, sys, bisect
sys.setrecursionlimit(1000000)
def getIntList():
return list(map(int, input().split()))
try :
#raise ModuleNotFoundError
import numpy
def dprint(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
# in python 3.4 **kwargs is invalid???
print(*args, file=sys.stderr)
dprint('debug mode')
except Exception:
def dprint(*args, **kwargs):
pass
inId = 0
outId = 0
if inId>0:
dprint('use input', inId)
sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件
if outId>0:
dprint('use output', outId)
sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件
atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit
N, M= getIntList()
ne = [0 for i in range(N+1) ]
za = getIntList()
for i in range(N-1):
ne[ za[i]] = za[i+1]
ne[za[-1]] = 0
for _ in range(1, M):
za = getIntList()
for i in range(N-1):
a = za[i]
b = za[i+1]
if ne[a] != b:
ne[a] = -1
a = za[-1]
if ne[a]!=0:
ne[a] = -1
tin = [0 for i in range(N+1) ]
for i in range(1,N+1):
a = ne[i]
if a>0:
tin[a] = 1
res = 0
for i in range(1,N+1):
if tin[i]: continue
n = 0
while i>0:
n+=1
i = ne[i]
res += n * (n+1) //2
print(res)
``` | vfc_15766 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1043/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2 3\n2 3 1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 6\n1 2 3 4 5\n2 3 1 4 5\n3 4 5 1 2\n3 5 4 2 1\n2 3 5 4 1\n1 2 3 4 5\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n1 2\n2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1504 | Solve the following coding problem using the programming language python:
You are given two lists of segments $[al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n]$ and $[bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n]$.
Initially, all segments $[al_i, ar_i]$ are equal to $[l_1, r_1]$ and all segments $[bl_i, br_i]$ are equal to $[l_2, r_2]$.
In one step, you can choose one segment (either from the first or from the second list) and extend it by $1$. In other words, suppose you've chosen segment $[x, y]$ then you can transform it either into $[x - 1, y]$ or into $[x, y + 1]$.
Let's define a total intersection $I$ as the sum of lengths of intersections of the corresponding pairs of segments, i.e. $\sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}$. Empty intersection has length $0$ and length of a segment $[x, y]$ is equal to $y - x$.
What is the minimum number of steps you need to make $I$ greater or equal to $k$?
-----Input-----
The first line contains the single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$; $1 \le k \le 10^9$) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers $l_1$ and $r_1$ ($1 \le l_1 \le r_1 \le 10^9$) — the segment all $[al_i, ar_i]$ are equal to initially.
The third line of each test case contains two integers $l_2$ and $r_2$ ($1 \le l_2 \le r_2 \le 10^9$) — the segment all $[bl_i, br_i]$ are equal to initially.
It's guaranteed that the sum of $n$ doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $t$ integers — one per test case. For each test case, print the minimum number of step you need to make $I$ greater or equal to $k$.
-----Example-----
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
-----Note-----
In the first test case, we can achieve total intersection $5$, for example, using next strategy: make $[al_1, ar_1]$ from $[1, 2]$ to $[1, 4]$ in $2$ steps; make $[al_2, ar_2]$ from $[1, 2]$ to $[1, 3]$ in $1$ step; make $[bl_1, br_1]$ from $[3, 4]$ to $[1, 4]$ in $2$ steps; make $[bl_2, br_2]$ from $[3, 4]$ to $[1, 4]$ in $2$ steps. In result, $I = \text{intersection_length}([al_1, ar_1], [bl_1, br_1]) + \text{intersection_length}([al_2, ar_2], [bl_2, br_2]) + \\ + \text{intersection_length}([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5$
In the second test case, we can make $[al_1, ar_1] = [0, 1000000000]$ in $1000000000$ steps and $[bl_1, br_1] = [0, 1000000000]$ in $1000000000$ steps.
In the third test case, the total intersection $I$ is already equal to $10 > 3$, so we don't need to do any steps.
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, k = [int(x) for x in input().split()]
l1, r1 = [int(x) for x in input().split()]
l2, r2 = [int(x) for x in input().split()]
if l1 > l2:
l1, r1, l2, r2 = l2, r2, l1, r1
if l2 < r1:
# they already intersect.
start = (min(r1, r2) - max(l1, l2))*n
if start >= k:
print(0)
continue
cheap = n*(max(r1, r2) - min(l1, l2)) - start
if start + cheap >= k:
print(k - start)
continue
else:
print(cheap + (k - start - cheap)*2)
continue
# they do not intersect yet.
best = 10**100
cost_sf = 0
intersection_sf = 0
for j in range(n):
# compute price using j-th interval as the last.
cost_sf += l2 - r1
cheap = r2 - l1
if intersection_sf + cheap >= k:
best = min(best, cost_sf + max((k - intersection_sf), 0))
intersection_sf += cheap
cost_sf += cheap
best = min(best, cost_sf + max((k - intersection_sf)*2, 0))
print(best)
``` | vfc_15770 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1389/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 5\n1 2\n3 4\n2 1000000000\n1 1\n999999999 999999999\n10 3\n5 10\n7 8\n",
"output": "7\n2000000000\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n200000 88635750\n4971058 40181766\n6012372 78925196\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n200000 598920770\n24529366 24846325\n35694819 90253337\n",
"output": "703962247\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1505 | Solve the following coding problem using the programming language python:
Petya has recently started working as a programmer in the IT city company that develops computer games.
Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.
A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.
The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.
Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.
[Image]
-----Input-----
The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx^2 + vy^2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).
-----Output-----
Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10^{ - 9}.
-----Examples-----
Input
8 8 0 2 8 3 4 5
Output
8.000000000000 11.000000000000
4.000000000000 8.000000000000
6.000000000000 8.000000000000
6.000000000000 3.000000000000
10.000000000000 3.000000000000
10.000000000000 8.000000000000
12.000000000000 8.000000000000
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
px, py, vx, vy, a, b, c, d = map(int, input().split())
vl = (vx**2 + vy**2)**0.5
vx /= vl
vy /= vl
print(px + vx * b, py + vy * b)
print(px - vy * a / 2, py + vx * a / 2)
print(px - vy * c / 2, py + vx * c / 2)
print(px - vy * c / 2 - vx * d, py + vx * c / 2 - vy * d)
print(px + vy * c / 2 - vx * d, py - vx * c / 2 - vy * d)
print(px + vy * c / 2, py - vx * c / 2)
print(px + vy * a / 2, py - vx * a / 2)
``` | vfc_15774 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/630/O",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8 8 0 2 8 3 4 5\n",
"output": "8.000000000000 11.000000000000\n4.000000000000 8.000000000000\n6.000000000000 8.000000000000\n6.000000000000 3.000000000000\n10.000000000000 3.000000000000\n10.000000000000 8.000000000000\n12.000000000000 8.000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 7 0 5 8 2 11\n",
"output": "18.000000000000 10.000000000000\n10.000000000000 12.500000000000\n10.000000000000 11.000000000000\n-1.000000000000 11.000000000000\n-1.000000000000 9.000000000000\n10.000000000000 9.000000000000\n10.000000000000 7.500000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 0 7 5 8 2 11\n",
"output": "10.000000000000 18.000000000000\n7.500000000000 10.000000000000\n9.000000000000 10.000000000000\n9.000000000000 -1.000000000000\n11.000000000000 -1.000000000000\n11.000000000000 10.000000000000\n12.500000000000 10.000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 -7 0 5 8 2 11\n",
"output": "2.000000000000 10.000000000000\n10.000000000000 7.500000000000\n10.000000000000 9.000000000000\n21.000000000000 9.000000000000\n21.000000000000 11.000000000000\n10.000000000000 11.000000000000\n10.000000000000 12.500000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 0 -7 5 8 2 11\n",
"output": "10.000000000000 2.000000000000\n12.500000000000 10.000000000000\n11.000000000000 10.000000000000\n11.000000000000 21.000000000000\n9.000000000000 21.000000000000\n9.000000000000 10.000000000000\n7.500000000000 10.000000000000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1506 | Solve the following coding problem using the programming language python:
You are given an array a of length n. We define f_{a} the following way:
Initially f_{a} = 0, M = 1; for every 2 ≤ i ≤ n if a_{M} < a_{i} then we set f_{a} = f_{a} + a_{M} and then set M = i.
Calculate the sum of f_{a} over all n! permutations of the array a modulo 10^9 + 7.
Note: two elements are considered different if their indices differ, so for every array a there are exactly n! permutations.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the size of array a.
Second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the only integer, the sum of f_{a} over all n! permutations of the array a modulo 10^9 + 7.
-----Examples-----
Input
2
1 3
Output
1
Input
3
1 1 2
Output
4
-----Note-----
For the second example all the permutations are:
p = [1, 2, 3] : f_{a} is equal to 1; p = [1, 3, 2] : f_{a} is equal to 1; p = [2, 1, 3] : f_{a} is equal to 1; p = [2, 3, 1] : f_{a} is equal to 1; p = [3, 1, 2] : f_{a} is equal to 0; p = [3, 2, 1] : f_{a} is equal to 0.
Where p is the array of the indices of initial array a. The sum of f_{a} is equal to 4.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
f= [1]
for i in range(1,1000002):
f.append((f[-1] * i)%1000000007)
n = int(input())
a = sorted(int(x) for x in input().split())
sol = 0
j = 0
s = 1
sq = 1
for i in range(n - 1):
sq = sq * (n - i) % 1000000007
if a[i] != a[i + 1]:
sol += a[i] * (i - j + 1) * f[n - j - 1] * s
j = i + 1
s = sq
print(sol % 1000000007)
def __starting_point():
main()
__starting_point()
``` | vfc_15778 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/938/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 3\n",
"output": "1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1507 | Solve the following coding problem using the programming language python:
[Image]
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.
There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.
For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.
Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened.
-----Input-----
Two integers are given in the first string: the number of guests n and the number of guards k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 26).
In the second string, n uppercase English letters s_1s_2... s_{n} are given, where s_{i} is the entrance used by the i-th guest.
-----Output-----
Output «YES» if at least one door was unguarded during some time, and «NO» otherwise.
You can output each letter in arbitrary case (upper or lower).
-----Examples-----
Input
5 1
AABBB
Output
NO
Input
5 1
ABABB
Output
YES
-----Note-----
In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened.
In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
s = input()
our = set()
opened = set()
for i in range(ord('A'), ord('Z') + 1):
sym = chr(i)
if sym in s:
our.add(s.rfind(sym))
for i in range(len(s)):
if s[i] not in opened:
opened.add(s[i])
k -= 1
if k < 0:
print('YES')
return
if i in our:
k += 1
print('NO')
``` | vfc_15782 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/834/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 1\nAABBB\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1508 | Solve the following coding problem using the programming language python:
You want to arrange n integers a_1, a_2, ..., a_{n} in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers x_1, x_2, ..., x_{n}, where sequence x is a permutation of sequence a. The value of such an arrangement is (x_1 - x_2) + (x_2 - x_3) + ... + (x_{n} - 1 - x_{n}).
Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.
-----Input-----
The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 1000).
-----Output-----
Print the required sequence x_1, x_2, ..., x_{n}. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value.
-----Examples-----
Input
5
100 -100 50 0 -50
Output
100 -50 0 50 -100
-----Note-----
In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.
Sequence x_1, x_2, ... , x_{p} is lexicographically smaller than sequence y_1, y_2, ... , y_{p} if there exists an integer r (0 ≤ r < p) such that x_1 = y_1, x_2 = y_2, ... , x_{r} = y_{r} and x_{r} + 1 < y_{r} + 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
A = list(map(int, input().split()))
A.sort()
A[0], A[-1] = A[-1], A[0]
print(" ".join(list(map(str, A))))
``` | vfc_15786 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/347/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n100 -100 50 0 -50\n",
"output": "100 -50 0 50 -100 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n764 -367 0 963 -939 -795 -26 -49 948 -282\n",
"output": "963 -795 -367 -282 -49 -26 0 764 948 -939 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 1509 | Solve the following coding problem using the programming language python:
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of $n$ vertices. Each vertex $i$ has its own value $a_i$. All vertices are connected in series by edges. Formally, for every $1 \leq i < n$ there is an edge between the vertices of $i$ and $i+1$.
Denote the function $f(l, r)$, which takes two integers $l$ and $r$ ($l \leq r$):
We leave in the tree only vertices whose values range from $l$ to $r$. The value of the function will be the number of connected components in the new graph.
Your task is to calculate the following sum: $$\sum_{l=1}^{n} \sum_{r=l}^{n} f(l, r) $$
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of vertices in the tree.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n$) — the values of the vertices.
-----Output-----
Print one number — the answer to the problem.
-----Examples-----
Input
3
2 1 3
Output
7
Input
4
2 1 1 3
Output
11
Input
10
1 5 2 5 5 3 10 6 5 1
Output
104
-----Note-----
In the first example, the function values will be as follows: $f(1, 1)=1$ (there is only a vertex with the number $2$, which forms one component) $f(1, 2)=1$ (there are vertices $1$ and $2$ that form one component) $f(1, 3)=1$ (all vertices remain, one component is obtained) $f(2, 2)=1$ (only vertex number $1$) $f(2, 3)=2$ (there are vertices $1$ and $3$ that form two components) $f(3, 3)=1$ (only vertex $3$) Totally out $7$.
In the second example, the function values will be as follows: $f(1, 1)=1$ $f(1, 2)=1$ $f(1, 3)=1$ $f(1, 4)=1$ $f(2, 2)=1$ $f(2, 3)=2$ $f(2, 4)=2$ $f(3, 3)=1$ $f(3, 4)=1$ $f(4, 4)=0$ (there is no vertex left, so the number of components is $0$) Totally out $11$.
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())
v = [0] + [int(e) for e in input().split()]
ans = 0
for a, b in zip(v[:-1], v[1:]):
if a < b:
ans += (b-a)*(n-b+1)
else:
ans += b*(a-b)
print(ans)
``` | vfc_15790 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1151/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 1 3\n",
"output": "7",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits