context stringlengths 88 7.54k | groundtruth stringlengths 9 28.8k | groundtruth_language stringclasses 3 values | type stringclasses 2 values | code_test_cases listlengths 1 565 ⌀ | dataset stringclasses 6 values | code_language stringclasses 1 value | difficulty float64 0 1 ⌀ | mid stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.
You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.
Help Pashmak, print the number of edges in the required path.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi.
It's guaranteed that the graph doesn't contain self-loops and multiple edges.
Output
Print a single integer — the answer to the problem.
Examples
Input
3 3
1 2 1
2 3 1
3 1 1
Output
1
Input
3 3
1 2 1
2 3 2
3 1 3
Output
3
Input
6 7
1 2 1
3 2 5
2 4 2
2 5 2
2 6 9
5 4 3
4 3 4
Output
6
Note
In the first sample the maximum trail can be any of this trails: <image>.
In the second sample the maximum trail is <image>.
In the third sample the maximum trail is <image>.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import *
f = list(map(int, stdin.read().split()))
n, m = f[0], f[1]
d = [[] for i in range(100001)]
for j in range(2, len(f), 3):
x, y, w = f[j:j + 3]
d[w].append((y, x))
s = [0] * (n + 1)
for q in d:
for y, k in [(y, s[x]) for y, x in q]: s[y] = max(s[y], k + 1)
print(max(s)) | python | code_algorithm | [
{
"input": "6 7\n1 2 1\n3 2 5\n2 4 2\n2 5 2\n2 6 9\n5 4 3\n4 3 4\n",
"output": "6\n"
},
{
"input": "3 3\n1 2 1\n2 3 1\n3 1 1\n",
"output": "1\n"
},
{
"input": "3 3\n1 2 1\n2 3 2\n3 1 3\n",
"output": "3\n"
},
{
"input": "6 7\n1 2 1\n1 5 1\n5 2 3\n2 3 3\n3 4 4\n1 6 1\n6 2 3\n",... | code_contests | python | 0 | e21d9b9503193907eb32bc7fa85a1b5f |
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.
A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.
You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.
Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively.
Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v).
You may assume that there is at most one railway connecting any two towns.
Output
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1.
Examples
Input
4 2
1 3
3 4
Output
2
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Input
5 5
4 2
3 5
4 5
5 1
1 2
Output
3
Note
In the first sample, the train can take the route <image> and the bus can take the route <image>. Note that they can arrive at town 4 at the same time.
In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, m = map(int, input().split())
dist = [0] * (n + 1)
for row in range(n + 1):
dist[row] = [1] * (n + 1)
for i in range(m):
a, b = map(int, input().split())
dist[a][b] = dist[b][a] = 2
x, v, i = 3 - dist[1][n], [0] * (n + 1), 1
d = [n + 1] * (n + 1)
res = d[1] = 0
while i != n:
v[i] = 1
for j in range(1, n + 1):
if v[j] == 0 and dist[i][j] == x and d[j] > d[i] + 1:
d[j] = d[i] + 1
meu = n + 1
for j in range(1, n + 1):
if v[j] == 0 and d[j] < meu:
meu = d[j]
i = j
if meu == n + 1:
res = -1
break
elif i == n:
res = d[n]
break
print(res)
| python | code_algorithm | [
{
"input": "5 5\n4 2\n3 5\n4 5\n5 1\n1 2\n",
"output": "3\n"
},
{
"input": "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n",
"output": "-1\n"
},
{
"input": "4 2\n1 3\n3 4\n",
"output": "2\n"
},
{
"input": "3 1\n1 2\n",
"output": "-1\n"
},
{
"input": "3 1\n1 3\n",
"output... | code_contests | python | 0.9 | 5e927a266845e46a27bf299ba6f4c031 |
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.
For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.
There are <image> non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls.
The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball.
Output
Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.
Examples
Input
4
1 2 1 2
Output
7 3 0 0
Input
3
1 1 1
Output
6 0 0
Note
In the first sample, color 2 is dominant in three intervals:
* An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.
* An interval [4, 4] contains one ball, with color 2 again.
* An interval [2, 4] contains two balls of color 2 and one ball of color 1.
There are 7 more intervals and color 1 is dominant in all of them.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def main():
n = int(input())
a = [int(i) for i in input().strip().split()]
res = [0] * n
for st in range(n):
cnt = [0] * n
x = 0
y = 0
for ed in range(st, n):
cnt[a[ed] - 1] += 1
if (cnt[a[ed] - 1] > x) or (cnt[a[ed] - 1] == x and a[ed] - 1 < y):
x = cnt[a[ed] - 1]
y = a[ed] - 1
res[y] += 1
print(" ".join(map(str, res)))
if __name__ == "__main__":
main() | python | code_algorithm | [
{
"input": "3\n1 1 1\n",
"output": "6 0 0\n"
},
{
"input": "4\n1 2 1 2\n",
"output": "7 3 0 0\n"
},
{
"input": "10\n9 1 5 2 9 2 9 2 1 1\n",
"output": "18 30 0 0 1 0 0 0 6 0\n"
},
{
"input": "50\n17 13 19 19 19 34 32 24 24 13 34 17 19 19 7 32 19 13 13 30 19 34 34 28 41 24 24 4... | code_contests | python | 0 | 22312ec0c815c6e805298d7f35a963c2 |
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.
Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.
For example, consider the case when the mother has 5 flowers, and their moods are equal to 1, - 2, 1, 3, - 4. Suppose the mother suggested subarrays (1, - 2), (3, - 4), (1, 3), (1, - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:
* the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,
* the second flower adds ( - 2)·1 = - 2, because he is in one of chosen subarrays,
* the third flower adds 1·2 = 2, because he is in two of chosen subarrays,
* the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,
* the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays.
Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!
Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother.
The second line contains the flowers moods — n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100).
The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≤ li ≤ ri ≤ n) denoting the subarray a[li], a[li + 1], ..., a[ri].
Each subarray can encounter more than once.
Output
Print single integer — the maximum possible value added to the Alyona's happiness.
Examples
Input
5 4
1 -2 1 3 -4
1 2
4 5
3 4
1 4
Output
7
Input
4 3
1 2 3 4
1 3
2 4
1 1
Output
16
Input
2 2
-1 -2
1 1
1 2
Output
0
Note
The first example is the situation described in the statements.
In the second example Alyona should choose all subarrays.
The third example has answer 0 because Alyona can choose none of the subarrays.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | I=lambda:map(int,input().split())
R=range
ans=0
n,m=I()
a=list(I())
for _ in R(m):l,r=I();ans+=max(0,sum(a[i]for i in R(l-1,r)))
print(ans) | python | code_algorithm | [
{
"input": "4 3\n1 2 3 4\n1 3\n2 4\n1 1\n",
"output": "16\n"
},
{
"input": "5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4\n",
"output": "7\n"
},
{
"input": "2 2\n-1 -2\n1 1\n1 2\n",
"output": "0\n"
},
{
"input": "3 3\n1 -1 3\n1 2\n2 3\n1 3\n",
"output": "5\n"
},
{
"input":... | code_contests | python | 0.2 | 2cf19a2e9a276fc27bcaf3d76233ad85 |
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.
Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day consists of minutes 1, 2, ..., z. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.
Input
The only string contains three integers — n, m and z (1 ≤ n, m, z ≤ 104).
Output
Print single integer — the minimum number of artists that should be killed so that there are no artists in the room when Ilia calls.
Examples
Input
1 1 10
Output
10
Input
1 2 5
Output
2
Input
2 3 9
Output
1
Note
Taymyr is a place in the north of Russia.
In the first test the artists come each minute, as well as the calls, so we need to kill all of them.
In the second test we need to kill artists which come on the second and the fourth minutes.
In the third test — only the artist which comes on the sixth minute.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from math import *
def lcm(a, b): return a*b//gcd(a, b)
n, m, z = map(int, input().split())
print(z//lcm(n, m))
| python | code_algorithm | [
{
"input": "1 1 10\n",
"output": "10\n"
},
{
"input": "2 3 9\n",
"output": "1\n"
},
{
"input": "1 2 5\n",
"output": "2\n"
},
{
"input": "972 1 203\n",
"output": "0\n"
},
{
"input": "6 4 36\n",
"output": "3\n"
},
{
"input": "550 1 754\n",
"output": ... | code_contests | python | 1 | 154944a21f0f834a4675f2825c3d1c13 |
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except 1).
During his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ( + ) instead of division button (÷) and got sum of numerator and denominator that was equal to n instead of the expected decimal notation.
Petya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction <image> such that sum of its numerator and denominator equals n. Help Petya deal with this problem.
Input
In the only line of input there is an integer n (3 ≤ n ≤ 1000), the sum of numerator and denominator of the fraction.
Output
Output two space-separated positive integers a and b, numerator and denominator of the maximum possible proper irreducible fraction satisfying the given sum.
Examples
Input
3
Output
1 2
Input
4
Output
1 3
Input
12
Output
5 7
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
n=int(input())
d=n//2
c=n-d
while math.gcd(c,d)!=1:
c+=1
d-=1
print(d,c)
| python | code_algorithm | [
{
"input": "12\n",
"output": "5 7\n"
},
{
"input": "4\n",
"output": "1 3\n"
},
{
"input": "3\n",
"output": "1 2\n"
},
{
"input": "998\n",
"output": "497 501\n"
},
{
"input": "69\n",
"output": "34 35\n"
},
{
"input": "9\n",
"output": "4 5\n"
},
... | code_contests | python | 0.6 | 1d6d7c416d72c0e1447b1af70105e5b6 |
Pig is visiting a friend.
Pig's house is located at point 0, and his friend's house is located at point m on an axis.
Pig can use teleports to move along the axis.
To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.
Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds.
<image>
Determine if Pig can visit the friend using teleports only, or he should use his car.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of teleports and the location of the friend's house.
The next n lines contain information about teleports.
The i-th of these lines contains two integers ai and bi (0 ≤ ai ≤ bi ≤ m), where ai is the location of the i-th teleport, and bi is its limit.
It is guaranteed that ai ≥ ai - 1 for every i (2 ≤ i ≤ n).
Output
Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise.
You can print each letter in arbitrary case (upper or lower).
Examples
Input
3 5
0 2
2 4
3 5
Output
YES
Input
3 7
0 4
2 5
6 7
Output
NO
Note
The first example is shown on the picture below:
<image>
Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.
The second example is shown on the picture below:
<image>
You can see that there is no path from Pig's house to his friend's house that uses only teleports.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, m = list( map( int, input().split() ) )
A = []
B = []
CanReach = []
start_idx = 0
end_idx = 0
for i in range( n ):
a, b = list( map( int, input().split() ) )
A.append( a )
B.append( b )
memo = {}
def best( i ):
if A[i] <= m <= B[i]:
return ( True )
if i in memo:
return memo[i]
Best = False
for j in range( i+1, n ):
if A[j] <= B[i] <= B[j]:
Best |= best( j )
if i not in memo:
memo[i] = Best
return ( Best )
for i in range( n ):
if A[i] == 0:
if best( i ):
print( "YES" )
exit(0)
print( "NO" )
| python | code_algorithm | [
{
"input": "3 5\n0 2\n2 4\n3 5\n",
"output": "YES\n"
},
{
"input": "3 7\n0 4\n2 5\n6 7\n",
"output": "NO\n"
},
{
"input": "50 10\n0 2\n0 2\n0 6\n1 9\n1 3\n1 2\n1 6\n1 1\n1 1\n2 7\n2 6\n2 4\n3 9\n3 8\n3 8\n3 8\n3 6\n3 4\n3 7\n3 4\n3 6\n3 5\n4 8\n5 5\n5 7\n6 7\n6 6\n7 7\n7 7\n7 7\n7 8\n7 8... | code_contests | python | 0.7 | 34454032af38960590476fed66332631 |
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.
Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.
Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.
Input
The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of days.
The second line contains n space-separated integers m1, m2, ..., mn (0 ≤ mi < i) — the number of marks strictly above the water on each day.
Output
Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.
Examples
Input
6
0 1 0 3 0 2
Output
6
Input
5
0 1 2 1 2
Output
1
Input
5
0 1 1 2 2
Output
0
Note
In the first example, the following figure shows an optimal case.
<image>
Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.
In the second example, the following figure shows an optimal case.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | N = int(input())
above = list(map(int, input().split()))
if N == 1:
print(0)
quit()
required_mark = [0] * N
required_mark[N-2] = above[N-1]
for i in reversed(range(N-2)):
required_mark[i] = max(above[i+1], required_mark[i+1] - 1)
d = 0
mark = 1
for i in range(1, N):
if mark == above[i]:
mark += 1
elif mark >= required_mark[i]:
d += mark - above[i] - 1
else:
d += mark - above[i]
mark += 1
print(d) | python | code_algorithm | [
{
"input": "5\n0 1 1 2 2\n",
"output": "0\n"
},
{
"input": "6\n0 1 0 3 0 2\n",
"output": "6\n"
},
{
"input": "5\n0 1 2 1 2\n",
"output": "1\n"
},
{
"input": "7\n0 1 1 3 0 0 6\n",
"output": "10\n"
},
{
"input": "1\n0\n",
"output": "0\n"
},
{
"input": "3... | code_contests | python | 0 | 47571ebd8dda43e2dfc3912d99a43711 |
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard).
<image>
Input
The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have.
The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.
Output
Output a single number.
Examples
Input
9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard
Output
3
Input
6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard
Output
4
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | a, b = 0, 0
n = int(input())
for i in range(n):
x, y = input().split()
if y == 'soft':
a += 1
else:
b += 1
for i in range(1, 1000):
n = i*i
y = n // 2
x = n - y
if (a <= x and b <= y) or (a <= y and b <= x):
print(i)
break | python | code_algorithm | [
{
"input": "6\nparmesan hard\nemmental hard\nedam hard\ncolby hard\ngruyere hard\nasiago hard\n",
"output": "4\n"
},
{
"input": "9\nbrie soft\ncamembert soft\nfeta soft\ngoat soft\nmuenster soft\nasiago hard\ncheddar hard\ngouda hard\nswiss hard\n",
"output": "3\n"
},
{
"input": "9\ngorg... | code_contests | python | 0 | 479b392e3d2c3a2034263a11f1590a3e |
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.
To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
Input
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
Output
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
Examples
Input
5
270
250
250
230
250
Output
20 ml. from cup #4 to cup #1.
Input
5
250
250
250
250
250
Output
Exemplary pages.
Input
5
270
250
249
230
250
Output
Unrecoverable configuration.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
arr = [int(input()) for _ in range(n)]
if len(set(arr)) == 1:
print('Exemplary pages.')
elif len(set(arr)) > 3:
print('Unrecoverable configuration.')
else:
kek = set(arr)
kek = list(kek)
kek.sort()
val = kek[-1] - kek[0]
if val % 2 == 1:
print('Unrecoverable configuration.')
else:
val //= 2
if len(kek) > 2 and (kek[1] - val != kek[0] or kek[1] + val != kek[-1]):
print('Unrecoverable configuration.')
else:
x = kek[-1]
y = kek[0]
cnt1 = cnt2 = 0
for x1 in arr:
if x1 == x:
cnt1 += 1
if x1 == y:
cnt2 += 1
if cnt1 > 1 or cnt2 > 1:
print('Unrecoverable configuration.')
else:
ind1, ind2 = 0, 0
for i in range(n):
if arr[i] == x:
ind1 = i + 1
if arr[i] == y:
ind2 = i + 1
print(str(val) + ' ml. from cup #' + str(ind2) + ' to cup #' + str(ind1) + '.')
| python | code_algorithm | [
{
"input": "5\n250\n250\n250\n250\n250\n",
"output": "Exemplary pages.\n"
},
{
"input": "5\n270\n250\n250\n230\n250\n",
"output": "20 ml. from cup #4 to cup #1.\n"
},
{
"input": "5\n270\n250\n249\n230\n250\n",
"output": "Unrecoverable configuration.\n"
},
{
"input": "3\n1\n1\... | code_contests | python | 0 | f181be8f34ec3e6eaac6dc0efbb53aae |
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.
The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.
There are n winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office.
Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.
What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?
The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.
Input
The first line contains one integer n (1 ≤ n ≤ 100) — the number of T-shirts.
The i-th of the next n lines contains a_i — the size of the i-th T-shirt of the list for the previous year.
The i-th of the next n lines contains b_i — the size of the i-th T-shirt of the list for the current year.
It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list b from the list a.
Output
Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.
Examples
Input
3
XS
XS
M
XL
S
XS
Output
2
Input
2
XXXL
XXL
XXL
XXXS
Output
1
Input
2
M
XS
XS
M
Output
0
Note
In the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".
In the second example Ksenia should replace "L" in "XXXL" with "S".
In the third example lists are equal.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | t=int(input())
pre=[]
curr=[]
for i in range(t):
s1=input()
pre.append(s1)
for i in range(t):
s2=input()
curr.append(s2)
z=0
for i in range(t):
if pre[i] in curr:
curr.remove(pre[i])
pass
else:
z+=1
print(z) | python | code_algorithm | [
{
"input": "2\nM\nXS\nXS\nM\n",
"output": "0\n"
},
{
"input": "3\nXS\nXS\nM\nXL\nS\nXS\n",
"output": "2\n"
},
{
"input": "2\nXXXL\nXXL\nXXL\nXXXS\n",
"output": "1\n"
},
{
"input": "6\nM\nXXS\nXXL\nXXL\nL\nL\nXXS\nXXL\nS\nXXS\nL\nL\n",
"output": "2\n"
},
{
"input":... | code_contests | python | 0.6 | e8ceeb0158c8782ef04a2b0cc91a7d59 |
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} ≤ a_{2},
a_{n} ≤ a_{n-1} and
a_{i} ≤ 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 ≤ n ≤ 10^{5}) — size of the array.
Second line of input contains n integers a_{i} — elements of array. Either a_{i} = -1 or 1 ≤ a_{i} ≤ 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.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import os
from io import BytesIO
from math import trunc
if os.name == 'nt':
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
MX = 201
MOD = 998244353
MODF = float(MOD)
MODF_inv = 1.0 / MODF
quickmod1 = lambda x: x - MODF * trunc(x / MODF)
def quickmod(a):
return a - MODF * trunc(a * MODF_inv)
def main():
n = int(input())
a = map(int, input().split())
dp0 = [1.0] * MX
dp1 = [0.0] * MX
for x in a:
pomdp0 = [0.0] * MX
pomdp1 = [0.0] * MX
if x == -1:
for val in range(1, MX):
pomdp0[val] = quickmod(
pomdp0[val - 1] + dp1[val - 1] + dp0[val - 1])
pomdp1[val] = quickmod(
pomdp1[val - 1] + dp1[MX - 1] - dp1[val - 1] + dp0[val] -
dp0[val - 1])
else:
pomdp0[x] = quickmod(dp1[x - 1] + dp0[x - 1])
pomdp1[x] = quickmod(dp1[MX - 1] - dp1[x - 1] + dp0[x] - dp0[x - 1])
for val in range(x + 1, MX):
pomdp0[val] = pomdp0[val - 1]
pomdp1[val] = pomdp1[val - 1]
dp0, dp1 = pomdp0, pomdp1
print(int(dp1[MX - 1] if n > 1 else dp0[MX - 1]) % MOD)
if __name__ == "__main__":
main()
| python | code_algorithm | [
{
"input": "3\n1 -1 2\n",
"output": "1\n"
},
{
"input": "2\n-1 -1\n",
"output": "200\n"
},
{
"input": "8\n-1 -1 -1 59 -1 -1 -1 -1\n",
"output": "658449230\n"
},
{
"input": "2\n38 38\n",
"output": "1\n"
},
{
"input": "2\n-1 35\n",
"output": "1\n"
},
{
"... | code_contests | python | 0 | 14cb7d5fdb07ce4dae5e9100b7545609 |
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed n.
You are standing at 0 and want to reach n+1 somehow. If you are standing at the position x, you can jump to any position in the range [x + 1; x + d]. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if d=1, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells 0 and n+1 belong to wooden platforms.
You want to know if it is possible to reach n+1 from 0 if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.
Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).
For example, if n=7, m=3, d=2 and c = [1, 2, 1], then one of the ways to reach 8 from 0 is follow:
<image> The first example: n=7.
Input
The first line of the input contains three integers n, m and d (1 ≤ n, m, d ≤ 1000, m ≤ n) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly.
The second line of the input contains m integers c_1, c_2, ..., c_m (1 ≤ c_i ≤ n, ∑_{i=1}^{m} c_i ≤ n), where c_i is the length of the i-th platform.
Output
If it is impossible to reach n+1 from 0, print NO in the first line. Otherwise, print YES in the first line and the array a of length n in the second line — the sequence of river cells (excluding cell 0 and cell n + 1).
If the cell i does not belong to any platform, a_i should be 0. Otherwise, it should be equal to the index of the platform (1-indexed, platforms are numbered from 1 to m in order of input) to which the cell i belongs.
Note that all a_i equal to 1 should form a contiguous subsegment of the array a of length c_1, all a_i equal to 2 should form a contiguous subsegment of the array a of length c_2, ..., all a_i equal to m should form a contiguous subsegment of the array a of length c_m. The leftmost position of 2 in a should be greater than the rightmost position of 1, the leftmost position of 3 in a should be greater than the rightmost position of 2, ..., the leftmost position of m in a should be greater than the rightmost position of m-1.
See example outputs for better understanding.
Examples
Input
7 3 2
1 2 1
Output
YES
0 1 0 2 2 0 3
Input
10 1 11
1
Output
YES
0 0 0 0 0 0 0 0 0 1
Input
10 1 5
2
Output
YES
0 0 0 0 1 1 0 0 0 0
Note
Consider the first example: the answer is [0, 1, 0, 2, 2, 0, 3]. The sequence of jumps you perform is 0 → 2 → 4 → 5 → 7 → 8.
Consider the second example: it does not matter how to place the platform because you always can jump from 0 to 11.
Consider the third example: the answer is [0, 0, 0, 0, 1, 1, 0, 0, 0, 0]. The sequence of jumps you perform is 0 → 5 → 6 → 11.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from collections import defaultdict
import sys
input=sys.stdin.readline
n,m,d=map(int,input().split())
c=[int(i) for i in input().split()]
ind=defaultdict(int)
suff=n
for i in range(m-1,-1,-1):
suff-=c[i]
ind[i+1]=suff+1
indl=[]
for i in ind:
indl.append(i)
indl.reverse()
cur=0
for i in indl:
if ind[i]-cur>d:
ind[i]=cur+d
cur+=d
cur+=c[i-1]-1
else:
cur=ind[i]+c[i-1]-1
#print(ind)
if n+1-cur>d:
print('NO')
else:
print('YES')
ans=[0]*(n)
for i in range(1,m+1):
for j in range(ind[i]-1,min(n,ind[i]+c[i-1]-1)):
ans[j]=i
print(*ans)
| python | code_algorithm | [
{
"input": "7 3 2\n1 2 1\n",
"output": "YES\n0 1 0 2 2 0 3\n"
},
{
"input": "10 1 5\n2\n",
"output": "YES\n0 0 0 0 1 1 0 0 0 0\n"
},
{
"input": "10 1 11\n1\n",
"output": "YES\n0 0 0 0 0 0 0 0 0 1\n"
},
{
"input": "15 2 5\n1 1\n",
"output": "NO\n"
},
{
"input": "10... | code_contests | python | 0 | 981e2072ff27748f562e8ad295354c7f |
Bob is about to take a hot bath.
There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second.
If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be:
<image>
Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.
Determine how much each tap should be opened so that Bob was pleased with the result in the end.
Input
You are given five integers t1, t2, x1, x2 and t0 (1 ≤ t1 ≤ t0 ≤ t2 ≤ 106, 1 ≤ x1, x2 ≤ 106).
Output
Print two space-separated integers y1 and y2 (0 ≤ y1 ≤ x1, 0 ≤ y2 ≤ x2).
Examples
Input
10 70 100 100 25
Output
99 33
Input
300 500 1000 1000 300
Output
1000 0
Input
143 456 110 117 273
Output
76 54
Note
In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
def gcd(a,b):
if(b==0):
return a
return gcd(b,a%b)
l=input().split()
t1=int(l[0])
t2=int(l[1])
x1=int(l[2])
x2=int(l[3])
t0=int(l[4])
num1=t2-t0
num2=t0-t1
if(t1==t2):
print(x1,x2)
quit()
if(num1==0):
print(0,x2)
quit()
if(num2==0):
print(x1,0)
quit()
z=num2/num1
maxa=10**18
ans=(0,0)
for i in range(1,x1+1):
ok=z*i
if(ok>x2):
break
num1=i
num2=math.ceil(ok)
if(maxa==((num2/num1)-z) and num2+num1>ans[0]+ans[1]):
ans=(num1,num2)
elif(maxa>((num2/num1)-z)):
ans=(num1,num2)
maxa=((num2/num1-z))
if(ans==(0,0)):
ans=(0,x2)
print(ans[0],ans[1])
| python | code_algorithm | [
{
"input": "300 500 1000 1000 300\n",
"output": "1000 0\n"
},
{
"input": "10 70 100 100 25\n",
"output": "99 33\n"
},
{
"input": "143 456 110 117 273\n",
"output": "76 54\n"
},
{
"input": "176902 815637 847541 412251 587604\n",
"output": "228033 410702\n"
},
{
"in... | code_contests | python | 0 | 927a8764fc85e7579a727e6046721238 |
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:
—Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.
—No problem! — said Bob and immediately gave her an answer.
Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
Input
The first line contains one integer n (0 ≤ n ≤ 109) without leading zeroes. The second lines contains one integer m (0 ≤ m ≤ 109) — Bob's answer, possibly with leading zeroes.
Output
Print OK if Bob's answer is correct and WRONG_ANSWER otherwise.
Examples
Input
3310
1033
Output
OK
Input
4
5
Output
WRONG_ANSWER
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def sort(s):
return sorted(sorted(s), key=str.upper)
s=input()
s1=input()
l=sort(s)
c=l.count('0')
res=""
if(len(l)>c):
res=res+l[c]
for i in range(c):
res=res+l[i]
for i in range(c+1,len(s)):
res=res+l[i]
if(s1==res):
print("OK")
else:
print("WRONG_ANSWER") | python | code_algorithm | [
{
"input": "3310\n1033\n",
"output": "OK\n"
},
{
"input": "4\n5\n",
"output": "WRONG_ANSWER\n"
},
{
"input": "17109\n01179\n",
"output": "WRONG_ANSWER\n"
},
{
"input": "111111111\n111111111\n",
"output": "OK\n"
},
{
"input": "912\n9123\n",
"output": "WRONG_ANS... | code_contests | python | 0.1 | 26616726f7f771e1409e4c088d37b7da |
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute
$$$ (a_1 + a_2) ⊕ (a_1 + a_3) ⊕ … ⊕ (a_1 + a_n) \\\ ⊕ (a_2 + a_3) ⊕ … ⊕ (a_2 + a_n) \\\ … \\\ ⊕ (a_{n-1} + a_n) \\\ $$$
Here x ⊕ y is a bitwise XOR operation (i.e. x ^ y in many modern programming languages). You can read about it in Wikipedia: <https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation>.
Input
The first line contains a single integer n (2 ≤ n ≤ 400 000) — the number of integers in the array.
The second line contains integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^7).
Output
Print a single integer — xor of all pairwise sums of integers in the given array.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
2
Note
In the first sample case there is only one sum 1 + 2 = 3.
In the second sample case there are three sums: 1 + 2 = 3, 1 + 3 = 4, 2 + 3 = 5. In binary they are represented as 011_2 ⊕ 100_2 ⊕ 101_2 = 010_2, thus the answer is 2.
⊕ is the bitwise xor operation. To define x ⊕ y, consider binary representations of integers x and y. We put the i-th bit of the result to be 1 when exactly one of the i-th bits of x and y is 1. Otherwise, the i-th bit of the result is put to be 0. For example, 0101_2 ⊕ 0011_2 = 0110_2.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from bisect import bisect_left, bisect_right
def go():
n = int(input())
a = list(map(int, input().split()))
b = max(a).bit_length()
res = 0
vals = a
for i in range(b + 1):
# print("")
b2 = 2 << i
b1 = 1 << i
a0 = [aa for aa in a if aa & b1==0]
a1 = [aa for aa in a if aa & b1]
a = a0 + a1
vals = [aa % b2 for aa in a]
cnt = 0
# vals = sorted(aa % b2 for aa in a)
x1, x2, y1 = n - 1, n - 1, n - 1
for j, v in enumerate(vals):
while x1 > -1 and vals[x1] >= b1 - v:
x1 -= 1
while y1 > -1 and vals[y1] > b2 - v - 1:
y1 -= 1
# x, y = bisect_left(vals,b1-v), bisect_right(vals,b2-v-1)
x, y = x1 + 1, y1 + 1
# print('+++', x, y, bisect_left(vals, b1 - v), bisect_right(vals, b2 - v - 1))
cnt += y - x
if x <= j < y:
cnt -= 1
while x2 > -1 and vals[x2] >= b2 + b1 - v:
x2 -= 1
# x, y = bisect_left(vals,b2+b1-v), len(vals)
x, y = x2 + 1, n
# print('---', x, y, bisect_left(vals, b2 + b1 - v), len(vals))
cnt += y - x
if x <= j < y:
cnt -= 1
res += b1 * (cnt // 2 % 2)
return res
print(go())
| python | code_algorithm | [
{
"input": "3\n1 2 3\n",
"output": "2\n"
},
{
"input": "2\n1 2\n",
"output": "3\n"
},
{
"input": "51\n50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100\n",
"output": "148\n"
},
... | code_contests | python | 0 | 8081dfe29155a81c1b0a9eb265ec8301 |
Given an array a of length n, find another array, b, of length n such that:
* for each i (1 ≤ i ≤ n) MEX(\\{b_1, b_2, …, b_i\})=a_i.
The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set.
If such array doesn't exist, determine this.
Input
The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of the array a.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ i) — the elements of the array a. It's guaranteed that a_i ≤ a_{i+1} for 1≤ i < n.
Output
If there's no such array, print a single line containing -1.
Otherwise, print a single line containing n integers b_1, b_2, …, b_n (0 ≤ b_i ≤ 10^6)
If there are multiple answers, print any.
Examples
Input
3
1 2 3
Output
0 1 2
Input
4
0 0 0 2
Output
1 3 4 0
Input
3
1 1 3
Output
0 2 1
Note
In the second test case, other answers like [1,1,1,0], for example, are valid.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
arr=list(map(int,input().split()))
flag=0
vis=[0]*(10**6+1)
for i in range(n):
if arr[i]>i+1:
flag=1
vis[arr[i]]=1
if flag==1:
print(-1)
quit()
b=[-1]*(n)
for i in range(1,n):
if arr[i-1]!=arr[i]:
b[i]=arr[i-1]
not_vis=[]
for i in range(10**6+1):
if vis[i]==0:
not_vis.append(i)
j=0
for i in range(n):
if b[i]==-1:
b[i]=not_vis[j]
j+=1
print(*b)
| python | code_algorithm | [
{
"input": "3\n1 2 3\n",
"output": "0 1 2\n"
},
{
"input": "3\n1 1 3\n",
"output": "0 2 1\n"
},
{
"input": "4\n0 0 0 2\n",
"output": "1 3 4 0\n"
},
{
"input": "7\n0 0 2 2 5 5 6\n",
"output": "1 3 0 4 2 7 5\n"
},
{
"input": "1\n1\n",
"output": "0\n"
},
{
... | code_contests | python | 0 | 971e2db40403f97027b64f636b525277 |
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
Input
The first line contains the single integer n (1 ≤ n ≤ 1000) — the number of contests where the coder participated.
The next line contains n space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.
Output
Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.
Examples
Input
5
100 50 200 150 200
Output
2
Input
10
4664 6496 5814 7010 5762 5736 6944 4850 3698 7242
Output
4
Note
In the first sample the performances number 2 and 3 are amazing.
In the second sample the performances number 2, 4, 9 and 10 are amazing.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
a=list(map(int,input().split()))
c=[]
d=0
c.append(a[0])
for i in range(1,n):
y=a[i]-a[i-1]
if y>0 and a[i]>max(c):
c.append(a[i])
d+=1
elif y<0 and a[i]<min(c):
c.append(a[i])
d+=1
print(d)
#print(c) | python | code_algorithm | [
{
"input": "10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242\n",
"output": "4\n"
},
{
"input": "5\n100 50 200 150 200\n",
"output": "2\n"
},
{
"input": "5\n100 36 53 7 81\n",
"output": "2\n"
},
{
"input": "5\n100 81 53 36 7\n",
"output": "4\n"
},
{
"input": "... | code_contests | python | 1 | 585d767940b35031d9378b62e25715be |
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.
Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.
Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.
Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:
1. thread x is not updated (it has no new messages);
2. the list order 1, 2, ..., n changes to a1, a2, ..., an.
Input
The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1 ≤ ai ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.
Output
Output a single integer — the number of threads that surely contain a new message.
Examples
Input
5
5 2 1 3 4
Output
2
Input
3
1 2 3
Output
0
Input
4
4 3 2 1
Output
3
Note
In the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.
In the second test case, there may be no new messages at all, since the thread order hasn't changed.
In the third test case, only thread 1 can contain no new messages.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
arr = list(map(int,input().split()))
ans = n-1
for i in range(-1,-n,-1):
if arr[i]>arr[i-1]:
ans-=1
else:
break
print(ans) | python | code_algorithm | [
{
"input": "5\n5 2 1 3 4\n",
"output": "2\n"
},
{
"input": "4\n4 3 2 1\n",
"output": "3\n"
},
{
"input": "3\n1 2 3\n",
"output": "0\n"
},
{
"input": "4\n2 3 1 4\n",
"output": "2\n"
},
{
"input": "3\n1 3 2\n",
"output": "2\n"
},
{
"input": "6\n3 2 1 6 4... | code_contests | python | 0 | df014ff102c3733628e2f179889077ac |
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from bisect import bisect_left, bisect_right, insort
R = lambda: map(int, input().split())
n, arr = int(input()), list(R())
dp = []
for i in range(n):
idx = bisect_left(dp, arr[i])
if idx >= len(dp):
dp.append(arr[i])
else:
dp[idx] = arr[i]
print(len(dp)) | python | code_algorithm | [
{
"input": "3\n3 1 2\n",
"output": "2\n"
},
{
"input": "100\n36 48 92 87 28 85 42 10 44 41 39 3 79 9 14 56 1 16 46 35 93 8 82 26 100 59 60 2 96 52 13 98 70 81 71 94 54 91 17 88 33 30 19 50 18 73 65 29 78 21 61 7 99 97 45 89 57 27 76 11 49 72 84 69 43 62 4 22 75 6 66 83 38 34 86 15 40 51 37 74 67 31 ... | code_contests | python | 1 | ed4bf8d99b7591584ee78f8503172fde |
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card.
The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.
Suppose Ciel and Jiro play optimally, what is the score of the game?
Input
The first line contain an integer n (1 ≤ n ≤ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≤ si ≤ 100) — the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≤ ck ≤ 1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.
Output
Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.
Examples
Input
2
1 100
2 1 10
Output
101 10
Input
1
9 2 8 6 5 9 4 7 1 3
Output
30 15
Input
3
3 1 3 2
3 5 4 6
2 8 7
Output
18 18
Input
3
3 1000 1000 1000
6 1000 1000 1000 1000 1000 1000
5 1000 1000 1000 1000 1000
Output
7000 7000
Note
In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10.
In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import re
def main():
n=eval(input())
a=[]
s=[]
s.append(0)
s.append(0)
while n:
n-=1
temp=re.split(' ',input())
k=eval(temp[0])
for i in range(k>>1):
s[0]+=eval(temp[i+1])
if k&1:
a.append(eval(temp[(k+1)>>1]))
for i in range((k+1)>>1,k):
s[1]+=eval(temp[i+1])
a.sort(reverse=True)
k=0
for i in a:
s[k]+=i
k^=1
print(s[0],s[1])
main() | python | code_algorithm | [
{
"input": "3\n3 1 3 2\n3 5 4 6\n2 8 7\n",
"output": "18 18\n"
},
{
"input": "2\n1 100\n2 1 10\n",
"output": "101 10\n"
},
{
"input": "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000\n",
"output": "7000 7000\n"
},
{
"input": "1\n9 2 8 6 5 9 4 ... | code_contests | python | 0.1 | 708d90da4d95de1a2e484592f7bc06be |
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers — ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
Input
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries.
Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
5 7
1 5 1
2 5 1
3 5 1
4 5 1
1 2 2
2 3 2
3 4 2
5
1 5
5 1
2 5
1 5
1 4
Output
1
1
1
1
2
Note
Let's consider the first sample.
<image> The figure above shows the first sample.
* Vertex 1 and vertex 2 are connected by color 1 and 2.
* Vertex 3 and vertex 4 are connected by color 3.
* Vertex 1 and vertex 4 are not connected by any single color.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def build_graph():
line1 = input().strip().split()
n = int(line1[0])
m = int(line1[1])
graph = {}
for _ in range(m):
line = input().strip().split()
u = int(line[0])
v = int(line[1])
c = int(line[2])
if c not in graph:
graph[c] = {j: [] for j in range(1, n+1)}
graph[c][u].append(v)
graph[c][v].append(u)
return graph
def no_of_paths(u, v, graph):
x = 0
for c in graph:
parent = {}
parent = dfs_visit(v, graph[c], parent)
if u in parent:
x += 1
return x
def dfs_visit(i, adj_list, parent):
for j in adj_list[i]:
if j not in parent:
parent[j] = i
dfs_visit(j, adj_list, parent)
return parent
if __name__ == "__main__":
graph = build_graph()
for _ in range(int(input())):
line = input().strip().split()
print(no_of_paths(int(line[0]), int(line[1]), graph)) | python | code_algorithm | [
{
"input": "5 7\n1 5 1\n2 5 1\n3 5 1\n4 5 1\n1 2 2\n2 3 2\n3 4 2\n5\n1 5\n5 1\n2 5\n1 5\n1 4\n",
"output": "1\n1\n1\n1\n2\n"
},
{
"input": "4 5\n1 2 1\n1 2 2\n2 3 1\n2 3 3\n2 4 3\n3\n1 2\n3 4\n1 4\n",
"output": "2\n1\n0\n"
},
{
"input": "2 1\n1 2 1\n1\n1 2\n",
"output": "1\n"
},
... | code_contests | python | 1 | c6d15422c40ce0a7a175dc309b5a26e3 |
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin
c = [[0]*1002 for _ in range(0,1002)]
MOD = int(1e9+7)
for i in range(0,1002):
c[i][0] = c[i][i] = 1
for j in range(0,i):
c[i][j] = (c[i-1][j-1] + c[i-1][j])%MOD
r = map(int,stdin.read().split())
n = next(r)
ans = 1
sum = 0
for _ in range(0,n):
x = next(r)
ans = (ans * c[sum+x-1][sum])%MOD
sum += x
print(ans) | python | code_algorithm | [
{
"input": "3\n2\n2\n1\n",
"output": "3\n"
},
{
"input": "4\n1\n2\n3\n4\n",
"output": "1680\n"
},
{
"input": "25\n35\n43\n38\n33\n47\n44\n40\n36\n41\n42\n33\n30\n49\n42\n62\n39\n40\n35\n43\n31\n42\n46\n42\n34\n33\n",
"output": "362689152\n"
},
{
"input": "47\n20\n21\n16\n18\n... | code_contests | python | 0 | efd4e1d387c490f1552ee16dae2621d1 |
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
tl = list(map(int, input().split()))
time=cnt=0
while cnt <15 and time<90:
time+=1
if tl.count(time)>0:
cnt=0
else:
cnt+=1
print(time) | python | code_algorithm | [
{
"input": "3\n7 20 88\n",
"output": "35\n"
},
{
"input": "9\n15 20 30 40 50 60 70 80 90\n",
"output": "90\n"
},
{
"input": "9\n16 20 30 40 50 60 70 80 90\n",
"output": "15\n"
},
{
"input": "2\n1 18\n",
"output": "16\n"
},
{
"input": "9\n6 20 27 28 40 53 59 70 85\... | code_contests | python | 0 | 1bd1caf7bdabf2fc9a0af0feedc377ec |
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #http://codeforces.com/problemset/problem/719/B
#solved
n = int(input())
s = input()
red_black = True
swap_red = {"b": 0, "r": 0}
swap_black = {"b": 0, "r": 0}
for c in s:
if red_black is True and c != "b":
swap_black["r"] += 1
elif red_black is False and c != "r":
swap_black["b"] += 1
if red_black is True and c != "r":
swap_red["b"] += 1
elif red_black is False and c != "b":
swap_red["r"] += 1
red_black = True if red_black is False else False
black = (swap_black[max(swap_black, key=swap_black.get)] - swap_black[min(swap_black, key=swap_black.get)]) + swap_black[min(swap_black, key=swap_black.get)]
red = (swap_red[max(swap_red, key=swap_red.get)] - swap_red[min(swap_red, key=swap_red.get)]) + swap_red[min(swap_red, key=swap_red.get)]
print(int(min(red, black)))
| python | code_algorithm | [
{
"input": "5\nrbbrr\n",
"output": "1\n"
},
{
"input": "5\nbbbbb\n",
"output": "2\n"
},
{
"input": "3\nrbr\n",
"output": "0\n"
},
{
"input": "166\nrbbbbbbbbbbbbrbrrbbrbbbrbbbbbbbbbbrbbbbbbrbbbrbbbbbrbbbbbbbrbbbbbbbrbbrbbbbbbbbrbbbbbbbbbbbbbbrrbbbrbbbbbbbbbbbbbbrbrbbbbbbbbbbbr... | code_contests | python | 0 | 1c30fa1473cb7131b46d15a3422e2ee0 |
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
R=lambda:list(map(int,input().split()))
a,b=R()
c,d=R()
if abs(b-d)%math.gcd(a,c)!=0:
print(-1)
exit(0)
while b != d:
if b<d: b+=a
else: d+=c
print(b)
| python | code_algorithm | [
{
"input": "20 2\n9 19\n",
"output": "82\n"
},
{
"input": "2 1\n16 12\n",
"output": "-1\n"
},
{
"input": "84 82\n38 6\n",
"output": "82\n"
},
{
"input": "2 3\n2 2\n",
"output": "-1\n"
},
{
"input": "2 3\n4 99\n",
"output": "99\n"
},
{
"input": "3 7\n3 ... | code_contests | python | 0.2 | c3d3121a64b3490edbc1f9e1bbd71cf1 |
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def f():
n, m = map(int, input().split())
l = list(tuple(map(int, input().split())) for _ in range(n))
l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
last, r = [0] * 4, 0
for i, (w, c) in enumerate(l):
if m < w:
break
m -= w
r += c
last[w] = c
else:
return r
if not m:
return r
res, tail = [r], (None, [], [], [])
for w, c in l[i:]:
tail[w].append(c)
for w in 1, 2, 3:
tail[w].append(0)
_, t1, t2, t3 = tail
if m == 1:
res.append(r + t1[0])
if last[1]:
res.append(r - last[1] + t2[0])
if last[2]:
res.append(r - last[2] + t3[0])
if last[3]:
r -= last[3]
res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
else: # m == 2
res += (r + sum(t1[:2]), r + t2[0])
if last[1]:
res.append(r - last[1] + t3[0])
if last[2]:
res.append(r - last[2] + t3[0] + t1[0])
return max(res)
def main():
print(f())
if __name__ == '__main__':
main()
| python | code_algorithm | [
{
"input": "4 3\n3 10\n2 7\n2 8\n1 1\n",
"output": "10\n"
},
{
"input": "2 2\n1 3\n2 2\n",
"output": "3\n"
},
{
"input": "1 1\n2 1\n",
"output": "0\n"
},
{
"input": "52 102\n3 199\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 100\n2 10... | code_contests | python | 0.5 | c7bdeebc3ab1bec429122f4b93485a4d |
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai.
Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times).
After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.
Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.
Input
The first line contains three integers n, k and m (1 ≤ n ≤ 105, 2 ≤ k ≤ 109, 1 ≤ m ≤ 109).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number of city, person from which must take seat i in the bus.
Output
Output the number of remaining participants in the line.
Examples
Input
4 2 5
1 2 3 1
Output
12
Input
1 9 10
1
Output
1
Input
3 2 10
1 2 1
Output
0
Note
In the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from collections import deque
input=sys.stdin.readline
n,k,m=map(int,input().split())
a=list(map(int,input().split()))
r=a[0]
flag=0
for i in range(n):
if r!=a[i]:
flag=1
break
if flag==0:
print((m*n)%k)
sys.exit()
if k>n:
print(m*n)
sys.exit()
curr=a[0]
tmp=1
que=deque([(a[0],1)])
for i in range(1,n):
if a[i]==curr:
tmp+=1
que.append((a[i],tmp))
if tmp==k:
for j in range(k):
que.pop()
if que:
tmp=que[-1][1]
curr=que[-1][0]
else:
curr=-1
else:
tmp=1
curr=a[i]
que.append((a[i],tmp))
quecop=[]
for i in que:
quecop.append(i[0])
leftrem=0
rightrem=0
if not que:
print(0)
sys.exit()
while que[0][0]==que[-1][0]:
r=que[0][0]
count1=0
p=len(que)
count2=p-1
while count1<p and que[count1][0]==r:
count1+=1
if count1==p:
break
while count2>=0 and que[count2][0]==r:
count2-=1
if count1+p-1-count2<k:
break
leftrem+=count1
rightrem+=k-count1
for i in range(count1):
que.popleft()
for i in range(k-count1):
que.pop()
if que:
t=que[0][0]
flag=0
for i in que:
if i[0]!=t:
flag=1
break
if flag:
print(leftrem+rightrem+len(que)*m)
else:
r=[]
for i in range(leftrem):
if r and r[-1][0]==quecop[i]:
r[-1][1]+=1
else:
r.append([quecop[i],1])
if r and r[-1][0]==que[0][0]:
r[-1][0]=(r[-1][0]+(len(que)*m))%k
if r[-1][1]==0:
r.pop()
else:
if (len(que)*m)%k:
r.append([que[0][0],(len(que)*m)%k])
for i in range(len(quecop)-rightrem,len(quecop)):
if r and r[-1][0]==quecop[i]:
r[-1][1]+=1
if r[-1][1]==k:
r.pop()
else:
r.append([quecop[i],1])
finans=0
for i in r:
finans+=i[1]
print(finans) | python | code_algorithm | [
{
"input": "4 2 5\n1 2 3 1\n",
"output": "12\n"
},
{
"input": "1 9 10\n1\n",
"output": "1\n"
},
{
"input": "3 2 10\n1 2 1\n",
"output": "0\n"
},
{
"input": "10 5 1000000000\n1 1 1 2 2 1 2 2 2 2\n",
"output": "10000000000\n"
},
{
"input": "5 3 3\n1 2 2 1 1\n",
... | code_contests | python | 0 | 75a333362852698e353d5c5724912d03 |
There is a rectangular grid of n rows of m initially-white cells each.
Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.
There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i, j) (i < j) exists such that <image> or <image>, where <image> denotes intersection of sets, and <image> denotes the empty set.
You are to determine whether a valid sequence of operations exists that produces a given final grid.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the grid, respectively.
Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.
Output
If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes).
You can print each character in any case (upper or lower).
Examples
Input
5 8
.#.#..#.
.....#..
.#.#..#.
#.#....#
.....#..
Output
Yes
Input
5 5
..#..
..#..
#####
..#..
..#..
Output
No
Input
5 9
........#
#........
..##.#...
.......#.
....#.#.#
Output
No
Note
For the first example, the desired setup can be produced by 3 operations, as is shown below.
<image>
For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def read_data():
n, m = map(int, input().strip().split())
a = []
for i in range(n):
line = list(input().strip())
for j in range(len(line)):
if line[j] == ".":
line[j] = 0
else:
line[j] = 1
a.append(line)
return n, m, a
def get_step(i,j):
rows = []
cols = []
for k in range(m):
if a[i][k] == 1:
cols.append(k)
if k in usedc:
return "No"
else:
usedc.append(k)
for k in range(n):
if a[k][j] == 1:
rows.append(k)
if k in usedr:
return "No"
else:
usedr.append(k)
for row in rows:
for col in cols:
if a[row][col] == 0:
return "No"
else:
a[row][col] = 0
return "Ok"
def solve():
for i in range(n):
for j in range(m):
if a[i][j] == 1:
step = get_step(i,j)
if step == "No":
return "No"
return "Yes"
n, m, a = read_data()
usedr = []
usedc = []
print(solve())
| python | code_algorithm | [
{
"input": "5 9\n........#\n#........\n..##.#...\n.......#.\n....#.#.#\n",
"output": "No\n"
},
{
"input": "5 5\n..#..\n..#..\n#####\n..#..\n..#..\n",
"output": "No\n"
},
{
"input": "5 8\n.#.#..#.\n.....#..\n.#.#..#.\n#.#....#\n.....#..\n",
"output": "Yes\n"
},
{
"input": "9 5... | code_contests | python | 0 | 866e1b1a5024d76d0150325413102f70 |
Kuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games.
Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity.
The paper is divided into n pieces enumerated from 1 to n. Shiro has painted some pieces with some color. Specifically, the i-th piece has color c_{i} where c_{i} = 0 defines black color, c_{i} = 1 defines white color and c_{i} = -1 means that the piece hasn't been colored yet.
The rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by at most one arrow. After that the players must choose the color (0 or 1) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, [1 → 0 → 1 → 0], [0 → 1 → 0 → 1], [1], [0] are valid paths and will be counted. You can only travel from piece x to piece y if and only if there is an arrow from x to y.
But Kuro is not fun yet. He loves parity. Let's call his favorite parity p where p = 0 stands for "even" and p = 1 stands for "odd". He wants to put the arrows and choose colors in such a way that the score has the parity of p.
It seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo 10^{9} + 7.
Input
The first line contains two integers n and p (1 ≤ n ≤ 50, 0 ≤ p ≤ 1) — the number of pieces and Kuro's wanted parity.
The second line contains n integers c_{1}, c_{2}, ..., c_{n} (-1 ≤ c_{i} ≤ 1) — the colors of the pieces.
Output
Print a single integer — the number of ways to put the arrows and choose colors so the number of valid paths of alternating colors has the parity of p.
Examples
Input
3 1
-1 0 1
Output
6
Input
2 1
1 0
Output
1
Input
1 1
-1
Output
2
Note
In the first example, there are 6 ways to color the pieces and add the arrows, as are shown in the figure below. The scores are 3, 3, 5 for the first row and 5, 3, 3 for the second row, both from left to right.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n,p=map(int,input().split())
nums=[0]+list(map(int,input().split()))
mod=10**9+7
f=[[[[0]*2 for _ in range(2)] for _ in range(2)] for _ in range(n+1)]
_2=[0]*(n+1)
_2[0]=1
for i in range(1,n+1):
_2[i]=(_2[i-1]<<1)%mod
f[0][0][0][0]=1
if nums[1]!=0:
f[1][1][0][1]+=1
if nums[1]!=1:
f[1][1][1][0]+=1
for i in range(2,n+1):
for j in range(2):
for ob in range(2):
for ow in range(2):
qwq=f[i-1][j][ob][ow]
if nums[i]!=0:
if ob:
f[i][j][ob][ow]=(f[i][j][ob][ow]+qwq*_2[i-2])%mod
f[i][j^1][ob][ow|1]=(f[i][j^1][ob][ow|1]+qwq*_2[i-2])%mod
else:
f[i][j^1][ob][ow|1]=(f[i][j^1][ob][ow|1]+qwq*_2[i-1])%mod
if nums[i]!=1:
if ow:
f[i][j][ob][ow]=(f[i][j][ob][ow]+qwq*_2[i-2])%mod
f[i][j^1][ob|1][ow]=(f[i][j^1][ob|1][ow]+qwq*_2[i-2])%mod
else:
f[i][j^1][ob|1][ow]=(f[i][j^1][ob|1][ow]+qwq*_2[i-1])%mod
ans=0
for i in range(2):
for j in range(2):
ans=(ans+f[n][p][i][j])%mod
print(ans)
| python | code_algorithm | [
{
"input": "3 1\n-1 0 1\n",
"output": "6\n"
},
{
"input": "2 1\n1 0\n",
"output": "1\n"
},
{
"input": "1 1\n-1\n",
"output": "2\n"
},
{
"input": "9 1\n0 1 -1 -1 -1 -1 1 1 1\n",
"output": "755810045\n"
},
{
"input": "16 0\n-1 0 0 1 0 0 0 0 -1 -1 -1 -1 1 1 0 1\n",
... | code_contests | python | 0 | fc73d0f162bb4f216933bd024cf06cb7 |
There are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.
There are k ⋅ n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, ..., h_k. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, ..., h_k is the same for all the players.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ 10) — the number of players and the number of cards each player will get.
The second line contains k ⋅ n integers c_1, c_2, ..., c_{k ⋅ n} (1 ≤ c_i ≤ 10^5) — the numbers written on the cards.
The third line contains n integers f_1, f_2, ..., f_n (1 ≤ f_j ≤ 10^5) — the favorite numbers of the players.
The fourth line contains k integers h_1, h_2, ..., h_k (1 ≤ h_t ≤ 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t ∈ [2..k].
Output
Print one integer — the maximum possible total joy levels of the players among all possible card distributions.
Examples
Input
4 3
1 3 2 8 5 5 8 2 2 8 5 2
1 2 2 5
2 6 7
Output
21
Input
3 3
9 9 9 9 9 9 9 9 9
1 2 3
1 2 3
Output
0
Note
In the first example, one possible optimal card distribution is the following:
* Player 1 gets cards with numbers [1, 3, 8];
* Player 2 gets cards with numbers [2, 2, 8];
* Player 3 gets cards with numbers [2, 2, 8];
* Player 4 gets cards with numbers [5, 5, 5].
Thus, the answer is 2 + 6 + 6 + 7 = 21.
In the second example, no player can get a card with his favorite number. Thus, the answer is 0.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def solve():
n, k = map(int, input().split())
c = list(map(int, input().split()))
f = list(map(int, input().split()))
h = list(map(int, input().split()))
cnt = {}
for i in c:
cnt[i] = cnt.get(i, 0) + 1
likecolor = {}
for i in range(n):
likecolor.setdefault(f[i], []).append(i)
cnt[f[i]] = cnt.get(f[i], 0)
ans = 0
for key, v in likecolor.items():
n1 = len(v)
if cnt[key] >= n1 * k:
ans += n1 * h[k - 1]
continue
dp = [[-float("INF")] * (cnt[key]+1) for _ in range(n1 + 1)]
dp[0][0] = 0
for i in range(n1):
j = i + 1
for e in range(cnt[key] + 1):
dp[j][e] = max(dp[j][e], dp[i][e])
for w in range(e + 1, min(cnt[key] + 1, e + k + 1)):
dp[j][w] = max(dp[i][e] + h[w - e - 1], dp[j][w])
ans += dp[n1][cnt[key]]
print(ans)
solve()
| python | code_algorithm | [
{
"input": "4 3\n1 3 2 8 5 5 8 2 2 8 5 2\n1 2 2 5\n2 6 7\n",
"output": "21\n"
},
{
"input": "3 3\n9 9 9 9 9 9 9 9 9\n1 2 3\n1 2 3\n",
"output": "0\n"
},
{
"input": "1 1\n1\n2\n1\n",
"output": "0\n"
},
{
"input": "1 1\n1\n1\n100000\n",
"output": "100000\n"
},
{
"in... | code_contests | python | 0 | 767770e7bb2d67963fdd7bcc0f4c0f57 |
Enough is enough. Too many times it happened that Vasya forgot to dispose of garbage and his apartment stank afterwards. Now he wants to create a garbage disposal plan and stick to it.
For each of next n days Vasya knows a_i — number of units of garbage he will produce on the i-th day. Each unit of garbage must be disposed of either on the day it was produced or on the next day. Vasya disposes of garbage by putting it inside a bag and dropping the bag into a garbage container. Each bag can contain up to k units of garbage. It is allowed to compose and drop multiple bags into a garbage container in a single day.
Being economical, Vasya wants to use as few bags as possible. You are to compute the minimum number of bags Vasya needs to dispose of all of his garbage for the given n days. No garbage should be left after the n-th day.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 2⋅10^5, 1 ≤ k ≤ 10^9) — number of days to consider and bag's capacity. The second line contains n space separated integers a_i (0 ≤ a_i ≤ 10^9) — the number of units of garbage produced on the i-th day.
Output
Output a single integer — the minimum number of bags Vasya needs to dispose of all garbage. Each unit of garbage should be disposed on the day it was produced or on the next day. No garbage can be left after the n-th day. In a day it is allowed to compose and drop multiple bags.
Examples
Input
3 2
3 2 1
Output
3
Input
5 1
1000000000 1000000000 1000000000 1000000000 1000000000
Output
5000000000
Input
3 2
1 0 1
Output
2
Input
4 4
2 8 4 1
Output
4
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
n, k = tuple(int(i) for i in sys.stdin.readline().split())
a = tuple(int(i) for i in sys.stdin.readline().split())
assert len(a) == n
bags = 0
r = 0
for ai in a:
leftovers = (r > 0)
q, r = divmod(ai + r, k)
if q == 0:
if leftovers:
bags += 1
r = 0
else:
bags += q
if r > 0:
bags += 1
print(bags)
| python | code_algorithm | [
{
"input": "3 2\n1 0 1\n",
"output": "2\n"
},
{
"input": "4 4\n2 8 4 1\n",
"output": "4\n"
},
{
"input": "3 2\n3 2 1\n",
"output": "3\n"
},
{
"input": "5 1\n1000000000 1000000000 1000000000 1000000000 1000000000\n",
"output": "5000000000\n"
},
{
"input": "3 10\n5 ... | code_contests | python | 0 | 9bce6b905241c743c39e8dcc7f0ba0a6 |
Vasya has a pile, that consists of some number of stones. n times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.
You are given n operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.
Input
The first line contains one positive integer n — the number of operations, that have been made by Vasya (1 ≤ n ≤ 100).
The next line contains the string s, consisting of n symbols, equal to "-" (without quotes) or "+" (without quotes). If Vasya took the stone on i-th operation, s_i is equal to "-" (without quotes), if added, s_i is equal to "+" (without quotes).
Output
Print one integer — the minimal possible number of stones that can be in the pile after these n operations.
Examples
Input
3
---
Output
0
Input
4
++++
Output
4
Input
2
-+
Output
1
Input
5
++-++
Output
3
Note
In the first test, if Vasya had 3 stones in the pile at the beginning, after making operations the number of stones will be equal to 0. It is impossible to have less number of piles, so the answer is 0. Please notice, that the number of stones at the beginning can't be less, than 3, because in this case, Vasya won't be able to take a stone on some operation (the pile will be empty).
In the second test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 4. It is impossible to have less number of piles because after making 4 operations the number of stones in the pile increases on 4 stones. So, the answer is 4.
In the third test, if Vasya had 1 stone in the pile at the beginning, after making operations the number of stones will be equal to 1. It can be proved, that it is impossible to have less number of stones after making the operations.
In the fourth test, if Vasya had 0 stones in the pile at the beginning, after making operations the number of stones will be equal to 3.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | '''
t= input()
lng= len(t)
li1=[]; li2=[]
for i in range(lng):
if t[i]!='a':
li1.append(t[i])
elif t[i]=='a':
li2.append(i)
aa= ''.join(li1)
if len(aa)==0:
print(t); exit(0)
if len(aa)%2==1:
print(':('); exit(0)
if len(aa)%2==0:
#print(123)
l= int(len(aa)/2); lp= l#; print(l)
ll= aa[l:]; lll=aa[0:l] #; print(ll)
if ll!=lll:
print(':('); exit(0)
if ll not in t:
print(':('); exit(0)
tp= t[::-1]; tc= ll[::-1]#; print(tp,tc)
if tp.find(tc)!=0:
print(':('); exit(0)
if tp.find(tc)==0:
ul= len(tc)
lu= tp[ul:][::-1]
print(lu); exit(0)
'''
n= int(input()); s= input(); ln= len(s); sv=0
for i in s:
if i=='+':
sv+=1
if i=='-' and sv>0:
sv-=1
print(sv)
| python | code_algorithm | [
{
"input": "2\n-+\n",
"output": "1\n"
},
{
"input": "3\n---\n",
"output": "0\n"
},
{
"input": "5\n++-++\n",
"output": "3\n"
},
{
"input": "4\n++++\n",
"output": "4\n"
},
{
"input": "4\n-+--\n",
"output": "0\n"
},
{
"input": "2\n++\n",
"output": "2\... | code_contests | python | 0.5 | 541774b1dd7591868bbbbde785d3a7d9 |
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.
The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.
Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts.
It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).
Input
The first line contains three integers x, y and z (0 ≤ x, y ≤ 10^{18}, 1 ≤ z ≤ 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.
Output
Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.
Examples
Input
5 4 3
Output
3 1
Input
6 8 2
Output
7 0
Note
The first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | x,y,z=map(int,input().split())
sum=(x+y)//z
i1=x//z
i2=y//z
x=x%z
y=y%z
current=i1+i2
nu=0
if current==sum:
print(sum,end=' ')
print(nu)
else:
if x>y:
h=x
else:
h=y
current=sum-current
current=current*z
nu=current-h
print(sum, end=' ')
print(nu) | python | code_algorithm | [
{
"input": "6 8 2\n",
"output": "7 0\n"
},
{
"input": "5 4 3\n",
"output": "3 1\n"
},
{
"input": "5000000000000 6000000000000 10000000000000\n",
"output": "1 4000000000000\n"
},
{
"input": "2778787205 1763925790 48326734\n",
"output": "93 0\n"
},
{
"input": "58242... | code_contests | python | 0.5 | e18f9cc7dd9c4db26d3b72216b069719 |
The only difference between the easy and the hard versions is the maximum value of k.
You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2, the third one — from 1 to 3, ..., the i-th block consists of all numbers from 1 to i.
So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0.
Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 500) — the number of queries.
The i-th of the following q lines contains one integer k_i (1 ≤ k_i ≤ 10^9) — the description of the corresponding query.
Output
Print q lines. In the i-th line print one digit x_i (0 ≤ x_i ≤ 9) — the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence.
Examples
Input
5
1
3
20
38
56
Output
1
2
5
2
0
Input
4
2132
506
999999999
1000000000
Output
8
2
9
8
Note
Answers on queries from the first example are described in the problem statement.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def isqrt(x):
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
p = [0, 45, 9045, 1395495, 189414495, 23939649495, 2893942449495, 339393974949495, 38939394344949495, 1000000000000000001];
nx = [0, 9, 189, 2889, 38889, 488889, 5888889, 68888889, 788888889, 8888888889]
q = int(input())
for ut in range(q):
lk = int(input())
k = lk
idx = 0;
for i in range(len(p)-1):
if (p[i] <= k) and (p[i + 1] > k):
idx = i;
idx = idx;
k-=1
k -= p[idx];
a = idx + 1
b = 2 * nx[idx] + idx + 1;
k = -2 * k;
d = isqrt(b*b-4 * a*k);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
a1 = int(x1);
z = lk - p[idx] - nx[idx] * a1 - (a1 * (a1 + 1) // 2) * (idx + 1);
cnt = 0
ww = 1
pow = 0;
pow = 1;
while ((cnt + pow * ww) * 9 < z) :
cnt += pow * ww;
ww+=1
pow *= 10;
sym_cnt = (z - (cnt * 9)) - 1;
ok = (pow)+sym_cnt / ww;
s = str(ok);
if (z < 10):
print(z)
else:
print(s[sym_cnt % ww]) | python | code_algorithm | [
{
"input": "4\n2132\n506\n999999999\n1000000000\n",
"output": "8\n2\n9\n8\n"
},
{
"input": "5\n1\n3\n20\n38\n56\n",
"output": "1\n2\n5\n2\n0\n"
},
{
"input": "1\n755045\n",
"output": "4\n"
},
{
"input": "19\n1\n10\n100\n1000\n10000\n100000\n1000000\n10000000\n100000000\n10000... | code_contests | python | 0 | 81d8018afb841321c7a3b4877c0f5e8e |
Lengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.
You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.
Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.
Input
The only line contains an integer n (1 ≤ n ≤ 10000).
Output
Print two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.
Examples
Input
42
Output
1 2
Input
5
Output
0 2
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
e=(n+1)//36
n-=36*e
print(e,(n+1)//3) | python | code_algorithm | [
{
"input": "42\n",
"output": "1 2\n"
},
{
"input": "5\n",
"output": "0 2\n"
},
{
"input": "4\n",
"output": "0 1\n"
},
{
"input": "71\n",
"output": "2 0\n"
},
{
"input": "9999\n",
"output": "277 9\n"
},
{
"input": "35\n",
"output": "1 0\n"
},
{
... | code_contests | python | 1 | fc3686e6bc050a7353cf335b4bacd967 |
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning:
* If ℓ = 0, then the cursor is located before the first character of s.
* If ℓ = |s|, then the cursor is located right after the last character of s.
* If 0 < ℓ < |s|, then the cursor is located between s_ℓ and s_{ℓ+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments ℓ once.
* The Cut action. Set c ← s_right, then set s ← s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at ℓ = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_ℓ times.
4. If ℓ = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that ℓ ≤ |s| at any time.
Input
The first line of input contains a single integer t (1 ≤ t ≤ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 ≤ x ≤ 10^6). The second line of each test case consists of the initial string s (1 ≤ |s| ≤ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that ℓ ≤ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, ℓ = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get ℓ = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_ℓ = 2 times: we get s = 23131.
* Step 4: ℓ = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_ℓ = 3 times: we get s = 23131131131.
* Step 4: ℓ = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_ℓ = 1 time: we get s = 23131131131.
* Step 4: ℓ = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_ℓ = 3 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get ℓ = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_ℓ = 1 times: we get s = 2313113113111311311131131.
* Step 4: ℓ = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
MAX=10**9+7
def solve():
x = int(input())
s = [int(i) for i in input()]
ans=len(s)
c = ""
l = 0
while l < x:
l += 1
k=len(s)
if k < x:
#s += s[l:]*(s[l - 1]-1)
for i in range(s[l-1] - 1):
for j in range(l, k):
s.append(s[j])
ans+= (s[l - 1]-1) *(ans - l)
ans%=MAX
print(ans)
t=int(input())
for _ in range(t):
solve()
#
# mod = 10 ** 9 + 7
#
#
# def solve():
# x = int(input())
# s = [int(i) for i in input()]
# ans = len(s)
# cur = -1
# while cur != x - 1:
# cur += 1
# if len(s) < x:
# k = len(s)
# for _ in range(s[cur] - 1):
# for j in range(cur + 1, k):
# s.append(s[j])
# ans += (s[cur] - 1) * (ans - (cur + 1))
# ans %= mod
# print(ans)
#
#
# t = int(input())
# for i in range(t):
# solve()
| python | code_algorithm | [
{
"input": "4\n5\n231\n7\n2323\n6\n333\n24\n133321333\n",
"output": "25\n1438\n1101\n686531475\n"
},
{
"input": "9\n1500\n1212\n1500\n1221\n1500\n122\n1500\n12121\n1500\n22\n1500\n1111112111111112\n1500\n1111111111221111111\n1500\n111111122\n1500\n11111121111121111111\n",
"output": "1504\n1599\n... | code_contests | python | 0 | 98aebc8d9ac047c5cbd30b0aa6d75430 |
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2020/6/16
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def check(row):
start, end = 0, len(row) - 1
while start < len(row) and row[start] == 0:
start += 1
if start >= len(row):
return True, True
while end >= start and row[end] == 0:
end -= 1
for i in range(start, end):
if row[i] == 0:
return False, False
return True, False
def solve(N, M, A):
blankrow = []
for r in range(N):
row = A[r]
a, b = check(row)
if not a:
return -1
if b:
blankrow.append(r)
blankcol = []
for c in range(M):
col = [A[r][c] for r in range(N)]
a, b = check(col)
if not a:
return -1
if b:
blankcol.append(c)
if (len(blankcol) > 0 and len(blankrow) == 0) or (len(blankrow) > 0 and len(blankcol) == 0):
return -1
if len(blankcol) * len(blankrow) == N * M:
return 0
for r in blankrow:
for c in blankcol:
A[r][c] = 2
idx = 2
for r in range(N):
for c in range(M):
if A[r][c] == 1:
idx += 1
A[r][c] = idx
q = [(r, c)]
while q:
nq = []
for x, y in q:
for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
if 0 <= nx < N and 0 <= ny < M and A[nx][ny] == 1:
A[nx][ny] = idx
nq.append((nx, ny))
q = nq
# for row in A:
# print(' '.join(map(str, row)))
return idx - 2
if __name__ == '__main__':
N, M = map(int, input().split())
A = []
for i in range(N):
row = [1 if v == '#' else 0 for v in list(input())]
A.append(row)
print(solve(N, M, A))
| python | code_algorithm | [
{
"input": "3 3\n.#.\n###\n##.\n",
"output": "1\n"
},
{
"input": "4 5\n....#\n####.\n.###.\n.#...\n",
"output": "2\n"
},
{
"input": "4 2\n##\n.#\n.#\n##\n",
"output": "-1\n"
},
{
"input": "3 5\n.....\n.....\n.....\n",
"output": "0\n"
},
{
"input": "2 1\n.\n#\n",
... | code_contests | python | 0 | 255050c78acc6bcbb32f0419cc20e189 |
You are given a non-decreasing array of non-negative integers a_1, a_2, …, 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, …, b_m, such that:
* The size of b_i is equal to n for all 1 ≤ i ≤ m.
* For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j} + … + 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 ≤ i ≤ 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 ≤ t ≤ 100): the number of test cases.
The first line of each test case contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ n).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_1 ≤ a_2 ≤ … ≤ a_n ≤ 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.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys as _sys
def main():
t = int(input())
for i_t in range(t):
n, k = _read_ints()
a = tuple(_read_ints())
try:
result = find_min_m(a, k)
except ValueError:
result = -1
print(result)
def _read_line():
result = _sys.stdin.readline()
assert result[-1] == "\n"
return result[:-1]
def _read_ints():
return map(int, _read_line().split(" "))
def find_min_m(a_seq, k):
assert k >= 1
a_seq = tuple(a_seq)
if a_seq.count(0) == len(a_seq):
return 0
steps_n = sum(x1 != x2 for x1, x2 in zip(a_seq, a_seq[1:]))
if k == 1:
if steps_n == 0:
return 1
else:
raise ValueError("can't find min m")
result = 0
steps_per_b_seq = k - 1
if a_seq[0] != 0:
steps_n += 1
if steps_n <= k:
return 1
steps_n -= k
result += 1
result += _ceil_div(steps_n, steps_per_b_seq)
return result
def _ceil_div(x, y):
assert y > 0
result = x // y
if x % y != 0:
result += 1
return result
if __name__ == '__main__':
main()
| python | code_algorithm | [
{
"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"
},
{
"input": "1\n3 2\n3 3 3\n",
"output": "1\n"
},
{
"input": "1\n3 3\n1 1 1\n",
"output": "1\n"
},
{
... | code_contests | python | 0 | e1df76d623d2f5d639901c90d4147c82 |
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought n carrots with lengths a_1, a_2, a_3, …, a_n. However, rabbits are very fertile and multiply very quickly. Zookeeper now has k rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into k pieces. For some reason, all resulting carrot lengths must be positive integers.
Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size x is x^2.
Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.
Input
The first line contains two integers n and k (1 ≤ n ≤ k ≤ 10^5): the initial number of carrots and the number of rabbits.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6): lengths of carrots.
It is guaranteed that the sum of a_i is at least k.
Output
Output one integer: the minimum sum of time taken for rabbits to eat carrots.
Examples
Input
3 6
5 3 1
Output
15
Input
1 4
19
Output
91
Note
For the first test, the optimal sizes of carrots are \{1,1,1,2,2,2\}. The time taken is 1^2+1^2+1^2+2^2+2^2+2^2=15
For the second test, the optimal sizes of carrots are \{4,5,5,5\}. The time taken is 4^2+5^2+5^2+5^2=91.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from heapq import heapify, heappush, heappop
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)]
def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10**19
MOD = 10**9 + 7
EPS = 10**-10
N, K = MAP()
A = LIST()
def calc(a, cnt):
d, m = divmod(a, cnt)
return d**2 * (cnt-m) + (d+1)**2 * m
que = []
for a in A:
if a // 2 == 0:
que.append((0, 1, a))
else:
que.append((calc(a, 2) - calc(a, 1), 1, a))
heapify(que)
for _ in range(K-N):
val, cnt, a = heappop(que)
if a // (cnt+2) == 0:
heappush(que, (0, cnt+1, a))
else:
heappush(que, (calc(a, cnt+2) - calc(a, cnt+1), cnt+1, a))
ans = 0
for _, cnt, a in que:
ans += calc(a, cnt)
print(ans)
| python | code_algorithm | [
{
"input": "1 4\n19\n",
"output": "91\n"
},
{
"input": "3 6\n5 3 1\n",
"output": "15\n"
},
{
"input": "10 23\n343 984 238 758983 231 74 231 548 893 543\n",
"output": "41149446942\n"
},
{
"input": "1 1\n1\n",
"output": "1\n"
},
{
"input": "29 99047\n206580 305496 6... | code_contests | python | 0 | 8f0262c2791be779d2fb78fa6a934511 |
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.
The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.
One move is choosing an integer i (1 ≤ i ≤ n) such that ai > 0 and an integer t (t ≥ 0) such that i + 2t ≤ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).
You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≤ k < n).
Input
The first input line contains a single integer n. The second line contains n integers ai (0 ≤ ai ≤ 104), separated by single spaces.
The input limitations for getting 20 points are:
* 1 ≤ n ≤ 300
The input limitations for getting 50 points are:
* 1 ≤ n ≤ 2000
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 105
Output
Print exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.
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
4
1 0 1 2
Output
1
1
3
Input
8
1 2 3 4 5 6 7 8
Output
1
3
6
10
16
24
40
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from math import log
n=int(input())
s=list(map(int,input().split( )))
p=[]
for i in range(0,n-1):
m=(log(n-1-i,2))//1
p.append(i+2**m)
for k in range(1,n):
g=0
f=s[:]
for i in range(0,k):
g+=f[i]
f[int(p[i])]+=f[i]
print(g)
| python | code_algorithm | [
{
"input": "8\n1 2 3 4 5 6 7 8\n",
"output": "1\n3\n6\n10\n16\n24\n40\n"
},
{
"input": "4\n1 0 1 2\n",
"output": "1\n1\n3\n"
},
{
"input": "9\n13 13 7 11 3 9 3 5 5\n",
"output": "13\n26\n33\n44\n47\n69\n79\n117\n"
},
{
"input": "80\n72 66 82 46 44 22 63 92 71 65 5 30 45 84 29... | code_contests | python | 0.2 | 043f64ecc6672429ce73691532d7cb26 |
Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an).
Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws each box vertically down on the first wi stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., wi. Each thrown box flies vertically down until at least one of the two following events happen:
* the bottom of the box touches the top of a stair;
* the bottom of the box touches the top of a box, thrown earlier.
We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width wi cannot touch the stair number wi + 1.
You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a1, a2, ..., an (1 ≤ ai ≤ 109; ai ≤ ai + 1).
The next line contains integer m (1 ≤ m ≤ 105) — the number of boxes. Each of the following m lines contains a pair of integers wi, hi (1 ≤ wi ≤ n; 1 ≤ hi ≤ 109) — the size of the i-th thrown box.
The numbers in the lines are separated by spaces.
Output
Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input.
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
5
1 2 3 6 6
4
1 1
3 1
1 1
4 3
Output
1
3
4
6
Input
3
1 2 3
2
1 1
3 1
Output
1
3
Input
1
1
5
1 2
1 10
1 10
1 10
1 10
Output
1
3
13
23
33
Note
The first sample are shown on the picture.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # https://codeforces.com/problemset/problem/272/C
# we just check if the box dropped falls above the previous box or on stair number(1...w)
# the box is dropped from the top and hence we need to check the heights from the top -
# which height is suitable and higher
m = int(input())
arr = list(map(int, input().split()))
t = int(input())
for i in range(t):
w, h = map(int, input().split())
p = max(arr[0], arr[w - 1]) # checking which height is higher
print(p)
# increase the height for the next box to drop - can only drop above the
arr[0] = p + h
# current box
| python | code_algorithm | [
{
"input": "1\n1\n5\n1 2\n1 10\n1 10\n1 10\n1 10\n",
"output": "1\n3\n13\n23\n33\n"
},
{
"input": "3\n1 2 3\n2\n1 1\n3 1\n",
"output": "1\n3\n"
},
{
"input": "5\n1 2 3 6 6\n4\n1 1\n3 1\n1 1\n4 3\n",
"output": "1\n3\n4\n6\n"
},
{
"input": "2\n1 6\n5\n2 6\n1 2\n1 1\n1 2\n1 7\n"... | code_contests | python | 0.8 | f9b6d2ce10a613c111a140a866040bbd |
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.
When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number hi. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h1, h2, ..., hn have been read at the beginning of the operation.
<image>
Mike needs to read the data on m distinct tracks with numbers p1, p2, ..., pm. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.
Input
The first line of the input contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of disk heads and the number of tracks to read, accordingly. The second line contains n distinct integers hi in ascending order (1 ≤ hi ≤ 1010, hi < hi + 1) — the initial positions of the heads. The third line contains m distinct integers pi in ascending order (1 ≤ pi ≤ 1010, pi < pi + 1) - the numbers of tracks to read.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier.
Output
Print a single number — the minimum time required, in seconds, to read all the needed tracks.
Examples
Input
3 4
2 5 6
1 3 6 8
Output
2
Input
3 3
1 2 3
1 2 3
Output
0
Input
1 2
165
142 200
Output
81
Note
The first test coincides with the figure. In this case the given tracks can be read in 2 seconds in the following way:
1. during the first second move the 1-st head to the left and let it stay there;
2. move the second head to the left twice;
3. move the third head to the right twice (note that the 6-th track has already been read at the beginning).
One cannot read the tracks in 1 second as the 3-rd head is at distance 2 from the 8-th track.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
from itertools import *
from math import *
def solve():
n, m = map(int, input().split())
h = list(map(int, input().split()))
p = list(map(int, input().split()))
ss, ll = 0, int(2.2e10)
while ss < ll:
avg = (ss + ll) // 2
works = True
hidx = 0
pidx = 0
while hidx < len(h) and pidx < len(p):
leftget = p[pidx]
curpos = h[hidx]
if curpos - leftget > avg:
works = False
break
getbacktime = max(0, 2*(curpos - leftget))
alsotoright = max(0, avg - getbacktime)
leftime = max(0, curpos - leftget)
remtime = max(0, (avg - leftime) // 2)
furthestright = curpos + max(alsotoright, remtime)
while pidx < len(p) and p[pidx] <= furthestright: pidx += 1
hidx += 1
if pidx != len(p): works = False
if works: ll = avg
else: ss = avg + 1
print(ss)
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve() | python | code_algorithm | [
{
"input": "3 4\n2 5 6\n1 3 6 8\n",
"output": "2\n"
},
{
"input": "3 3\n1 2 3\n1 2 3\n",
"output": "0\n"
},
{
"input": "1 2\n165\n142 200\n",
"output": "81\n"
},
{
"input": "10 11\n1 909090909 1818181817 2727272725 3636363633 4545454541 5454545449 6363636357 7272727265 818181... | code_contests | python | 0 | 947b381f28565ea5279da576cdf0a7c3 |
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as aij. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that aij = apq at (i, j) ≠ (p, q).
Dima has already written a song — a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).
We'll represent a way to play a song as a sequence of pairs (xi, yi) (1 ≤ i ≤ s), such that the xi-th string on the yi-th fret produces the i-th note from the song. The complexity of moving between pairs (x1, y1) and (x2, y2) equals <image> + <image>. The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.
Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!
Input
The first line of the input contains four integers n, m, k and s (1 ≤ n, m ≤ 2000, 1 ≤ k ≤ 9, 2 ≤ s ≤ 105).
Then follow n lines, each containing m integers aij (1 ≤ aij ≤ k). The number in the i-th row and the j-th column (aij) means a note that the guitar produces on the i-th string and the j-th fret.
The last line of the input contains s integers qi (1 ≤ qi ≤ k) — the sequence of notes of the song.
Output
In a single line print a single number — the maximum possible complexity of the song.
Examples
Input
4 6 5 7
3 1 2 2 3 1
3 2 2 2 5 5
4 2 2 2 5 3
3 2 2 1 4 3
2 3 1 4 1 5 1
Output
8
Input
4 4 9 5
4 7 9 5
1 2 1 7
8 3 4 9
5 7 7 2
7 1 9 2 5
Output
4
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def solution() : # 最大的距离来自于角落附近的点
n,m,k,s = map(int, input().split())
dis = lambda a,b : abs(a[0] - b[0]) + abs(a[1] - b[1])
corner = [(0,0), (0,m-1), (n-1,0), (n-1,m-1)]
vertex = [[(n,m), (n,-1), (-1,m), (-1,-1)] for _ in range(k+1)]
for i in range(n) :
for j,note in enumerate(map(int, input().split())) :
vertex[note] = [
(i,j) if dis((i,j), c) < dis(v, c) else v
for v,c in zip(vertex[note], corner)]
maxdis = [[-1] * (k+1) for _ in range(k+1)]
pairs = [(0,3),(3,0),(1,2),(2,1)]
for i in range(1, k+1) :
for j in range(i, k+1) :
vi,vj = vertex[i],vertex[j]
maxdis[i][j] = max(dis(vi[a], vj[b]) for a,b in pairs)
maxdis[j][i] = maxdis[i][j]
s = list(map(int, input().split()))
print(max(maxdis[s[i]][s[i+1]] for i in range(len(s) - 1)))
solution() | python | code_algorithm | [
{
"input": "4 6 5 7\n3 1 2 2 3 1\n3 2 2 2 5 5\n4 2 2 2 5 3\n3 2 2 1 4 3\n2 3 1 4 1 5 1\n",
"output": "8\n"
},
{
"input": "4 4 9 5\n4 7 9 5\n1 2 1 7\n8 3 4 9\n5 7 7 2\n7 1 9 2 5\n",
"output": "4\n"
},
{
"input": "10 1 9 5\n1\n2\n3\n4\n5\n6\n7\n8\n9\n1\n1 1 9 2 3\n",
"output": "9\n"
... | code_contests | python | 0.9 | cfba0cfe6cd64a232010e5b43494ebf5 |
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out!
Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:
* Character 'L' means "go to the left child of the current node";
* Character 'R' means "go to the right child of the current node";
* If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node;
* If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command;
* If he reached a leaf node that is not the exit, he returns to the parent of the current node;
* If he reaches an exit, the game is finished.
Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?
Input
Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h).
Output
Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.
Examples
Input
1 2
Output
2
Input
2 3
Output
5
Input
3 6
Output
10
Input
10 1024
Output
2046
Note
A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one.
Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
def main():
rdl = list(map(int,input().split()))
obx(rdl[0],rdl[1],0,1)
def obx(lvl, ind, kl, current):
if lvl ==0:
print(int(kl))
sys.exit()
all = 0
for i in range(lvl+1):
all += 2**i
all -= 1
if ind > (2**(lvl))/2:
if current == 1:
kl += all / 2 + 1
else:
kl += 1
current *= -1
obx(lvl-1,ind-(2**lvl)/2,kl,current)
else:
if current == -1:
kl += all/2+1
else:
kl += 1
current *= -1
obx(lvl-1,ind,kl,current)
main() | python | code_algorithm | [
{
"input": "1 2\n",
"output": "2\n"
},
{
"input": "10 1024\n",
"output": "2046\n"
},
{
"input": "3 6\n",
"output": "10\n"
},
{
"input": "2 3\n",
"output": "5\n"
},
{
"input": "49 295606900104348\n",
"output": "820858833984106\n"
},
{
"input": "1 1\n",
... | code_contests | python | 0 | 35fdb73e35023007302abb16f1264c50 |
You are given an array of positive integers a1, a2, ..., an × T of length n × T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
Input
The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 107). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 300).
Output
Print a single number — the length of a sought sequence.
Examples
Input
4 3
3 1 4 2
Output
5
Note
The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | f = lambda: map(int, input().split())
n, m = f()
t = list(f())
s = [0] * 301
d = s[:]
for i in t: d[i] += 1
for i in t * min(m, 2 * n): s[i] = max(s[:i + 1]) + 1
print(max(s) + max((m - n * 2) * max(d), 0)) | python | code_algorithm | [
{
"input": "4 3\n3 1 4 2\n",
"output": "5\n"
},
{
"input": "100 10000000\n1 2 2 1 2 2 1 1 2 2 1 2 1 1 1 1 1 2 2 2 1 2 1 2 1 2 1 2 1 1 2 1 1 1 2 2 2 1 1 2 2 1 1 2 2 2 2 2 2 1 1 2 2 1 1 2 1 1 2 1 2 1 1 2 1 2 2 2 1 1 2 2 1 2 1 1 2 2 1 1 1 2 1 2 1 1 1 2 1 1 1 1 1 1 1 1 2 1 1 1\n",
"output": "5600000... | code_contests | python | 0 | 6457a38e0443cca7b464c4cf46cb95cc |
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.
Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively.
The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.
Output
Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.
Examples
Input
2 1
2 5
Output
7
Input
4 3
2 3 5 9
Output
9
Input
3 2
3 5 7
Output
8
Note
In the first sample, Kevin must pack his two cowbells into the same box.
In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.
In the third sample, the optimal solution is {3, 5} and {7}.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, k = map(int, input().split())
a = [int(s) for s in input().split()]
p = n - k
q = 2*k - n
if n < k:
q = n
p = 0
ma = 0
for i in range ((n - q) // 2):
ma = max((a[i] + a[n - q - i - 1]), ma)
ma2 = 0
for i in range(n - q, n):
ma2 = max(a[i], ma2)
print(max(ma,ma2))
| python | code_algorithm | [
{
"input": "4 3\n2 3 5 9\n",
"output": "9\n"
},
{
"input": "2 1\n2 5\n",
"output": "7\n"
},
{
"input": "3 2\n3 5 7\n",
"output": "8\n"
},
{
"input": "10 5\n15 15 20 28 38 44 46 52 69 94\n",
"output": "109\n"
},
{
"input": "100 89\n474 532 759 772 803 965 1043 1325... | code_contests | python | 0 | 7f9cf4a2a4c3af97d75b14f1ecfa3414 |
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.
Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 100) — the size of the permutation.
The second line of the input contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n), where ai is equal to the element at the i-th position.
Output
Print a single integer — the maximum possible distance between the minimum and the maximum elements Nicholas can achieve by performing exactly one swap.
Examples
Input
5
4 5 1 3 2
Output
3
Input
7
1 6 5 3 4 7 2
Output
6
Input
6
6 5 4 3 2 1
Output
5
Note
In the first sample, one may obtain the optimal answer by swapping elements 1 and 2.
In the second sample, the minimum and the maximum elements will be located in the opposite ends of the array if we swap 7 and 2.
In the third sample, the distance between the minimum and the maximum elements is already maximum possible, so we just perform some unnecessary swap, for example, one can swap 5 and 2.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
a = list(map(int, input().split()))
maxLocate = a.index(n)
minLocate = a.index(1)
distanceMax = len(a) - 1 - a.index(n)
distanceMin = len(a) - 1 - a.index(1)
print(max(maxLocate, minLocate, distanceMax, distanceMin))
| python | code_algorithm | [
{
"input": "6\n6 5 4 3 2 1\n",
"output": "5\n"
},
{
"input": "7\n1 6 5 3 4 7 2\n",
"output": "6\n"
},
{
"input": "5\n4 5 1 3 2\n",
"output": "3\n"
},
{
"input": "76\n1 47 54 17 38 37 12 32 14 48 43 71 60 56 4 13 64 41 52 57 62 24 23 49 20 10 63 3 25 66 59 40 58 33 53 46 70 7 ... | code_contests | python | 0.4 | b867886dff7f284ed3e8facd3a5c54c3 |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
Input
The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100).
Output
Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.
Examples
Input
3
4 1 7
-2 4 -1
1 -5 -3
Output
NO
Input
3
3 -1 7
-5 2 -4
2 -1 -3
Output
YES
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | sum1,sum2,sum3 = 0,0,0
n = int(input())
while n:
n-=1
l = list(map(int, input().split()))
sum1 += l[0]
sum2 += l[1]
sum3 += l[2]
if sum1==0 and sum2 ==0 and sum3 ==0:
print("YES")
else:
print("NO") | python | code_algorithm | [
{
"input": "3\n3 -1 7\n-5 2 -4\n2 -1 -3\n",
"output": "YES\n"
},
{
"input": "3\n4 1 7\n-2 4 -1\n1 -5 -3\n",
"output": "NO\n"
},
{
"input": "14\n43 23 17\n4 17 44\n5 -5 -16\n-43 -7 -6\n47 -48 12\n50 47 -45\n2 14 43\n37 -30 15\n4 -17 -11\n17 9 -45\n-50 -3 -8\n-50 0 0\n-50 0 0\n-16 0 0\n",
... | code_contests | python | 0.8 | 4ce3a84bf637a8bb431758bcbc2fee81 |
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.
Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n.
<image>
Mehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.
Input
The single line of input contains one integer n (0 ≤ n ≤ 109).
Output
Print single integer — the last digit of 1378n.
Examples
Input
1
Output
8
Input
2
Output
4
Note
In the first example, last digit of 13781 = 1378 is 8.
In the second example, last digit of 13782 = 1378·1378 = 1898884 is 4.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
if n == 0:
print(1)
if n % 4 == 0 and n!= 0 :
print(6)
if n % 4 == 1:
print(8)
if n % 4 == 2:
print(4)
if n % 4 == 3:
print(2)
| python | code_algorithm | [
{
"input": "2\n",
"output": "4\n"
},
{
"input": "1\n",
"output": "8\n"
},
{
"input": "12\n",
"output": "6\n"
},
{
"input": "1378\n",
"output": "4\n"
},
{
"input": "51202278\n",
"output": "4\n"
},
{
"input": "989898989\n",
"output": "8\n"
},
{
... | code_contests | python | 0.9 | 0de5a85bbfe62f3985b3f35e79238e33 |
Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased:
<image>
Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.
Input
The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105).
Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.
Output
If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.
Examples
Input
6
1 2
2 3
2 4
4 5
1 6
Output
3
Input
7
1 2
1 3
3 4
1 5
5 6
6 7
Output
-1
Note
In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.
It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()
def main():
n = II()
d = collections.defaultdict(set)
for _ in range(n-1):
a,b = LI()
d[a].add(b)
d[b].add(a)
memo = [-1] * (n+1)
def path(t,s):
ps = set()
dt = list(d[t])
for k in dt:
if memo[k] < 0:
continue
ps.add(memo[k])
if s == -1 and len(ps) == 2:
memo[t] = sum(ps) + 2
return memo[t]
if len(ps) > 1:
return -t
if len(ps) == 0:
memo[t] = 0
return 0
memo[t] = list(ps)[0] + 1
return memo[t]
def _path(tt,ss):
q = [(tt,ss)]
tq = []
qi = 0
while len(q) > qi:
t,s = q[qi]
for k in d[t]:
if k == s:
continue
q.append((k,t))
qi += 1
for t,s in q[::-1]:
r = path(t,s)
if r < 0:
return r
return memo[tt]
def _path2(tt,ss):
q = [(tt,ss)]
tq = []
qi = 0
while len(q) > qi:
t,s = q[qi]
for k in d[t]:
if k == s or memo[k] >= 0:
continue
q.append((k,t))
qi += 1
for t,s in q[::-1]:
r = path(t,s)
if r < 0:
return r
return memo[tt]
t = _path(1,-1)
if t < 0:
t = _path2(-t,-1)
if t > 0:
while t%2 == 0:
t//=2
return t
return -1
print(main())
| python | code_algorithm | [
{
"input": "6\n1 2\n2 3\n2 4\n4 5\n1 6\n",
"output": "3\n"
},
{
"input": "7\n1 2\n1 3\n3 4\n1 5\n5 6\n6 7\n",
"output": "-1\n"
},
{
"input": "10\n4 2\n7 4\n2 6\n2 5\n4 8\n10 3\n2 9\n9 1\n5 10\n",
"output": "-1\n"
},
{
"input": "10\n5 10\n7 8\n8 3\n2 6\n3 2\n9 7\n4 5\n10 1\n6 ... | code_contests | python | 0 | 14554a81a0d901b36be2bcda3623a480 |
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.
You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i > 1 the respective term satisfies the condition bi = bi - 1·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.
Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≤ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.
But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
Input
The first line of input contains four integers b1, q, l, m (-109 ≤ b1, q ≤ 109, 1 ≤ l ≤ 109, 1 ≤ m ≤ 105) — the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively.
The second line contains m distinct integers a1, a2, ..., am (-109 ≤ ai ≤ 109) — numbers that will never be written on the board.
Output
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
Examples
Input
3 2 30 4
6 14 25 48
Output
3
Input
123 1 2143435 4
123 11 -5453 141245
Output
0
Input
123 1 2143435 4
54343 -13 6 124
Output
inf
Note
In the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.
In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.
In the third case, Masha will write infinitely integers 123.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | b1,q,l,m = map(int,input().split())
a = set(map(int,input().split()))
if q==0:
if 0 in a:
if b1 in a:
print(0)
elif abs(b1)<=l:
print(1)
else:
print(0)
elif abs(b1)<=l:
print("inf")
else:
print(0)
elif q==1:
if abs(b1)<=l and b1 not in a:
print("inf")
else:
print(0)
elif q==-1:
if abs(b1)<=l and (b1 not in a or -b1 not in a):
print('inf')
else:
print(0)
elif b1==0:
if 0 in a:
print(0)
else:
print("inf")
else:
cnt = 0
p = b1
while abs(p)<=l:
if p not in a:
cnt += 1
p *= q
print(cnt) | python | code_algorithm | [
{
"input": "123 1 2143435 4\n123 11 -5453 141245\n",
"output": "0\n"
},
{
"input": "3 2 30 4\n6 14 25 48\n",
"output": "3\n"
},
{
"input": "123 1 2143435 4\n54343 -13 6 124\n",
"output": "inf\n"
},
{
"input": "-100 0 50 1\n0\n",
"output": "0\n"
},
{
"input": "-100... | code_contests | python | 0 | 99a78cf79db538f4906fc1b2648d8954 |
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers can differ.
Input
The first line contains integer k (1 ≤ k ≤ 109).
The second line contains integer n (1 ≤ n < 10100000).
There are no leading zeros in n. It's guaranteed that this situation is possible.
Output
Print the minimum number of digits in which the initial number and n can differ.
Examples
Input
3
11
Output
1
Input
3
99
Output
0
Note
In the first example, the initial number could be 12.
In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | """
Author : Arif Ahmad
Date :
Algo :
Difficulty :
"""
from sys import stdin, stdout
def main():
k = int(stdin.readline().strip())
n = stdin.readline().strip()
n = sorted(n)
total = 0
for c in n:
d = ord(c) - 48
total += d
ans = 0
for c in n:
if total >= k: break
d = ord(c) - 48
total = total - d + 9
ans += 1
stdout.write(str(ans) + '\n')
if __name__ == '__main__':
main()
| python | code_algorithm | [
{
"input": "3\n11\n",
"output": "1\n"
},
{
"input": "3\n99\n",
"output": "0\n"
},
{
"input": "3\n21\n",
"output": "0\n"
},
{
"input": "3\n111\n",
"output": "0\n"
},
{
"input": "6\n33\n",
"output": "0\n"
},
{
"input": "6\n222\n",
"output": "0\n"
}... | code_contests | python | 0.3 | 6f7c2ea995f736f713637663d76cf96d |
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
border = 1 << 30
def build(x=0):
res = [0, 0]
i = 0
while x and i < 30:
if x & 1:
res[1] += (1 << i)
x >>= 1
i += 1
i = 0
while x:
if x & 1:
res[0] += (1 << i)
x >>= 1
i += 1
return res
n, r, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
k_big, k_small = build(k)
left = build(sum(a[:r]))
minus_big, minus_small = [0]*n, [0]*n
w = 2*r+1
def solve(level_big, level_small):
used_big = used_small = 0
acc_big, acc_small = left
for i in range(n):
if minus_small[i] or minus_big[i]:
acc_big -= minus_big[i]
acc_small -= minus_small[i]
if acc_small < 0:
acc_small += border
acc_big -= 1
elif acc_small >= border:
acc_small -= border
acc_big += 1
minus_big[i] = minus_small[i] = 0
acc_small += (a[i+r] if i+r < n else 0) - (a[i-r-1] if i-r >= 1 else 0)
if acc_small >= border:
acc_small -= border
acc_big += 1
elif acc_small < 0:
acc_small += border
acc_big -= 1
if acc_big < level_big or acc_big == level_big and acc_small < level_small:
used_big += level_big - acc_big
used_small += level_small - acc_small
if used_small >= border:
used_small -= border
used_big += 1
elif used_small < 0:
used_small += border
used_big -= 1
if used_big > k_big or used_big == k_big and used_small > k_small:
break
if i+w < n:
minus_big[i+w] = level_big - acc_big
minus_small[i+w] = level_small - acc_small
acc_big = level_big
acc_small = level_small
for i in range(i+1, n):
if minus_small[i] or minus_big[i]:
minus_small[i] = minus_big[i] = 0
return used_big < k_big or used_big == k_big and used_small <= k_small
ok, ng = min(a), k + sum(a) + 1
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if solve(*build(mid)):
ok = mid
else:
ng = mid
print(ok)
| python | code_algorithm | [
{
"input": "4 2 0\n1 2 3 4\n",
"output": "6\n"
},
{
"input": "5 0 6\n5 4 3 4 9\n",
"output": "5\n"
},
{
"input": "5 1 1\n2 1 2 1 2\n",
"output": "3\n"
},
{
"input": "1 0 0\n1\n",
"output": "1\n"
},
{
"input": "1 1 10\n23\n",
"output": "33\n"
},
{
"inpu... | code_contests | python | 0 | 5e76f05f19977ca99e53e2453a29ec12 |
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).
Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly m names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.
Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from 1 to n.
Input
The first line of the input contains two integers n, m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 10^9) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i means the number of names you will write in the notebook during the i-th day.
Output
Print exactly n integers t_1, t_2, ..., t_n, where t_i is the number of times you will turn the page during the i-th day.
Examples
Input
3 5
3 7 9
Output
0 2 1
Input
4 20
10 9 19 2
Output
0 0 1 1
Input
1 100
99
Output
0
Note
In the first example pages of the Death Note will look like this [1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | (n,m) = tuple(map(int, input().split(" ")))
x = list(map(int, input().split(" ")))
nib = 0
ans = []
cou = 0;
for i in x:
nib+=i
if (nib<m):
ans.append(nib//m)
else:
ans.append(nib//m)
nib-=(nib//m)*m
print (*ans) | python | code_algorithm | [
{
"input": "1 100\n99\n",
"output": "0\n"
},
{
"input": "4 20\n10 9 19 2\n",
"output": "0 0 1 1\n"
},
{
"input": "3 5\n3 7 9\n",
"output": "0 2 1\n"
},
{
"input": "1 1\n2\n",
"output": "2\n"
},
{
"input": "10 4\n9 5 6 4 3 9 5 1 10 7\n",
"output": "2 1 2 1 0 3 ... | code_contests | python | 0 | f6ee9fd4796df6687db5c33572266da9 |
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times:
* mul x: multiplies n by x (where x is an arbitrary positive integer).
* sqrt: replaces n with √{n} (to apply this operation, √{n} must be an integer).
You can perform these operations as many times as you like. What is the minimum value of n, that can be achieved and what is the minimum number of operations, to achieve that minimum value?
Apparently, no one in the class knows the answer to this problem, maybe you can help them?
Input
The only line of the input contains a single integer n (1 ≤ n ≤ 10^6) — the initial number.
Output
Print two integers: the minimum integer n that can be achieved using the described operations and the minimum number of operations required.
Examples
Input
20
Output
10 2
Input
5184
Output
6 4
Note
In the first example, you can apply the operation mul 5 to get 100 and then sqrt to get 10.
In the second example, you can first apply sqrt to get 72, then mul 18 to get 1296 and finally two more sqrt and you get 6.
Note, that even if the initial value of n is less or equal 10^6, it can still become greater than 10^6 after applying one or more operations.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import math
def sieve(n):
mark = [0]*(n+1)
prime = []
for i in range(3, n+1, 2):
if not mark[i]:
for j in range(3*i, n+1, i+i):
mark[j] = 1
prime.append(2)
for i in range(3, n+1, 2):
if not mark[i]:
prime.append(i)
return prime
def ispowerof2(x):
if x and not (x & (x-1)):
return 0
else:
return 1
n = int(input())
#h = n
prime = sieve(n)
l = []
countp = 0
ans = 1
for i in prime:
countp = 0
if n % i == 0:
ans *= i
while n % i == 0:
n //= i
countp += 1
l.append(countp)
if n == 1:
break
if len(l) != 0:
maxp = max(l)
else:
maxp = 0
flag = 0
for i in l:
if i != maxp:
flag = 1
temp = 0
if flag:
temp = 1
else:
temp = ispowerof2(maxp)
if maxp == 1:
maxp -= 1
elif maxp != 0:
maxp = math.ceil(math.log2(maxp)) + temp
print(ans, maxp)
| python | code_algorithm | [
{
"input": "20\n",
"output": "10 2\n"
},
{
"input": "5184\n",
"output": "6 4\n"
},
{
"input": "2\n",
"output": "2 0\n"
},
{
"input": "328509\n",
"output": "69 3\n"
},
{
"input": "279936\n",
"output": "6 4\n"
},
{
"input": "341\n",
"output": "341 0\... | code_contests | python | 0 | fdfb5915cfe41d7e3f66e1f0fae82048 |
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.
It was decided that elevator, when it is not used, will stay on the x-th floor, but x hasn't been chosen yet. When a person needs to get from floor a to floor b, elevator follows the simple algorithm:
* Moves from the x-th floor (initially it stays on the x-th floor) to the a-th and takes the passenger.
* Moves from the a-th floor to the b-th floor and lets out the passenger (if a equals b, elevator just opens and closes the doors, but still comes to the floor from the x-th floor).
* Moves from the b-th floor back to the x-th.
The elevator never transposes more than one person and always goes back to the floor x before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the a-th floor to the b-th floor requires |a - b| units of electricity.
Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the x-th floor. Don't forget than elevator initially stays on the x-th floor.
Input
The first line contains one integer n (1 ≤ n ≤ 100) — the number of floors.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 100) — the number of people on each floor.
Output
In a single line, print the answer to the problem — the minimum number of electricity units.
Examples
Input
3
0 2 1
Output
16
Input
2
1 1
Output
4
Note
In the first example, the answer can be achieved by choosing the second floor as the x-th floor. Each person from the second floor (there are two of them) would spend 4 units of electricity per day (2 to get down and 2 to get up), and one person from the third would spend 8 units of electricity per day (4 to get down and 4 to get up). 4 ⋅ 2 + 8 ⋅ 1 = 16.
In the second example, the answer can be achieved by choosing the first floor as the x-th floor.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
arr = list(map(int, input().split()))
cur = 0
ans = 100000000
for x in range(n):
cur = 0
for i in range(n):
summ = 0
summ += abs(x - i)
summ += i
summ += x
summ += x
summ += i
summ += abs(x - i)
summ *= arr[i]
cur += summ
if cur < ans:
ans = cur
print(ans) | python | code_algorithm | [
{
"input": "2\n1 1\n",
"output": "4\n"
},
{
"input": "3\n0 2 1\n",
"output": "16\n"
},
{
"input": "5\n6 1 1 8 3\n",
"output": "156\n"
},
{
"input": "5\n4 9 4 2 6\n",
"output": "188\n"
},
{
"input": "3\n1 2 2\n",
"output": "24\n"
},
{
"input": "100\n23 ... | code_contests | python | 0.2 | 2988712d1fa38c47fa6592f305c721a5 |
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 ≤ 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 ≤ 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: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 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.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input()) + 1
res = 0
a = tuple(map(int, input().split()))
for ai in a:
res += ai * (n - ai)
for ai, aj in map(sorted, zip(a, a[1:])):
res -= ai * (n - aj)
print(res)
# | python | code_algorithm | [
{
"input": "3\n2 1 3\n",
"output": "7\n"
},
{
"input": "10\n1 5 2 5 5 3 10 6 5 1\n",
"output": "104\n"
},
{
"input": "4\n2 1 1 3\n",
"output": "11\n"
},
{
"input": "9\n1 9 1 1 4 5 9 9 1\n",
"output": "60\n"
},
{
"input": "44\n42 44 4 24 29 17 32 30 30 9 28 9 22 16... | code_contests | python | 0 | 004c8c3b496cbfb833511df0f5bb2d49 |
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
n = int(sys.stdin.readline().strip())
D = [0] * n
p = 998244353
for i in range (0, n - 1):
u, v = list(map(int, sys.stdin.readline().strip().split()))
D[u-1] = D[u-1] + 1
D[v-1] = D[v-1] + 1
ans = n
for i in range (0, n):
for j in range (0, D[i]):
ans = (ans * (j + 1)) % p
print(ans)
| python | code_algorithm | [
{
"input": "4\n1 2\n1 3\n1 4\n",
"output": "24\n"
},
{
"input": "4\n1 2\n1 3\n2 4\n",
"output": "16\n"
},
{
"input": "8\n4 5\n1 2\n6 3\n2 3\n2 8\n4 7\n2 4\n",
"output": "2304\n"
},
{
"input": "7\n2 7\n2 6\n4 7\n7 3\n7 5\n1 7\n",
"output": "1680\n"
},
{
"input": "3... | code_contests | python | 0 | 7d4dddf256b4180bcb91f72347050a95 |
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP.
In general, different values of HP are grouped into 4 categories:
* Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is 1;
* Category B if HP is in the form of (4 n + 3), that is, when divided by 4, the remainder is 3;
* Category C if HP is in the form of (4 n + 2), that is, when divided by 4, the remainder is 2;
* Category D if HP is in the form of 4 n, that is, when divided by 4, the remainder is 0.
The above-mentioned n can be any integer.
These 4 categories ordered from highest to lowest as A > B > C > D, which means category A is the highest and category D is the lowest.
While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most 2 (that is, either by 0, 1 or 2). How much should she increase her HP so that it has the highest possible category?
Input
The only line contains a single integer x (30 ≤ x ≤ 100) — the value Tokitsukaze's HP currently.
Output
Print an integer a (0 ≤ a ≤ 2) and an uppercase letter b (b ∈ { A, B, C, D }), representing that the best way is to increase her HP by a, and then the category becomes b.
Note that the output characters are case-sensitive.
Examples
Input
33
Output
0 A
Input
98
Output
1 B
Note
For the first example, the category of Tokitsukaze's HP is already A, so you don't need to enhance her ability.
For the second example:
* If you don't increase her HP, its value is still 98, which equals to (4 × 24 + 2), and its category is C.
* If you increase her HP by 1, its value becomes 99, which equals to (4 × 24 + 3), and its category becomes B.
* If you increase her HP by 2, its value becomes 100, which equals to (4 × 25), and its category becomes D.
Therefore, the best way is to increase her HP by 1 so that the category of her HP becomes B.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
d={}
d[0]='1 A'
d[1]='0 A'
d[2]='1 B'
d[3]='2 A'
x=n%4
print(d[x]) | python | code_algorithm | [
{
"input": "33\n",
"output": "0 A\n"
},
{
"input": "98\n",
"output": "1 B\n"
},
{
"input": "85\n",
"output": "0 A\n"
},
{
"input": "99\n",
"output": "2 A\n"
},
{
"input": "50\n",
"output": "1 B\n"
},
{
"input": "100\n",
"output": "1 A\n"
},
{
... | code_contests | python | 0.2 | 41a97504183601abe3ceebe87312f47b |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≤ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.
You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.
Input
The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 109) — the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.
Output
In the single line print the result without spaces — the number after the k operations are fulfilled.
Examples
Input
7 4
4727447
Output
4427477
Input
4 2
4478
Output
4478
Note
In the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477.
In the second sample: 4478 → 4778 → 4478.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, k = map(int, input().split())
s = list(input())
cnt = 0
for i in range(n - 1):
if cnt == k:
break
if s[i] == '4' and s[i + 1] == '7':
if i & 1:
if s[i - 1] == '4':
if (cnt - k) & 1:
s[i] = '7'
print(''.join(s))
exit()
s[i] = '7'
else:
if i != n - 2:
if s[i + 2] == '7':
if (cnt - k) & 1:
s[i + 1] = '4'
print(''.join(s))
exit()
s[i + 1] = '4'
cnt += 1
print(''.join(s)) | python | code_algorithm | [
{
"input": "4 2\n4478\n",
"output": "4478\n"
},
{
"input": "7 4\n4727447\n",
"output": "4427477\n"
},
{
"input": "7 74\n4777774\n",
"output": "4777774\n"
},
{
"input": "3 99\n447\n",
"output": "477\n"
},
{
"input": "47 7\n777744777474744774774777747477474474477747... | code_contests | python | 0.1 | 13b7bb3a2fa26c6b74e81fb469268d50 |
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets.
The store does not sell single clothing items — instead, it sells suits of two types:
* a suit of the first type consists of one tie and one jacket;
* a suit of the second type consists of one scarf, one vest and one jacket.
Each suit of the first type costs e coins, and each suit of the second type costs f coins.
Calculate the maximum possible cost of a set of suits that can be composed from the delivered clothing items. Note that one item cannot be used in more than one suit (though some items may be left unused).
Input
The first line contains one integer a (1 ≤ a ≤ 100 000) — the number of ties.
The second line contains one integer b (1 ≤ b ≤ 100 000) — the number of scarves.
The third line contains one integer c (1 ≤ c ≤ 100 000) — the number of vests.
The fourth line contains one integer d (1 ≤ d ≤ 100 000) — the number of jackets.
The fifth line contains one integer e (1 ≤ e ≤ 1 000) — the cost of one suit of the first type.
The sixth line contains one integer f (1 ≤ f ≤ 1 000) — the cost of one suit of the second type.
Output
Print one integer — the maximum total cost of some set of suits that can be composed from the delivered items.
Examples
Input
4
5
6
3
1
2
Output
6
Input
12
11
13
20
4
6
Output
102
Input
17
14
5
21
15
17
Output
325
Note
It is possible to compose three suits of the second type in the first example, and their total cost will be 6. Since all jackets will be used, it's impossible to add anything to this set.
The best course of action in the second example is to compose nine suits of the first type and eleven suits of the second type. The total cost is 9 ⋅ 4 + 11 ⋅ 6 = 102.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | a = int(input())
b = int(input())
c = int(input())
d = int(input())
c1 = int(input())
c2 = int(input())
p = 0
if c2 > c1:
m = min(b,c,d)
b -= m
c -= m
d -= m
p += m * c2
if d > 0:
p += (min(a,d) * c1)
else:
m = min(a,d)
a -= m
d -= m
p += m * c1
if d > 0:
p += (min(b,c,d) * c2)
print(p) | python | code_algorithm | [
{
"input": "4\n5\n6\n3\n1\n2\n",
"output": "6\n"
},
{
"input": "17\n14\n5\n21\n15\n17\n",
"output": "325\n"
},
{
"input": "12\n11\n13\n20\n4\n6\n",
"output": "102\n"
},
{
"input": "88\n476\n735\n980\n731\n404\n",
"output": "256632\n"
},
{
"input": "844\n909\n790\n... | code_contests | python | 0.5 | d75a83eee11db3060300483d4159348f |
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).
Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.
The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.
After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.
Input
The first line contains a positive integer n (1 ≤ n ≤ 500) — the number of rooms in Boris's apartment.
Each of the next n lines contains three space-separated positive integers — the length, width and height of the walls in a given room in meters, respectively.
The next line contains a positive integer m (1 ≤ m ≤ 500) — the number of available wallpaper types.
Each of the following m lines contains three space-separated positive integers — the length and width in meters of a given wallpaper and the price of one roll, respectively.
All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.
Output
Print a single number — the minimum total cost of the rolls.
Examples
Input
1
5 5 3
3
10 1 100
15 2 320
3 19 500
Output
640
Note
Note to the sample:
The total length of the walls (the perimeter) of the room is 20 m.
One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700.
A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640.
One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now----------------------------------------------------
n = int(input())
rooms = []
for _ in range(n):
rooms.append(list(map(int, input().split())))
m = int(input())
wallpapers = []
for _ in range(m):
wallpapers.append(list(map(int, input().split())))
def room_cost(room, wallpapers):
min_cost = 10**18
parimeter = 2 * (room[0] + room[1])
if room[2] == 0:
return 0
for wallpaper in wallpapers:
if wallpaper[1] != 0:
stripes_needed = (parimeter + wallpaper[1] - 1) // wallpaper[1]
stripes_from_one_roll = wallpaper[0] // room[2]
if stripes_from_one_roll == 0:
continue
amount_of_rolls = (stripes_needed + stripes_from_one_roll - 1) // stripes_from_one_roll
min_cost = min([min_cost, amount_of_rolls * wallpaper[2]])
return min_cost
print(sum([room_cost(room, wallpapers) for room in rooms])) | python | code_algorithm | [
{
"input": "1\n5 5 3\n3\n10 1 100\n15 2 320\n3 19 500\n",
"output": "640\n"
},
{
"input": "1\n9 10 7\n1\n7 1 3\n",
"output": "114\n"
},
{
"input": "20\n110 466 472\n112 153 152\n424 492 490\n348 366 113\n208 337 415\n491 448 139\n287 457 403\n444 382 160\n325 486 284\n447 454 136\n216 41... | code_contests | python | 0.3 | ef09bc49c31ace0b4fad8719bed8d54d |
Input
The input contains two integers a1, a2 (0 ≤ ai ≤ 109), separated by a single space.
Output
Output a single integer.
Examples
Input
3 14
Output
44
Input
27 12
Output
48
Input
100 200
Output
102
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from math import floor
x, y = input().split()
x = int(x)
y = int(y)
rev = 0
while y > 0:
a = int(y % 10)
rev = rev * 10 + a
y = floor(y / 10)
b = x + rev
print(b)
| python | code_algorithm | [
{
"input": "27 12\n",
"output": "48\n"
},
{
"input": "3 14\n",
"output": "44\n"
},
{
"input": "100 200\n",
"output": "102\n"
},
{
"input": "59961393 89018456\n",
"output": "125442491\n"
},
{
"input": "937477084 827336327\n",
"output": "1661110812\n"
},
{
... | code_contests | python | 0 | cab2e7d856718bbbac601b174bae60f5 |
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.
* Current character pointer (CP);
* Direction pointer (DP) which can point left or right;
Initially CP points to the leftmost character of the sequence and DP points to the right.
We repeat the following steps until the first moment that CP points to somewhere outside the sequence.
* If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one.
* If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence.
If at any moment the CP goes outside of the sequence the execution is terminated.
It's obvious the every program in this language terminates after some steps.
We have a sequence s1, s2, ..., sn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language.
Input
The first line of input contains two integers n and q (1 ≤ n, q ≤ 105) — represents the length of the sequence s and the number of queries.
The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces.
The next q lines each contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query.
Output
For each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.
Examples
Input
7 4
1>3>22<
1 3
4 7
7 7
1 7
Output
0 1 0 1 0 0 0 0 0 0
2 2 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
2 3 2 1 0 0 0 0 0 0
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, q = map(int, input().split())
s = input()
for _ in range(q):
l, r = map(int, input().split())
t = list(s[l-1:r])
p, d = 0, 1
res = [0] * 10
while 0 <= p < len(t):
if '0' <= t[p] <= '9':
k = int(t[p])
res[k] += 1
if k > 0:
t[p] = str(k-1)
p += d
else:
t.pop(p)
if d == -1:
p += d
else:
d = -1 if t[p] == '<' else 1
if 0 <= p+d < len(t) and not ('0' <= t[p+d] <= '9'):
t.pop(p)
if d == -1:
p += d
else:
p += d
print(*res)
| python | code_algorithm | [
{
"input": "7 4\n1>3>22<\n1 3\n4 7\n7 7\n1 7\n",
"output": "0 1 0 0 0 0 0 0 0 0\n0 0 0 1 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0\n0 1 0 1 0 0 0 0 0 0\n"
},
{
"input": "5 1\n1>3><\n4 5\n",
"output": "0 0 0 0 0 0 0 0 0 0\n"
},
{
"input": "4 1\n34><\n1 4\n",
"output": "0 0 1 2 1 0 0 0... | code_contests | python | 0 | 2cba14933e8cb099ee4051fed894b301 |
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters.
A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe.
<image> The figure shows a 4-output splitter
Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible.
Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.
Input
The first line contains two space-separated integers n and k (1 ≤ n ≤ 1018, 2 ≤ k ≤ 109).
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.
Output
Print a single integer — the minimum number of splitters needed to build the pipeline. If it is impossible to build a pipeline with the given splitters, print -1.
Examples
Input
4 3
Output
2
Input
5 5
Output
1
Input
8 4
Output
-1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, k = map(int, input().split())
def prod(n):
if n%2:
return n*((n+1)//2)
else:
return (n//2)*(n+1)
def total_count(n, k):
if k >= n:
return (0, 0, 1)
else:
count = 0
l = 1; r = k
s = prod(k)
while l <= r:
mid = (l+r)//2
if n > s - prod(mid) + mid:
r = mid-1
else:
l = mid+1
n = n - (s - prod(l) + l)
count += (k-l+1)
k = l-1
return (n, k, count)
if prod(k) - (k-1) < n:
print(-1)
elif n == 1:
print(0)
elif k >= n:
print(1)
else:
n = n-k
k = k-2
count = 1
while n > 0:
(n, k, temp) = total_count(n, k)
count += temp
print(count) | python | code_algorithm | [
{
"input": "4 3\n",
"output": "2\n"
},
{
"input": "8 4\n",
"output": "-1\n"
},
{
"input": "5 5\n",
"output": "1\n"
},
{
"input": "1000000000000000000 1000000000\n",
"output": "-1\n"
},
{
"input": "525 34\n",
"output": "25\n"
},
{
"input": "1000000000 9... | code_contests | python | 0 | 367643f66a5a19054906d79c36c114d0 |
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).
We have a sequence of characters he has typed and we want to find the original message.
Input
First line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right).
Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard.
It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it.
Output
Print a line that contains the original message.
Examples
Input
R
s;;upimrrfod;pbr
Output
allyouneedislove
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | move=input()
ans=""
s=input()
keyboard=["qwertyuiop","asdfghjkl;","zxcvbnm,./"]
if move =="R":
for i in range(len(s)):
for j in range(len(keyboard)):
if s[i] in keyboard[j]:
ans+=keyboard[j][keyboard[j].index(s[i])-1]
elif move =="L":
for i in range(len(s)):
for j in range(len(keyboard)):
if s[i] in keyboard[j]:
ans+=keyboard[j][keyboard[j].index(s[i])+1]
print(ans) | python | code_algorithm | [
{
"input": "R\ns;;upimrrfod;pbr\n",
"output": "allyouneedislove\n"
},
{
"input": "R\nwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\n",
"output": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq... | code_contests | python | 0.1 | 442faa71de658fb7b4d867a378f31b60 |
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t):
<image> where <image> is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6
Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: <image>.
Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 105).
The second line of the input contains a single string of length n, consisting of characters "ACGT".
Output
Print a single number — the answer modulo 109 + 7.
Examples
Input
1
C
Output
1
Input
2
AG
Output
4
Input
3
TTT
Output
1
Note
Please note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.
In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.
In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.
In the third sample, ρ("TTT", "TTT") = 27
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # problem statement: https://codeforces.com/problemset/problem/520/C
modulo = 1000000007
n = int(input())
char_count = [0] * 256
s = input()
for i in range(n):
char_count[ord(s[i])] += 1
max_char_count = max(char_count)
num_max_char = 0
for i in range(256):
if char_count[i] == max_char_count:
num_max_char += 1
print(pow(num_max_char, n) % modulo)
| python | code_algorithm | [
{
"input": "2\nAG\n",
"output": "4\n"
},
{
"input": "3\nTTT\n",
"output": "1\n"
},
{
"input": "1\nC\n",
"output": "1\n"
},
{
"input": "20\nTAAGCGACCAGGTGCTTTAC\n",
"output": "511620083\n"
},
{
"input": "15\nAGCGAATCCCATTGT\n",
"output": "14348907\n"
},
{
... | code_contests | python | 0.4 | 9605a5006ef6d0d99a70e72bb28109bd |
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set.
Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' ≥ x and y' ≥ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.
Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w1, w2,..., wn, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to wi, that is s(xi, yi) = yi - xi = wi.
Now Wilbur asks you to help him with this challenge.
Input
The first line of the input consists of a single integer n (1 ≤ n ≤ 100 000) — the number of points in the set Wilbur is playing with.
Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≤ x, y ≤ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y, are also present in the input.
The last line of the input contains n integers. The i-th of them is wi ( - 100 000 ≤ wi ≤ 100 000) — the required special value of the point that gets number i in any aesthetically pleasing numbering.
Output
If there exists an aesthetically pleasant numbering of points in the set, such that s(xi, yi) = yi - xi = wi, then print "YES" on the first line of the output. Otherwise, print "NO".
If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them.
Examples
Input
5
2 0
0 0
1 0
1 1
0 1
0 -1 -2 1 0
Output
YES
0 0
1 0
2 0
0 1
1 1
Input
3
1 0
0 0
2 0
0 1 2
Output
NO
Note
In the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and yi - xi = wi.
In the second sample, the special values of the points in the set are 0, - 1, and - 2 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from collections import defaultdict
def solve():
N = int(input())
maxx = 0
maxy = 0
WS = defaultdict(list)
for i in range(N):
x, y = map(int, input().split())
WS[y - x].append((x, y))
maxx = max(maxx, x)
maxy = max(maxy, y)
for w in WS:
WS[w].sort(reverse=True)
W = list(map(int, input().split()))
ans = [None] * N
mx = [0] * (maxy + 1)
my = [0] * (maxx + 1)
for i in range(N):
w = W[i]
if WS[w]:
ans[i] = ax, ay = WS[w].pop()
if mx[ay] == ax and my[ax] == ay:
mx[ay] = ax + 1
my[ax] = ay + 1
else:
print('NO')
return
else:
print('NO')
return
print('YES')
for a in ans:
print(a[0], a[1])
if __name__ == '__main__':
solve()
| python | code_algorithm | [
{
"input": "5\n2 0\n0 0\n1 0\n1 1\n0 1\n0 -1 -2 1 0\n",
"output": "YES\n0 0\n1 0\n2 0\n0 1\n1 1\n"
},
{
"input": "3\n1 0\n0 0\n2 0\n0 1 2\n",
"output": "NO\n"
},
{
"input": "1\n0 0\n-9876\n",
"output": "NO\n"
},
{
"input": "9\n0 0\n1 0\n2 0\n0 1\n1 1\n2 1\n1 2\n2 2\n0 2\n0 0 ... | code_contests | python | 0.1 | 9890236fb3f3975336aea5408c25a8a2 |
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion:
* An 'L' indicates he should move one unit left.
* An 'R' indicates he should move one unit right.
* A 'U' indicates he should move one unit up.
* A 'D' indicates he should move one unit down.
But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.
Input
The first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given.
Output
If there is a string satisfying the conditions, output a single integer — the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.
Examples
Input
RRU
Output
-1
Input
UDUR
Output
1
Input
RUUR
Output
2
Note
In the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.
In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | s = input()
ud = lr = 0
for ch in s:
if(ch=='R'):
lr = lr+1
if(ch=='L'):
lr = lr-1
if(ch=='U'):
ud = ud+1
if(ch=='D'):
ud = ud-1
if((abs(lr) + abs(ud))%2==1):
print(-1)
else:
print(int((abs(lr) + abs(ud))/2))
| python | code_algorithm | [
{
"input": "UDUR\n",
"output": "1\n"
},
{
"input": "RUUR\n",
"output": "2\n"
},
{
"input": "RRU\n",
"output": "-1\n"
},
{
"input": "RDDLLDLUUUDDRDRURLUUURLLDDLRLUURRLLRRLDRLLUDRLRULLDLRRLRLRLRUDUUDLULURLLDUURULURLLRRRURRRDRUUDLDRLRDRLRRDDLDLDLLUDRUDRLLLLDRDUULRUURRDLULLULDUDU... | code_contests | python | 0.8 | 46baf946c94a65e603a4b1c4233ad894 |
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump.
Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability.
<image> The picture corresponds to the first example.
The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.
Input
The first line contains non-empty string consisting of capital English letters. It is guaranteed that the length of the string does not exceed 100.
Output
Print single integer a — the minimum jump ability of the Grasshopper (in the number of symbols) that is needed to overcome the given string, jumping only on vowels.
Examples
Input
ABABBBACFEYUKOTT
Output
4
Input
AAA
Output
1
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def solve(a):
l = [0]
li = []
j = 0
for i in range(len(a)):
if a[i] == "A" or a[i] == "E" or a[i] == "I" or a[i] == "O" or a[i] == "U" or a[i] == "Y":
l.append(i + 1)
j += 1
li.append(l[j] - l[j-1])
l.append(i + 1)
j += 1
li.append(l[j] - l[j-1] + 1)
li.sort()
print(li[-1])
solve(input()) | python | code_algorithm | [
{
"input": "ABABBBACFEYUKOTT\n",
"output": "4\n"
},
{
"input": "AAA\n",
"output": "1\n"
},
{
"input": "HDDRZDKCHHHEDKHZMXQSNQGSGNNSCCPVJFGXGNCEKJMRKSGKAPQWPCWXXWHLSMRGSJWEHWQCSJJSGLQJXGVTBYALWMLKTTJMFPFS\n",
"output": "28\n"
},
{
"input": "AABBYYYYYYYY\n",
"output": "3\n"... | code_contests | python | 0.5 | 93fc86dee7e882e2bb292136ae75a2ac |
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.
But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).
Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take?
Note: A Pokemon cannot fight with itself.
Input
The input consists of two lines.
The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab.
The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
Output
Print single integer — the maximum number of Pokemons Bash can take.
Examples
Input
3
2 3 4
Output
2
Input
5
2 3 4 6 7
Output
3
Note
gcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.
In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.
In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def function1(n,s):
if n==1:
return 1
pokemonj=0
pokecage=[0 for i in range(100001)]
for i in range(n):
pokecage[s[i]]+=1
maxyincage=min(pokecage[1],1)
a = [i for i in range(100001)]
a[1] = 0
i = 2
while i <= 100000:
if a[i] != 0:
pokemonj=0
for j in range(i, 100001, i):
a[j] = 0
pokemonj+=pokecage[j]
if pokemonj>maxyincage:
maxyincage=pokemonj
i += 1
return(maxyincage)
def main():
n=int(input())
s=list(map(int,input().split()))
print(function1(n,s))
if __name__=='__main__':
main()
| python | code_algorithm | [
{
"input": "5\n2 3 4 6 7\n",
"output": "3\n"
},
{
"input": "3\n2 3 4\n",
"output": "2\n"
},
{
"input": "3\n49999 49999 99998\n",
"output": "3\n"
},
{
"input": "3\n457 457 457\n",
"output": "3\n"
},
{
"input": "2\n4 9\n",
"output": "1\n"
},
{
"input": "... | code_contests | python | 0 | 120344dc268048cf5a44aae7954a9587 |
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour A liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes s_1, s_2, …, s_n. In other words, if the sum of sizes of non-blocked holes is S, and the i-th hole is not blocked, (s_i ⋅ A)/(S) liters of water will flow out of it.
What is the minimum number of holes Arkady should block to make at least B liters of water flow out of the first hole?
Input
The first line contains three integers n, A, B (1 ≤ n ≤ 100 000, 1 ≤ B ≤ A ≤ 10^4) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole.
The second line contains n integers s_1, s_2, …, s_n (1 ≤ s_i ≤ 10^4) — the sizes of the holes.
Output
Print a single integer — the number of holes Arkady should block.
Examples
Input
4 10 3
2 2 2 2
Output
1
Input
4 80 20
3 2 1 4
Output
0
Input
5 10 10
1000 1 1 1 1
Output
4
Note
In the first example Arkady should block at least one hole. After that, (10 ⋅ 2)/(6) ≈ 3.333 liters of water will flow out of the first hole, and that suits Arkady.
In the second example even without blocking any hole, (80 ⋅ 3)/(10) = 24 liters will flow out of the first hole, that is not less than 20.
In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
n, a, b = [int(i) for i in input().split(' ')]
sizes = [int(i) for i in input().split(' ')]
st = sum(sizes)
s = (sizes[0] * a) / b
sb = st - s
blockable = sorted(sizes[1:], reverse=True)
blocked_no = 0
blocked_amount = 0
for i in range(len(blockable)):
if blocked_amount < sb:
blocked_no += 1
blocked_amount += blockable[i]
else:
break
print(blocked_no)
| python | code_algorithm | [
{
"input": "4 10 3\n2 2 2 2\n",
"output": "1\n"
},
{
"input": "5 10 10\n1000 1 1 1 1\n",
"output": "4\n"
},
{
"input": "4 80 20\n3 2 1 4\n",
"output": "0\n"
},
{
"input": "2 10000 1\n1 9999\n",
"output": "0\n"
},
{
"input": "10 300 100\n20 1 3 10 8 5 3 6 4 3\n",
... | code_contests | python | 0.3 | 337d8d6e95f5e838f5013f84da60c5fb |
You are given a string s consisting of n lowercase Latin letters. n is even.
For each position i (1 ≤ i ≤ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.
For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.
That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' → 'd', 'o' → 'p', 'd' → 'e', 'e' → 'd', 'f' → 'e', 'o' → 'p', 'r' → 'q', 'c' → 'b', 'e' → 'f', 's' → 't').
String s is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.
Your goal is to check if it's possible to make string s a palindrome by applying the aforementioned changes to every position. Print "YES" if string s can be transformed to a palindrome and "NO" otherwise.
Each testcase contains several strings, for each of them you are required to solve the problem separately.
Input
The first line contains a single integer T (1 ≤ T ≤ 50) — the number of strings in a testcase.
Then 2T lines follow — lines (2i - 1) and 2i of them describe the i-th string. The first line of the pair contains a single integer n (2 ≤ n ≤ 100, n is even) — the length of the corresponding string. The second line of the pair contains a string s, consisting of n lowercase Latin letters.
Output
Print T lines. The i-th line should contain the answer to the i-th string of the input. Print "YES" if it's possible to make the i-th string a palindrome by applying the aforementioned changes to every position. Print "NO" otherwise.
Example
Input
5
6
abccba
2
cf
4
adfa
8
abaazaba
2
ml
Output
YES
NO
YES
NO
NO
Note
The first string of the example can be changed to "bcbbcb", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters.
The second string can be changed to "be", "bg", "de", "dg", but none of these resulting strings are palindromes.
The third string can be changed to "beeb" which is a palindrome.
The fifth string can be changed to "lk", "lm", "nk", "nm", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings "ll" or "mm".
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def get_mask(inp):
return(5 << ord(inp) - ord('a'))
n = int(input())
for i in range(0, n):
input()
st = input()
ls = []
for j in st:
ls.append(get_mask(j))
for j in range(0, len(ls) // 2):
if(ls[j] & ls[-1 * (j + 1)] == 0):
print("NO")
break
else:
print("YES") | python | code_algorithm | [
{
"input": "5\n6\nabccba\n2\ncf\n4\nadfa\n8\nabaazaba\n2\nml\n",
"output": "YES\nNO\nYES\nNO\nNO\n"
},
{
"input": "1\n4\nyaaa\n",
"output": "NO\n"
},
{
"input": "1\n6\ndazbyd\n",
"output": "NO\n"
},
{
"input": "4\n2\nay\n2\nbz\n2\nya\n2\nzb\n",
"output": "NO\nNO\nNO\nNO\n... | code_contests | python | 0.7 | bac863b34e4c94155d7a3fae631b8126 |
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.
The treasure map can be represented as a rectangle n × m in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.
Besides, the map also has a set of k instructions. Each instruction is in the following form:
"Walk n miles in the y direction"
The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried.
Unfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.
The captain wants to know which sights are worth checking. He asks you to help him with that.
Input
The first line contains two integers n and m (3 ≤ n, m ≤ 1000).
Then follow n lines containing m integers each — the island map's description. "#" stands for the sea. It is guaranteed that all cells along the rectangle's perimeter are the sea. "." stands for a penetrable square without any sights and the sights are marked with uppercase Latin letters from "A" to "Z". Not all alphabet letters can be used. However, it is guaranteed that at least one of them is present on the map. All local sights are marked by different letters.
The next line contains number k (1 ≤ k ≤ 105), after which k lines follow. Each line describes an instruction. Each instruction possesses the form "dir len", where dir stands for the direction and len stands for the length of the way to walk. dir can take values "N", "S", "W" and "E" for North, South, West and East correspondingly. At that, north is to the top, South is to the bottom, west is to the left and east is to the right. len is an integer from 1 to 1000.
Output
Print all local sights that satisfy to the instructions as a string without any separators in the alphabetical order. If no sight fits, print "no solution" without the quotes.
Examples
Input
6 10
##########
#K#..#####
#.#..##.##
#..L.#...#
###D###A.#
##########
4
N 2
S 1
E 1
W 2
Output
AD
Input
3 4
####
#.A#
####
2
W 1
N 2
Output
no solution
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #!/usr/bin/env python3
from sys import stdin
n, m = map(int, stdin.readline().rstrip().split())
island = []
pos = {}
for i in range(n):
island.append(stdin.readline().rstrip())
for j, c in enumerate(island[i]):
if c >= 'A' and c <= 'Z':
pos[c] = [i, j]
l_reach = [[-1 for j in range(m)] for i in range(n)]
r_reach = [[-1 for j in range(m)] for i in range(n)]
u_reach = [[-1 for j in range(m)] for i in range(n)]
d_reach = [[-1 for j in range(m)] for i in range(n)]
for i in range(1, n-1):
for j in range(1, m-1):
if island[i][j] != '#':
l_reach[i][j] = 1 + l_reach[i][j-1]
u_reach[i][j] = 1 + u_reach[i-1][j]
for i in range(n-2, 0, -1):
for j in range(m-2, 0, -1):
if island[i][j] != '#':
r_reach[i][j] = 1 + r_reach[i][j+1]
d_reach[i][j] = 1 + d_reach[i+1][j]
dir = [None] * 100
dir[ord('N')] = [-1, 0, u_reach]
dir[ord('W')] = [0, -1, l_reach]
dir[ord('S')] = [1, 0, d_reach]
dir[ord('E')] = [0, 1, r_reach]
for c in range(int(stdin.readline().rstrip())):
x, y, d = dir[ord(stdin.read(1))]
c = int(stdin.readline()[1:-1])
to_delete = []
for k, v in pos.items():
if c > d[v[0]][v[1]]:
to_delete.append(k)
else:
v[0] += c * x
v[1] += c * y
for k in to_delete:
del pos[k]
ans = ''.join(sorted(pos.keys()))
print(ans if ans else 'no solution')
| python | code_algorithm | [
{
"input": "3 4\n####\n#.A#\n####\n2\nW 1\nN 2\n",
"output": "no solution\n"
},
{
"input": "6 10\n##########\n#K#..#####\n#.#..##.##\n#..L.#...#\n###D###A.#\n##########\n4\nN 2\nS 1\nE 1\nW 2\n",
"output": "AD\n"
},
{
"input": "4 9\n#########\n#AB#CDEF#\n#.......#\n#########\n1\nW 3\n",
... | code_contests | python | 0.2 | e11319113dc00250049274dd2a01ef6c |
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well.
The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes the ball to his k-th neighbour in the direction of increasing ids, that person passes the ball to his k-th neighbour in the same direction, and so on until the person with the id 1 gets the ball back. When he gets it back, people do not pass the ball any more.
For instance, if n = 6 and k = 4, the ball is passed in order [1, 5, 3, 1].
Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be 1 + 5 + 3 = 9.
Find and report the set of possible fun values for all choices of positive integer k. It can be shown that under the constraints of the problem, the ball always gets back to the 1-st player after finitely many steps, and there are no more than 10^5 possible fun values for given n.
Input
The only line consists of a single integer n (2 ≤ n ≤ 10^9) — the number of people playing with the ball.
Output
Suppose the set of all fun values is f_1, f_2, ..., f_m.
Output a single line containing m space separated integers f_1 through f_m in increasing order.
Examples
Input
6
Output
1 5 9 21
Input
16
Output
1 10 28 64 136
Note
In the first sample, we've already shown that picking k = 4 yields fun value 9, as does k = 2. Picking k = 6 results in fun value of 1. For k = 3 we get fun value 5 and with k = 1 or k = 5 we get 21.
<image>
In the second sample, the values 1, 10, 28, 64 and 136 are achieved for instance for k = 16, 8, 4, 10 and 11, respectively.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
a={1}
for i in range(2,int(n**0.5)+1):
if n%i==0:
a.add(i)
a.add(n//i)
ans=[1]
a=list(a)
for i in a:
term=n//i
ans.append((term*(2+(term-1)*i))//2)
ans.sort()
print(*ans) | python | code_algorithm | [
{
"input": "6\n",
"output": "1 5 9 21\n"
},
{
"input": "16\n",
"output": "1 10 28 64 136\n"
},
{
"input": "536870912\n",
"output": "1 268435458 805306372 1879048200 4026531856 8321499168 16911433792 34091303040 68451041536 137170518528 274609472512 549487380480 1099243196416 21987548... | code_contests | python | 0 | c8cf70bcab968b0b563ba9864aa215c2 |
You are given an integer n (n ≥ 0) represented with k digits in base (radix) b. So,
$$$n = a_1 ⋅ b^{k-1} + a_2 ⋅ b^{k-2} + … a_{k-1} ⋅ b + a_k.$$$
For example, if b=17, k=3 and a=[11, 15, 7] then n=11⋅17^2+15⋅17+7=3179+255+7=3441.
Determine whether n is even or odd.
Input
The first line contains two integers b and k (2≤ b≤ 100, 1≤ k≤ 10^5) — the base of the number and the number of digits.
The second line contains k integers a_1, a_2, …, a_k (0≤ a_i < b) — the digits of n.
The representation of n contains no unnecessary leading zero. That is, a_1 can be equal to 0 only if k = 1.
Output
Print "even" if n is even, otherwise print "odd".
You can print each letter in any case (upper or lower).
Examples
Input
13 3
3 2 7
Output
even
Input
10 9
1 2 3 4 5 6 7 8 9
Output
odd
Input
99 5
32 92 85 74 4
Output
odd
Input
2 2
1 0
Output
even
Note
In the first example, n = 3 ⋅ 13^2 + 2 ⋅ 13 + 7 = 540, which is even.
In the second example, n = 123456789 is odd.
In the third example, n = 32 ⋅ 99^4 + 92 ⋅ 99^3 + 85 ⋅ 99^2 + 74 ⋅ 99 + 4 = 3164015155 is odd.
In the fourth example n = 2.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | b,k=map(int,input().split())
arr=list(map(int,input().split()))
arr.insert(0,0)
s=0
for i in range(1,len(arr)):
s=s+(arr[-i]*pow(b,i-1,1000000000))
if(s&1):
print("odd")
else:
print("even") | python | code_algorithm | [
{
"input": "13 3\n3 2 7\n",
"output": "even\n"
},
{
"input": "99 5\n32 92 85 74 4\n",
"output": "odd\n"
},
{
"input": "2 2\n1 0\n",
"output": "even\n"
},
{
"input": "10 9\n1 2 3 4 5 6 7 8 9\n",
"output": "odd\n"
},
{
"input": "6 1\n0\n",
"output": "even\n"
}... | code_contests | python | 0.5 | a623792bc6a6c8cf8d395d2867dc4e9d |
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l.
For example, let s = "1010111". A string t = "010" is an unique substring of s, because l = 2 is the only one suitable number. But, for example t = "10" isn't a unique substring of s, because l = 1 and l = 3 are suitable. And for example t ="00" at all isn't a substring of s, because there is no suitable l.
Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.
You are given 2 positive integers n and k, such that (n mod 2) = (k mod 2), where (x mod 2) is operation of taking remainder of x by dividing on 2. Find any string s consisting of n symbols "0" or "1", such that the length of its minimal unique substring is equal to k.
Input
The first line contains two integers n and k, separated by spaces (1 ≤ k ≤ n ≤ 100 000, (k mod 2) = (n mod 2)).
Output
Print a string s of length n, consisting of symbols "0" and "1". Minimal length of the unique substring of s should be equal to k. You can find any suitable string. It is guaranteed, that there exists at least one such string.
Examples
Input
4 4
Output
1111
Input
5 3
Output
01010
Input
7 3
Output
1011011
Note
In the first test, it's easy to see, that the only unique substring of string s = "1111" is all string s, which has length 4.
In the second test a string s = "01010" has minimal unique substring t ="101", which has length 3.
In the third test a string s = "1011011" has minimal unique substring t ="110", which has length 3.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | # ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
if __name__ == "__main__":
n,k = map(int,input().split())
a = (n - k)//2
ps = '0'*a + '1'
s = ""
i = 0
while i + a + 1 <= n:
s += ps
i += a+1
if i < n:
x = n - i
s += ps[:x]
print(s)
| python | code_algorithm | [
{
"input": "4 4\n",
"output": "1111\n"
},
{
"input": "7 3\n",
"output": "0010010\n"
},
{
"input": "5 3\n",
"output": "01010\n"
},
{
"input": "101 3\n",
"output": "00000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000010\n"
},... | code_contests | python | 0 | 1917645314ce8cecf81c61f0fa1df186 |
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid.
A 1-st order rhombus is just a square 1 × 1 (i.e just a cell).
A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look at the picture to understand it better).
<image>
Alex asks you to compute the number of cells in a n-th order rhombus.
Input
The first and only input line contains integer n (1 ≤ n ≤ 100) — order of a rhombus whose numbers of cells should be computed.
Output
Print exactly one integer — the number of cells in a n-th order rhombus.
Examples
Input
1
Output
1
Input
2
Output
5
Input
3
Output
13
Note
Images of rhombus corresponding to the examples are given in the statement.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n = int(input())
print(sum(range(n)) * 4 + 1)
| python | code_algorithm | [
{
"input": "3\n",
"output": "13\n"
},
{
"input": "1\n",
"output": "1\n"
},
{
"input": "2\n",
"output": "5\n"
},
{
"input": "37\n",
"output": "2665\n"
},
{
"input": "25\n",
"output": "1201\n"
},
{
"input": "64\n",
"output": "8065\n"
},
{
"in... | code_contests | python | 0.6 | c5951634089bc25da8e128401ab89b90 |
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n.
Help mayor find the earliest not-so-rainy day of summer.
Input
The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day.
Output
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
Examples
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
Note
In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier.
In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys,heapq,math
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
DBG = True # and False
R = 10**9 + 7
def ddprint(x):
if DBG:
print(x)
n,x,y = inm()
a = inl()
for i in range(n):
ok = True
mn = max(0,i-x)
mx = min(n-1,i+y)
for j in range(mn,mx+1):
if j!=i and a[j]<=a[i]:
ok = False
break
if ok:
print(i+1)
exit()
| python | code_algorithm | [
{
"input": "5 5 5\n100000 10000 1000 100 10\n",
"output": "5\n"
},
{
"input": "10 2 2\n10 9 6 7 8 3 2 1 4 5\n",
"output": "3\n"
},
{
"input": "10 2 3\n10 9 6 7 8 3 2 1 4 5\n",
"output": "8\n"
},
{
"input": "100 7 4\n100 99 98 97 96 95 94 70 88 73 63 40 86 28 20 39 74 82 87 62... | code_contests | python | 0.7 | 39bf79ed716f3e171c7d8773b865a82a |
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.
Input
The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 10^9 + 7.
Example
Input
2 3
Output
8
Note
The picture below shows all possible random pictures of size 2 by 3.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, m = map(int, input().split())
mod = 10**9+7
a = []
a.append(0)
a.append(2)
a.append(4)
for i in range(3, max(n, m)+1):
a.append((a[i-1]+a[i-2])%mod)
print((a[m]-2 + a[n])%mod) | python | code_algorithm | [
{
"input": "2 3\n",
"output": "8\n"
},
{
"input": "2 1\n",
"output": "4\n"
},
{
"input": "3 6\n",
"output": "30\n"
},
{
"input": "2 5\n",
"output": "18\n"
},
{
"input": "1 2\n",
"output": "4\n"
},
{
"input": "100000 100000\n",
"output": "870472905\... | code_contests | python | 0 | 9e1a1e64e5b4c58793c210b16b532fbc |
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | R = lambda:map(int,input().split())
n = int(input())
a = list(R())
b = list(R())
dif = [(b[i] - a[i], 1) for i in range(n)]
for x in dif:
if x[0] < 0: dif.append((-x[0], 0))
dif = sorted(dif)
count = 0
ans = 0
for i in range(1, len(dif)):
if dif[i][1] == 1: count += 1
if dif[i][1] == 0:
ans += count
count = max(0, count-1)
print(ans)
| python | code_algorithm | [
{
"input": "4\n1 3 2 4\n1 3 2 4\n",
"output": "0\n"
},
{
"input": "5\n4 8 2 6 2\n4 5 4 1 3\n",
"output": "7\n"
},
{
"input": "4\n289148443 478308391 848805621 903326233\n164110294 114400164 187849556 86077714\n",
"output": "6\n"
},
{
"input": "2\n335756331 677790822\n38899334... | code_contests | python | 1 | 2bab43c17aa1f9eb392a37f5baf4d2d5 |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | t = int(input())
for tt in range(t):
n = int(input())
arr = list(map(int,input().split()))
mx = arr[0]
sm = 0
for j in range(n):
if (arr[j] * mx < 0 ):
sm += mx
mx = arr[j]
else:
mx = max(mx , arr[j])
print(sm + mx)
| python | code_algorithm | [
{
"input": "4\n5\n1 2 3 -1 -2\n4\n-1 -2 -1 -3\n10\n-2 8 3 8 -4 -15 5 -2 -3 1\n6\n1 -1000000000 1 -1000000000 1 -1000000000\n",
"output": "2\n-1\n6\n-2999999997\n"
},
{
"input": "2\n2\n-1 -1\n1\n-2\n",
"output": "-1\n-2\n"
},
{
"input": "10\n10\n-1 5 6 2 -8 -7 -6 5 -3 -1\n10\n1 2 3 4 5 6 ... | code_contests | python | 0.1 | 731b4f97785ccdc75d138de7f5574cd2 |
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him.
Input
The input data contain four lines. Each of these lines contains four integers x1, y1, x2, y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — coordinates of segment's beginning and end positions. The given segments can degenerate into points.
Output
Output the word «YES», if the given four segments form the required rectangle, otherwise output «NO».
Examples
Input
1 1 6 1
1 0 6 0
6 0 6 1
1 1 1 0
Output
YES
Input
0 0 0 3
2 0 0 0
2 2 2 0
0 2 2 2
Output
NO
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
def is_rect(es):
v = set([])
for e in es:
if not ((e[0] == e[2]) or (e[1] == e[3])):
return False
v.add((e[0], e[1]))
v.add((e[2], e[3]))
if len(v) != 4:
return False
xs = set([])
ys = set([])
for vi in v:
xs.add(vi[0])
ys.add(vi[1])
if len(xs) != 2 or len(ys) != 2:
return False
t = b = r = l = False
for e in es:
t = t or (e[1] == e[3] and e[0] != e[2] and e[1] == max(ys))
b = b or (e[1] == e[3] and e[0] != e[2] and e[1] == min(ys))
r = r or (e[0] == e[2] and e[1] != e[3] and e[0] == max(xs))
l = l or (e[0] == e[2] and e[1] != e[3] and e[0] == min(xs))
return t and b and l and r
e1 = list(map(int, input().split(' ')))
e2 = list(map(int, input().split(' ')))
e3 = list(map(int, input().split(' ')))
e4 = list(map(int, input().split(' ')))
if is_rect((e1, e2, e3, e4)):
print("YES")
else:
print("NO")
| python | code_algorithm | [
{
"input": "0 0 0 3\n2 0 0 0\n2 2 2 0\n0 2 2 2\n",
"output": "NO\n"
},
{
"input": "1 1 6 1\n1 0 6 0\n6 0 6 1\n1 1 1 0\n",
"output": "YES\n"
},
{
"input": "2 -1 -2 -1\n2 -1 2 -1\n2 -1 -2 -1\n2 -1 2 -1\n",
"output": "NO\n"
},
{
"input": "0 0 0 1\n0 1 0 1\n0 1 0 0\n0 1 0 1\n",
... | code_contests | python | 0 | bb3acb6b6f823724e889c57b9ec99a7e |
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).
Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?
Input
The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n).
It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.
Output
Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.
Examples
Input
1 1
+1
Output
Truth
Input
3 2
-1
-2
-3
Output
Not defined
Not defined
Not defined
Input
4 1
+2
-3
+4
-1
Output
Lie
Not defined
Lie
Not defined
Note
The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.
In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.
In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n, m = map(int, input().split())
t = [int(input()) for i in range(n)]
s, p = 0, [0] * (n + 1)
for i in t:
if i < 0:
m -= 1
p[-i] -= 1
else: p[i] += 1
q = {i for i in range(1, n + 1) if p[i] == m}
if len(q) == 0: print('Not defined\n' * n)
elif len(q) == 1:
j = q.pop()
print('\n'.join(['Truth' if i == j or (i < 0 and i + j) else 'Lie' for i in t]))
else:
q.update({-i for i in q})
print('\n'.join(['Not defined' if i in q else ('Truth' if i < 0 else 'Lie') for i in t])) | python | code_algorithm | [
{
"input": "4 1\n+2\n-3\n+4\n-1\n",
"output": "Lie\nNot defined\nLie\nNot defined\n"
},
{
"input": "1 1\n+1\n",
"output": "Truth\n"
},
{
"input": "3 2\n-1\n-2\n-3\n",
"output": "Not defined\nNot defined\nNot defined\n"
},
{
"input": "10 4\n-8\n+1\n-6\n-10\n+5\n-6\n-8\n-8\n-4\... | code_contests | python | 0 | 822eb83c27b1798ae511bac48fa88feb |
The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series.
There are n single men and n single women among the main characters. An opinion poll showed that viewers like several couples, and a marriage of any of them will make the audience happy. The Smart Beaver formalized this fact as k triples of numbers (h, w, r), where h is the index of the man, w is the index of the woman, and r is the measure of the audience's delight in case of the marriage of this couple. The same poll showed that the marriage of any other couple will leave the audience indifferent, so the screenwriters decided not to include any such marriages in the plot.
The script allows you to arrange several marriages between the heroes or not to arrange marriages at all. A subset of some of the k marriages is considered acceptable if each man and each woman is involved in at most one marriage of the subset (the series won't allow any divorces). The value of the acceptable set of marriages is the total delight the spectators will get from the marriages included in this set.
Obviously, there is a finite number of acceptable sets, and they all describe some variants of the script. The screenwriters do not want to choose a set with maximum value — it would make the plot too predictable. So the Smart Beaver offers the following option: sort all the acceptable sets in increasing order of value and choose the t-th set from the sorted list. Thus, t = 1 corresponds to a plot without marriages, t = 2 — to a single marriage resulting in minimal delight for the audience, and so on.
Help the Beaver to implement the algorithm for selecting the desired set.
Input
The first input line contains integers n, k and t (1 ≤ k ≤ min(100, n2), 1 ≤ t ≤ 2·105), separated by single spaces. Next k lines contain triples of integers (h, w, r) (1 ≤ h, w ≤ n; 1 ≤ r ≤ 1000), separated by single spaces, which describe the possible marriages. It is guaranteed that the input data is correct: t doesn't exceed the total number of acceptable sets, and each pair (h, w) is present in at most one triple.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 20
Output
Print a single number — the value of the t-th acceptable variant.
Examples
Input
2 4 3
1 1 1
1 2 2
2 1 3
2 2 7
Output
2
Input
2 4 7
1 1 1
1 2 2
2 1 3
2 2 7
Output
8
Note
The figure shows 7 acceptable sets of marriages that exist in the first sample.
<image>
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | I=lambda:list(map(int,input().split()))
n,k,T=I()
t=[I()for _ in '0'*k]
def b(h,w,r,a):
if h>n:a+=[r]
else:
b(h+1,w,r,a)
for f,s,v in t:
if f==h and s in w:b(h+1,w-set([s]),r+v,a)
return a
print(sorted(b(1,set(range(1,n+1)), 0,[]))[T-1]) | python | code_algorithm | [
{
"input": "2 4 3\n1 1 1\n1 2 2\n2 1 3\n2 2 7\n",
"output": "2\n"
},
{
"input": "2 4 7\n1 1 1\n1 2 2\n2 1 3\n2 2 7\n",
"output": "8\n"
},
{
"input": "4 16 105\n2 4 15\n1 1 16\n2 2 57\n3 4 31\n1 2 47\n2 3 28\n1 3 70\n4 2 50\n3 1 10\n4 1 11\n4 4 27\n1 4 56\n3 3 28\n3 2 28\n2 1 33\n4 3 63\n... | code_contests | python | 0 | 1442eaf458478c73a7487c64e5fc51c6 |
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high.
At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kx + b bacteria.
The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point.
For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment.
Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment.
Input
The first line contains four space-separated integers k, b, n and t (1 ≤ k, b, n, t ≤ 106) — the parameters of bacterial growth, the time Qwerty needed to grow z bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly.
Output
Print a single number — the minimum number of seconds Qwerty needs to grow at least z bacteria in the tube.
Examples
Input
3 1 3 5
Output
2
Input
1 4 4 7
Output
3
Input
2 2 4 100
Output
0
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def canMake(iter):
pass
k,b,n,t=value()
z=1
reduced=0
# for i in range(n):
# z=z*k+b
# print(z)
# print()
# z=t
# for i in range(n):
# z=z*k+b
# print(z)
while(z<=t):
reduced+=1
z=z*k+b
print(max(0,n-reduced+1))
| python | code_algorithm | [
{
"input": "2 2 4 100\n",
"output": "0\n"
},
{
"input": "3 1 3 5\n",
"output": "2\n"
},
{
"input": "1 4 4 7\n",
"output": "3\n"
},
{
"input": "5 5 2 10\n",
"output": "1\n"
},
{
"input": "1000000 1000000 1 1\n",
"output": "1\n"
},
{
"input": "5 5 2 1\n"... | code_contests | python | 0 | 41909479015d1a4e47d82f07cb965c55 |
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.
Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.
Input
The first line contains two space-separated integers n, x (1 ≤ n ≤ 105; 0 ≤ x ≤ 2·105) — the number of Olympiad participants and the minimum number of points Vasya earned.
The second line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the participants' points in the first tour.
The third line contains n space-separated integers: b1, b2, ..., bn (0 ≤ bi ≤ 105) — the participants' points in the second tour.
The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers i, j (1 ≤ i, j ≤ n) such, that ai + bj ≥ x.
Output
Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad.
Examples
Input
5 2
1 1 1 1 1
1 1 1 1 1
Output
1 5
Input
6 7
4 3 5 6 4 4
8 6 0 4 3 4
Output
1 5
Note
In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.
In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.
In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.
In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from sys import stdin
from collections import deque
n,x = [int(x) for x in stdin.readline().split()]
s1 = deque(sorted([int(x) for x in stdin.readline().split()]))
s2 = deque(sorted([int(x) for x in stdin.readline().split()]))
place = 0
for score in s1:
if s2[-1] + score >= x:
place += 1
s2.pop()
else:
s2.popleft()
print(1,place)
| python | code_algorithm | [
{
"input": "6 7\n4 3 5 6 4 4\n8 6 0 4 3 4\n",
"output": "1 5\n"
},
{
"input": "5 2\n1 1 1 1 1\n1 1 1 1 1\n",
"output": "1 5\n"
},
{
"input": "1 100\n56\n44\n",
"output": "1 1\n"
},
{
"input": "3 10\n9 9 0\n0 0 10\n",
"output": "1 1\n"
},
{
"input": "5 45\n1 2 3 4 ... | code_contests | python | 0 | ad2c6c3e3dba17ce0fea0e88c8c9c05a |
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:
* he chooses two elements of the array ai, aj (i ≠ j);
* he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1.
The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times.
Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.
Output
Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.
Examples
Input
2
2 1
Output
1
Input
3
1 4 1
Output
3
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | x=int(input())
sm=sum(list(map(int,input().split())))%x
if sm==0:
print(x)
else:
print(x-1) | python | code_algorithm | [
{
"input": "3\n1 4 1\n",
"output": "3\n"
},
{
"input": "2\n2 1\n",
"output": "1\n"
},
{
"input": "6\n-1 1 0 0 -1 -1\n",
"output": "5\n"
},
{
"input": "4\n2 0 -2 -1\n",
"output": "3\n"
},
{
"input": "4\n2 -7 -2 -6\n",
"output": "3\n"
},
{
"input": "100\... | code_contests | python | 1 | d282912f16421a353c0e1838fa1b729b |
Petya loves computer games. Finally a game that he's been waiting for so long came out!
The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values of <image> for all i from 1 to n. The expression ⌊ x⌋ denotes the result of rounding the number x down to the nearest integer.
At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.
Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.
Input
The first line of the input contains two positive integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 107) — the number of skills of the character and the number of units of improvements at Petya's disposal.
The second line of the input contains a sequence of n integers ai (0 ≤ ai ≤ 100), where ai characterizes the level of the i-th skill of the character.
Output
The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using k or less improvement units.
Examples
Input
2 4
7 9
Output
2
Input
3 8
17 15 19
Output
5
Input
2 2
99 100
Output
20
Note
In the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to lfloor frac{100}{10} rfloor + lfloor frac{100}{10} rfloor = 10 + 10 = 20.
In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is <image>.
In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to <image>.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n,k=map(int,input().split())
l=list(map(int,input().split()))
rem=[]
ans=0
for i in l:
rem.append(i%10)
ans=ans+i//10
#print(ans)
rem.sort() # 0 1 2 3.. 9 9 9..
i=n-1
while(i>=0 and k>0):
if(rem[i]!=0): #starting from back 9 -> 8 .... -> 2 -> 1->0
sm=10-(rem[i])
if(k>=sm):
k=k-sm
rem[i]=0
ans=ans+1
#print(ans)
i=i-1
#after coming out of while , either k==0, then some or all of rem values are 0 , it means actual value id div by 10
#if k>0 , it means all values are div by 10, so we can add 10 to get more max answer, and use them, until we reach n*10
print(min(ans + k//10 ,n*10))
| python | code_algorithm | [
{
"input": "2 2\n99 100\n",
"output": "20\n"
},
{
"input": "2 4\n7 9\n",
"output": "2\n"
},
{
"input": "3 8\n17 15 19\n",
"output": "5\n"
},
{
"input": "100 9455943\n44 8 21 71 7 29 40 65 91 70 48 19 77 48 16 22 54 4 29 34 9 22 73 34 47 41 5 83 32 91 52 6 74 64 18 23 9 4 36 7... | code_contests | python | 0.1 | f6b9d6dc4ce1ad8d9e59a7f5b25ff792 |
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that si = b. Of course, you are the person he asks for a help.
Input
The first line of the input contain three integers a, b and c ( - 109 ≤ a, b, c ≤ 109) — the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively.
Output
If b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes).
Examples
Input
1 7 3
Output
YES
Input
10 10 0
Output
YES
Input
1 -4 5
Output
NO
Input
0 60 50
Output
NO
Note
In the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element.
In the second sample, the favorite integer of Vasya is equal to the first element of the sequence.
In the third sample all elements of the sequence are greater than Vasya's favorite integer.
In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | a, b, c = map(int, input().split())
if b == a:
print('YES')
elif not c:
print('NO')
elif (a < b) and c < 0:
print('NO')
elif (a > b) and c > 0:
print('NO')
else:
print('NO' if ((b-a) % c) else 'YES')
| python | code_algorithm | [
{
"input": "1 -4 5\n",
"output": "NO\n"
},
{
"input": "1 7 3\n",
"output": "YES\n"
},
{
"input": "0 60 50\n",
"output": "NO\n"
},
{
"input": "10 10 0\n",
"output": "YES\n"
},
{
"input": "1 6 1\n",
"output": "YES\n"
},
{
"input": "-2 -2 0\n",
"outpu... | code_contests | python | 0.4 | 739f82910ee3a61e5a51ff7e5d124f18 |
You are given a description of a depot. It is a rectangular checkered field of n × m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*").
You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y.
You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the depot field.
The next n lines contain m symbols "." and "*" each — the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall.
Output
If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes).
Otherwise print "YES" (without quotes) in the first line and two integers in the second line — the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them.
Examples
Input
3 4
.*..
....
.*..
Output
YES
1 2
Input
3 3
..*
.*.
*..
Output
NO
Input
6 5
..*..
..*..
*****
..*..
..*..
..*..
Output
YES
3 3
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def bombs(array, rows, cols, walls, wallsInRows, wallsInCols):
if walls == 0:
print("YES")
print(1, 1)
return
for i in range(0, rows):
for j in range(0, cols):
s = wallsInRows[i] + wallsInCols[j]
if (array[i][j] == '*' and s - 1 == walls) or (array[i][j] == "." and s == walls):
print("YES")
print(i + 1, j + 1)
return
print("NO")
return
def readArray():
k = input().split(" ")
rows, cols = int(k[0]), int(k[1])
array = []
wallsInRows = []
wallsInCols = [0 for i in range(0, cols)]
walls = 0
for i in range(0, rows):
array.append(list(input()))
wallsInRows.append(0)
for j in range(0, cols):
if array[i][j] == "*":
wallsInRows[i] += 1
wallsInCols[j] += 1
walls += 1
return array, rows, cols, walls, wallsInRows, wallsInCols
array, rows, cols, walls, wallsInRows, wallsInCols = readArray()
bombs(array, rows, cols, walls, wallsInRows, wallsInCols)
# Sun Nov 24 2019 00:47:50 GMT+0300 (MSK)
# Sun Nov 24 2019 00:50:51 GMT+0300 (MSK)
| python | code_algorithm | [
{
"input": "3 3\n..*\n.*.\n*..\n",
"output": "NO\n"
},
{
"input": "6 5\n..*..\n..*..\n*****\n..*..\n..*..\n..*..\n",
"output": "YES\n3 3\n"
},
{
"input": "3 4\n.*..\n....\n.*..\n",
"output": "YES\n1 2\n"
},
{
"input": "3 3\n*..\n**.\n...\n",
"output": "YES\n2 1\n"
},
... | code_contests | python | 0.2 | b91312534884e6456434b99042a26f35 |
As you have noticed, there are lovely girls in Arpa’s land.
People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.
<image>
Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.
The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.
Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.
Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i).
Input
The first line of input contains integer n (1 ≤ n ≤ 100) — the number of people in Arpa's land.
The second line contains n integers, i-th of them is crushi (1 ≤ crushi ≤ n) — the number of i-th person's crush.
Output
If there is no t satisfying the condition, print -1. Otherwise print such smallest t.
Examples
Input
4
2 3 1 4
Output
3
Input
4
4 4 4 4
Output
-1
Input
4
2 1 4 3
Output
1
Note
In the first sample suppose t = 3.
If the first person starts some round:
The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.
The process is similar for the second and the third person.
If the fourth person starts some round:
The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4.
In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def gcd(a,b):
if b==0:
return a
return gcd(b, a%b)
def lcm(a,b):
return a*b/gcd(a,b)
def dfs(sad, num, posjeceno):
"""if sad==a[sad]-1 and posjeceno!=[0]*n:
return (-10, [])"""
posjeceno[sad]=1
if posjeceno[a[sad]-1]==1:
return (num+1, posjeceno)
return dfs(a[sad]-1, num+1, posjeceno)
def trazi(oznaka):
global memo
if memo[oznaka]==[]:
memo[oznaka]=dfs(oznaka, 0, [0]*n)
return memo[oznaka]
n=int(input())
a=list(map(int,input().split()))
d=set()
brojac=n
memo=[[] for e in range (n)]
while brojac>-1:
brojac-=1
if memo[brojac]==[]:
trazi(brojac)
"""if memo[brojac][0]==-10:
d=-10
break"""
l=memo[brojac][1]
for w in range(n):
if l[w]==1:
if trazi(w)[1]!=l:
d=-10
break
if d==-10:
break
vrati, l=trazi(brojac)
if vrati%2==0:
d.add(float(vrati/2))
else:
d.add(float(vrati))
if d==-10:
print(-1)
else:
sol=1
for r in d:
sol=lcm(sol, r)
print(int(sol))
| python | code_algorithm | [
{
"input": "4\n2 1 4 3\n",
"output": "1\n"
},
{
"input": "4\n4 4 4 4\n",
"output": "-1\n"
},
{
"input": "4\n2 3 1 4\n",
"output": "3\n"
},
{
"input": "100\n99 7 60 94 9 96 38 44 77 12 75 88 47 42 88 95 59 4 12 96 36 16 71 6 26 19 88 63 25 53 90 18 95 82 63 74 6 60 84 88 80 95... | code_contests | python | 0 | eb99a5a5e9ca63e9fff3abba8acc53de |
<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 ≤ 106, 1 ≤ k ≤ 26).
In the second string, n uppercase English letters s1s2... sn are given, where si 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.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
n, k = map(int, input().split())
a = list(input())
st = [0] * 26
ed = [0] * 26
for i in range(n):
if st[ord(a[i])-65] == 0:
st[ord(a[i])-65] = i + 1
else:
ed[ord(a[i])-65] = i + 1
for i in range(26):
if st[i] != 0 and ed[i] == 0:
ed[i] = st[i]
n = 52
i = 0
j = 0
maxi = -1 * sys.maxsize
l = 0
st.sort()
ed.sort()
while i < 26 and j < 26:
if st[i] == 0:
i += 1
continue
if ed[j] == 0:
j += 1
continue
if st[i] <= ed[j]:
l += 1
i += 1
if l > maxi:
maxi = l
else:
l -= 1
j += 1
if maxi > k:
print("YES")
else:
print("NO")
| python | code_algorithm | [
{
"input": "5 1\nAABBB\n",
"output": "NO\n"
},
{
"input": "5 1\nABABB\n",
"output": "YES\n"
},
{
"input": "433 3\nFZDDHMJGBZCHFUXBBPIEBBEFDWOMXXEPOMDGSMPIUZOMRZQNSJAVNATGIWPDFISKFQXJNVFXPHOZDAEZFDAHDXXQKZMGNSGKQNWGNGJGJZVVITKNFLVCPMZSDMCHBTVAWYVZLIXXIADXNYILEYNIQHKMOGMVOCWGHCWIYMPEPADSJA... | code_contests | python | 0 | a5cfdd631d261f425b1632c21b39c227 |
In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?"
Input
The first line contains five integers n, m, c_l, c_e, v (2 ≤ n, m ≤ 10^8, 0 ≤ c_l, c_e ≤ 10^5, 1 ≤ c_l + c_e ≤ m - 1, 1 ≤ v ≤ n - 1) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≤ l_i ≤ m), denoting the positions of the stairs. If c_l = 0, the second line is empty.
The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct.
The fourth line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i.
Output
Print q integers, one per line — the answers for the queries.
Example
Input
5 6 1 1 3
2
5
3
1 1 5 6
1 3 5 4
3 3 5 3
Output
7
5
4
Note
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | def takeClosest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
if len(myList) == 0:
return 9e10
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after
else:
return before
from bisect import bisect_left
from math import ceil
n, m, n_stairs, n_elevators, v = map(int, input().split(" "))
if n_stairs > 0:
stairs = list(map(int, input().split(" ")))
else:
stairs = []
input()
if n_elevators > 0:
elevators = list(map(int, input().split(" ")))
else:
elevators = []
input()
queries = int(input())
res = []
for i in range(queries):
x1, y1, x2, y2 = map(int, input().split(" "))
next_elevator = takeClosest(elevators, (y1 + y2) / 2)
next_stairs = takeClosest(stairs, (y1 + y2) / 2)
time_elevator = abs(x1 - x2) / v
time_stairs = abs(x1 - x2)
mi = min(y1, y2)
ma = max(y1, y2)
if next_elevator < mi:
time_elevator += (mi - next_elevator) * 2
elif next_elevator > ma:
time_elevator += (next_elevator - ma) * 2
if next_stairs < mi:
time_stairs += (mi - next_stairs) * 2
elif next_stairs > ma:
time_stairs += (next_stairs - ma) * 2
dis = abs(y1 - y2)
if time_elevator < time_stairs:
dis += time_elevator
else:
dis += time_stairs
if x1 == x2:
res.append(abs(y1 - y2))
else:
res.append(ceil(dis))
print(*res, sep="\n") | python | code_algorithm | [
{
"input": "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n",
"output": "7\n5\n4\n"
},
{
"input": "2 10 1 1 1\n1\n10\n1\n1 5 1 8\n",
"output": "3\n"
},
{
"input": "4 4 1 0 1\n1\n\n1\n1 2 1 4\n",
"output": "2\n"
},
{
"input": "2 5 1 0 1\n2\n\n1\n1 4 1 5\n",
"output": "1\n"... | code_contests | python | 0.1 | dc6ab0680aaba2dcc60202f47422f4ee |
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard.
Initially, you have an empty string. Until you type the whole string, you may perform the following operation:
* add a character to the end of the string.
Besides, at most once you may perform one additional operation: copy the string and append it to itself.
For example, if you have to type string abcabca, you can type it in 7 operations if you type all the characters one by one. However, you can type it in 5 operations if you type the string abc first and then copy it and type the last character.
If you have to type string aaaaaaaaa, the best option is to type 4 characters one by one, then copy the string, and then type the remaining character.
Print the minimum number of operations you need to type the given string.
Input
The first line of the input containing only one integer number n (1 ≤ n ≤ 100) — the length of the string you have to type. The second line containing the string s consisting of n lowercase Latin letters.
Output
Print one integer number — the minimum number of operations you need to type the given string.
Examples
Input
7
abcabca
Output
5
Input
8
abcdefgh
Output
8
Note
The first test described in the problem statement.
In the second test you can only type all the characters one by one.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | n=int(input())
s=input()
i=0
d=""
ls=[]
mx=-1
while i<n:
temp=s[0:i+1]
for j in range(i+1,n+1):
if temp==s[i+1:j]:
mx=max(mx,len(temp))
i+=1
if mx>0:
print(len(temp)-mx+1)
else:
print(len(temp)) | python | code_algorithm | [
{
"input": "8\nabcdefgh\n",
"output": "8\n"
},
{
"input": "7\nabcabca\n",
"output": "5\n"
},
{
"input": "5\nababa\n",
"output": "4\n"
},
{
"input": "8\naaabcabc\n",
"output": "8\n"
},
{
"input": "7\nabcdabc\n",
"output": "7\n"
},
{
"input": "29\nabbabb... | code_contests | python | 0 | bf10f9b3251139e2c39530129620e5e9 |
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
Input
The only line of the input file contains two natural numbers Y and W — the results of Yakko's and Wakko's die rolls.
Output
Output the required probability in the form of irreducible fraction in format «A/B», where A — the numerator, and B — the denominator. If the required probability equals to zero, output «0/1». If the required probability equals to 1, output «1/1».
Examples
Input
4 2
Output
1/2
Note
Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | x, y = input().split()
x = int(x)
y = int(y)
z = 7 - max(x, y)
ans = z/6
if ans == (1/6):
print("1/6")
elif ans == (2/6):
print("1/3")
elif ans == (3/6):
print("1/2")
elif ans == (4/6):
print("2/3")
elif ans == (5/6):
print("5/6")
else:
print("1/1")
| python | code_algorithm | [
{
"input": "4 2\n",
"output": "1/2\n"
},
{
"input": "6 6\n",
"output": "1/6\n"
},
{
"input": "1 4\n",
"output": "1/2\n"
},
{
"input": "4 4\n",
"output": "1/2\n"
},
{
"input": "3 3\n",
"output": "2/3\n"
},
{
"input": "6 4\n",
"output": "1/6\n"
},
... | code_contests | python | 0.6 | 14c948fe89b366c62fc244a013f8b329 |
You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have n tiles in your hand. Each tile has an integer between 1 and m written on it.
To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, 7, 7, 7 is a valid triple, and so is 12, 13, 14, but 2,2,3 or 2,4,6 are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple.
To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.
Input
The first line contains two integers integer n and m (1 ≤ n, m ≤ 10^6) — the number of tiles in your hand and the number of tiles types.
The second line contains integers a_1, a_2, …, a_n (1 ≤ a_i ≤ m), where a_i denotes the number written on the i-th tile.
Output
Print one integer: the maximum number of triples you can form.
Examples
Input
10 6
2 3 3 3 4 4 4 5 5 6
Output
3
Input
12 6
1 5 3 3 3 4 3 5 3 2 3 3
Output
3
Input
13 5
1 1 5 1 2 3 3 2 4 2 3 4 5
Output
4
Note
In the first example, we have tiles 2, 3, 3, 3, 4, 4, 4, 5, 5, 6. We can form three triples in the following way: 2, 3, 4; 3, 4, 5; 4, 5, 6. Since there are only 10 tiles, there is no way we could form 4 triples, so the answer is 3.
In the second example, we have tiles 1, 2, 3 (7 times), 4, 5 (2 times). We can form 3 triples as follows: 1, 2, 3; 3, 3, 3; 3, 4, 5. One can show that forming 4 triples is not possible.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | from collections import Counter
n, m = map(int, input().split())
B = list(map(int, input().split()))
cnt = Counter(B)
A = sorted(cnt.keys())
n = len(A)
dp = [[0] * 3 for _ in range(3)]
for i, a in enumerate(A):
dp2 = [[0] * 3 for _ in range(3)]
for x in range(1 if i >= 2 and a - 2 != A[i - 2] else 3):
for y in range(1 if i >= 1 and a - 1 != A[i - 1] else 3):
for z in range(3):
if x + y + z <= cnt[a]:
dp2[y][z] = max(dp2[y][z], dp[x][y] + z + (cnt[a] - x - y - z) // 3)
dp = dp2
print (dp[0][0]) | python | code_algorithm | [
{
"input": "10 6\n2 3 3 3 4 4 4 5 5 6\n",
"output": "3\n"
},
{
"input": "13 5\n1 1 5 1 2 3 3 2 4 2 3 4 5\n",
"output": "4\n"
},
{
"input": "12 6\n1 5 3 3 3 4 3 5 3 2 3 3\n",
"output": "3\n"
},
{
"input": "14 9\n5 5 6 8 8 4 3 2 2 7 3 9 5 4\n",
"output": "4\n"
},
{
... | code_contests | python | 0 | 270183a4d815949dbaf157abb006a401 |
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i ≥ i).
Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page i such that Ivan already has read it, but hasn't read page a_i). After that, he closes the book and continues to read it on the following day from the next page.
How many days will it take to read the whole book?
Input
The first line contains single integer n (1 ≤ n ≤ 10^4) — the number of pages in the book.
The second line contains n integers a_1, a_2, ..., a_n (i ≤ a_i ≤ n), where a_i is the number of page which contains the explanation of the mystery on page i.
Output
Print one integer — the number of days it will take to read the whole book.
Example
Input
9
1 3 3 6 7 6 8 8 9
Output
4
Note
Explanation of the example test:
During the first day Ivan will read only the first page. During the second day Ivan will read pages number 2 and 3. During the third day — pages 4-8. During the fourth (and the last) day Ivan will read remaining page number 9.
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` | import sys
#p = [[] for i in range(N)]
#for i in range(N):
# p[i] += map(int, sys.stdin.readline().split())
#Q = input()
#for i in range(Q):
# print(list(map(int, sys.stdin.readline().split())))
n = int(input())
a = [int(c) for c in sys.stdin.readline().split()]
aktmax, d = 0, 0
for i, c in enumerate(a, start=1):
aktmax = max(aktmax, c)
if aktmax <= i:
d += 1
print(d)
| python | code_algorithm | [
{
"input": "9\n1 3 3 6 7 6 8 8 9\n",
"output": "4\n"
},
{
"input": "1\n1\n",
"output": "1\n"
},
{
"input": "13\n1 2 3 4 5 6 7 8 9 10 11 12 13\n",
"output": "13\n"
},
{
"input": "11\n1 2 3 4 5 6 7 8 9 10 11\n",
"output": "11\n"
},
{
"input": "15\n1 2 3 4 5 6 7 8 9 ... | code_contests | python | 0.8 | 9ea0e803aacc8baf2edc41dc0b55e242 |
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.
In this task you are given a cell field n ⋅ m, consisting of n rows and m columns, where point's coordinates (x, y) mean it is situated in the x-th row and y-th column, considering numeration from one (1 ≤ x ≤ n, 1 ≤ y ≤ m). Initially, you stand in the cell (1, 1). Every move you can jump from cell (x, y), which you stand in, by any non-zero vector (dx, dy), thus you will stand in the (x+dx, y+dy) cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).
Tolik's uncle is a very respectful person. Help him to solve this task!
Input
The first and only line contains two positive integers n, m (1 ≤ n ⋅ m ≤ 10^{6}) — the number of rows and columns of the field respectively.
Output
Print "-1" (without quotes) if it is impossible to visit every cell exactly once.
Else print n ⋅ m pairs of integers, i-th from them should contain two integers x_i, y_i (1 ≤ x_i ≤ n, 1 ≤ y_i ≤ m) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too.
Notice that the first cell should have (1, 1) coordinates, according to the statement.
Examples
Input
2 3
Output
1 1
1 3
1 2
2 2
2 3
2 1
Input
1 1
Output
1 1
Note
The vectors from the first example in the order of making jumps are (0, 2), (0, -1), (1, 0), (0, 1), (0, -2).
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
```
Write Python code to solve the problem. Present the code in the code block:
```python
Your code
``` |
# [0,0,0]
# [0,0,0]
# [1,0,0]
# [0,0,0]
# [0,0,0]
# [1,0,1]
# [0,0,0]
# [0,0,0]
# [1,1,1]
# [0,0,0]
# [0,0,0]
# [1,1,1]
# [0,0,1]
# [0,0,0]
# [0,0,0] 3,2
#
# 0,0 3,2
# 0,1 3,1
# 0,2 3,0
# 1,0 2,2
# 1,1 2,1
# 1,2 2,0
n, m = map(int, input().split())
ans = []
if n % 2 == 0:
for i in range(int(n / 2)):
for j in range(m):
ans.append(f'{i+1} {j+1}')
ans.append(f'{n-i} {m-j}')
else:
for i in range(int(n / 2)):
for j in range(m):
ans.append(f'{i+1} {j+1}')
ans.append(f'{n-i} {m-j}')
mid = int(n/2)
for j in range(m//2):
ans.append(f'{mid+1} {j+1}')
ans.append(f'{mid+1} {m-j}')
if m % 2 != 0:
ans.append(f'{n//2+1} {m//2+1}')
print('\n'.join(ans))
"""
0 0 0
0 0 0
1 0 0
0 0 0
1 0 0
0 0 1
1 1 0
0 0 1
1 1 0
0 1 1
1 1 1
0 1 1
1 1 1
1 1 1
"""
| python | code_algorithm | [
{
"input": "1 1\n",
"output": "1 1\n"
},
{
"input": "2 3\n",
"output": "1 1\n2 3\n1 2\n2 2\n1 3\n2 1\n"
},
{
"input": "782 19\n",
"output": "1 1\n782 19\n1 2\n782 18\n1 3\n782 17\n1 4\n782 16\n1 5\n782 15\n1 6\n782 14\n1 7\n782 13\n1 8\n782 12\n1 9\n782 11\n1 10\n782 10\n1 11\n782 9\... | code_contests | python | 0 | a0a5a88660c891ae9eda2eeec0b98c0b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.