index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
2,800 | 7 | One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages.
Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week.
Assuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book.
Input
The first input line contains the single integer n (1 β€ n β€ 1000) β the number of pages in the book.
The second line contains seven non-negative space-separated integers that do not exceed 1000 β those integers represent how many pages Petr can read on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday correspondingly. It is guaranteed that at least one of those numbers is larger than zero.
Output
Print a single number β the number of the day of the week, when Petr will finish reading the book. The days of the week are numbered starting with one in the natural order: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.
Examples
Input
100
15 20 20 15 10 30 45
Output
6
Input
2
1 0 0 0 0 0 0
Output
1
Note
Note to the first sample:
By the end of Monday and therefore, by the beginning of Tuesday Petr has 85 pages left. He has 65 pages left by Wednesday, 45 by Thursday, 30 by Friday, 20 by Saturday and on Saturday Petr finishes reading the book (and he also has time to read 10 pages of something else).
Note to the second sample:
On Monday of the first week Petr will read the first page. On Monday of the second week Petr will read the second page and will finish reading the book. | def solve():
n = int(input())
a = list(map(int, input().split()))
pages = 0
while True:
for i in range(7):
pages += a[i]
if pages >= n:
return i + 1
print(solve()) | {
"input": [
"100\n15 20 20 15 10 30 45\n",
"2\n1 0 0 0 0 0 0\n"
],
"output": [
"6\n",
"1\n"
]
} |
2,801 | 12 | There are n persons located on a plane. The i-th person is located at the point (x_i, y_i) and initially looks at the point (u_i, v_i).
At the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full 360-degree turn.
It is said that persons A and B made eye contact if person A looks in person B's direction at the same moment when person B looks in person A's direction. If there is a person C located between persons A and B, that will not obstruct A and B from making eye contact. A person can make eye contact with more than one person at the same time.
Calculate the number of pairs of persons that will make eye contact at least once during the rotation (including the initial moment).
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of persons. The following n lines describe persons, each line containing four space-separated integers x_i, y_i, u_i, v_i (|x_i|, |y_i|, |u_i|, |v_i| β€ 10^9; x_i β u_i or y_i β v_i), where (x_i, y_i) are the coordinates of the point where the i-th person is located and (u_i, v_i) are the coordinates of the point that the i-th person looks at initially. Each person's location is unique in each test case.
The sum of n over all test cases does not exceed 10^5.
Output
For each test case, print one integer β the number of pairs of persons who will make eye contact at least once during the rotation, including the initial moment.
Example
Input
3
2
0 0 0 1
1 0 2 0
3
0 0 1 1
1 1 0 0
1 0 2 0
6
0 0 0 1
1 0 1 2
2 0 2 3
3 0 3 -5
4 0 4 -5
5 0 5 -5
Output
0
1
9 | import math
def hash(x, y, u, v):
g = math.gcd(u - x, v - y)
return ((u - x) // g, (v - y) // g)
t = int(input())
for case in range(t):
n = int(input())
d = {}
for p in range(n):
x = hash(*[int(s) for s in input().split(' ')])
if x in d:
d[x] += 1
else:
d[x] = 1
cnt = 0
for k in d:
z = (-k[0], -k[1])
if z in d:
cnt += d[k] * d[z]
cnt //= 2
print(cnt)
| {
"input": [
"3\n2\n0 0 0 1\n1 0 2 0\n3\n0 0 1 1\n1 1 0 0\n1 0 2 0\n6\n0 0 0 1\n1 0 1 2\n2 0 2 3\n3 0 3 -5\n4 0 4 -5\n5 0 5 -5\n"
],
"output": [
"\n0\n1\n9\n"
]
} |
2,802 | 11 | You are storing an integer array of length m in a database. To maintain internal integrity and protect data, the database stores n copies of this array.
Unfortunately, the recent incident may have altered the stored information in every copy in the database.
It's believed, that the incident altered at most two elements in every copy. You need to recover the original array based on the current state of the database.
In case there are multiple ways to restore the array, report any. If there is no array that differs from every copy in no more than two positions, report that as well.
Input
The first line contains integers n and m (2 β€ n; 1 β€ m; n β
m β€ 250 000) β the number of copies and the size of the array.
Each of the following n lines describes one of the currently stored copies in the database, it consists of m integers s_{i, 1}, s_{i, 2}, ..., s_{i, m} (1 β€ s_{i, j} β€ 10^9).
Output
If there is an array consistent with all given copies, print "Yes" and then the array itself. The array must have length m and contain integers between 1 and 10^9 only.
Otherwise, print "No".
If there are multiple possible arrays, print any of them.
Examples
Input
3 4
1 10 10 100
1 1 1 100
10 100 1 100
Output
Yes
1 10 1 100
Input
10 7
1 1 1 1 1 1 1
1 1 1 1 1 1 2
1 1 1 1 1 2 2
1 1 1 1 2 2 1
1 1 1 2 2 1 1
1 1 2 2 1 1 1
1 2 2 1 1 1 1
2 2 1 1 1 1 1
2 1 1 1 1 1 1
1 1 1 1 1 1 1
Output
Yes
1 1 1 1 1 1 1
Input
2 5
2 2 1 1 1
1 1 2 2 2
Output
No
Note
In the first example, the array [1, 10, 1, 100] differs from first and second copies in just one position, and from the third copy in two positions.
In the second example, array [1, 1, 1, 1, 1, 1, 1] is the same as the first copy and differs from all other copies in at most two positions.
In the third example, there is no array differing in at most two positions from every database's copy. | def solve():
n, m = map(int,input().split());a = [list(map(int, input().split())) for i in range(n)];c = [];row = 0
for i in range(1,n):
c1 = [j for j in range(m) if a[0][j] != a[i][j]]
if len(c1) > len(c):c = c1;row = i
if len(c) > 4:print('No');return
c = [];row2 = row
for i in range(n):
c1 = [j for j in range(m) if a[row][j] != a[i][j]]
if len(c1) > len(c):c = c1;row2 = i
b = a[row2].copy()
for i in range(2**len(c)):
for j in range(len(c)):cc = c[j];b[cc] = (a[row][cc] if ((i >> j) & 1) != 0 else a[row2][cc])
bad = False
for j in range(n):
cnt = 0
for k in range(m):cnt += int(b[k] != a[j][k])
if cnt > 2:bad = True;break
if not bad:print('Yes');print(' '.join(map(str,b)));return
print('No')
solve() | {
"input": [
"3 4\n1 10 10 100\n1 1 1 100\n10 100 1 100\n",
"10 7\n1 1 1 1 1 1 1\n1 1 1 1 1 1 2\n1 1 1 1 1 2 2\n1 1 1 1 2 2 1\n1 1 1 2 2 1 1\n1 1 2 2 1 1 1\n1 2 2 1 1 1 1\n2 2 1 1 1 1 1\n2 1 1 1 1 1 1\n1 1 1 1 1 1 1\n",
"2 5\n2 2 1 1 1\n1 1 2 2 2\n"
],
"output": [
"\nYes\n1 10 1 100\n",
"\nYes\n1 1 1 1 1 1 1\n",
"\nNo\n"
]
} |
2,803 | 12 | Phoenix's homeland, the Fire Nation had n cities that were connected by m roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair n-1 of these roads so that all the cities are connected again.
The i-th city has a_i tons of asphalt. x tons of asphalt are used up when repairing a road, and to repair a road between i and j, cities i and j must have at least x tons of asphalt between them. In other words, if city i had a_i tons of asphalt and city j had a_j tons, there would remain a_i+a_j-x tons after repairing the road between them. Asphalt can be moved between cities if the road between them is already repaired.
Please determine if it is possible to connect all the cities, and if so, output any sequence of roads to repair.
Input
The first line contains integers n, m, and x (2 β€ n β€ 3 β
10^5; n-1 β€ m β€ 3 β
10^5; 1 β€ x β€ 10^9) β the number of cities, number of roads, and amount of asphalt needed to repair one road.
The next line contains n space-separated integer a_i (0 β€ a_i β€ 10^9) β the amount of asphalt initially at city i.
The next m lines contains two integers x_i and y_i (x_iβ y_i; 1 β€ x_i, y_i β€ n) β the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities, and that the city was originally connected before the earthquake.
Output
If it is not possible to connect all the cities, print NO. Otherwise, print YES followed by n-1 integers e_1, e_2, ..., e_{n-1}, the order in which the roads should be repaired. e_i is the index of the i-th road to repair. If there are multiple solutions, print any.
Examples
Input
5 4 1
0 0 0 4 0
1 2
2 3
3 4
4 5
Output
YES
3
2
1
4
Input
2 1 2
1 1
1 2
Output
YES
1
Input
2 1 2
0 1
1 2
Output
NO
Input
5 6 5
0 9 4 0 10
1 2
1 3
2 3
3 4
1 4
4 5
Output
YES
6
4
1
2
Note
In the first example, the roads are repaired in the following order:
* Road 3 is repaired, connecting cities 3 and 4. City 4 originally had 4 tons of asphalt. After this road is constructed, 3 tons remain.
* Road 2 is repaired, connecting cities 2 and 3. The asphalt from city 4 can be transported to city 3 and used for the road. 2 tons remain.
* Road 1 is repaired, connecting cities 1 and 2. The asphalt is transported to city 2 and used for the road. 1 ton remain.
* Road 4 is repaired, connecting cities 4 and 5. The asphalt is transported to city 4 and used for the road. No asphalt remains.
All the cities are now connected.
In the second example, cities 1 and 2 use all their asphalt together to build the road. They each have 1 ton, so together they have 2 tons, which is enough.
In the third example, there isn't enough asphalt to connect cities 1 and 2. | import sys
f = sys.stdin
def line():
return f.readline().strip().split()
def dfs(st):
seen=[-1]*N
q=[st]
seen[st]=0
parent=[None]*N
road=[None]*N
front=[]
back=[]
while q:
n=q[-1]
chs=G[n]
if seen[n]==len(chs):
m = q.pop()
if m != st:
if A[m]+A[parent[m]] >= X:
front.append(road[m])
A[parent[m]]+=A[m]-X
else:
back.append(road[m])
else:
ch,r = chs[seen[n]]
if seen[ch]==-1:
seen[ch]=0
q.append(ch)
parent[ch]=n
road[ch]=r
seen[n]+=1
back.reverse()
return front+back
def solve():
s=sum(v for v in A)
if s<(N-1)*X:
return "NO"
res = dfs(0)
return str("YES\n"+ '\n'.join(str(v) for v in res))
T = 1
for test in range(1,T+1):
N,M,X = map(int,line())
A = list(map(int,line()))
G=[[] for _ in range(N)]
R=[]
for r in range(1,M+1):
i,j = map(int,line())
G[i-1].append((j-1,r))
G[j-1].append((i-1,r))
print(solve())
f.close() | {
"input": [
"2 1 2\n0 1\n1 2\n",
"5 4 1\n0 0 0 4 0\n1 2\n2 3\n3 4\n4 5\n",
"2 1 2\n1 1\n1 2\n",
"5 6 5\n0 9 4 0 10\n1 2\n1 3\n2 3\n3 4\n1 4\n4 5\n"
],
"output": [
"\nNO\n",
"\nYES\n3\n2\n1\n4\n",
"\nYES\n1\n",
"\nYES\n6\n4\n1\n2\n"
]
} |
2,804 | 11 | This is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved.
A permutation of 1, 2, β¦, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] is a permutation of 1, 2, 3, 4, but [1,4,2,2] isn't because 2 appears twice in it.
Recall that the number of inversions in a permutation a_1, a_2, β¦, a_n is the number of pairs of indices (i, j) such that i < j and a_i > a_j.
Let p and q be two permutations of 1, 2, β¦, n. Find the number of permutation pairs (p,q) that satisfy the following conditions:
* p is lexicographically smaller than q.
* the number of inversions in p is greater than the number of inversions in q.
Print the number of such pairs modulo mod. Note that mod may not be a prime.
Input
The only line contains two integers n and mod (1β€ nβ€ 50, 1β€ modβ€ 10^9).
Output
Print one integer, which is the answer modulo mod.
Example
Input
4 403458273
Output
17
Note
The following are all valid pairs (p,q) when n=4.
* p=[1,3,4,2], q=[2,1,3,4],
* p=[1,4,2,3], q=[2,1,3,4],
* p=[1,4,3,2], q=[2,1,3,4],
* p=[1,4,3,2], q=[2,1,4,3],
* p=[1,4,3,2], q=[2,3,1,4],
* p=[1,4,3,2], q=[3,1,2,4],
* p=[2,3,4,1], q=[3,1,2,4],
* p=[2,4,1,3], q=[3,1,2,4],
* p=[2,4,3,1], q=[3,1,2,4],
* p=[2,4,3,1], q=[3,1,4,2],
* p=[2,4,3,1], q=[3,2,1,4],
* p=[2,4,3,1], q=[4,1,2,3],
* p=[3,2,4,1], q=[4,1,2,3],
* p=[3,4,1,2], q=[4,1,2,3],
* p=[3,4,2,1], q=[4,1,2,3],
* p=[3,4,2,1], q=[4,1,3,2],
* p=[3,4,2,1], q=[4,2,1,3]. | def solve():
n, mod = map(int, input().split());m = n*(n-1)//2;dp = [[0]*(n*(n-1)+1) for i in range(n+1)];dp1 = [[0]*(n*(n-1)+1) for i in range(n+1)];dp[1][m] = 1
for i in range(2, n+1):
for x in range(m-(i-1)*(i-2)//2, m+(i-1)*(i-2)//2+1):
for d in range(-i+1, i):dp[i][x+d] = (dp[i][x+d]+dp[i-1][x]*(i-abs(d))) % mod
for i in range(2, n+1):
for x in range(m-(i-1)*(i-2)//2, m+(i-1)*(i-2)//2+1):dp1[i][x] = dp1[i-1][x] * i % mod
for x in range(m-(i-1)*(i-2)//2, m+(i-1)*(i-2)//2+1):
for d in range(1, i):dp1[i][x-d] = (dp1[i][x-d]+dp[i-1][x]*(i-d)) % mod
return sum(dp1[-1][m+1:]) % mod
import sys;input = lambda: sys.stdin.readline().rstrip();print(solve()) | {
"input": [
"4 403458273\n"
],
"output": [
"17\n"
]
} |
2,805 | 11 | n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.
Input
The first line contains integer n (1 β€ n β€ 18) β the amount of fish in the lake. Then there follow n lines with n real numbers each β matrix a. aij (0 β€ aij β€ 1) β the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.
Output
Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.
Examples
Input
2
0 0.5
0.5 0
Output
0.500000 0.500000
Input
5
0 1 1 1 1
0 0 0.5 0.5 0.5
0 0.5 0 0.5 0.5
0 0.5 0.5 0 0.5
0 0.5 0.5 0.5 0
Output
1.000000 0.000000 0.000000 0.000000 0.000000 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
prob = [tuple(map(float, input().split())) for _ in range(n)]
full_bit = (1 << n) - 1
dp = [0.0] * full_bit + [1.0]
for bit in range(full_bit, 0, -1):
popcount = len([1 for i in range(n) if (1 << i) & bit])
if popcount == 1 or dp[bit] == 0.0:
continue
div = 1 / ((popcount * (popcount - 1)) >> 1)
for i in range(n):
if ((1 << i) & bit) == 0:
continue
for j in range(i + 1, n):
if ((1 << j) & bit) == 0:
continue
dp[bit - (1 << j)] += dp[bit] * prob[i][j] * div
dp[bit - (1 << i)] += dp[bit] * prob[j][i] * div
print(*(dp[1 << i] for i in range(n)))
| {
"input": [
"2\n0 0.5\n0.5 0\n",
"5\n0 1 1 1 1\n0 0 0.5 0.5 0.5\n0 0.5 0 0.5 0.5\n0 0.5 0.5 0 0.5\n0 0.5 0.5 0.5 0\n"
],
"output": [
"0.500000 0.500000 ",
"1.000000 0.000000 0.000000 0.000000 0.000000 "
]
} |
2,806 | 9 | Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.
We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.
Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--:
* First, a type is a string "int".
* Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces.
* No other strings can be regarded as types.
More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.
Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.
Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.
Input
The first line contains a single integer n (1 β€ n β€ 105), showing how many numbers the type dictated by Gena contains.
The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes).
It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int".
Output
If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters.
It is guaranteed that if such type exists, then it is unique.
Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.
Examples
Input
3
pair pair int int int
Output
pair<pair<int,int>,int>
Input
1
pair int
Output
Error occurred | def solve():
n = int(input())
words = [1 if x == 'pair' else 0 for x in input().split()]
m = 2*n - 1
if len(words) != m:
return False
stack = []
E = {}
for i in range(m-1, -1, -1):
if not words[i]:
stack.append(i)
elif len(stack) < 2:
return False
else:
x, y = stack.pop(), stack.pop()
E[i] = (x, y)
stack.append(i)
if len(stack) > 1:
return False
parse(E, 0)
return True
def parse(E, v):
stack = [(v, 1)]
while stack:
node, ind = stack.pop()
if node in E:
if ind == 1:
x, y = E[node]
print('pair<', end = '')
stack.append((v, -1))
stack.append((y, 1))
stack.append((v, 0))
stack.append((x, 1))
elif ind == 0:
print(',', end='')
else:
print('>', end = '')
else:
print('int', end='')
print('Error occurred' if not solve() else '')
| {
"input": [
"3\npair pair int int int\n",
"1\npair int\n"
],
"output": [
"pair<pair<int,int>,int>\n",
"Error occurred\n"
]
} |
2,807 | 9 | Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies.
Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions:
* Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer.
* Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that.
* Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that.
* Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that.
* Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that.
* Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that.
* Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that.
Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.
Input
The first line contains integer n (1 β€ n β€ 200) β the number of game parts. The next line contains n integers, the i-th integer β ci (1 β€ ci β€ 3) represents the number of the computer, on which you can complete the game part number i.
Next n lines contain descriptions of game parts. The i-th line first contains integer ki (0 β€ ki β€ n - 1), then ki distinct integers ai, j (1 β€ ai, j β€ n; ai, j β i) β the numbers of parts to complete before part i.
Numbers on all lines are separated by single spaces. You can assume that the parts of the game are numbered from 1 to n in some way. It is guaranteed that there are no cyclic dependencies between the parts of the game.
Output
On a single line print the answer to the problem.
Examples
Input
1
1
0
Output
1
Input
5
2 2 1 1 3
1 5
2 5 1
2 5 4
1 5
0
Output
7
Note
Note to the second sample: before the beginning of the game the best strategy is to stand by the third computer. First we complete part 5. Then we go to the 1-st computer and complete parts 3 and 4. Then we go to the 2-nd computer and complete parts 1 and 2. In total we get 1+1+2+1+2, which equals 7 hours. | n = int(input())
h = [int(q) - 1 for q in input().split()]
u = [set([int(q) - 1 for q in input().split()][1:]) for i in range(n)]
t = 1e9
def g():
for i in p:
if h[i] == k and not v[i]:
return i
for k in range(3):
p = list(range(n))
d = -1
v = [q.copy() for q in u]
while p:
i = g()
while i != None:
d += 1
p.remove(i)
for q in v :
q.discard(i)
i = g()
k = (k + 1) % 3
d += 1
t = min(d, t)
print(t)
| {
"input": [
"1\n1\n0\n",
"5\n2 2 1 1 3\n1 5\n2 5 1\n2 5 4\n1 5\n0\n"
],
"output": [
"1",
"7"
]
} |
2,808 | 7 | You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes i and i + 1 for some integer i (1 β€ i < 5).
2. Swap two neighboring matrix columns, that is, columns with indexes j and j + 1 for some integer j (1 β€ j < 5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
Input
The input consists of five lines, each line contains five integers: the j-th integer in the i-th line of the input represents the element of the matrix that is located on the intersection of the i-th row and the j-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one.
Output
Print a single integer β the minimum number of moves needed to make the matrix beautiful.
Examples
Input
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Output
3
Input
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
Output
1 | def beautiful(n,i):
m=input()
if"1"in m:
print(i+n[m.find("1")//2])
n=[2,1,0,1,2]
for i in n:
beautiful(n,i)
| {
"input": [
"0 0 0 0 0\n0 0 0 0 1\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n",
"0 0 0 0 0\n0 0 0 0 0\n0 1 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n"
],
"output": [
"3\n",
"1\n"
]
} |
2,809 | 7 | In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 Γ 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 Γ 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed.
Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 Γ 2 square, consisting of cells of the same color.
Input
Four lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.
Output
Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.
Examples
Input
####
.#..
####
....
Output
YES
Input
####
....
####
....
Output
NO
Note
In the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 Γ 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column. | def solution():
st=[]
for i in range(4):
s=input()
st.append(s)
for i in range(0,3):
for j in range(0,3):
p=[st[i][j],st[i+1][j],st[i][j+1],st[i+1][j+1]]
if p.count('#')==3 or p.count('.')==3 or p.count('#')==4 or p.count('.')==4:
print('YES')
return
print('NO')
return
solution()
| {
"input": [
"####\n....\n####\n....\n",
"####\n.#..\n####\n....\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
2,810 | 7 | One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.
Input
The first line of the input contains an integer n (1 β€ n β€ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesnβt exceed 100.
Output
For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 canβt recognize whose sentence it is. He canβt recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.
Examples
Input
5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .
Output
Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know! | def solve():
s = input()
if(s[-5:] == 'lala.' and s[:5] != "miao."):
print("Freda's")
elif(s[-5:] != 'lala.' and s[:5] == "miao."):
print("Rainbow's")
else:
print("OMG>.< I don't know!")
n = int(input())
for _ in range(n):
solve() | {
"input": [
"5\nI will go to play with you lala.\nwow, welcome.\nmiao.lala.\nmiao.\nmiao .\n"
],
"output": [
"Freda's\nOMG>.< I don't know!\nOMG>.< I don't know!\nRainbow's\nOMG>.< I don't know!\n"
]
} |
2,811 | 10 | Gerald plays the following game. He has a checkered field of size n Γ n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:
* At least one of the chips at least once fell to the banned cell.
* At least once two chips were on the same cell.
* At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row).
In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 1000, 0 β€ m β€ 105) β the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 β€ xi, yi β€ n) β the coordinates of the i-th banned cell. All given cells are distinct.
Consider the field rows numbered from top to bottom from 1 to n, and the columns β from left to right from 1 to n.
Output
Print a single integer β the maximum points Gerald can earn in this game.
Examples
Input
3 1
2 2
Output
0
Input
3 0
Output
1
Input
4 3
3 1
3 2
3 3
Output
1
Note
In the first test the answer equals zero as we can't put chips into the corner cells.
In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.
In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4). | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect 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=1000000007
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
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()
n,m=value()
row_blocked=defaultdict(bool)
col_blocked=defaultdict(bool)
for i in range(m):
x,y=value()
row_blocked[x]=True
col_blocked[y]=True
ans=0
for i in range(2,n):
if(not row_blocked[i]): ans+=1
if(not col_blocked[i]): ans+=1
if(n%2):
if(not row_blocked[n//2+1] and not col_blocked[n//2+1]): ans-=1
print(ans)
| {
"input": [
"3 0\n",
"4 3\n3 1\n3 2\n3 3\n",
"3 1\n2 2\n"
],
"output": [
"1",
"1",
"0\n"
]
} |
2,812 | 9 | Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".
Sereja needs to answer m queries, each of them is described by two integers li, ri (1 β€ li β€ ri β€ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.
You can find the definitions for a subsequence and a correct bracket sequence in the notes.
Input
The first line contains a sequence of characters s1, s2, ..., sn (1 β€ n β€ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 β€ m β€ 105) β the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 β€ li β€ ri β€ n) β the description of the i-th query.
Output
Print the answer to each question on a single line. Print the answers in the order they go in the input.
Examples
Input
())(())(())(
7
1 1
2 3
1 2
1 12
8 12
5 11
2 10
Output
0
0
2
10
4
6
6
Note
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 β€ k1 < k2 < ... < k|x| β€ |s|).
A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.
For the third query required sequence will be Β«()Β».
For the fourth query required sequence will be Β«()(())(())Β». | import sys
import math
input=sys.stdin.readline
s=input().rstrip()
n=len(s)
q=int(input())
class segTree:
def __init__(self):
self.a=[0]*(2*n)
self.b=[0]*(2*n)
self.c=[0]*(2*n)
def build(self,arr):
for i in range(n):
self.a[i+n]=0
self.b[i+n]=1 if arr[i]=="(" else 0
self.c[i+n]=1 if arr[i]==")" else 0
for i in range(n-1,0,-1):
t=min(self.b[i<<1],self.c[i<<1|1])
self.a[i]=self.a[i<<1]+self.a[i<<1|1]+2*t
self.b[i]=self.b[i<<1]+self.b[i<<1|1]-t
self.c[i]=self.c[i<<1]+self.c[i<<1|1]-t
def query(self,l,r):
left=[]
right=[]
l+=n
r+=n
while l<=r:
if (l&1):
left.append([self.a[l],self.b[l],self.c[l]])
l+=1
if not (r&1):
right.append([self.a[r],self.b[r],self.c[r]])
r-=1
l>>=1
r>>=1
a1=b1=c1=0
for a2,b2,c2 in left+right[::-1]:
t=min(b1,c2)
a1+=a2+2*t
b1+=b2-t
c1+=c2-t
return a1
tr=segTree()
tr.build(s)
for _ in range(q):
l,r=map(int,input().split())
print(tr.query(l-1,r-1)) | {
"input": [
"())(())(())(\n7\n1 1\n2 3\n1 2\n1 12\n8 12\n5 11\n2 10\n"
],
"output": [
"0\n0\n2\n10\n4\n6\n6\n"
]
} |
2,813 | 8 | Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.
Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier β a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.
Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.
Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.
Input
The first line contains two integers: x (1 β€ x β€ 4000) β the round Sereja is taking part in today, and k (0 β€ k < 4000) β the number of rounds he took part in.
Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.
Output
Print in a single line two integers β the minimum and the maximum number of rounds that Sereja could have missed.
Examples
Input
3 2
2 1
2 2
Output
0 0
Input
9 3
1 2 3
2 8
1 4 5
Output
2 3
Input
10 0
Output
5 9
Note
In the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round.
The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds. | def main():
x, k = map(int, input().split())
A = [0] * x
mx = x - 1
for i in range(k):
s = list(map(int, input().split()))
A[s[1] - 1] = 1
if len(s) == 3:
A[s[2] - 1] = 1
mx -= len(s) - 1
mn = 0
for i in range(x - 1):
if A[i] == 0:
mn += 1
if A[i + 1] == 0:
A[i + 1] = 1
print(mn, mx)
main() | {
"input": [
"10 0\n",
"3 2\n2 1\n2 2\n",
"9 3\n1 2 3\n2 8\n1 4 5\n"
],
"output": [
"5 9\n",
"0 0\n",
"2 3\n"
]
} |
2,814 | 9 | Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.
Iahub asks Iahubina: can you build a rooted tree, such that
* each internal node (a node with at least one son) has at least two sons;
* node i has ci nodes in its subtree?
Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes.
Input
The first line of the input contains integer n (1 β€ n β€ 24). Next line contains n positive integers: the i-th number represents ci (1 β€ ci β€ n).
Output
Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes).
Examples
Input
4
1 1 1 4
Output
YES
Input
5
1 1 5 2 1
Output
NO | def DFS(x):
for i in range(x):
if(Seen[i][x]):
continue
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Parent[x]=i
Children[i].append(x)
return True
for i in range(x):
if(Seen[i][x]):
continue
Y=[]
for j in range(len(Children[i])):
child=Children[i][j]
Parent[child]=-1
Rem[i]+=C[child]
Seen[i][child]=True
Seen[child][i]=True
if(DFS(child)):
Seen[i][child]=False
Seen[child][i]=False
continue
Seen[i][child]=False
Seen[child][i]=False
Parent[child]=i
Rem[i]-=C[child]
Y.append(child)
Children[i]=list(Y)
if(Rem[i]>=C[x]):
if(Rem[i]==C[x] and len(Children[i])==0):
continue
Rem[i]-=C[x]
Children[i].append(x)
Parent[x]=i
return True
return False
n=int(input())
C=list(map(int,input().split()))
Rem=[-1]*n
Parent=[-1]*n
Children=[]
Seen=[]
for i in range(n):
Seen.append([False]*n)
C.sort(reverse=True)
if(C[0]!=n or C.count(2)>0):
print("NO")
else:
for i in range(n):
Rem[i]=C[i]-1
Children.append([])
Parent[0]=0
Ans="YES"
for i in range(1,n):
if(DFS(i)==False):
Ans="NO"
break
for i in range(n):
if(Rem[i]!=0 and C[i]!=1):
Ans="NO"
break
print(Ans)
| {
"input": [
"5\n1 1 5 2 1\n",
"4\n1 1 1 4\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
2,815 | 7 | After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown below, n = 3 and m = 3. There are n + m = 6 sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are nΒ·m = 9 intersection points, numbered from 1 to 9.
<image>
The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).
Assume that both players play optimally. Who will win the game?
Input
The first line of input contains two space-separated integers, n and m (1 β€ n, m β€ 100).
Output
Print a single line containing "Akshat" or "Malvika" (without the quotes), depending on the winner of the game.
Examples
Input
2 2
Output
Malvika
Input
2 3
Output
Malvika
Input
3 3
Output
Akshat
Note
Explanation of the first sample:
The grid has four intersection points, numbered from 1 to 4.
<image>
If Akshat chooses intersection point 1, then he will remove two sticks (1 - 2 and 1 - 3). The resulting grid will look like this.
<image>
Now there is only one remaining intersection point (i.e. 4). Malvika must choose it and remove both remaining sticks. After her move the grid will be empty.
In the empty grid, Akshat cannot make any move, hence he will lose.
Since all 4 intersection points of the grid are equivalent, Akshat will lose no matter which one he picks. | def main():
x=min(map(int,input().split()))
if(x%2==0):
print("Malvika")
else:
print("Akshat")
main()
| {
"input": [
"2 3\n",
"3 3\n",
"2 2\n"
],
"output": [
"Malvika\n",
"Akshat\n",
"Malvika\n"
]
} |
2,816 | 8 | Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n Γ m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.
<image>
They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.
Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.
Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
Input
The first line of input contains three integers n, m and q (1 β€ n, m β€ 500 and 1 β€ q β€ 5000).
The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes).
The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 β€ i β€ n and 1 β€ j β€ m), the row number and the column number of the bear changing his state.
Output
After each round, print the current score of the bears.
Examples
Input
5 4 5
0 1 1 0
1 0 0 1
0 1 1 0
1 0 0 1
0 0 0 0
1 1
1 4
1 1
4 2
4 3
Output
3
4
3
3
4 | def f(s):
s = ''.join(s).split('0')
return max(len(i) for i in s)
n, m, q = map(int, input().split())
arr = [input().split() for i in range(n)]
b = [f(s) for s in arr]
for i in range(q):
x, y = map(int, input().split())
x -= 1 ; y -= 1
arr[x][y] = str(1 - int(arr[x][y]))
b[x] = f(arr[x])
print(max(b))
| {
"input": [
"5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3\n"
],
"output": [
"3\n4\n3\n3\n4\n"
]
} |
2,817 | 10 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.
Limak will repeat the following operation till everything is destroyed.
Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.
Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
Input
The first line contains single integer n (1 β€ n β€ 105).
The second line contains n space-separated integers h1, h2, ..., hn (1 β€ hi β€ 109) β sizes of towers.
Output
Print the number of operations needed to destroy all towers.
Examples
Input
6
2 1 4 6 2 2
Output
3
Input
7
3 3 3 1 3 3 3
Output
2
Note
The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.
<image> After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | def main():
n = int(input())
a = [int(i) for i in input().split()]
dpl = [1] * n
dpr = [1] * n
for i in range(1, n):
dpl[i] = min(dpl[i - 1] + 1, a[i])
for i in range(n - 2, -1, -1):
dpr[i] = min(dpr[i + 1] + 1, a[i])
ans = 0
for i in range(n):
ans = max(ans, min(dpl[i], dpr[i]))
print(ans)
main() | {
"input": [
"6\n2 1 4 6 2 2\n",
"7\n3 3 3 1 3 3 3\n"
],
"output": [
"3\n",
"2\n"
]
} |
2,818 | 8 | Wilbur the pig is tinkering with arrays again. He has the array a1, a2, ..., an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai, ai + 1, ... , an or subtract 1 from all elements ai, ai + 1, ..., an. His goal is to end up with the array b1, b2, ..., bn.
Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the length of the array ai. Initially ai = 0 for every position i, so this array is not given in the input.
The second line of the input contains n integers b1, b2, ..., bn ( - 109 β€ bi β€ 109).
Output
Print the minimum number of steps that Wilbur needs to make in order to achieve ai = bi for all i.
Examples
Input
5
1 2 3 4 5
Output
5
Input
4
1 2 2 1
Output
3
Note
In the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.
In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1. | def arr_inp():
return [int(x) for x in input().split()]
n, a = int(input()), arr_inp()
s = abs(a[0])
for i in range(1, n):
s += abs(a[i] - a[i - 1])
print(s)
| {
"input": [
"4\n1 2 2 1\n",
"5\n1 2 3 4 5\n"
],
"output": [
"3\n",
"5\n"
]
} |
2,819 | 10 | There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.
Input
Each of the three lines of the input contains two integers. The i-th line contains integers xi and yi ( - 109 β€ xi, yi β€ 109) β the coordinates of the i-th point. It is guaranteed that all points are distinct.
Output
Print a single number β the minimum possible number of segments of the polyline.
Examples
Input
1 -1
1 1
1 2
Output
1
Input
-1 -1
-1 3
4 3
Output
2
Input
1 1
2 3
3 2
Output
3
Note
The variant of the polyline in the first sample: <image> The variant of the polyline in the second sample: <image> The variant of the polyline in the third sample: <image> | def fun(x,y,z):
a,b,c,d,e,f=aa[x]+aa[y]+aa[z]
# print(a,b,c,d,e,f)
return (a==c and not (b<f<d or d<f<b)) or (b==d and not(a<e<c or c<e<a))
inn=lambda:map(int,input().split())
aa=[list(inn()),list(inn()),list(inn())]
#print(aa)
if aa[0][0]==aa[1][0]==aa[2][0] or aa[0][1]==aa[1][1]==aa[2][1]:
print(1)
elif fun(0,1,2) or fun(1,2,0) or fun(0,2,1):
print(2)
else:
print(3)
| {
"input": [
"-1 -1\n-1 3\n4 3\n",
"1 -1\n1 1\n1 2\n",
"1 1\n2 3\n3 2\n"
],
"output": [
"2\n",
"1\n",
"3\n"
]
} |
2,820 | 7 | The main street of Berland is a straight line with n houses built along it (n is an even number). The houses are located at both sides of the street. The houses with odd numbers are at one side of the street and are numbered from 1 to n - 1 in the order from the beginning of the street to the end (in the picture: from left to right). The houses with even numbers are at the other side of the street and are numbered from 2 to n in the order from the end of the street to its beginning (in the picture: from right to left). The corresponding houses with even and odd numbers are strictly opposite each other, that is, house 1 is opposite house n, house 3 is opposite house n - 2, house 5 is opposite house n - 4 and so on.
<image>
Vasya needs to get to house number a as quickly as possible. He starts driving from the beginning of the street and drives his car to house a. To get from the beginning of the street to houses number 1 and n, he spends exactly 1 second. He also spends exactly one second to drive the distance between two neighbouring houses. Vasya can park at any side of the road, so the distance between the beginning of the street at the houses that stand opposite one another should be considered the same.
Your task is: find the minimum time Vasya needs to reach house a.
Input
The first line of the input contains two integers, n and a (1 β€ a β€ n β€ 100 000) β the number of houses on the street and the number of the house that Vasya needs to reach, correspondingly. It is guaranteed that number n is even.
Output
Print a single integer β the minimum time Vasya needs to get from the beginning of the street to house a.
Examples
Input
4 2
Output
2
Input
8 5
Output
3
Note
In the first sample there are only four houses on the street, two houses at each side. House 2 will be the last at Vasya's right.
The second sample corresponds to picture with n = 8. House 5 is the one before last at Vasya's left. | def f(l):
n,a = l
return (a+1)//2 if a%2>0 else (n+2-a)//2
l = list(map(int,input().split()))
print(f(l))
| {
"input": [
"4 2\n",
"8 5\n"
],
"output": [
"2",
"3"
]
} |
2,821 | 7 | There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure:
* The crow sets ai initially 0.
* The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi + 2 - bi + 3....
Memory gives you the values a1, a2, ..., an, and he now wants you to find the initial numbers b1, b2, ..., bn written in the row? Can you do it?
Input
The first line of the input contains a single integer n (2 β€ n β€ 100 000) β the number of integers written in the row.
The next line contains n, the i'th of which is ai ( - 109 β€ ai β€ 109) β the value of the i'th number.
Output
Print n integers corresponding to the sequence b1, b2, ..., bn. It's guaranteed that the answer is unique and fits in 32-bit integer type.
Examples
Input
5
6 -4 8 -2 3
Output
2 4 6 1 3
Input
5
3 -2 -1 5 6
Output
1 -3 4 11 6
Note
In the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and - 4 = 4 - 6 + 1 - 3.
In the second sample test, the sequence 1, - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6. | import sys
def main():
s = list(map(int, sys.stdin.read().strip().split()[1:]))
return [i + j for i, j in zip(s, s[1:])] + [s[-1]]
print(*main())
| {
"input": [
"5\n3 -2 -1 5 6\n",
"5\n6 -4 8 -2 3\n"
],
"output": [
"1 -3 4 11 6\n",
"2 4 6 1 3\n"
]
} |
2,822 | 7 | Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.
Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case β the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.
Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?
Note: uppercase and lowercase letters are considered different.
Input
Input contains a single line containing a string s (1 β€ |s| β€ 105) β the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s.
The string s contains lowercase and uppercase English letters, i.e. <image>.
Output
Output a single integer, the answer to the problem.
Examples
Input
Bulbbasaur
Output
1
Input
F
Output
0
Input
aBddulbasaurrgndgbualdBdsagaurrgndbb
Output
2
Note
In the first case, you could pick: Bulbbasaur.
In the second case, there is no way to pick even a single Bulbasaur.
In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur". |
def main():
text = str(input())
wanted = 'Bulbasaur'
c = text.count(wanted[0])
for w in wanted:
c = min(c, text.count(w)//wanted.count(w))
print(c)
main() | {
"input": [
"Bulbbasaur\n",
"F\n",
"aBddulbasaurrgndgbualdBdsagaurrgndbb\n"
],
"output": [
"1\n",
"0\n",
"2\n"
]
} |
2,823 | 12 | Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request.
Also, there are now villages with as few as a single inhabitant, meaning that <image>.
Can you help Heidi find out whether a village follows a Poisson or a uniform distribution?
Input
Same as for the easy and medium versions. But remember that now 1 β€ P β€ 1000 and that the marmots may provide positive as well as negative integers.
Output
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answers came from a uniform distribution. | def sampleVariance(V):
X = sum(V) / len(V)
S = 0.0
for x in V:
S += (X-x)**2
S /= (len(V)-1)
return (X, S)
#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
V = list(map(int, input().split()))
X, S = sampleVariance(V)
print("{}".format("uniform" if max(V) < 1.9*(S**0.5) else "poisson")) | {
"input": [],
"output": []
} |
2,824 | 8 | Alice and Bob play 5-in-a-row game. They have a playing field of size 10 Γ 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.
In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.
Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.
Input
You are given matrix 10 Γ 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell.
It is guaranteed that in the current arrangement nobody has still won.
Output
Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.
Examples
Input
XX.XX.....
.....OOOO.
..........
..........
..........
..........
..........
..........
..........
..........
Output
YES
Input
XXOXX.....
OO.O......
..........
..........
..........
..........
..........
..........
..........
..........
Output
NO | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
a = [ minp() for i in range(10) ]
d = [(1,0), (1,1), (0,1), (1, -1)]
for x in range(10):
for y in range(10):
for dx, dy in d:
c1 = 0
c2 = 0
for j in range(5):
xx = x+dx*j
yy = y+dy*j
if xx < 10 and yy < 10 and yy >= 0:
w = a[x+dx*j][y+dy*j]
if w == 'X':
c1 += 1
elif w == '.':
c2 += 1
if c1 == 4 and c2 == 1:
print("YES")
exit(0)
print("NO") | {
"input": [
"XX.XX.....\n.....OOOO.\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n",
"XXOXX.....\nOO.O......\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
2,825 | 8 | This is an interactive problem. Refer to the Interaction section below for better understanding.
Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.
<image>
Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.
This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).
Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.
Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.
Input
The first line contains 3 integers n, m and c (<image>, <image> means <image> rounded up) β the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.
Interaction
In each round, your program needs to read one line containing a single integer pi (1 β€ pi β€ c), indicating the number given to Chtholly.
Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in.
After outputting each line, don't forget to flush the output. For example:
* fflush(stdout) in C/C++;
* System.out.flush() in Java;
* sys.stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game.
Example
Input
2 4 4
2
1
3
Output
1
2
2
Note
In the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game.
Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.
The input format for hacking:
* The first line contains 3 integers n, m and c;
* The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round. | def get_int(string, n):
i = j = k = 0
for s in string:
k += 1
for s in string:
if i == n - 1:
break
if s == ' ':
i += 1
j += 1
i = 0
while j < k:
if string[j] == ' ':
break
i = 10 * i + int(string[j])
j += 1
return i
def check_order(ls, n):
for i in ls:
if i == None:
return 0
for i in range(0, n - 1):
if ls[i] > ls[i + 1]:
return -1
return 1
def forward(p, ls, n):
for i in range(0, n):
if ls[i] == None:
ls[i] = p
print(i + 1)
return 0
if ls[i] > p:
ls[i] = p
print(i + 1)
return 0
def reverse(p, ls, n):
for i in range(0, n):
if ls[n - 1 - i] == None:
ls[n - 1 - i] = p
print(n - i)
return 0
elif ls[n - 1 - i] < p:
ls[n - i - 1] = p
print(n - i)
return 0
x = input()
n = get_int(x, 1)
m = get_int(x, 2)
c = get_int(x, 3)
ls = []
for i in range(0, n):
ls += [None]
for i in range(0, m):
p = int(input())
if p > c/2:
reverse(p, ls, n)
else:
forward(p, ls, n)
if check_order(ls, n) == 1:
break
| {
"input": [
"2 4 4\n2\n1\n3\n"
],
"output": [
"1\n1\n2\n"
]
} |
2,826 | 9 | After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "Azembler. Principally New Approach".
Having carefully thumbed through the book, Igor K. realised that, as it turns out, you can multiply the numbers dozens of times faster. "Search Ultimate will be faster than it has ever been!" β the fellow shouted happily and set to work.
Let us now clarify what Igor's idea was. The thing is that the code that was generated by a compiler was far from perfect. Standard multiplying does work slower than with the trick the book mentioned.
The Azembler language operates with 26 registers (eax, ebx, ..., ezx) and two commands:
* [x] β returns the value located in the address x. For example, [eax] returns the value that was located in the address, equal to the value in the register eax.
* lea x, y β assigns to the register x, indicated as the first operand, the second operand's address. Thus, for example, the "lea ebx, [eax]" command will write in the ebx register the content of the eax register: first the [eax] operation will be fulfilled, the result of it will be some value that lies in the address written in eax. But we do not need the value β the next operation will be lea, that will take the [eax] address, i.e., the value in the eax register, and will write it in ebx.
On the first thought the second operation seems meaningless, but as it turns out, it is acceptable to write the operation as
lea ecx, [eax + ebx],
lea ecx, [k*eax]
or even
lea ecx, [ebx + k*eax],
where k = 1, 2, 4 or 8.
As a result, the register ecx will be equal to the numbers eax + ebx, k*eax and ebx + k*eax correspondingly. However, such operation is fulfilled many times, dozens of times faster that the usual multiplying of numbers. And using several such operations, one can very quickly multiply some number by some other one. Of course, instead of eax, ebx and ecx you are allowed to use any registers.
For example, let the eax register contain some number that we should multiply by 41. It takes us 2 lines:
lea ebx, [eax + 4*eax] // now ebx = 5*eax
lea eax, [eax + 8*ebx] // now eax = eax + 8*ebx = 41*eax
Igor K. got interested in the following question: what is the minimum number of lea operations needed to multiply by the given number n and how to do it? Your task is to help him.
Consider that at the initial moment of time eax contains a number that Igor K. was about to multiply by n, and the registers from ebx to ezx contain number 0. At the final moment of time the result can be located in any register.
Input
The input data contain the only integer n (1 β€ n β€ 255), which Igor K. is about to multiply.
Output
On the first line print number p, which represents the minimum number of lea operations, needed to do that. Then print the program consisting of p commands, performing the operations. It is guaranteed that such program exists for any n from 1 to 255.
Use precisely the following format of commands (here k is equal to 1, 2, 4 or 8, and x, y and z are any, even coinciding registers):
lea x, [y]
lea x, [y + z]
lea x, [k*y]
lea x, [y + k*z]
Please note that extra spaces at the end of a command are unacceptable.
Examples
Input
41
Output
2
lea ebx, [eax + 4*eax]
lea ecx, [eax + 8*ebx]
Input
2
Output
1
lea ebx, [eax + eax]
Input
4
Output
1
lea ebx, [4*eax] | n=int(input())
mn=[float('inf')]*256
ans=""
done=set()
def gen(vals,st):
global mn,ans
#print(*vals)
if('|'.join([str(x) for x in vals]) in done):
return
done.add('|'.join([str(x) for x in vals]))
if(vals[-1]==n):
if(len(vals)<mn[n]):
mn[n]=len(vals)
ans=st
return
if(len(vals)>5):
return
"""if(len(vals)-2>mn[vals[-1]]):
return
mn[vals[-1]]=len(vals)"""
for i in range(len(vals)):
for z in [8,4,2,1]:
e=vals[i]*z
if(e>n):
continue
if(e>vals[-1]):
nw='e'+chr(ord('a')+len(vals))+'x'
I='e'+chr(ord('a')+i)+'x'
gen(vals+[e],st+"lea "+nw+", ["+str(z)+"*"+I+"]\n")
for j in range(len(vals)):
for z in [8,4,2,1]:
e=vals[i]+z*vals[j]
if(e>n):
continue
if(e>vals[-1]):
nw='e'+chr(ord('a')+len(vals))+'x'
I='e'+chr(ord('a')+i)+'x'
J='e'+chr(ord('a')+j)+'x'
gen(vals+[e],st+"lea "+nw+", ["+I+" + "+str(z)+"*"+J+"]\n")
gen([1],"")
print(ans.count("\n"))
print(ans,end="")
| {
"input": [
"4\n",
"2\n",
"41\n"
],
"output": [
"1\nlea ebx, [4*eax]\n",
"1\nlea ebx, [2*eax]",
"2\nlea ebx, [eax + 4*eax]\nlea ecx, [eax + 8*ebx]\n"
]
} |
2,827 | 7 | These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute.
He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least s minutes from both sides.
Find the earliest time when Arkady can insert the takeoff.
Input
The first line of input contains two integers n and s (1 β€ n β€ 100, 1 β€ s β€ 60) β the number of landings on the schedule and the minimum allowed time (in minutes) between a landing and a takeoff.
Each of next n lines contains two integers h and m (0 β€ h β€ 23, 0 β€ m β€ 59) β the time, in hours and minutes, when a plane will land, starting from current moment (i. e. the current time is 0 0). These times are given in increasing order.
Output
Print two integers h and m β the hour and the minute from the current moment of the earliest time Arkady can insert the takeoff.
Examples
Input
6 60
0 0
1 20
3 21
5 0
19 30
23 40
Output
6 1
Input
16 50
0 30
1 20
3 0
4 30
6 10
7 50
9 30
11 10
12 50
14 30
16 10
17 50
19 30
21 10
22 50
23 59
Output
24 50
Input
3 17
0 30
1 0
12 0
Output
0 0
Note
In the first example note that there is not enough time between 1:20 and 3:21, because each landing and the takeoff take one minute.
In the second example there is no gaps in the schedule, so Arkady can only add takeoff after all landings. Note that it is possible that one should wait more than 24 hours to insert the takeoff.
In the third example Arkady can insert the takeoff even between the first landing. | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int,minp().split())
n,s = mints()
a = []
for i in range(n):
h,m = mints()
a.append(h*60+m)
if a[0] >= s+1:
print(0, 0)
else:
for i in range(n-1):
if a[i+1]-a[i]-1 >= s*2+1:
print((a[i]+s+1)//60,(a[i]+s+1)%60)
exit(0)
print((a[-1]+1+s)//60,(a[-1]+1+s)%60)
| {
"input": [
"3 17\n0 30\n1 0\n12 0\n",
"16 50\n0 30\n1 20\n3 0\n4 30\n6 10\n7 50\n9 30\n11 10\n12 50\n14 30\n16 10\n17 50\n19 30\n21 10\n22 50\n23 59\n",
"6 60\n0 0\n1 20\n3 21\n5 0\n19 30\n23 40\n"
],
"output": [
"0 0\n",
"24 50\n",
"6 1\n"
]
} |
2,828 | 7 | You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.
The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
Input
The input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order.
The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees.
All the values are integer and between -100 and 100.
Output
Print "Yes" if squares intersect, otherwise print "No".
You can print each letter in any case (upper or lower).
Examples
Input
0 0 6 0 6 6 0 6
1 3 3 5 5 3 3 1
Output
YES
Input
0 0 6 0 6 6 0 6
7 3 9 5 11 3 9 1
Output
NO
Input
6 0 6 6 0 6 0 0
7 4 4 7 7 10 10 7
Output
YES
Note
In the first example the second square lies entirely within the first square, so they do intersect.
In the second sample squares do not have any points in common.
Here are images corresponding to the samples:
<image> <image> <image> | I=lambda:list(map(int,input().split()))
q,w=I(),I()
def c(q,w):
l=0
w+=[(w[0]+w[4])/2,(w[1]+w[5])/2]
for j in range(0,10,2):
e,r=w[j],w[j+1]
o=0
for i in range(0,8,2):
a,b=q[(i+4)%8],q[(i+5)%8]
s=(b-q[i+1])*(q[(i+2)%8]-q[i])-(q[(i+3)%8]-q[i+1])*(a-q[i])
if s>0:
if (r-q[i+1])*(q[(i+2)%8]-q[i])-(q[(i+3)%8]-q[i+1])*(e-q[i])>=0:o+=1
else:
if (r-q[i+1])*(q[(i+2)%8]-q[i])-(q[(i+3)%8]-q[i+1])*(e-q[i])<=0:o+=1
if o==4:l=1
return l
print("YES" if c(q,w)+c(w,q)else"NO") | {
"input": [
"6 0 6 6 0 6 0 0\n7 4 4 7 7 10 10 7\n",
"0 0 6 0 6 6 0 6\n1 3 3 5 5 3 3 1\n",
"0 0 6 0 6 6 0 6\n7 3 9 5 11 3 9 1\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n"
]
} |
2,829 | 11 | You are given n segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.
Count the number of distinct points with integer coordinates, which are covered by at least one segment.
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of segments.
Each of the next n lines contains four integers Ax_i, Ay_i, Bx_i, By_i (-10^6 β€ Ax_i, Ay_i, Bx_i, By_i β€ 10^6) β the coordinates of the endpoints A, B (A β B) of the i-th segment.
It is guaranteed that no two segments lie on the same line.
Output
Print a single integer β the number of distinct points with integer coordinates, which are covered by at least one segment.
Examples
Input
9
0 0 4 4
-1 5 4 0
4 0 4 4
5 2 11 2
6 1 6 7
5 6 11 6
10 1 10 7
7 0 9 8
10 -1 11 -1
Output
42
Input
4
-1 2 1 2
-1 0 1 0
-1 0 0 3
0 3 1 0
Output
7
Note
The image for the first example:
<image>
Several key points are marked blue, the answer contains some non-marked points as well.
The image for the second example:
<image> | #
import sys
def getIntList():
return list(map(int, input().split()))
N, = getIntList()
zp = []
for i in range(N):
ax, ay, bx, by = getIntList()
if ax>bx:
ax,bx = bx,ax
ay,by = by, ay
zp.append( (ax,ay, bx,by))
res = 0
def gcd(a,b):
if b==0:return a
return gcd(b, a%b)
zgcd = []
for i in range(N):
ax, ay, bx, by = zp[i]
tx = abs(bx-ax)
ty = abs(by - ay)
g = gcd(tx, ty)
res += g+1
zgcd .append(g)
"""
ax + k1 dax = bx + k2 dbx
ay + k1 day = by + k2 dby
"""
for i in range(N):
ax = zp[i][0]
dax = (zp[i][2] - ax) // zgcd[i]
ay = zp[i][1]
day = (zp[i][3] - ay) // zgcd[i]
cross = []
for j in range(i+1, N):
#dprint('node',i,j)
bx = zp[j][0]
dbx = (zp[j][2] - bx) // zgcd[j]
by = zp[j][1]
dby = (zp[j][3] - by) // zgcd[j]
#dprint(ax,dax,ay,day)
#dprint(bx,dbx,by,dby)
t1 = ax * day - ay * dax - bx * day + by * dax
t2 = dbx *day - dby * dax
#dprint(t1,t2)
if t2==0:
continue
if t1%t2!=0:
continue
k2 = t1 // t2
if k2 <0 or k2 > zgcd[j]:
continue
if dax!=0:
t3 = k2*dbx + bx - ax
if t3%dax!=0:
continue
k1 = t3//dax
else:
t3 = k2* dby + by - ay
if t3%day !=0:
continue
k1 = t3//day
if k1<0 or k1 > zgcd[i]:
continue
#dprint(ax + k1 * dax, ay+k1 * day)
cross.append(k1)
if not cross: continue
cross.sort()
d = 1
for j in range(1, len(cross)):
if cross[j]!=cross[j-1]:
d+=1
res-=d
print(res)
| {
"input": [
"4\n-1 2 1 2\n-1 0 1 0\n-1 0 0 3\n0 3 1 0\n",
"9\n0 0 4 4\n-1 5 4 0\n4 0 4 4\n5 2 11 2\n6 1 6 7\n5 6 11 6\n10 1 10 7\n7 0 9 8\n10 -1 11 -1\n"
],
"output": [
"7\n",
"42\n"
]
} |
2,830 | 10 | There is a forest that we model as a plane and live n rare animals. Animal number i has its lair in the point (x_{i}, y_{i}). In order to protect them, a decision to build a nature reserve has been made.
The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.
For convenience, scientists have made a transformation of coordinates so that the river is defined by y = 0. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.
Input
The first line contains one integer n (1 β€ n β€ 10^5) β the number of animals.
Each of the next n lines contains two integers x_{i}, y_{i} (-10^7 β€ x_{i}, y_{i} β€ 10^7) β the coordinates of the i-th animal's lair. It is guaranteed that y_{i} β 0. No two lairs coincide.
Output
If the reserve cannot be built, print -1. Otherwise print the minimum radius. Your answer will be accepted if absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a - b|}{max{(1, |b|)}} β€ 10^{-6}.
Examples
Input
1
0 1
Output
0.5
Input
3
0 1
0 2
0 -3
Output
-1
Input
2
0 1
1 1
Output
0.625
Note
In the first sample it is optimal to build the reserve with the radius equal to 0.5 and the center in (0,\ 0.5).
In the second sample it is impossible to build a reserve.
In the third sample it is optimal to build the reserve with the radius equal to 5/8 and the center in (1/2,\ 5/8). | def check(mid):
mx=0
for i in range(n):
mx=max(mx,(x[i]-mid)**2/(2*y[i])+(y[i]/2))
return mx
n=int(input())
l=-100000000
r= 100000000
x=[]
y=[]
c1,c2=0,0
for i in range(n):
a,b=map(int,input().split())
if b>=0:
c1+=1
else:
c2+=1
x.append(a)
y.append(abs(b))
if c1 and c2:
print(-1)
exit()
for i in range(100):
m1=l+(r-l)/3
m2=r-(r-l)/3
if check(m1)>check(m2):
l=m1
else:
r=m2
print(check(l)) | {
"input": [
"2\n0 1\n1 1\n",
"1\n0 1\n",
"3\n0 1\n0 2\n0 -3\n"
],
"output": [
"0.624999999750000000077378853325\n",
"0.499999999874999999984479318038\n",
"-1\n"
]
} |
2,831 | 11 | Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect the sum x with the minimum amount of coins. Greedy algorithm with each its step takes the coin of the highest face value, not exceeding x. Obviously, if among the coins' face values exists the face value 1, any sum x can be collected with the help of greedy algorithm. However, greedy algorithm does not always give the optimal representation of the sum, i.e. the representation with the minimum amount of coins. For example, if there are face values {1, 3, 4} and it is asked to collect the sum 6, greedy algorithm will represent the sum as 4 + 1 + 1, while the optimal representation is 3 + 3, containing one coin less. By the given set of face values find out if there exist such a sum x that greedy algorithm will collect in a non-optimal way. If such a sum exists, find out the smallest of these sums.
Input
The first line contains an integer n (1 β€ n β€ 400) β the amount of the coins' face values. The second line contains n integers ai (1 β€ ai β€ 109), describing the face values. It is guaranteed that a1 > a2 > ... > an and an = 1.
Output
If greedy algorithm collects any sum in an optimal way, output -1. Otherwise output the smallest sum that greedy algorithm collects in a non-optimal way.
Examples
Input
5
25 10 5 2 1
Output
-1
Input
3
4 3 1
Output
6 | __author__ = 'Darren'
def solve():
n = int(input())
coins = list(map(int, input().split()))
def greedy(amount):
num = 0
for i in range(n):
num += amount // coins[i]
amount %= coins[i]
return num
result = 1 << 31
for i in range(1, n):
for j in range(i, n):
temp = coins[i-1] - 1
count, value = 0, 0
for k in range(j+1):
c = temp // coins[k]
count += c
value += coins[k] * c
temp %= coins[k]
value += coins[j]
count += 1
if count < greedy(value):
result = min(result, value)
if result == 1 << 31:
print(-1)
else:
print(result)
if __name__ == '__main__':
solve() | {
"input": [
"3\n4 3 1\n",
"5\n25 10 5 2 1\n"
],
"output": [
"6\n",
"-1\n"
]
} |
2,832 | 10 | At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence a_1, a_2, ..., a_m, where a_i is an integer that denotes the type of flower at the position i. This year the liana is very long (m β₯ n β
k), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts k flowers from the beginning of the liana, then another k flowers and so on. Each such piece of k flowers is called a workpiece. The machine works until there are less than k flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, k flowers must contain flowers of types b_1, b_2, ..., b_s, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least n workpieces?
Input
The first line contains four integers m, k, n and s (1 β€ n, k, m β€ 5 β
10^5, k β
n β€ m, 1 β€ s β€ k): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains m integers a_1, a_2, ..., a_m (1 β€ a_i β€ 5 β
10^5) β types of flowers on the liana.
The third line contains s integers b_1, b_2, ..., b_s (1 β€ b_i β€ 5 β
10^5) β the sequence in Diana's schematic.
Output
If it's impossible to remove some of the flowers so that there would be at least n workpieces and at least one of them fullfills Diana's schematic requirements, output -1.
Otherwise in the first line output one integer d β the number of flowers to be removed by Diana.
In the next line output d different integers β the positions of the flowers to be removed.
If there are multiple answers, print any.
Examples
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
Note
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types [1, 2, 3] and [3, 2, 1]. Those workpieces don't fit Diana's schematic. But if you remove flower on 4-th place, the machine would output workpieces [1, 2, 3] and [2, 1, 2]. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs. | def main():
m, k, n, s = map(int, input().split())
a = list(map(int, input().split())) # prevbug: input in a line!
b = list(map(int, input().split())) # prevbug: convert to list
b_dict = {}
for x in b:
b_dict.setdefault(x, 0)
b_dict[x] += 1 # prevbug: b or b_dict
left = 0
right = 0
max_cut = m - n * k
condition_not_met = len(b_dict)
a_dict = {}
while right < m and condition_not_met > 0:
x = a[right]
a_dict.setdefault(x, 0)
a_dict[x] += 1
if x in b_dict and a_dict[x] == b_dict[x]:
condition_not_met -= 1
right += 1 # prevbug: ftl
if condition_not_met > 0:
print(-1)
return
def num_to_remove(lft, rgt):
lft = lft // k * k
num_in_seq = rgt - lft
if num_in_seq < k:
return 0 # prevbug: if sequence is shorter than k, then no need to remove flowers
return num_in_seq - k
def test_plan():
nonlocal left
if num_to_remove(left, right) <= max_cut:
tot = num_to_remove(left, right)
print(tot)
left = left // k * k
while tot > 0:
x = a[left]
if x in b_dict:
b_dict[x] -= 1
if b_dict[x] == 0:
del b_dict[x]
else:
print(left + 1, end=' ')
tot -= 1 # prevbug: ftl
left += 1
return True
return False
while True:
while left < right: # prevbug: should shift left before shifting right
x = a[left]
if x in b_dict and a_dict[x] - 1 < b_dict[x]:
break
else:
a_dict[x] -= 1
if a_dict[x] == 0:
del a_dict[x] # prevbug: ftl
left += 1
if test_plan():
return
if right < m:
a_dict.setdefault(a[right], 0)
a_dict[a[right]] += 1
right += 1
else:
break
print(-1)
if __name__ == '__main__':
main()
| {
"input": [
"13 4 3 3\n3 2 6 4 1 4 4 7 1 3 3 2 4\n4 3 4\n",
"13 4 1 3\n3 2 6 4 1 4 4 7 1 3 3 2 4\n4 3 4\n",
"7 3 2 2\n1 2 3 3 2 1 2\n2 2\n"
],
"output": [
"-1\n",
"2\n2 3 \n",
"1\n4 "
]
} |
2,833 | 9 | A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 β€ n β€ 2000) β the number of employees.
The next n lines contain the integers pi (1 β€ pi β€ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi β i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5 | from sys import setrecursionlimit
setrecursionlimit(30000)
maxl = -1
def dfs(v, lvl):
used[v] = True
global maxl
if lvl > maxl:
maxl = lvl
for u in ch[v]:
dfs(u, lvl + 1)
n = int(input())
used = [False] * n
p = [int(input()) - 1 for i in range(n)]
ch = [[] for i in range(n)]
for i in range(n):
if p[i] != -2:
ch[p[i]].append(i)
for i in range(n):
if p[i] == -2:
dfs(i, 1)
print(maxl) | {
"input": [
"5\n-1\n1\n2\n1\n-1\n"
],
"output": [
"3\n"
]
} |
2,834 | 8 | You are given a prime number p, n integers a_1, a_2, β¦, a_n, and an integer k.
Find the number of pairs of indexes (i, j) (1 β€ i < j β€ n) for which (a_i + a_j)(a_i^2 + a_j^2) β‘ k mod p.
Input
The first line contains integers n, p, k (2 β€ n β€ 3 β
10^5, 2 β€ p β€ 10^9, 0 β€ k β€ p-1). p is guaranteed to be prime.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ p-1). It is guaranteed that all elements are different.
Output
Output a single integer β answer to the problem.
Examples
Input
3 3 0
0 1 2
Output
1
Input
6 7 2
1 2 3 4 5 6
Output
3
Note
In the first example:
(0+1)(0^2 + 1^2) = 1 β‘ 1 mod 3.
(0+2)(0^2 + 2^2) = 8 β‘ 2 mod 3.
(1+2)(1^2 + 2^2) = 15 β‘ 0 mod 3.
So only 1 pair satisfies the condition.
In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6). | from collections import Counter
def pr(a):return (a*(a-1))//2
n,p,k=map(int,input().split())
a=map(int,input().split())
a=Counter([(x**4-x*k+p)%p for x in a])
print(sum(pr(a[x]) for x in a)) | {
"input": [
"6 7 2\n1 2 3 4 5 6\n",
"3 3 0\n0 1 2\n"
],
"output": [
"3\n",
"1\n"
]
} |
2,835 | 9 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consisting of n characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.
Usually, we can install the pipeline along the road on height of 1 unit with supporting pillars in each integer point (so, if we are responsible for [0, n] road, we must install n + 1 pillars). But on crossroads we should lift the pipeline up to the height 2, so the pipeline won't obstruct the way for cars.
We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment [x, x + 1] with integer x consisting of three parts: 0.5 units of horizontal pipe + 1 unit of vertical pipe + 0.5 of horizontal. Note that if pipeline is currently on height 2, the pillars that support it should also have length equal to 2 units.
<image>
Each unit of gas pipeline costs us a bourles, and each unit of pillar β b bourles. So, it's not always optimal to make the whole pipeline on the height 2. Find the shape of the pipeline with minimum possible cost and calculate that cost.
Note that you must start and finish the pipeline on height 1 and, also, it's guaranteed that the first and last characters of the input string are equal to 0.
Input
The fist line contains one integer T (1 β€ T β€ 100) β the number of queries. Next 2 β
T lines contain independent queries β one query per two lines.
The first line contains three integers n, a, b (2 β€ n β€ 2 β
10^5, 1 β€ a β€ 10^8, 1 β€ b β€ 10^8) β the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively.
The second line contains binary string s (|s| = n, s_i β \{0, 1\}, s_1 = s_n = 0) β the description of the road.
It's guaranteed that the total length of all strings s doesn't exceed 2 β
10^5.
Output
Print T integers β one per query. For each query print the minimum possible cost of the constructed pipeline.
Example
Input
4
8 2 5
00110010
8 1 1
00110010
9 100000000 100000000
010101010
2 5 1
00
Output
94
25
2900000000
13
Note
The optimal pipeline for the first query is shown at the picture above.
The optimal pipeline for the second query is pictured below:
<image>
The optimal (and the only possible) pipeline for the third query is shown below:
<image>
The optimal pipeline for the fourth query is shown below:
<image> | def next_int(): return int(input())
def next_int_arr(): return map(int, input().split())
INF = 1 << 60
for _ in range(next_int()):
n, a, b = next_int_arr()
s = input()
dp0, dp1 = b, INF
for ch in s:
if ch == '1':
dp0, dp1 = INF, dp1 + 2*b
else:
dp0, dp1 = min(dp0, dp1 + a) + b, \
min(dp1, dp0 + a) + 2*b
print(dp0+a*n)
| {
"input": [
"4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00\n"
],
"output": [
"94\n25\n2900000000\n13\n"
]
} |
2,836 | 10 | You are given n positive integers a_1, β¦, a_n, and an integer k β₯ 2. Count the number of pairs i, j such that 1 β€ i < j β€ n, and there exists an integer x such that a_i β
a_j = x^k.
Input
The first line contains two integers n and k (2 β€ n β€ 10^5, 2 β€ k β€ 100).
The second line contains n integers a_1, β¦, a_n (1 β€ a_i β€ 10^5).
Output
Print a single integer β the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 β
a_4 = 8 = 2^3;
* a_1 β
a_6 = 1 = 1^3;
* a_2 β
a_3 = 27 = 3^3;
* a_3 β
a_5 = 216 = 6^3;
* a_4 β
a_6 = 8 = 2^3. | from math import sqrt
def gd(n, k):
ans = 1
obrans = 1
for i in range(2, int(sqrt(n) + 1)):
j = 0
while n % i == 0:
j += 1
n //= i
ans *= pow(i, j%k)
obrans *= pow(i, (-j)%k)
ans *= n
obrans *= pow(n, (k-1))
return ans, obrans
n, k = map(int,input().split())
oba = set()
dct = {}
for i in list(map(int,input().split())):
a,b = gd(i, k)
dct[a] = dct.get(a, 0) + 1
a,b = min(a,b), max(a,b)
oba.add((a,b))
ans = 0
for i, j in oba:
if i == j:
ans += (dct.get(i, 0) * dct.get(j, 0) - dct.get(i, 0)) // 2
else:
ans += dct.get(i, 0) * dct.get(j, 0)
print(ans) | {
"input": [
"6 3\n1 3 9 8 24 1\n"
],
"output": [
"5\n"
]
} |
2,837 | 12 | You are given a tree, which consists of n vertices. Recall that a tree is a connected undirected graph without cycles.
<image> Example of a tree.
Vertices are numbered from 1 to n. All vertices have weights, the weight of the vertex v is a_v.
Recall that the distance between two vertices in the tree is the number of edges on a simple path between them.
Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance k or less between them in this subset.
Input
The first line of the input contains two integers n and k (1 β€ n, k β€ 200) β the number of vertices in the tree and the distance restriction, respectively.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5), where a_i is the weight of the vertex i.
The next n - 1 lines contain edges of the tree. Edge i is denoted by two integers u_i and v_i β the labels of vertices it connects (1 β€ u_i, v_i β€ n, u_i β v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer β the maximum total weight of the subset in which all pairs of vertices have distance more than k.
Examples
Input
5 1
1 2 3 4 5
1 2
2 3
3 4
3 5
Output
11
Input
7 2
2 1 2 1 2 1 1
6 4
1 5
3 1
2 3
7 5
7 4
Output
4 | n, k = map(int, input().split())
a = list(map(int, input().split()))
g = {}
def dfs(v, p=-1):
c = [dfs(child, v) for child in g.get(v, set()) - {p}]
c.sort(key=len, reverse=True)
r = []
i = 0
while c:
if i >= len(c[-1]):
c.pop()
else:
o = max(i, k - i - 1)
s = q = 0
for x in c:
if len(x) <= o:
q = max(q, x[i])
else:
s += x[o]
q = max(q, x[i] - x[o])
r.append(q + s)
i += 1
r.append(0)
for i in range(len(r) - 1, 0, -1):
r[i - 1] = max(r[i - 1], r[i])
while len(r) > 1 and r[-2] == 0:
r.pop()
o = (r[k] if k < len(r) else 0) + a[v]
r.insert(0, max(o, r[0]))
return r
for _ in range(1, n):
u, v = map(lambda x: int(x) - 1, input().split())
g.setdefault(u, set()).add(v)
g.setdefault(v, set()).add(u)
print(dfs(0)[0])
| {
"input": [
"7 2\n2 1 2 1 2 1 1\n6 4\n1 5\n3 1\n2 3\n7 5\n7 4\n",
"5 1\n1 2 3 4 5\n1 2\n2 3\n3 4\n3 5\n"
],
"output": [
"4\n",
"11\n"
]
} |
2,838 | 9 | You are given a permutation p_1, p_2, β¦, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,β¦, k, in other words in the end there should be an integer i, 1 β€ i β€ n-k+1 such that p_i = 1, p_{i+1} = 2, β¦, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,β¦,k appear in the permutation.
You need to find f(1), f(2), β¦, f(n).
Input
The first line of input contains one integer n (1 β€ n β€ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, β¦, p_n: given permutation (1 β€ p_i β€ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,β¦,k appear in the permutation, for k=1, 2, β¦, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0 | n = int(input())
a = [0] + list(map(int, input().split()))
pos, pb, ps = [[0] * (n + 1) for x in range(3)]
def add(bit, i, val):
while i <= n:
bit[i] += val
i += i & -i
def sum(bit, i):
res = 0
while i > 0:
res += bit[i]
i -= i & -i
return res
def find(bit, sum):
i, t = 0, 0
if sum == 0:
return 0
for k in range(17, -1, -1):
i += 1 << k
if i <= n and t + bit[i] < sum:
t += bit[i]
else:
i -= 1 << k
return i + 1
for i in range(1, n + 1):
pos[a[i]] = i
invSum = 0
totalSum = 0
for i in range(1, n + 1):
totalSum += pos[i]
invSum += i - sum(pb, pos[i]) - 1
add(pb, pos[i], 1)
add(ps, pos[i], pos[i])
mid = find(pb, i // 2)
if i % 2 == 1:
mid2 = find(pb, i // 2 + 1)
seqSum = (i + 1) * (i // 2) // 2
else:
mid2 = mid
seqSum = i * (i // 2) // 2
leftSum = sum(ps, mid)
rightSum = totalSum - sum(ps, mid2)
print(rightSum - leftSum - seqSum + invSum, end=" ")
| {
"input": [
"5\n5 4 3 2 1\n",
"3\n1 2 3\n"
],
"output": [
"0 1 3 6 10 ",
"0 0 0 "
]
} |
2,839 | 9 | Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | def solve(a):
seen = {0:-1}
res = curr = mx = 0
for i, x in enumerate(a):
curr += x
if curr in seen:
mx = max(mx, seen[curr] + 2)
res += mx
seen[curr] = i
return len(a)*(len(a)+1)//2 - res
input()
a = list(map(int, input().split()))
print(solve(a)) | {
"input": [
"3\n1 2 -3\n",
"3\n41 -41 41\n"
],
"output": [
"5\n",
"3\n"
]
} |
2,840 | 12 | You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size n Γ m, where the height of the cell (i, j) is a_{i, j}.
You are in the cell (1, 1) right now and want to get in the cell (n, m). You can move only down (from the cell (i, j) to the cell (i + 1, j)) or right (from the cell (i, j) to the cell (i, j + 1)). There is an additional restriction: if the height of the current cell is x then you can move only to the cell with height x+1.
Before the first move you can perform several operations. During one operation, you can decrease the height of any cell by one. I.e. you choose some cell (i, j) and assign (set) a_{i, j} := a_{i, j} - 1. Note that you can make heights less than or equal to zero. Also note that you can decrease the height of the cell (1, 1).
Your task is to find the minimum number of operations you have to perform to obtain at least one suitable path from the cell (1, 1) to the cell (n, m). It is guaranteed that the answer exists.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and m (1 β€ n, m β€ 100) β the number of rows and the number of columns in the map of the world. The next n lines contain m integers each, where the j-th integer in the i-th line is a_{i, j} (1 β€ a_{i, j} β€ 10^{15}) β the height of the cell (i, j).
It is guaranteed that the sum of n (as well as the sum of m) over all test cases does not exceed 100 (β n β€ 100; β m β€ 100).
Output
For each test case, print the answer β the minimum number of operations you have to perform to obtain at least one suitable path from the cell (1, 1) to the cell (n, m). It is guaranteed that the answer exists.
Example
Input
5
3 4
1 2 3 4
5 6 7 8
9 10 11 12
5 5
2 5 4 8 3
9 10 11 5 1
12 8 4 2 5
2 2 5 4 1
6 8 2 4 2
2 2
100 10
10 1
1 2
123456789876543 987654321234567
1 1
42
Output
9
49
111
864197531358023
0 | #!/usr/bin/env python
# Pajenegod :orz:
import os
import sys
from io import BytesIO, IOBase
def main():
for _ in range(int(input())):
n,m=map(int,input().split())
a=[ [int(x) for x in input().split()] for _ in range(n)]
if m>n:
b=[ [a[j][i] for j in range(n)] for i in range(m)]
a=b
n,m=m,n
for i in range(n):
for j in range(m):
a[i][j]-=i+j
INF=1<<60
ans=INF
def solve(d,x1,y1,x2,y2):
if d>a[x1][y1]:
return INF
dp=[INF]*(y2-y1)
dp[0]=0
for i in range(x1,x2):
curR=a[i]
if d>curR[y1] or dp[0]==INF:
dp[0]=INF
else:
dp[0]+=curR[y1]
for j in range(1,y2-y1):
dp[j]=min(dp[j],dp[j-1],INF)+curR[j+y1] if curR[j+y1]>=d else INF
return dp[-1]
ans=INF
for i in range(n):
for j in range(m):
ans=min(ans,solve(a[i][j],i,j,n,m)+solve(a[i][j],0,0,i+1,j+1)-(n+m)*a[i][j])
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | {
"input": [
"5\n3 4\n1 2 3 4\n5 6 7 8\n9 10 11 12\n5 5\n2 5 4 8 3\n9 10 11 5 1\n12 8 4 2 5\n2 2 5 4 1\n6 8 2 4 2\n2 2\n100 10\n10 1\n1 2\n123456789876543 987654321234567\n1 1\n42\n"
],
"output": [
"9\n49\n111\n864197531358023\n0\n"
]
} |
2,841 | 11 | Let f(x) be the sum of digits of a decimal number x.
Find the smallest non-negative integer x such that f(x) + f(x + 1) + ... + f(x + k) = n.
Input
The first line contains one integer t (1 β€ t β€ 150) β the number of test cases.
Each test case consists of one line containing two integers n and k (1 β€ n β€ 150, 0 β€ k β€ 9).
Output
For each test case, print one integer without leading zeroes. If there is no such x that f(x) + f(x + 1) + ... + f(x + k) = n, print -1; otherwise, print the minimum x meeting that constraint.
Example
Input
7
1 0
1 1
42 7
13 7
99 1
99 0
99 2
Output
1
0
4
-1
599998
99999999999
7997 | import sys
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")
def main():
for _ in range(int(input())):
N, K = map(int, input().split())
ans = INF
for i in range(100 - K):
val = 0
for j in range(i, i + K + 1):val += sum(list(map(int, list(str(j)))))
if (N - val) % (K + 1) == 0 and N >= val:
x = int((N - val) // (K + 1))
tail = str(x % 9) + str("9") * int(x // 9)
ans = min(ans, (int(tail + "0" + str(i)) if i < 10 else int(tail + str(i))))
print(-1) if ans == INF else print(ans)
if __name__ == '__main__':
main() | {
"input": [
"7\n1 0\n1 1\n42 7\n13 7\n99 1\n99 0\n99 2\n"
],
"output": [
"1\n0\n4\n-1\n599998\n99999999999\n7997\n"
]
} |
2,842 | 7 | For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?
Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!
Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent β cubes.
For completing the chamber Wheatley needs n cubes. i-th cube has a volume a_i.
Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each i>1, a_{i-1} β€ a_i must hold.
To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any i>1 you can exchange cubes on positions i-1 and i.
But there is a problem: Wheatley is very impatient. If Wheatley needs more than (n β
(n-1))/(2)-1 exchange operations, he won't do this boring work.
Wheatly wants to know: can cubes be sorted under this conditions?
Input
Each test contains multiple test cases.
The first line contains one positive integer t (1 β€ t β€ 1000), denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer n (2 β€ n β€ 5 β
10^4) β number of cubes.
The second line contains n positive integers a_i (1 β€ a_i β€ 10^9) β volumes of cubes.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.
Example
Input
3
5
5 3 2 1 4
6
2 2 2 2 2 2
2
2 1
Output
YES
YES
NO
Note
In the first test case it is possible to sort all the cubes in 7 exchanges.
In the second test case the cubes are already sorted.
In the third test case we can make 0 exchanges, but the cubes are not sorted yet, so the answer is "NO". | def solve(n,a):
for i in range(1,n):
if a[i] - a[i-1] >= 0:
return "YES"
return "NO"
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int,input().split()))
print(solve(n,a)) | {
"input": [
"3\n5\n5 3 2 1 4\n6\n2 2 2 2 2 2\n2\n2 1\n"
],
"output": [
"YES\nYES\nNO\n"
]
} |
2,843 | 11 | Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | def main():
n,k = map(int, input().split());pp = [int(a)-1 for a in input().split()];chainhead = [True]*n;follower = [None]*n
for _ in range(k):
x, y = map(int, input().split())
if follower[x-1]:print(0);return
else:follower[x-1] = y-1;chainhead[y-1] = False
chain = list(range(n));cd = [0]*n
for i in range(n):
if chainhead[i]:
f = follower[i];d = 1
while f != None:cd[f] = d;d += 1;chain[f] = i;f = follower[f]
chainparents = [[] for _ in range(n)];ccount = [0]*n
for i in range(n):
if pp[i] != -1:
if chain[i] != chain[pp[i]]:chainparents[chain[i]].append(chain[pp[i]]);ccount[chain[pp[i]]] += 1
elif cd[pp[i]] > cd[i]:print(0);return
s = [i for i in range(n) if chainhead[i] and ccount[i] == 0];l = [];res = []
while s:
v = s.pop();l.append(v)
for p in chainparents[v]:
ccount[p] -= 1
if ccount[p] == 0:s.append(p)
if any(ccount[i] != 0 for i in range(n)):print(0);return
for h in l[::-1]:
c = h
while c != None:res.append(c+1);c = follower[c]
print(' '.join(map(str, res)))
main() | {
"input": [
"5 2\n2 3 0 5 3\n1 5\n5 1\n",
"5 4\n2 3 0 5 3\n2 1\n3 5\n5 2\n1 4\n",
"5 2\n2 3 0 5 3\n1 5\n5 4\n",
"5 1\n2 3 0 5 3\n4 5\n"
],
"output": [
"\n0\n",
"\n3 5 2 1 4\n",
"\n3 2 1 5 4\n",
"\n0\n"
]
} |
2,844 | 11 | During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed.
The collection of porcelain is arranged neatly on n shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items β the leftmost or the rightmost item, not the ones in the middle of the shelf. Once an item is taken, the next item on that side of the shelf can be accessed (see example). Once an item is taken, it can't be returned to the shelves.
You are given the values of all items. Your task is to find the maximal damage the princess' tantrum of m shrieks can inflict on the collection of porcelain.
Input
The first line of input data contains two integers n (1 β€ n β€ 100) and m (1 β€ m β€ 10000). The next n lines contain the values of the items on the shelves: the first number gives the number of items on this shelf (an integer between 1 and 100, inclusive), followed by the values of the items (integers between 1 and 100, inclusive), in the order in which they appear on the shelf (the first number corresponds to the leftmost item, the last one β to the rightmost one). The total number of items is guaranteed to be at least m.
Output
Output the maximal total value of a tantrum of m shrieks.
Examples
Input
2 3
3 3 7 2
3 4 1 5
Output
15
Input
1 3
4 4 3 1 2
Output
9
Note
In the first case there are two shelves, each with three items. To maximize the total value of the items chosen, one can take two items from the left side of the first shelf and one item from the right side of the second shelf.
In the second case there is only one shelf, so all three items are taken from it β two from the left side and one from the right side. | f = lambda: list(map(int, input().split()))
def g(t):
n = t[0]
for i in range(1, n): t[i + 1] += t[i]
p = [t[n]] * (n + 1)
p[n] = t[0] = 0
for d in range(1, n):
p[d] -= min(t[j + d] - t[j] for j in range(n - d + 1))
return p[::-1]
n, m = f()
u = g(f())
for i in range(n - 1):
v = g(f())
p = [0] * (min(m, len(u) + len(v)) + 1)
for i, x in enumerate(u):
for j, y in enumerate(v, i):
if j > m: break
p[j] = max(p[j], x + y)
u = p
print(u[m]) | {
"input": [
"2 3\n3 3 7 2\n3 4 1 5\n",
"1 3\n4 4 3 1 2\n"
],
"output": [
"15\n",
"9\n"
]
} |
2,845 | 9 | You are given a string s consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'. Note that each of the characters '?' is replaced independently from the others.
A string t of length n is called a palindrome if the equality t[i] = t[n-i+1] is true for all i (1 β€ i β€ n).
For example, if s="01?????0", a=4 and b=4, then you can replace the characters '?' in the following ways:
* "01011010";
* "01100110".
For the given string s and the numbers a and b, replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'.
Input
The first line contains a single integer t (1 β€ t β€ 10^4). Then t test cases follow.
The first line of each test case contains two integers a and b (0 β€ a, b β€ 2 β
10^5, a + b β₯ 1).
The second line of each test case contains the string s of length a+b, consisting of the characters '0', '1', and '?'.
It is guaranteed that the sum of the string lengths of s over all test cases does not exceed 2 β
10^5.
Output
For each test case, output:
* "-1", if you can't replace all the characters '?' in the string s by '0' or '1' so that the string becomes a palindrome and that it contains exactly a characters '0' and exactly b characters '1';
* the string that is obtained as a result of the replacement, otherwise.
If there are several suitable ways to replace characters, you can output any.
Example
Input
9
4 4
01?????0
3 3
??????
1 0
?
2 2
0101
2 2
01?0
0 1
0
0 3
1?1
2 2
?00?
4 3
??010?0
Output
01011010
-1
0
-1
0110
-1
111
1001
0101010 | import math
testcases = int(input())
f = []
def apply(h):
for i in range(len(h)):
if h[i]!="?" and h[len(h)-1-i] == "?":
h[len(h)-1-i]=l[i]
def palidrome(h):
for i in range(len(h)//2+1):
if h[len(h)-1-i]!=l[i]:
return False
return True
for j in range(testcases):
a,b = [int(k) for k in input().split()]
s = input()
l = ["" for i in range(len(s))]
for i in range(len(s)):
l[i]=s[i]
apply(l)
count0 = l.count("0")
count1 = l.count("1")
for i in range(len(l)):
if a-count0>b-count1 and l[i]=="?":
l[i] = "0"
count0+=2
l[len(l)-1-i]=l[i]
elif(l[i]=="?"):
l[i]="1"
count1+=2
l[len(l)-1-i]=l[i]
if l.count("0")==a and l.count("1")==b and palidrome(l):
f.append([])
f[j]=l
else:
f.append([])
f[j]=[-1,""]
for i in range(testcases):
print(*f[i],sep="") | {
"input": [
"9\n4 4\n01?????0\n3 3\n??????\n1 0\n?\n2 2\n0101\n2 2\n01?0\n0 1\n0\n0 3\n1?1\n2 2\n?00?\n4 3\n??010?0\n"
],
"output": [
"\n01011010\n-1\n0\n-1\n0110\n-1\n111\n1001\n0101010\n"
]
} |
2,846 | 9 | The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>. | n, m = map(int, input().split())
adj = [[] for i in range(n)]
for _ in range(m):
a, b = map(int, input().split())
adj[a-1].append(b-1)
adj[b-1].append(a-1)
def bfs(s):
q, d, res = [s], [-1] * n, [0] * n
d[s] = 0
res[s] = 1
i = 0
while i < len(q):
v = q[i]
for u in adj[v]:
if d[u] == -1:
d[u] = d[v] + 1
q.append(u)
if d[u] == d[v] + 1:
res[u] += res[v]
i += 1
return q, d, res
q0, d0, res0 = bfs(0)
q1, d1, res1 = bfs(n-1)
min_dist = d0[n-1]
num_paths = res0[n-1]
res = num_paths
for v in range(1, n-1):
if d0[v] + d1[v] == min_dist:
res = max(res, 2 * res0[v] * res1[v])
print('%.7f' % (res / num_paths)) | {
"input": [
"11 14\n1 2\n1 3\n2 4\n3 4\n4 5\n4 6\n5 11\n6 11\n1 8\n8 9\n9 7\n11 7\n1 10\n10 4\n",
"4 4\n1 2\n2 4\n1 3\n3 4\n"
],
"output": [
"1.714285714\n",
"1.000000000\n"
]
} |
2,847 | 9 | Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0 | def maxx(n):
l=[]
while(n>0):
l.append(n%10)
n = int(n/10)
return max(l)
n =int(input())
j=0
while(n>0):
n = n- maxx(n)
j+=1
print(j) | {
"input": [
"24\n"
],
"output": [
"5\n"
]
} |
2,848 | 9 | Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27. |
def main():
n = int(input())
a = list(map(int, input().split()))
k = input()
ans, s = 0, 0
for i in range(n):
if k[i] == "1":
ans = max(ans + a[i], s)
s += a[i]
print(ans)
if __name__ == '__main__':
main()
| {
"input": [
"5\n17 0 10 2 1\n11010\n",
"2\n3 8\n10\n"
],
"output": [
"27\n",
"3\n"
]
} |
2,849 | 10 | Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game.
Each worker has a certain skill level vi. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the i-th worker won't work with those whose skill is less than li, and with those whose skill is more than ri.
Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of workers Pavel hired.
Each of the following n lines contains three space-separated integers li, vi, ri (1 β€ li β€ vi β€ ri β€ 3Β·105) β the minimum skill value of the workers that the i-th worker can work with, the i-th worker's skill and the maximum skill value of the workers that the i-th worker can work with.
Output
In the first line print a single integer m β the number of workers Pavel must pick for developing the game.
In the next line print m space-separated integers β the numbers of the workers in any order.
If there are multiple optimal solutions, print any of them.
Examples
Input
4
2 8 9
1 4 7
3 6 8
5 8 10
Output
3
1 3 4
Input
6
3 5 16
1 6 11
4 8 12
7 9 16
2 10 14
8 13 15
Output
4
1 2 3 5 | import os
import sys
from io import BytesIO, IOBase
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')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
# 2020/12/17
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
# Tell all nodes above of the updated area of the updates
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=None):
"""func of data[start, stop)"""
start += self._size
stop += self._size
# Apply all the lazily stored queries
self._update(start)
self._update(stop - 1)
res = self._default if default is None else default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({})".format(list(map(lambda i: self.query(i, i + 1), range(self._len))))
class SweepLine:
def __init__(self, data=None, inclusive=True):
"""
:param data: [((1, 2), (3, 4)), (left_bottom, right_top), ...]
:param inclusive: include the right bound
"""
if data:
# [((1, 2), (3, 4), 0), ...]
self.data = [(*pair, i) for i, pair in enumerate(data)]
else:
self.data = []
self.discrete_dict = self.restore = None
self.INCLUSIVE = inclusive
def add_rectangle(self, rectangle):
self.data.append((*rectangle, len(self.data)))
def _discrete(self):
st = set()
operations = []
for p1, p2, i in self.data:
st |= {*p1, *p2}
# we want add operation go first, so *= -1
# we calculate the line intersect
operations.append((p1[1], -1, p1[0], p2[0], i)) # add
operations.append((p2[1], 1, p1[0], p2[0], i)) # subtract
self.restore = sorted(st)
self.discrete_dict = dict(zip(self.restore, range(len(st))))
self.operations = sorted(operations)
# print(*self.operations, sep='\n')
def max_intersect(self, get_points=False):
"""
:return intersect, i (ith rectangle)
:return intersect, i, x
"""
if not self.restore:
self._discrete()
d = self.discrete_dict
tree = LazySegmentTree([0] * len(self.restore))
result = 0, None
for y, v, left, right, i in self.operations:
# print(f"left={left}, right={right}")
left, right, v = d[left], d[right], -v
# print(f"dis -> left={left}, right={right}")
tree.add(left, right + self.INCLUSIVE, v)
if v == 1:
intersect = tree.query(left, right + self.INCLUSIVE)
if intersect > result[0]:
result = intersect, i
tree = LazySegmentTree([0] * len(self.restore))
if get_points:
for y, v, left, right, i in self.operations:
left, right, v = d[left], d[right], -v
tree.add(left, right + self.INCLUSIVE, v)
if i == result[1]:
for lf in range(left, right + self.INCLUSIVE):
if tree.query(lf, lf + 1) == result[0]:
return result[0], i, self.restore[lf]
return result
# ############################## main
def main():
n = itg()
data = []
for _ in range(n):
lf, md, rg = mpint()
data.append(((lf, md), (md, rg)))
sweep = SweepLine(data)
ans1, idx, left = sweep.max_intersect(True)
right = data[idx][0][1]
print(ans1)
# print(idx)
# print(f"intersect = {ans1}")
# print(f"left = {left}, right = {right}")
ans2 = []
for i, pair in enumerate(data):
lf, md, rg = pair[0][0], pair[0][1], pair[1][1]
if lf <= left <= md <= right <= rg:
ans2.append(i + 1)
if len(ans2) != ans1:
print(AssertionError, len(ans2))
else:
print(*ans2)
DEBUG = 0
URL = 'https://codeforces.com/contest/377/problem/D'
if __name__ == '__main__':
# 0: normal, 1: runner, 2: interactive, 3: debug
if DEBUG == 1:
import requests
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
if DEBUG != 3:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if DEBUG:
_print = print
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
main()
# Please check!
| {
"input": [
"6\n3 5 16\n1 6 11\n4 8 12\n7 9 16\n2 10 14\n8 13 15\n",
"4\n2 8 9\n1 4 7\n3 6 8\n5 8 10\n"
],
"output": [
"4\n1 2 3 5 \n",
"3\n1 3 4 \n"
]
} |
2,850 | 7 | C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too. | import re
class Term:
def __init__(self, factor, type):
self.factor = factor
self.type = type
def __str__(self):
return '(%d * %s)' % (self.factor, self.type)
a = int(input())
s = '+' + input().strip()
terms = []
pos = 0
while pos != len(s):
sign = 1
if s[pos] == '-':
sign = -1
factor = 1
if re.match('\d', s[pos + 1]):
start = pos + 1
pos = start + 1
while s[pos] != '*':
pos += 1
factor = int(s[start:pos])
pos += 4
term_type = 'pre'
if s[pos - 3: pos] == 'a++':
term_type = 'post'
terms.append(Term(sign * factor, term_type))
terms.sort(key = lambda term: term.factor)
#print(', '.join(map(str, terms)))
result = 0
for term in terms:
if term.type == 'pre':
a += 1
result += term.factor * a
if term.type == 'post':
a += 1
print(result)
| {
"input": [
"3\na+++++a\n",
"1\n5*a++-3*++a+a++\n"
],
"output": [
"8\n",
"11\n"
]
} |
2,851 | 8 | The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1 | n, k = map(int, input().split())
if k >= 1000000:
print('0')
exit(0)
def f():
x, y, d = map(int, input().split())
return (x * x + y * y, d)
t = [f() for i in range(n)]
t.sort()
for r, d in t:
k += d
if k >= 1000000:
print(r ** 0.5)
break
else: print('-1') | {
"input": [
"4 999998\n1 1 2\n2 2 1\n3 3 1\n2 -2 1\n",
"4 999998\n1 1 1\n2 2 1\n3 3 1\n2 -2 1\n",
"2 1\n1 1 999997\n2 2 1\n"
],
"output": [
"1.41421356237\n",
"2.82842712475\n",
"-1\n"
]
} |
2,852 | 11 | Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2, 9, 1]) = [1, 2, 1, 3, 9, 1].
Let's determine the sequence Xi, for integer i (i β₯ 0): X0 = [X] ([X] is a sequence consisting of a single number X), Xi = f(Xi - 1) (i > 0). For example, at X = 6 we get X0 = [6], X1 = [1, 2, 3, 6], X2 = [1, 1, 2, 1, 3, 1, 2, 3, 6].
Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.
Input
A single line contains two space-separated integers β X (1 β€ X β€ 1012) and k (0 β€ k β€ 1018).
Output
Print the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.
Examples
Input
6 1
Output
1 2 3 6
Input
4 2
Output
1 1 2 1 2 4
Input
10 3
Output
1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10 | import sys
solSaved = {}
solSavedPropios = {}
def DivisorsN(n):
key = solSaved.get(str(n))
if key == None :
divisors = []
divisors2 = []
for i in range(1,int(n ** (1/2)) + 1):
if n % i == 0 :
if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int(i))
else :
divisors.append(int(i))
temp = []
temp.append(int(n/i))
divisors2 = temp + divisors2
divisors = divisors + divisors2
solSaved[str(n)] = divisors.copy()
return divisors
return key
def TodosLosDivisores(arrayN) :
sol = []
if len(arrayN) > 10 ** 5 :
newArrayN = []
for k in range(len(arrayN)):
newArrayN.append(arrayN[k])
arrayN = newArrayN
for i in range(len(arrayN) - 1):
temp = DivisorsN(arrayN[i])
for t in range(len(temp)) : sol.append(temp[t])
#sol = sol + solSaved.get(str(arrayN[len(arrayN) - 1]))
temp = sol.copy()
temp2 = solSaved.get(str(arrayN[len(arrayN) - 1]))
sol.append(temp2)
for t in range(len(temp2)) : temp.append(temp2[t])
solSaved[str(temp2)] = temp
return sol
def DivisorsXk():
a, b = input().split()
x = int(a)
k = int(b)
if x == 1 : return 1
if k == 0 : return x
if k == 1 : return DivisorsN(x)
sol = []
sol.append(x)
solSaved[str(x)] = DivisorsN(x)
# index = 0
# for i in range(k):
# prev_index = len(sol)
# for j in range(index, len(sol)):
# divs = DivisorsN(sol[j])
# sol = sol + divs
# index = prev_index
i = 1
while i <= k :
# j = 0
# while j < len(sol):
# if type(sol[j]) == int : newSol.append(DivisorsN(sol[j]))
# else : newSol = newSol + DivisorAll(sol[j])
# j+=1
# sol = newSol
if type(sol[i - 1]) == int : sol.append(DivisorsN(sol[i - 1]))
else : sol.append(TodosLosDivisores(sol[i - 1]))
i += 1
temp = []
temp2 = sol[len(sol) - 1]
for t in range(len(temp2) - 1) : temp.append(temp2[t])
temp = temp + temp2[len(temp2) - 1]
return temp
def LosFuckingDivisoresDeUnArrayConLista(a) :
sol = []
if type(a) == int : return DivisorsN(a)
for i in range(len(a)) :
temp = []
key = solSaved.get(str(a[i]))
if key == None : temp = LosFuckingDivisoresDeUnArrayConLista(a[i])
else : temp = key
sol.append(temp)
solSaved[str(a)] = sol
return sol
def Divisors(x, k) :
if k == 0 : return x
if k > 10 ** 5 :
Ones = []
for i in range(10 ** 5) : Ones.append(1)
return Ones
key = solSaved.get(str((x,k)))
if key == None :
sol = []
if type(x) == int : return Divisors(DivisorsN(x), k - 1)
else :
sol = []
for i in range(len(x)) :
temp = []
temp.append(Divisors(x[i], k - 1))
sol = sol + temp
return sol
else : return key
def DivisorsPropios(n) :
key = solSavedPropios.get(str(n))
if key == None :
divisors = []
divisors2 = []
for i in range(2,int(n ** (1/2)) + 1):
if n % i == 0 :
if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int(i))
else :
divisors.append(int(i))
temp = []
temp.append(int(n/i))
divisors2 = temp + divisors2 #divisors2.append(int(n / i))
divisors = divisors + divisors2
solSavedPropios[str(n)] = divisors.copy()
return divisors
return key
def UltimateDivisors(x, k) :
if x == 1 : return 1
if k == 0 : return x
if k == 1 : return DivisorsN(x)
if k >= 10 ** 5 :
a = []
for i in range(10 ** 5) : a.append(1)
return a
Unos = []
sol = []
sol.append(1)
temp = DivisorsPropios(x).copy()
for i in range(k - 1) : Unos.append(1)
if len(temp) == 0 : return [1] + Unos + [x]
temp.append(x)
for t in range(len(temp)) :
if len(sol) >= 10 ** 5 : return sol
temp3 = DivisorsPropios(temp[t]).copy()
if len(temp3) == 0 :
temp4 = UltimateDivisors(temp[t], k - 1)
if type(temp4) == int : sol = sol + [temp4]
else : sol = sol + temp4
else : sol = sol + NewUltimateDivisores(temp[t], k - 1)
return sol
def NewUltimateDivisores(x, k) :
temp = DivisorsPropios(x)
i = k - 1
sol = []
while i >= 1 :
if len(sol) >= 10**5 : return sol
sol = sol + [1]
for t in range(len(temp)) :
temp2 = UltimateDivisors(temp[t], i)
if type(temp2) == int : sol = sol + [temp2]
else : sol = sol + temp2
i -= 1
return sol + DivisorsN(x)
#print(UltimateDivisors(963761198400,65535))
#print(UltimateDivisors(549755813888,269))
a, b = input().split()
x = int(a)
k = int(b)
sol = UltimateDivisors(x,k)
if type(sol) == int : print(sol)
else :
if(len(sol) >= 10 ** 5):
for i in range(10 ** 5 - 1) :
sys.stdout.write(str(sol[i]) + ' ')
sys.stdout.write(str(sol[10**5 - 1]))
else :
for i in range(len(sol) - 1) :
sys.stdout.write(str(sol[i]) + ' ')
sys.stdout.write(str(sol[len(sol) - 1]))
| {
"input": [
"10 3\n",
"6 1\n",
"4 2\n"
],
"output": [
" 1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10 ",
" 1 2 3 6 ",
" 1 1 2 1 2 4 "
]
} |
2,853 | 12 | Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books.
You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could
* open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);
* move freely from a room to a room if a corresponding door is open;
* give keys to one another, being in one room.
"Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.
Input
The first line contains three preset integers n, m ΠΈ k (1 β€ n, m, k β€ 1000) β the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space β the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.
Output
Print "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".
Examples
Input
2 1 2
1 2
Dmitry 1 1 1
Natalia 2 0
Natalia 1 1 1
Dmitry 2 0
Output
YES
Input
4 4 3
1 3
1 2
2 3
3 4
Artem 1 1 4
Dmitry 1 1 2
Edvard 4 2 1 3
Artem 2 0
Dmitry 1 0
Edvard 4 4 1 2 3 4
Output
NO | def solve(n,m,k,edge_list,house_members):
room_sets=[i for i in range(n)]
valid_move=[True for i in range(n)]
room_status=[ [1<<i,0,[]] for i in range(n)]
# room_status[i]->informacion de todo otro cuarto,persona y llave alcanzable para el cuarto i
# room_status[i][0]->los cuartos alcanzables por el cuarto i
# room_status[i][1]->las personas que pueden llegar al i
# room_status[i][2]->las llaves alcanzables por el cuarto i
for i in range(k):
room_status[house_members[i][1]][1]|=1<<i
for j in house_members[i][2]:
room_status[house_members[i][1]][2].append(j)
#print(room_status)
move=True
while move:
move=False
for i in range(n):
#print(valid_move)
if valid_move[i]:
move=move or expand(i,room_sets,valid_move,room_status,edge_list)
house_part=[]
for i in range(n):
if room_sets[i]==i:
house_part.append(i)
return adjust_answer(house_part,room_status,n,m,k)
def setoff(index,room_sets):
if room_sets[index]==index:
return index
else:
new_val=setoff(room_sets[index],room_sets)
room_sets[index]=new_val
return new_val
def expand(current_room,room_sets,valid_move,room_status,edge_list):
moving=room_status[current_room][2]
move=False
#print(current_room)
#print(edge_list)
for i in moving:
edge=edge_list[i]
#print(edge)
if setoff(edge[0],room_sets)==current_room:
move =move or merge(current_room,edge[1],room_sets,valid_move,room_status)
if setoff(edge[1],room_sets)==current_room:
move=move or merge(current_room,edge[0],room_sets,valid_move,room_status)
return move
def merge(x,y,room_sets,valid_move,room_status):
#print(x,y)
setx=setoff(x,room_sets)
sety=setoff(y,room_sets)
#print(setx,sety)
if setx==sety:
return False
else:
m=(len(room_status[setx][2]))
m1=len(room_status[sety][2])
if m >= m1:
head=setx
tail=sety
else:
head=sety
tail=setx
# print(head,tail)
valid_move[tail]=0
room_sets[tail]=head
keys=room_status[tail][2]
while len(keys)>0:
room_status[head][2].append(keys.pop())
room_status[head][1]|=room_status[tail][1]
room_status[head][0]|=room_status[tail][0]
return True
def adjust_answer(house_part,room_status,n,m,k):
size=len(house_part)
#print(house_part)
rooms=[0 for i in range(size)]
members=[0 for i in range(size)]
keys=[0 for i in range(size)]
for i in range(size):
keys_list=room_status[house_part[i]][2]
for j in keys_list:
keys[i]|=1<<j
rooms[i]=room_status[house_part[i]][0]
members[i]=room_status[house_part[i]][1]
#print(rooms)
#print(members)
#print(keys)
#rooms.sort()
#members.sort()
#keys.sort()
return [rooms,members,keys]
def compare_answer(answer_1,answer_2,n,m,k):
rooms1=answer_1[0]
members1=answer_1[1]
keys1=answer_1[2]
if len(rooms1)!=len(members1)!=len(keys1):
return False
rooms2=answer_2[0]
members2=answer_2[1]
keys2=answer_2[2]
if len(rooms2)!=len(members2)!=len(keys2):
return False
if len(rooms1)!=len(rooms2):
return False
for i in range(len(rooms1)):
if rooms1[i]!=rooms2[i] or keys1[i]!=keys2[i] or members1[i]!=members2[i]:
return False
return True
data=[int(i) for i in input().split()]
n,m,k=data[0],data[1],data[2]
house_members=[["",0,[]]for i in range(k)]
house_members_2=[["",0,[]]for i in range(k)]
pos_adjustment={}
edge_list=[]
for i in range(m):
doors_data=[int(i) for i in input().split()]
a,b=doors_data[0]-1,doors_data[1]-1
edge_list.append((a,b))
for i in range(k):
temp=input().split()
pos_adjustment[temp[0]]=i
house_members[i][0]=temp[0]
house_members[i][1]=int(temp[1])-1
for j in range(3,len(temp)):
val=int(temp[j])-1
house_members[i][2].append(val)
answer_1=solve(n,m,k,edge_list,house_members)
for i in range(k):
temp=input().split()
house_members_2[pos_adjustment[temp[0]]][0]=temp[0]
house_members_2[pos_adjustment[temp[0]]][1]=int(temp[1])-1
for j in range(3,len(temp)):
val=int(temp[j])-1
house_members_2[pos_adjustment[temp[0]]][2].append(val)
answer_2=solve(n,m,k,edge_list,house_members_2)
if compare_answer(answer_1,answer_2,n,m,k):
print("YES")
else :
print("NO") | {
"input": [
"4 4 3\n1 3\n1 2\n2 3\n3 4\nArtem 1 1 4\nDmitry 1 1 2\nEdvard 4 2 1 3\nArtem 2 0\nDmitry 1 0\nEdvard 4 4 1 2 3 4\n",
"2 1 2\n1 2\nDmitry 1 1 1\nNatalia 2 0\nNatalia 1 1 1\nDmitry 2 0\n"
],
"output": [
"NO",
"YES"
]
} |
2,854 | 8 | Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a. | def who(a,b):
for i in range(min(len(a),len(b))):
if a[i] > b[i]:
return 'first'
if a[i] < b[i]:
return 'second'
if len(a) < len(b):
return 'first'
return 'second'
f,s,t = [],[],0
for _ in range(int(input())):
n = int(input())
if n < 0:
s.append(-n)
else:
f.append(n)
t = n
if sum(s) == sum(f):
if s == f:
print('first' if t>0 else 'second')
else:
print(who(f,s))
elif sum(s) < sum(f):
print('first')
else:
print('second')
| {
"input": [
"5\n1\n2\n-3\n-4\n3\n",
"3\n-1\n-2\n3\n",
"2\n4\n-4\n"
],
"output": [
"second\n",
"first\n",
"second\n"
]
} |
2,855 | 7 | Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 β€ |s| β€ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti. | def f(s): return f(s[:-1])+'a' if s[-1] == 'z'else s[:-1]+chr(ord(s[-1])+1)
s = f(input())
print(('No such string', s)[s < input()])
| {
"input": [
"aaa\nzzz\n",
"a\nc\n",
"abcdefg\nabcdefh\n"
],
"output": [
"aab",
"b",
"No such string"
]
} |
2,856 | 7 | You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 β€ k β€ 26) β the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}. | def fun(k,q):
if len(set(q)) < k:
return "NO"
cs = list(set(q)-{q[0]})[:k-1]
for c in cs:
index = q.find(c)
q = q[:index]+"\n"+q[index:]
return "YES"+"\n"+q
k = int(input())
q = input()
print(fun(k, q)) | {
"input": [
"1\nabca\n",
"4\nabc\n",
"2\naaacas\n"
],
"output": [
"YES\nabca\n",
"NO\n",
"YES\naaa\ncas\n"
]
} |
2,857 | 9 | Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 β€ xi β€ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 β€ n, m β€ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 β€ xi β€ n, ci β a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." β "hb.bz[..].." β "hb.bz[..]." β "hb.bz[..]" β "hb.bz.")
* after the second query f(hbΡ.bz....) = 3 ("hbΡ.bz[..].." β "hbΡ.bz[..]." β "hbΡ.bz[..]" β "hbΡ.bz.")
* after the third query f(hbΡ.bz..f.) = 1 ("hbΡ.bz[..]f." β "hbΡ.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." β ".c.")
* after the second query: f(....) = 3 ("[..].." β "[..]." β "[..]" β ".")
* after the third query: f(.a..) = 1 (".a[..]" β ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" β "aa.") | from sys import stdin,stdout
input = stdin.readline
n,m = map(int,input().split())
def calc():
s = bytearray(c == '.' for c in 'a' + input())
res = sum(a and b for a,b in zip(s[1:],s))
for i in range(m):
x,c = input().split()
x = int(x)
nc = c == '.'
if s[x] != nc:
diff = s[x-1] + s[x+1]
res += (-diff,diff) [nc]
s[x] = nc
yield str(res)
stdout.write('\n'.join(calc())) | {
"input": [
"10 3\n.b..bz....\n1 h\n3 c\n9 f\n",
"4 4\n.cc.\n2 .\n3 .\n2 a\n1 a\n"
],
"output": [
"4\n3\n1\n",
"1\n3\n1\n1\n"
]
} |
2,858 | 7 | Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named Β«PawnChessΒ».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner. | def board(lst):
A, B = 1000, 1000
for i in range(8):
for j in range(8):
if lst[j][i] == "B":
break
if lst[j][i] == 'W':
A = min(A, j)
for j in range(8):
if lst[7 - j][i] == "W":
break
if lst[7 - j][i] == "B":
B = min(B, j)
if A <= B:
return 'A'
return 'B'
a = [input() for x in range(8)]
print(board(a))
| {
"input": [
"........\n........\n.B....B.\n....W...\n........\n..W.....\n........\n........\n",
"..B.....\n..W.....\n......B.\n........\n.....W..\n......B.\n........\n........\n"
],
"output": [
"A\n",
"B\n"
]
} |
2,859 | 10 | Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.
What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.
Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.
Help the King to calculate this characteristic for each of his plan.
Input
The first line of the input contains integer n (1 β€ n β€ 100 000) β the number of cities in the kingdom.
Each of the next n - 1 lines contains two distinct integers ui, vi (1 β€ ui, vi β€ n) β the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.
The next line contains a single integer q (1 β€ q β€ 100 000) β the number of King's plans.
Each of the next q lines looks as follows: first goes number ki β the number of important cities in the King's plan, (1 β€ ki β€ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to n β the numbers of important cities in this plan.
The sum of all ki's does't exceed 100 000.
Output
For each plan print a single integer β the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective.
Examples
Input
4
1 3
2 3
4 3
4
2 1 2
3 2 3 4
3 1 2 4
4 1 2 3 4
Output
1
-1
1
-1
Input
7
1 2
2 3
3 4
1 5
5 6
5 7
1
4 2 4 6 7
Output
2
Note
In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.
In the second sample the cities to capture are 3 and 5. | import sys
from collections import deque
def solve():
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
# Euler tour technique
S = []
FS = [0]*N; LS = [0]*N
depth = [0]*N
stk = [-1, 0]
it = [0]*N
while len(stk) > 1:
v = stk[-1]
i = it[v]
if i == 0:
FS[v] = len(S)
depth[v] = len(stk)
if i < len(G[v]) and G[v][i] == stk[-2]:
it[v] += 1
i += 1
if i == len(G[v]):
LS[v] = len(S)
stk.pop()
else:
stk.append(G[v][i])
it[v] += 1
S.append(v)
L = len(S)
lg = [0]*(L+1)
# Sparse Table
for i in range(2, L+1):
lg[i] = lg[i >> 1] + 1
st = [[L]*(L - (1 << i) + 1) for i in range(lg[L]+1)]
st[0][:] = S
b = 1
for i in range(lg[L]):
st0 = st[i]
st1 = st[i+1]
for j in range(L - (b<<1) + 1):
st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
b <<= 1
INF = 10**18
ans = []
Q = int(readline())
G0 = [[]]*N
P = [0]*N
deg = [0]*N
KS = [0]*N
A = [0]*N
B = [0]*N
for t in range(Q):
k, *vs = map(int, readline().split())
for i in range(k):
vs[i] -= 1
KS[vs[i]] = 1
vs.sort(key=FS.__getitem__)
for i in range(k-1):
x = FS[vs[i]]; y = FS[vs[i+1]]
l = lg[y - x + 1]
w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
vs.append(w)
vs.sort(key=FS.__getitem__)
stk = []
prv = -1
for v in vs:
if v == prv:
continue
while stk and LS[stk[-1]] < FS[v]:
stk.pop()
if stk:
G0[stk[-1]].append(v)
G0[v] = []
it[v] = 0
stk.append(v)
prv = v
que = deque()
prv = -1
P[vs[0]] = -1
for v in vs:
if v == prv:
continue
for w in G0[v]:
P[w] = v
deg[v] = len(G0[v])
if deg[v] == 0:
que.append(v)
prv = v
while que:
v = que.popleft()
if KS[v]:
a = 0
for w in G0[v]:
ra = A[w]; rb = B[w]
if depth[v]+1 < depth[w]:
a += min(ra, rb+1)
else:
a += ra
A[v] = INF
B[v] = a
else:
a = 0; b = c = INF
for w in G0[v]:
ra = A[w]; rb = B[w]
a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb))
A[v] = min(a, b+1, c+1)
B[v] = b
p = P[v]
if p != -1:
deg[p] -= 1
if deg[p] == 0:
que.append(p)
v = min(A[vs[0]], B[vs[0]])
if v >= INF:
ans.append("-1\n")
else:
ans.append("%d\n" % v)
for v in vs:
KS[v] = 0
writelines(ans)
solve() | {
"input": [
"4\n1 3\n2 3\n4 3\n4\n2 1 2\n3 2 3 4\n3 1 2 4\n4 1 2 3 4\n",
"7\n1 2\n2 3\n3 4\n1 5\n5 6\n5 7\n1\n4 2 4 6 7\n"
],
"output": [
"1\n-1\n1\n-1\n",
"2\n"
]
} |
2,860 | 10 | Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | def go(a,b):
ret,c=0,a+b
if d.get(c) and d[c]>0:
d[c]-=1
ret=go(b,c)+1
d[c]+=1
return ret
input()
d={}
for i in map(int,input().split()):
if d.get(i):d[i]+=1
else: d[i]=1
ans=2
for a in d:
for b in d:
if a!=b or d[a]>1:
d[a]-=1
d[b]-=1
temp=go(a,b)+2
ans=max(temp,ans)
d[a]+=1
d[b]+=1
print(ans)
| {
"input": [
"3\n1 2 -1\n",
"5\n28 35 7 14 21\n"
],
"output": [
"3\n",
"4\n"
]
} |
2,861 | 8 | Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 β€ n β€ 100) β number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 β€ li < ri β€ n) β descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed. | n=int(input())
a=list(map(int, input().split() ) )
def swap(i):
global a
x=a[i]
a[i]=a[i+1]
a[i+1]=x
print(i+1, i+2)
c=True
while c:
c=False
for i in range(n):
if i<n-1 and a[i]>a[i+1]:
swap(i)
c=True
| {
"input": [
"5\n1 2 1 2 1\n",
"4\n2 1 4 3\n",
"7\n36 28 57 39 66 69 68\n"
],
"output": [
"2 3\n4 5\n3 4\n",
"1 2\n3 4\n",
"1 2\n3 4\n6 7\n"
]
} |
2,862 | 7 | Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
Input
The first line of the input contains three integers n, b and d (1 β€ n β€ 100 000, 1 β€ b β€ d β€ 1 000 000) β the number of oranges, the maximum size of the orange that fits in the juicer and the value d, which determines the condition when the waste section should be emptied.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1 000 000) β sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.
Output
Print one integer β the number of times Kolya will have to empty the waste section.
Examples
Input
2 7 10
5 6
Output
1
Input
1 5 10
7
Output
0
Input
3 10 10
5 7 7
Output
1
Input
1 1 1
1
Output
0
Note
In the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.
In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all. | def solve():
n,b,d = map(int,input().split())
ors = map(int,input().split())
ans = 0
trs = 0
for o in ors:
if o > b: continue
trs += o
if trs > d:
ans += 1
trs = 0
return ans
print(solve()) | {
"input": [
"1 1 1\n1\n",
"2 7 10\n5 6\n",
"3 10 10\n5 7 7\n",
"1 5 10\n7\n"
],
"output": [
"0\n",
"1\n",
"1\n",
"0\n"
]
} |
2,863 | 7 | Santa Claus has n candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.
Input
The only line contains positive integer number n (1 β€ n β€ 1000) β number of candies Santa Claus has.
Output
Print to the first line integer number k β maximal number of kids which can get candies.
Print to the second line k distinct integer numbers: number of candies for each of k kid. The sum of k printed numbers should be exactly n.
If there are many solutions, print any of them.
Examples
Input
5
Output
2
2 3
Input
9
Output
3
3 5 1
Input
2
Output
1
2 | def f(k):
return (k * (k + 1)) // 2
n = int(input())
k = 1
while f(k) <= n:
k += 1
k -= 1
print(k)
for i in range(1, k):
print(i, end=" ")
print(n - f(k - 1))
| {
"input": [
"2\n",
"9\n",
"5\n"
],
"output": [
"1\n2 ",
"3\n1 2 6 ",
"2\n1 4 "
]
} |
2,864 | 8 | Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,..., 10" will be corrected to "1, 2, 3, ..., 10".
In this task you are given a string s, which is composed by a concatination of terms, each of which may be:
* a positive integer of an arbitrary length (leading zeroes are not allowed),
* a "comma" symbol (","),
* a "space" symbol (" "),
* "three dots" ("...", that is, exactly three points written one after another, also known as suspension points).
Polycarp wants to add and remove spaces in the string s to ensure the following:
* each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it),
* each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term),
* if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left,
* there should not be other spaces.
Automate Polycarp's work and write a program that will process the given string s.
Input
The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.
Output
Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.
Examples
Input
1,2 ,3,..., 10
Output
1, 2, 3, ..., 10
Input
1,,,4...5......6
Output
1, , , 4 ...5 ... ...6
Input
...,1,2,3,...
Output
..., 1, 2, 3, ... | import sys
from itertools import *
from math import *
def solve():
s = input()
res = ""
i = 0
while i < len(s):
if s[i] == ' ':
i+=1
continue
if s[i] == '.':
if len(res) > 0 and res[-1] != ' ': res += ' ...'
else: res += '...'
i += 2
if s[i] == ',':
res += ', '
if s[i].isdigit():
if len(res) > 0 and res[-1].isdigit() and i > 0 and s[i-1] == ' ': res+=' '
res += s[i]
i += 1
if res[-1] == ' ': res = res[:len(res) - 1]
print(res)
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve() | {
"input": [
"1,2 ,3,..., 10\n",
"1,,,4...5......6\n",
"...,1,2,3,...\n"
],
"output": [
"1, 2, 3, ..., 10\n",
"1, , , 4 ...5 ... ...6\n",
"..., 1, 2, 3, ...\n"
]
} |
2,865 | 11 | The capital of Berland looks like a rectangle of size n Γ m of the square blocks of same size.
Fire!
It is known that k + 1 blocks got caught on fire (k + 1 β€ nΒ·m). Those blocks are centers of ignition. Moreover positions of k of these centers are known and one of these stays unknown. All k + 1 positions are distinct.
The fire goes the following way: during the zero minute of fire only these k + 1 centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner.
Berland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of k blocks (centers of ignition) are known and (k + 1)-th can be positioned in any other block.
Help Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.
Input
The first line contains three integers n, m and k (1 β€ n, m β€ 109, 1 β€ k β€ 500).
Each of the next k lines contain two integers xi and yi (1 β€ xi β€ n, 1 β€ yi β€ m) β coordinates of the i-th center of ignition. It is guaranteed that the locations of all centers of ignition are distinct.
Output
Print the minimal time it takes the fire to lighten up the whole city (in minutes).
Examples
Input
7 7 3
1 2
2 1
5 5
Output
3
Input
10 5 1
3 3
Output
2
Note
In the first example the last block can have coordinates (4, 4).
In the second example the last block can have coordinates (8, 3). | import sys
from collections import Counter
from operator import itemgetter
from heapq import heappop, heappush
n, m, k = map(int, input().split())
points = [list(map(int, line.split())) for line in sys.stdin]
pts_sorted_x = sorted(points)
pts_sorted_y = sorted(points, key=itemgetter(1, 0))
inf = 10**9+1
OK = (inf, inf)
def solve2(imos, t):
acc, cur = 0, 0
for k in sorted(imos.keys()):
if t < k:
break
if acc <= 0 and cur+1 < k or acc + imos[k] <= 0:
acc = 0
break
acc += imos[k]
return acc <= 0
def add_imos(imos, x, y):
imos[x] += y
if imos[x] == 0:
del imos[x]
def solve(t, px=-1, py=-1):
set_x = {1, n}
set_y = {1, m}
for x, y in points:
set_x.update((max(1, x-t), max(1, x-t-1), min(n, x+t), min(n, x+t+1)))
set_y.update((max(1, y-t), max(1, y-t-1), min(m, y+t), min(m, y+t+1)))
ans_x = ans_y = inf
pi, imos, hq = 0, Counter(), []
if px != -1:
imos[py] += 1
imos[py+t*2+1] -= 1
for cx in sorted(set_x):
while hq and hq[0][0] < cx:
add_imos(imos, hq[0][1], -1)
add_imos(imos, hq[0][2], +1)
heappop(hq)
while pi < k and pts_sorted_x[pi][0]-t <= cx <= pts_sorted_x[pi][0]+t:
x, y = pts_sorted_x[pi]
add_imos(imos, max(1, y-t), 1)
add_imos(imos, y+t+1, -1)
heappush(hq, (x+t, max(1, y-t), y+t+1))
pi += 1
if solve2(imos, m):
ans_x = cx
break
pi = 0
imos.clear()
hq.clear()
if px != -1:
imos[px] += 1
imos[px+t*2+1] -= 1
for cy in sorted(set_y):
while hq and hq[0][0] < cy:
add_imos(imos, hq[0][1], -1)
add_imos(imos, hq[0][2], +1)
heappop(hq)
while pi < k and pts_sorted_y[pi][1]-t <= cy <= pts_sorted_y[pi][1]+t:
x, y = pts_sorted_y[pi]
add_imos(imos, max(1, x-t), 1)
add_imos(imos, x+t+1, -1)
heappush(hq, (y+t, max(1, x-t), x+t+1))
pi += 1
if solve2(imos, n):
ans_y = cy
break
return ans_x, ans_y
ok, ng = 10**9+1, -1
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
p = solve(mid)
if p == OK:
ok = mid
continue
if solve(mid, p[0], p[1]) == OK:
ok = mid
else:
ng = mid
print(ok)
| {
"input": [
"10 5 1\n3 3\n",
"7 7 3\n1 2\n2 1\n5 5\n"
],
"output": [
"2\n",
"3\n"
]
} |
2,866 | 8 | Hands that shed innocent blood!
There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j β₯ i - Li.
You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
Input
The first line contains one integer n (1 β€ n β€ 106) β the number of guilty people.
Second line contains n space-separated integers L1, L2, ..., Ln (0 β€ Li β€ 109), where Li is the length of the i-th person's claw.
Output
Print one integer β the total number of alive people after the bell rings.
Examples
Input
4
0 1 0 10
Output
1
Input
2
0 0
Output
2
Input
10
1 1 3 0 0 0 2 1 0 3
Output
3
Note
In first sample the last person kills everyone in front of him. | def solve():
a=int(input())
b=list(map(int,input().split()))
k=a+15
survive=0
for i in range(a-1,-1,-1):
if i<k:
survive+=1
k=min(k,i-b[i])
print(survive)
solve() | {
"input": [
"10\n1 1 3 0 0 0 2 1 0 3\n",
"4\n0 1 0 10\n",
"2\n0 0\n"
],
"output": [
"3\n",
"1\n",
"2\n"
]
} |
2,867 | 8 | Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.
They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj < ai.
A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
Input
The first line contains an integer n (1 β€ n β€ 105) β the number of cards Conan has.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ 105), where ai is the number on the i-th card.
Output
If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).
Examples
Input
3
4 5 7
Output
Conan
Input
2
1 1
Output
Agasa
Note
In the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.
In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again. | from collections import Counter
def func(n):
return n % 2
n = int(input())
ls = list(map(int, input().split()))
foo = list(Counter(ls).values())
print("Conan" if 1 in list(map(func, foo)) else "Agasa")
| {
"input": [
"3\n4 5 7\n",
"2\n1 1\n"
],
"output": [
"Conan",
"Agasa"
]
} |
2,868 | 8 | There are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.
The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so that:
* no student-programmer is sitting next to the student-programmer;
* and no student-athlete is sitting next to the student-athlete.
In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.
Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
Input
The first line contain three integers n, a and b (1 β€ n β€ 2β
10^{5}, 0 β€ a, b β€ 2β
10^{5}, a + b > 0) β total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes.
The second line contains a string with length n, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
Output
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
Examples
Input
5 1 1
*...*
Output
2
Input
6 2 3
*...*.
Output
4
Input
11 3 10
.*....**.*.
Output
7
Input
3 2 3
***
Output
0
Note
In the first example you can put all student, for example, in the following way: *.AB*
In the second example you can put four students, for example, in the following way: *BAB*B
In the third example you can put seven students, for example, in the following way: B*ABAB**A*B
The letter A means a student-programmer, and the letter B β student-athlete. | def main():
n, a, b = (int(x) for x in input().split())
total = a + b
string = input().split("*")
for i in string:
if a > b:
a, b = b, a
a -= min(a, len(i)//2)
b -= min(b, len(i)-len(i)//2)
print(total - a - b)
if __name__ == '__main__':
main() | {
"input": [
"11 3 10\n.*....**.*.\n",
"5 1 1\n*...*\n",
"3 2 3\n***\n",
"6 2 3\n*...*.\n"
],
"output": [
"7\n",
"2\n",
"0\n",
"4\n"
]
} |
2,869 | 7 | Little C loves number Β«3Β» very much. He loves all things about it.
Now he has a positive integer n. He wants to split n into 3 positive integers a,b,c, such that a+b+c=n and none of the 3 integers is a multiple of 3. Help him to find a solution.
Input
A single line containing one integer n (3 β€ n β€ 10^9) β the integer Little C has.
Output
Print 3 positive integers a,b,c in a single line, such that a+b+c=n and none of them is a multiple of 3.
It can be proved that there is at least one solution. If there are multiple solutions, print any of them.
Examples
Input
3
Output
1 1 1
Input
233
Output
77 77 79 | def prog():
n = int(input())
if (n-2)%3==0:
print(1,2,n-3)
else:
print(1,1,n-2)
prog() | {
"input": [
"233",
"3\n"
],
"output": [
"1 2 230\n",
"1 1 1\n"
]
} |
2,870 | 11 | You are given a forest β an undirected graph with n vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.
If there are multiple correct answers, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 1000, 0 β€ m β€ n - 1) β the number of vertices of the graph and the number of edges, respectively.
Each of the next m lines contains two integers v and u (1 β€ v, u β€ n, v β u) β the descriptions of the edges.
It is guaranteed that the given graph is a forest.
Output
In the first line print the diameter of the resulting tree.
Each of the next (n - 1) - m lines should contain two integers v and u (1 β€ v, u β€ n, v β u) β the descriptions of the added edges.
The resulting graph should be a tree and its diameter should be minimal possible.
For m = n - 1 no edges are added, thus the output consists of a single integer β diameter of the given tree.
If there are multiple correct answers, print any of them.
Examples
Input
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
Note
In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.
Edge (1, 2) is the only option you have for the second example. The diameter is 1.
You can't add any edges in the third example. The diameter is already 2. | import sys
def dfs(v, d, prev, i):
global mid
global M
M[v] = False
way[d] = v
if way[d + 1] == 0:
mid[i] = way[d // 2]
mx = (d, v)
for x in E[v]:
if x != prev:
mx = max(mx, dfs(x, d + 1, v, i))
return mx
sys.setrecursionlimit(2000)
n, m = map(int, input().split())
E = [[] for i in range(n + 1)]
for i in range(m):
a, b = map(int, input().split())
E[a].append(b)
E[b].append(a)
mid = [0] * (n + 2)
c = 0
k = 0
way = [0] * (n + 2)
M = [True] * (n + 1)
M[0] = False
i = -1
while True in M:
i += 1
idx = M.index(True)
p1 = dfs(idx, 0, 0, i)[1]
way = [0] * (n + 2)
s, p2 = dfs(p1, 0, 0, i)
if s > c:
c = s
k = i
r = []
for j in range(0, i + 1):
if j == k:
continue
r.append((mid[k], mid[j]))
E[mid[k]].append(mid[j])
E[mid[j]].append(mid[k])
p1 = dfs(1, 0, 0, n + 1)[1]
s, p2 = dfs(p1, 0, 0, n + 1)
print(s)
for item in r:
print(item[0], item[1])
| {
"input": [
"3 2\n1 3\n2 3\n",
"2 0\n",
"4 2\n1 2\n2 3\n"
],
"output": [
"2\n",
"1\n1 2\n",
"2\n2 4\n"
]
} |
2,871 | 10 | There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.
Each colony arrangement can be expressed as a string of even length, where the i-th character of the string represents the type of villain in the i-th hole.
Iron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.
His assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.
Now Iron Man asks Jarvis q questions. In each question, he gives Jarvis two numbers x and y. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in x-th hole or y-th hole live in the same half and the Iron Man can destroy that colony arrangement.
Two colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.
Input
The first line contains a string s (2 β€ |s| β€ 10^{5}), representing the initial colony arrangement. String s can have both lowercase and uppercase English letters and its length is even.
The second line contains a single integer q (1 β€ q β€ 10^{5}) β the number of questions.
The i-th of the next q lines contains two integers x_i and y_i (1 β€ x_i, y_i β€ |s|, x_i β y_i) β the two numbers given to the Jarvis for the i-th question.
Output
For each question output the number of arrangements possible modulo 10^9+7.
Examples
Input
abba
2
1 4
1 2
Output
2
0
Input
AAaa
2
1 2
1 3
Output
2
0
Input
abcd
1
1 3
Output
8
Note
Consider the first example. For the first question, the possible arrangements are "aabb" and "bbaa", and for the second question, index 1 contains 'a' and index 2 contains 'b' and there is no valid arrangement in which all 'a' and 'b' are in the same half. | from sys import stdin
MOD = 1000000007
s = stdin.readline().strip()
n = len(s)
buc = [0] * 101
fac = [0] * (n + 1)
inv = [0] * (n + 1)
dp = [0] * (n + 1)
# temp_dp = [0] * (n+1)
ans = [[0] * 55 for _ in range(55)]
def find(c: 'str') -> 'int':
if 'A' <= c <= 'Z':
return ord(c) - ord('A') + 26
else:
return ord(c) - ord('a')
# c = Counter(s)
# # store frequency
# for k in c.keys():
# buc[find(k)] = c[k]
for i in s:
buc[find(i)] += 1
# compute factorial and inv
fac[0] = 1
for i in range(1, n + 1):
fac[i] = (fac[i - 1] * i) % MOD
inv[n] = pow(fac[n], MOD - 2, MOD)
for i in range(n - 1, -1, -1):
inv[i] = (inv[i + 1] * (i + 1)) % MOD
num = pow(fac[n // 2], 2, MOD)
for i in range(0, 52):
num = (num * inv[buc[i]]) % MOD
dp[0] = 1
for i in range(0, 52):
if not buc[i]:
continue
for j in range(n, buc[i] - 1, -1):
dp[j] += dp[j - buc[i]]
if dp[j] >= MOD:
dp[j] -= MOD
for i in range(52):
ans[i][i] = dp[n // 2]
for i in range(52):
if not buc[i]:
continue
temp_dp = dp.copy()
for k in range(buc[i], n + 1):
temp_dp[k] -= temp_dp[k - buc[i]]
if temp_dp[k] < 0:
temp_dp[k] += MOD
for j in range(i + 1, 52):
if not buc[j]:
continue
for k in range(buc[j], n + 1):
temp_dp[k] -= temp_dp[k - buc[j]]
if temp_dp[k] < 0:
temp_dp[k] += MOD
ans[i][j] = (2 * temp_dp[n // 2]) % MOD
for k in range(n, buc[j] - 1, -1):
temp_dp[k] += temp_dp[k - buc[j]]
if temp_dp[k] >= MOD:
temp_dp[k] -= MOD
q = int(input())
l = stdin.read().splitlines()
for i in l:
x, y = map(int, i.split())
l, r = find(s[x - 1]), find(s[y - 1])
if l > r:
l, r = r, l
print(num * ans[l][r] % MOD)
| {
"input": [
"abcd\n1\n1 3\n",
"abba\n2\n1 4\n1 2\n",
"AAaa\n2\n1 2\n1 3\n"
],
"output": [
"8\n",
"2\n0\n",
"2\n0\n"
]
} |
2,872 | 8 | Each day in Berland consists of n hours. Polycarp likes time management. That's why he has a fixed schedule for each day β it is a sequence a_1, a_2, ..., a_n (each a_i is either 0 or 1), where a_i=0 if Polycarp works during the i-th hour of the day and a_i=1 if Polycarp rests during the i-th hour of the day.
Days go one after another endlessly and Polycarp uses the same schedule for each day.
What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.
Input
The first line contains n (1 β€ n β€ 2β
10^5) β number of hours per day.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 β€ a_i β€ 1), where a_i=0 if the i-th hour in a day is working and a_i=1 if the i-th hour is resting. It is guaranteed that a_i=0 for at least one i.
Output
Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.
Examples
Input
5
1 0 1 0 1
Output
2
Input
6
0 1 0 1 1 0
Output
2
Input
7
1 0 1 1 1 0 1
Output
3
Input
3
0 0 0
Output
0
Note
In the first example, the maximal rest starts in last hour and goes to the first hour of the next day.
In the second example, Polycarp has maximal rest from the 4-th to the 5-th hour.
In the third example, Polycarp has maximal rest from the 3-rd to the 5-th hour.
In the fourth example, Polycarp has no rest at all. | def sleep(h, arr):
length = list(map(lambda a: len(a), arr))
return max(len(arr[0]) + len(arr[-1]), max(length))
h = int(input())
arr = "".join(input().split())
print(sleep(h, arr.split("0")))
| {
"input": [
"5\n1 0 1 0 1\n",
"6\n0 1 0 1 1 0\n",
"3\n0 0 0\n",
"7\n1 0 1 1 1 0 1\n"
],
"output": [
"2\n",
"2\n",
"0\n",
"3\n"
]
} |
2,873 | 7 | A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:
* Employee A is the immediate manager of employee B
* Employee B has an immediate manager employee C such that employee A is the superior of employee C.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.
What is the minimum number of groups that must be formed?
Input
The first line contains integer n (1 β€ n β€ 2000) β the number of employees.
The next n lines contain the integers pi (1 β€ pi β€ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.
It is guaranteed, that no employee will be the immediate manager of him/herself (pi β i). Also, there will be no managerial cycles.
Output
Print a single integer denoting the minimum number of groups that will be formed in the party.
Examples
Input
5
-1
1
2
1
-1
Output
3
Note
For the first example, three groups are sufficient, for example:
* Employee 1
* Employees 2 and 4
* Employees 3 and 5 | n = int(input())
m = []
for _ in range(n):
m.append(int(input()) - 1)
mx = 1
def depth(i):
t = 0
while i != -2:
i = m[i]
t += 1
return t
for i in range(n):
mx = max(mx, depth(i))
print(mx) | {
"input": [
"5\n-1\n1\n2\n1\n-1\n"
],
"output": [
"3\n"
]
} |
2,874 | 7 | You have a given integer n. Find the number of ways to fill all 3 Γ n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.
<image> This picture describes when n = 4. The left one is the shape and the right one is 3 Γ n tiles.
Input
The only line contains one integer n (1 β€ n β€ 60) β the length.
Output
Print the number of ways to fill.
Examples
Input
4
Output
4
Input
1
Output
0
Note
In the first example, there are 4 possible cases of filling.
In the second example, you cannot fill the shapes in 3 Γ 1 tiles. |
def df(n):
if n&1:
return 0
return 1<<(n>>1)
print(df(int(input()))) | {
"input": [
"1\n",
"4\n"
],
"output": [
"0",
"4"
]
} |
2,875 | 7 | A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.
You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?
Input
The first line of the input contains two integer numbers n and d (2 β€ n β€ 2000, 1 β€ d β€ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 β€ bi β€ 106).
Output
Output the minimal number of moves needed to make the sequence increasing.
Examples
Input
4 2
1 3 3 2
Output
3 | def readln(): return tuple(map(int, input().split()))
n, d = readln()
ans = 0
b = list(readln())
for i in range(1, n):
if b[i] <= b[i - 1]:
c = (b[i - 1] - b[i]) // d + 1
ans += c
b[i] += c * d
print(ans)
| {
"input": [
"4 2\n1 3 3 2\n"
],
"output": [
"3\n"
]
} |
2,876 | 10 | You are given a directed graph with n vertices and m directed edges without self-loops or multiple edges.
Let's denote the k-coloring of a digraph as following: you color each edge in one of k colors. The k-coloring is good if and only if there no cycle formed by edges of same color.
Find a good k-coloring of given digraph with minimum possible k.
Input
The first line contains two integers n and m (2 β€ n β€ 5000, 1 β€ m β€ 5000) β the number of vertices and edges in the digraph, respectively.
Next m lines contain description of edges β one per line. Each edge is a pair of integers u and v (1 β€ u, v β€ n, u β v) β there is directed edge from u to v in the graph.
It is guaranteed that each ordered pair (u, v) appears in the list of edges at most once.
Output
In the first line print single integer k β the number of used colors in a good k-coloring of given graph.
In the second line print m integers c_1, c_2, ..., c_m (1 β€ c_i β€ k), where c_i is a color of the i-th edge (in order as they are given in the input).
If there are multiple answers print any of them (you still have to minimize k).
Examples
Input
4 5
1 2
1 3
3 4
2 4
1 4
Output
1
1 1 1 1 1
Input
3 3
1 2
2 3
3 1
Output
2
1 1 2 | colors = 1
n, m = map(int, input().split(' '))
adj = [[] for i in range(n)]
color = [0 for i in range(m)]
vis = [0 for i in range(n)]
def dfs(u):
global colors
vis[u] = 1
for i, v in adj[u]:
if vis[v] == 1:
colors = 2
color[i] = 2
else:
color[i] = 1
if vis[v] == 0:
dfs(v)
vis[u] = 2
for i in range(m):
u, v = map(int, input().split(' '))
adj[u-1].append((i, v-1))
for i in range(n):
if vis[i] == 0:
dfs(i)
print(colors)
print(' '.join(map(str, color)))
| {
"input": [
"3 3\n1 2\n2 3\n3 1\n",
"4 5\n1 2\n1 3\n3 4\n2 4\n1 4\n"
],
"output": [
"2\n1 1 2\n",
"1\n1 1 1 1 1\n"
]
} |
2,877 | 7 | You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose:
* The x\% of the price of each the a-th sold ticket (a-th, 2a-th, 3a-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources.
* The y\% of the price of each the b-th sold ticket (b-th, 2b-th, 3b-th and so on) in the order you chose is aimed for pollution abatement.
If the ticket is in both programs then the (x + y) \% are used for environmental activities. Also, it's known that all prices are multiples of 100, so there is no need in any rounding.
For example, if you'd like to sell tickets with prices [400, 100, 300, 200] and the cinema pays 10\% of each 2-nd sold ticket and 20\% of each 3-rd sold ticket, then arranging them in order [100, 200, 300, 400] will lead to contribution equal to 100 β
0 + 200 β
0.1 + 300 β
0.2 + 400 β
0.1 = 120. But arranging them in order [100, 300, 400, 200] will lead to 100 β
0 + 300 β
0.1 + 400 β
0.2 + 200 β
0.1 = 130.
Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least k in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least k.
Input
The first line contains a single integer q (1 β€ q β€ 100) β the number of independent queries. Each query consists of 5 lines.
The first line of each query contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of tickets.
The second line contains n integers p_1, p_2, ..., p_n (100 β€ p_i β€ 10^9, p_i mod 100 = 0) β the corresponding prices of tickets.
The third line contains two integers x and a (1 β€ x β€ 100, x + y β€ 100, 1 β€ a β€ n) β the parameters of the first program.
The fourth line contains two integers y and b (1 β€ y β€ 100, x + y β€ 100, 1 β€ b β€ n) β the parameters of the second program.
The fifth line contains single integer k (1 β€ k β€ 10^{14}) β the required total contribution.
It's guaranteed that the total number of tickets per test doesn't exceed 2 β
10^5.
Output
Print q integers β one per query.
For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least k if you can sell tickets in any order.
If the total contribution can not be achieved selling all the tickets, print -1.
Example
Input
4
1
100
50 1
49 1
100
8
100 200 100 200 100 200 100 100
10 2
15 3
107
3
1000000000 1000000000 1000000000
50 1
50 1
3000000000
5
200 100 100 100 100
69 5
31 2
90
Output
-1
6
3
4
Note
In the first query the total contribution is equal to 50 + 49 = 99 < 100, so it's impossible to gather enough money.
In the second query you can rearrange tickets in a following way: [100, 100, 200, 200, 100, 200, 100, 100] and the total contribution from the first 6 tickets is equal to 100 β
0 + 100 β
0.1 + 200 β
0.15 + 200 β
0.1 + 100 β
0 + 200 β
0.25 = 10 + 30 + 20 + 50 = 110.
In the third query the full price of each ticket goes to the environmental activities.
In the fourth query you can rearrange tickets as [100, 200, 100, 100, 100] and the total contribution from the first 4 tickets is 100 β
0 + 200 β
0.31 + 100 β
0 + 100 β
0.31 = 62 + 31 = 93. | def cout(n):
cxy, cx, cy, s = 0, 0, 0, 0
for i in range(1, n + 1):
if not i % a:
if not i % b: cxy += 1
else: cx += 1
elif not i % b: cy += 1
return (sum(p[:cxy])*(x+y)+sum(p[cxy:cxy+cx])*x+sum(p[cxy+cx:cxy+cx+cy])*y)//100
for q in range(int(input())):
n = int(input())
p = sorted(list(map(int, input().split())), reverse=True)
x, a = map(int, input().split())
y, b = map(int, input().split())
k = int(input())
if y > x: x, a, y, b = y, b, x, a
if cout(n) < k: print(-1)
else:
low, high = 1, n
while low < high:
mid = (low + high) // 2
if cout(mid) >= k: high = mid
else: low = mid + 1
print(low)
| {
"input": [
"4\n1\n100\n50 1\n49 1\n100\n8\n100 200 100 200 100 200 100 100\n10 2\n15 3\n107\n3\n1000000000 1000000000 1000000000\n50 1\n50 1\n3000000000\n5\n200 100 100 100 100\n69 5\n31 2\n90\n"
],
"output": [
"-1\n6\n3\n4\n"
]
} |
2,878 | 8 | You are given two integers a and b. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations.
Is it possible to make a and b equal to 0 simultaneously?
Your program should answer t independent test cases.
Input
The first line contains one integer t (1 β€ t β€ 100) β the number of test cases.
Then the test cases follow, each test case is represented by one line containing two integers a and b for this test case (0 β€ a, b β€ 10^9).
Output
For each test case print the answer to it β YES if it is possible to make a and b equal to 0 simultaneously, and NO otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
Example
Input
3
6 9
1 1
1 2
Output
YES
NO
YES
Note
In the first test case of the example two operations can be used to make both a and b equal to zero:
1. choose x = 4 and set a := a - x, b := b - 2x. Then a = 6 - 4 = 2, b = 9 - 8 = 1;
2. choose x = 1 and set a := a - 2x, b := b - x. Then a = 2 - 2 = 0, b = 1 - 1 = 0. | from sys import stdin
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
a,b = rl()
if a > b:
a,b = b,a
if 2*a >= b and (a+b)%3 == 0:
print("YES")
else:
print("NO") | {
"input": [
"3\n6 9\n1 1\n1 2\n"
],
"output": [
"YES\nNO\nYES\n"
]
} |
2,879 | 8 | This is the hard version of this problem. The only difference is the constraint on k β the number of gifts in the offer. In this version: 2 β€ k β€ n.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β today the offer "k of goods for the price of one" is held in store.
Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.
More formally, for each good, its price is determined by a_i β the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:
* Vasya can buy one good with the index i if he currently has enough coins (i.e p β₯ a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i).
* Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p β₯ a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i).
Please note that each good can be bought no more than once.
For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.
Help Vasya to find out the maximum number of goods he can buy.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases in the test.
The next lines contain a description of t test cases.
The first line of each test case contains three integers n, p, k (2 β€ n β€ 2 β
10^5, 1 β€ p β€ 2β
10^9, 2 β€ k β€ n) β the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.
The second line of each test case contains n integers a_i (1 β€ a_i β€ 10^4) β the prices of goods.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case in a separate line print one integer m β the maximum number of goods that Vasya can buy.
Example
Input
8
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
3 2 3
4 2 6
5 2 3
10 1 3 9 2
2 10000 2
10000 10000
2 9999 2
10000 10000
4 6 4
3 2 3 2
5 5 3
1 2 2 1 2
Output
3
4
1
1
2
0
4
5 |
def go():
n,p,k = map(int, input().split())
a = sorted(list(map(int, input().split())))
cost = [0]*(n+1)
for i in range(1,k):
cost[i]= a[i-1] + cost[i-1]
for i in range(k, n+1):
cost[i] = a[i-1] + cost[i-k]
while cost[n]>p:
n-=1
return n
t = int(input())
for _ in range(t):
print (go())
| {
"input": [
"8\n5 6 2\n2 4 3 5 7\n5 11 2\n2 4 3 5 7\n3 2 3\n4 2 6\n5 2 3\n10 1 3 9 2\n2 10000 2\n10000 10000\n2 9999 2\n10000 10000\n4 6 4\n3 2 3 2\n5 5 3\n1 2 2 1 2\n"
],
"output": [
"3\n4\n1\n1\n2\n0\n4\n5\n"
]
} |
2,880 | 9 | You are given a permutation p_1, p_2, β¦, p_n of integers from 1 to n and an integer k, such that 1 β€ k β€ n. A permutation means that every number from 1 to n is contained in p exactly once.
Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_1], [l_2, r_2], β¦, [l_k, r_k]\}, such that:
* 1 β€ l_i β€ r_i β€ n for all 1 β€ i β€ k;
* For all 1 β€ j β€ n there exists exactly one segment [l_i, r_i], such that l_i β€ j β€ r_i.
Two partitions are different if there exists a segment that lies in one partition but not the other.
Let's calculate the partition value, defined as β_{i=1}^{k} {max_{l_i β€ j β€ r_i} {p_j}}, for all possible partitions of the permutation into k disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by 998 244 353.
Input
The first line contains two integers, n and k (1 β€ k β€ n β€ 200 000) β the size of the given permutation and the number of segments in a partition.
The second line contains n different integers p_1, p_2, β¦, p_n (1 β€ p_i β€ n) β the given permutation.
Output
Print two integers β the maximum possible partition value over all partitions of the permutation into k disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo 998 244 353.
Please note that you should only find the second value modulo 998 244 353.
Examples
Input
3 2
2 1 3
Output
5 2
Input
5 5
2 1 5 3 4
Output
15 1
Input
7 3
2 7 3 1 5 4 6
Output
18 6
Note
In the first test, for k = 2, there exists only two valid partitions: \{[1, 1], [2, 3]\} and \{[1, 2], [3, 3]\}. For each partition, the partition value is equal to 2 + 3 = 5. So, the maximum possible value is 5 and the number of partitions is 2.
In the third test, for k = 3, the partitions with the maximum possible partition value are \{[1, 2], [3, 5], [6, 7]\}, \{[1, 3], [4, 5], [6, 7]\}, \{[1, 4], [5, 5], [6, 7]\}, \{[1, 2], [3, 6], [7, 7]\}, \{[1, 3], [4, 6], [7, 7]\}, \{[1, 4], [5, 6], [7, 7]\}. For all of them, the partition value is equal to 7 + 5 + 6 = 18.
The partition \{[1, 2], [3, 4], [5, 7]\}, however, has the partition value 7 + 3 + 6 = 16. This is not the maximum possible value, so we don't count it. | def I():return list(map(int,input().split()))
n,k=I()
p=I()
s=0
num=1
for i in range(k):
s+=n-i
markers=[]
for i in range(n):
if p[i]>=n-k+1:markers.append(i)
nums=1
for i in range(1,k):
nums*=(markers[i]-markers[i-1])
nums%=998244353
print(s,nums) | {
"input": [
"5 5\n2 1 5 3 4\n",
"3 2\n2 1 3\n",
"7 3\n2 7 3 1 5 4 6\n"
],
"output": [
"15 1\n",
"5 2\n",
"18 6\n"
]
} |
2,881 | 8 | A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
<image>
You start with n cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?
Input
Each test consists of multiple test cases. The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next t lines contain descriptions of test cases.
Each test case contains a single integer n (1β€ nβ€ 10^9) β the number of cards.
It is guaranteed that the sum of n over all test cases does not exceed 10^9.
Output
For each test case output a single integer β the number of pyramids you will have constructed in the end.
Example
Input
5
3
14
15
24
1
Output
1
2
1
3
0
Note
In the first test, you construct a pyramid of height 1 with 2 cards. There is 1 card remaining, which is not enough to build a pyramid.
In the second test, you build two pyramids, each of height 2, with no cards remaining.
In the third test, you build one pyramid of height 3, with no cards remaining.
In the fourth test, you build one pyramid of height 3 with 9 cards remaining. Then you build a pyramid of height 2 with 2 cards remaining. Then you build a final pyramid of height 1 with no cards remaining.
In the fifth test, one card is not enough to build any pyramids. | for i in range(int(input())):
n = int(input())
def pi(n):
a = 2
c = False
while n>=a:
n-=a
a+=3
return n
c = 0
while n>=2:
n = pi(n)
c+=1
print(c) | {
"input": [
"5\n3\n14\n15\n24\n1\n"
],
"output": [
"1\n2\n1\n3\n0\n"
]
} |
2,882 | 7 | Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a as follows: he writes all the substrings of length 2 of the string a in the order from left to right, and then joins them in the same order into the string b.
For example, if Bob came up with the string a="abac", then all the substrings of length 2 of the string a are: "ab", "ba", "ac". Therefore, the string b="abbaac".
You are given the string b. Help Alice to guess the string a that Bob came up with. It is guaranteed that b was built according to the algorithm given above. It can be proved that the answer to the problem is unique.
Input
The first line contains a single positive integer t (1 β€ t β€ 1000) β the number of test cases in the test. Then t test cases follow.
Each test case consists of one line in which the string b is written, consisting of lowercase English letters (2 β€ |b| β€ 100) β the string Bob came up with, where |b| is the length of the string b. It is guaranteed that b was built according to the algorithm given above.
Output
Output t answers to test cases. Each answer is the secret string a, consisting of lowercase English letters, that Bob came up with.
Example
Input
4
abbaac
ac
bccddaaf
zzzzzzzzzz
Output
abac
ac
bcdaf
zzzzzz
Note
The first test case is explained in the statement.
In the second test case, Bob came up with the string a="ac", the string a has a length 2, so the string b is equal to the string a.
In the third test case, Bob came up with the string a="bcdaf", substrings of length 2 of string a are: "bc", "cd", "da", "af", so the string b="bccddaaf". | def solve():
b=input()
print(b[0:2]+b[3::2])
t=int(input())
while t>0:
solve()
t=t-1 | {
"input": [
"4\nabbaac\nac\nbccddaaf\nzzzzzzzzzz\n"
],
"output": [
"abac\nac\nbcdaf\nzzzzzz\n"
]
} |
2,883 | 7 | Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer x as nearly prime if it can be represented as p β
q, where 1 < p < q and p and q are prime numbers. For example, integers 6 and 10 are nearly primes (since 2 β
3 = 6 and 2 β
5 = 10), but integers 1, 3, 4, 16, 17 or 44 are not.
Captain Flint guessed an integer n and asked you: can you represent it as the sum of 4 different positive integers where at least 3 of them should be nearly prime.
Uncle Bogdan easily solved the task and joined the crew. Can you do the same?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
Next t lines contain test cases β one per line. The first and only line of each test case contains the single integer n (1 β€ n β€ 2 β
10^5) β the number Flint guessed.
Output
For each test case print:
* YES and 4 different positive integers such that at least 3 of them are nearly prime and their sum is equal to n (if there are multiple answers print any of them);
* NO if there is no way to represent n as the sum of 4 different positive integers where at least 3 of them are nearly prime.
You can print each character of YES or NO in any case.
Example
Input
7
7
23
31
36
44
100
258
Output
NO
NO
YES
14 10 6 1
YES
5 6 10 15
YES
6 7 10 21
YES
2 10 33 55
YES
10 21 221 6
Note
In the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.
In the third test case, n=31=2 β
7 + 2 β
5 + 2 β
3 + 1: integers 14, 10, 6 are nearly prime.
In the fourth test case, n=36=5 + 2 β
3 + 2 β
5 + 3 β
5: integers 6, 10, 15 are nearly prime.
In the fifth test case, n=44=2 β
3 + 7 + 2 β
5 + 3 β
7: integers 6, 10, 21 are nearly prime.
In the sixth test case, n=100=2 + 2 β
5 + 3 β
11 + 5 β
11: integers 10, 33, 55 are nearly prime.
In the seventh test case, n=258=2 β
5 + 3 β
7 + 13 β
17 + 2 β
3: integers 10, 21, 221, 6 are nearly prime. | I = input
pr = print
def main():
for _ in range(int(I())):
n = int(I())
ar = [6,10,14]
if n<31:pr('NO');continue
else:
if (n-30) in ar: n-=5;ar[1]+=5
pr('YES');pr(*ar,n-30)
main() | {
"input": [
"7\n7\n23\n31\n36\n44\n100\n258\n"
],
"output": [
"NO\nNO\nYES\n6 10 14 1\nYES\n6 10 15 5\nYES\n6 10 15 13\nYES\n6 10 14 70\nYES\n6 10 14 228\n"
]
} |
2,884 | 8 | Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply).
As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!"
The drill exercises are held on a rectangular n Γ m field, split into nm square 1 Γ 1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (x1, y1) and (x2, y2) equals exactly (x1 - x2)2 + (y1 - y2)2. Now not all nm squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2, 2), then he cannot put soldiers in the squares (1, 4), (3, 4), (4, 1) and (4, 3) β each of them will conflict with the soldier in the square (2, 2).
Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.
Input
The single line contains space-separated integers n and m (1 β€ n, m β€ 1000) that represent the size of the drill exercise field.
Output
Print the desired maximum number of warriors.
Examples
Input
2 4
Output
4
Input
3 4
Output
6
Note
In the first sample test Sir Lancelot can place his 4 soldiers on the 2 Γ 4 court as follows (the soldiers' locations are marked with gray circles on the scheme):
<image>
In the second sample test he can place 6 soldiers on the 3 Γ 4 site in the following manner:
<image> | def li():
return list(map(int, input().split(" ")))
n, m = li()
if n < m:
t =n
n = m
m = t
if m == 1:
print(n)
elif m == 2:
print(2*(2*(n//4) + min(n%4, 2)))
else:
print((n*m) - (n*m)//2)
| {
"input": [
"2 4\n",
"3 4\n"
],
"output": [
"4\n",
"6\n"
]
} |
2,885 | 10 | There are n + 1 cities, numbered from 0 to n. n roads connect these cities, the i-th road connects cities i - 1 and i (i β [1, n]).
Each road has a direction. The directions are given by a string of n characters such that each character is either L or R. If the i-th character is L, it means that the i-th road initially goes from the city i to the city i - 1; otherwise it goes from the city i - 1 to the city i.
A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city i to the city i + 1, it is possible to travel from i to i + 1, but not from i + 1 to i. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.
The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city i, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city i.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases.
Each test case consists of two lines. The first line contains one integer n (1 β€ n β€ 3 β
10^5). The second line contains the string s consisting of exactly n characters, each character is either L or R.
It is guaranteed that the sum of n over all test cases does not exceed 3 β
10^5.
Output
For each test case, print n + 1 integers. The i-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the i-th city.
Example
Input
2
6
LRRRLL
3
LRL
Output
1 3 2 3 1 3 2
1 4 1 4 | def answer():
a=[0]*(n+1)
for i in range(1,n+1):
if(d[i-1]=='L'):
if(i >= 2 and d[i-2]=='R'):a[i]=a[i-2]+2
else:a[i]=1
b=[0]*(n+1)
for i in range(n-1,-1,-1):
if(d[i]=='R'):
if(i <= n-2 and d[i+1]=='L'):b[i]=b[i+2]+2
else:b[i]=1
for i in range(n+1):print(a[i]+b[i]+1,end=' ')
for T in range(int(input())):
n=int(input())
d=input()
answer()
print()
| {
"input": [
"2\n6\nLRRRLL\n3\nLRL\n"
],
"output": [
"\n1 3 2 3 1 3 2\n1 4 1 4\n"
]
} |
2,886 | 7 | A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.
You are given a binary string s of length n. Construct two balanced bracket sequences a and b of length n such that for all 1β€ iβ€ n:
* if s_i=1, then a_i=b_i
* if s_i=0, then a_iβ b_i
If it is impossible, you should report about it.
Input
The first line contains a single integer t (1β€ tβ€ 10^4) β the number of test cases.
The first line of each test case contains a single integer n (2β€ nβ€ 2β
10^5, n is even).
The next line contains a string s of length n, consisting of characters 0 and 1.
The sum of n across all test cases does not exceed 2β
10^5.
Output
If such two balanced bracked sequences exist, output "YES" on the first line, otherwise output "NO". You can print each letter in any case (upper or lower).
If the answer is "YES", output the balanced bracket sequences a and b satisfying the conditions on the next two lines.
If there are multiple solutions, you may print any.
Example
Input
3
6
101101
10
1001101101
4
1100
Output
YES
()()()
((()))
YES
()()((()))
(())()()()
NO
Note
In the first test case, a="()()()" and b="((()))". The characters are equal in positions 1, 3, 4, and 6, which are the exact same positions where s_i=1.
In the second test case, a="()()((()))" and b="(())()()()". The characters are equal in positions 1, 4, 5, 7, 8, 10, which are the exact same positions where s_i=1.
In the third test case, there is no solution. | def solve(n,s):
cnt=0
for i in s:
if i=='1':
cnt+=1
if cnt%2==1 or s[0]=='0' or s[-1]=='0':
print("NO")
return
k=0
flip=0
a=""
b=""
for i in range(n):
if s[i]=='1':
if 2*k<cnt:
a+="("
else:
a+=")"
b+=a[-1]
k+=1
else:
if flip==1:
a+="("
b+=")"
else:
a+=")"
b+="("
flip=not(flip)
print("YES")
print(a)
print(b)
return
for t in range(int(input())):
n=int(input())
s=input()
solve(n,s)
| {
"input": [
"3\n6\n101101\n10\n1001101101\n4\n1100\n"
],
"output": [
"\nYES\n()()()\n((()))\nYES\n()()((()))\n(())()()()\nNO\n"
]
} |
2,887 | 11 | Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array.
More formally, given a suffix array of length n and having an alphabet size k, count the number of strings that produce such a suffix array.
Let s be a string of length n. Then the i-th suffix of s is the substring s[i β¦ n-1]. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is [3,2,4,1,0,5,6] as the array of sorted suffixes is [imry,limry,mry,olimry,oolimry,ry,y].
A string x is lexicographically smaller than string y, if either x is a prefix of y (and xβ y), or there exists such i that x_i < y_i, and for any 1β€ j < i , x_j = y_j.
Input
The first line contain 2 integers n and k (1 β€ n β€ 200000,1 β€ k β€ 200000) β the length of the suffix array and the alphabet size respectively.
The second line contains n integers s_0, s_1, s_2, β¦, s_{n-1} (0 β€ s_i β€ n-1) where s_i is the i-th element of the suffix array i.e. the starting position of the i-th lexicographically smallest suffix. It is guaranteed that for all 0 β€ i< j β€ n-1, s_i β s_j.
Output
Print how many strings produce such a suffix array. Since the number can be very large, print the answer modulo 998244353.
Examples
Input
3 2
0 2 1
Output
1
Input
5 1
0 1 2 3 4
Output
0
Input
6 200000
0 1 2 3 4 5
Output
822243495
Input
7 6
3 2 4 1 0 5 6
Output
36
Note
In the first test case, "abb" is the only possible solution.
In the second test case, it can be easily shown no possible strings exist as all the letters have to be equal.
In the fourth test case, one possible string is "ddbacef".
Please remember to print your answers modulo 998244353. | n, k = map(int, input().split())
p = list(map(int, input().split()))
pos = [-1] * (n + 1)
for i, x in enumerate(p):
pos[x] = i
d = 0
for i in range(n - 1):
if pos[p[i + 1] + 1] < pos[p[i] + 1]:
d += 1
if k <= d:
print(0)
exit()
mod = 998244353
def modpow(x, p):
res = 1
while p:
if p % 2:
res = res * x % mod
x = x * x % mod
p //= 2
return res
def C(N, K):
num = 1
den = 1
for j in range(K):
num *= N - j
num %= mod
den *= K - j
den %= mod
return num * modpow(den, mod - 2) % mod
k -= 1
ans = C(n + k - d, n)
print(ans)
| {
"input": [
"6 200000\n0 1 2 3 4 5\n",
"3 2\n0 2 1\n",
"5 1\n0 1 2 3 4\n",
"7 6\n3 2 4 1 0 5 6\n"
],
"output": [
"\n822243495",
"\n1",
"\n0",
"\n36"
]
} |
2,888 | 9 | Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name β a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory β the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. Β«..Β» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 β€ n β€ 50) β the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/ | n = int(input())
d = '/'
def r(s):
e = s.split('/')
f = []
for g in e:
if g == '..':
f = f[:-1]
else:
f += [g]
return '/'.join(f) + '/'
for i in range(n):
a = input()
if len(a.split()) == 2:
b, c = a.split()
if c[0] == '/':
d = r(c)
else:
d = r(d + c)
else:
print(d) | {
"input": [
"7\npwd\ncd /home/vasya\npwd\ncd ..\npwd\ncd vasya/../petya\npwd\n",
"4\ncd /a/b\npwd\ncd ../a/b\npwd\n"
],
"output": [
"/\n/home/vasya/\n/home/\n/home/petya/\n",
"/a/b/\n/a/a/b/\n"
]
} |
2,889 | 11 | You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:
1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 β€ i β€ n) of array s equals <image>. The operation x mod y means that we take the remainder of the division of number x by number y.
2. Then we write the contents of the array s to the array a. Element number i (1 β€ i β€ n) of the array s becomes the i-th element of the array a (ai = si).
You task is to find array a after exactly k described operations are applied.
Input
The first line contains two space-separated integers n and k (1 β€ n β€ 2000, 0 β€ k β€ 109). The next line contains n space-separated integers a1, a2, ..., an β elements of the array a (0 β€ ai β€ 109).
Output
Print n integers β elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.
Examples
Input
3 1
1 2 3
Output
1 3 6
Input
5 0
3 14 15 92 6
Output
3 14 15 92 6 | def ncr(n, r, p):
# initialize numerator
# and denominator
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
p=10**9+7
n,k=map(int,input().split())
b=list(map(int,input().split()))
if k==0:
print(*b)
else:
k-=1
res=[]
for r in range(1,n+1):
res.append(ncr(r+k-1,r-1,p))
ans=[]
for i in range(n):
j=i
val=0
while(j>=0):
val+=res[j]*b[i-j]
j+=-1
ans.append(val%p)
print(*ans)
| {
"input": [
"3 1\n1 2 3\n",
"5 0\n3 14 15 92 6\n"
],
"output": [
"1 3 6 \n",
"3 14 15 92 6 \n"
]
} |
2,890 | 7 | You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110 | def play(s, t):
count1, count2 = 0, 0
for elem in s:
if elem == '1':
count1 += 1
for elem in t:
if elem == '1':
count2 += 1
if count2 - count1 > 1 or (count2 - count1 == 1 and count1 % 2 == 0):
return "NO"
return "YES"
a = input()
b = input()
print(play(a, b))
| {
"input": [
"01011\n0110\n",
"0011\n1110\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
2,891 | 10 | Bob has a rectangular chocolate bar of the size W Γ H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.
Input
The first line contains 3 integers W, H and n (1 β€ W, H, n β€ 100) β width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 β coordinates of the endpoints of the i-th break (0 β€ xi, 1 β€ xi, 2 β€ W, 0 β€ yi, 1 β€ yi, 2 β€ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order.
It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.
Output
Output n + 1 numbers β areas of the resulting parts in the increasing order.
Examples
Input
2 2 2
1 0 1 2
0 1 1 1
Output
1 1 2
Input
2 2 3
1 0 1 2
0 1 1 1
1 1 2 1
Output
1 1 1 1
Input
2 4 2
0 1 2 1
0 3 2 3
Output
2 2 4 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
w, h, n = map(int, input().split())
mat = [[0] * (2 * w) for _ in range(2 * h)]
for x1, y1, x2, y2 in (map(int, input().split()) for _ in range(n)):
if x1 == x2:
for y in range(2 * y1, 2 * y2):
mat[y][2 * x1 - 1] = 1
else:
for x in range(2 * x1, 2 * x2):
mat[2 * y1 - 1][x] = 1
ans = []
for i in range(0, 2 * h, 2):
for j in range(0, 2 * w, 2):
if mat[i][j]:
continue
mat[i][j] = 1
size = 1
stack = [(i, j)]
while stack:
y, x = stack.pop()
for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if 0 <= y + dy * 2 < 2 * h and 0 <= x + dx * 2 < 2 * w and mat[y + dy][x + dx] == 0 and mat[y + dy * 2][x + dx * 2] == 0:
mat[y + dy * 2][x + dx * 2] = 1
size += 1
stack.append((y + dy * 2, x + dx * 2))
ans.append(size)
print(*sorted(ans))
| {
"input": [
"2 4 2\n0 1 2 1\n0 3 2 3\n",
"2 2 3\n1 0 1 2\n0 1 1 1\n1 1 2 1\n",
"2 2 2\n1 0 1 2\n0 1 1 1\n"
],
"output": [
"2 2 4 \n",
"1 1 1 1 \n",
"1 1 2 \n"
]
} |
2,892 | 10 | Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.
The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):
<image>
Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.
To understand the problem better please read the notes to the test samples.
Input
The single line of the input contains a sequence of characters "+" and "-" of length n (1 β€ n β€ 100000). The i-th (1 β€ i β€ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.
Output
Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.
Examples
Input
-++-
Output
Yes
Input
+-
Output
No
Input
++
Output
Yes
Input
-
Output
No
Note
The first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.
In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled:
<image>
In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher:
<image>
In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
<image> | #! /usr/local/bin/python3
def untangle(joints):
tangled = []
for joint in joints:
if len(tangled) == 0 or tangled[-1] != joint:
tangled.append(joint)
else:
tangled.pop()
return len(tangled) == 0
joints = input()
if untangle(joints):
print('Yes')
else:
print('No')
| {
"input": [
"++\n",
"+-\n",
"-++-\n",
"-\n"
],
"output": [
"Yes\n",
"No\n",
"Yes\n",
"No\n"
]
} |
2,893 | 7 | Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs ai rubles. Only one person can hang clothes on one hook.
Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price (if there are multiple such hooks, he chooses any of them). However if the moment a guest arrives the rack has no available hooks, Sereja must pay a d ruble fine to the guest.
Help Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, all hooks on the rack are available, all guests come at different time, nobody besides the m guests is visiting Sereja's restaurant tonight.
Input
The first line contains two integers n and d (1 β€ n, d β€ 100). The next line contains integers a1, a2, ..., an (1 β€ ai β€ 100). The third line contains integer m (1 β€ m β€ 100).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
2 1
2 1
2
Output
3
Input
2 1
2 1
10
Output
-5
Note
In the first test both hooks will be used, so Sereja gets 1 + 2 = 3 rubles.
In the second test both hooks will be used but Sereja pays a fine 8 times, so the answer is 3 - 8 = - 5. | #!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, d = readln()
a = sorted(readln())
m, = readln()
if m <= n:
print(sum(a[:m]))
else:
print(sum(a) - (m - n) * d)
| {
"input": [
"2 1\n2 1\n2\n",
"2 1\n2 1\n10\n"
],
"output": [
"3\n",
"-5\n"
]
} |
2,894 | 8 | Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.
A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1 β€ v β€ ai; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal bi. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes xi and yi (xi + yi = bi) correspondingly, Sereja's joy rises by xiΒ·yi.
Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!
Input
The first line of the input contains integer n (1 β€ n β€ 105) β the number of notes in the song. The second line contains n integers ai (1 β€ ai β€ 106). The third line contains n integers bi (1 β€ bi β€ 106).
Output
In a single line print an integer β the maximum possible joy Sereja feels after he listens to a song.
Examples
Input
3
1 1 2
2 2 3
Output
4
Input
1
2
5
Output
-1
Note
In the first sample, Dima and Inna play the first two notes at volume 1 (1 + 1 = 2, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1Β·1 + 1Β·1 + 1Β·2 = 4.
In the second sample, there is no such pair (x, y), that 1 β€ x, y β€ 2, x + y = 5, so Dima and Inna skip a note. Sereja's total joy equals -1. | n = int(input())
a = list(map(int, input().strip().split()))
b = list(map(int, input().strip().split()))
def vol(x, y):
if 2 * x >= y:
a = y // 2
return a * (y - a) or -1
else:
return -1
print(sum(map(vol, a, b)))
| {
"input": [
"3\n1 1 2\n2 2 3\n",
"1\n2\n5\n"
],
"output": [
"4\n",
"-1\n"
]
} |
2,895 | 7 | The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.
Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.
Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
Input
The first line contains two integers, n and k (1 β€ k β€ n β€ 100) β the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.
Output
In t lines, print the actions the programmers need to make. In the i-th line print:
* "LEFT" (without the quotes), if the i-th action was "move the ladder to the left";
* "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right";
* "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder".
The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.
Examples
Input
2 2
R1
Output
PRINT 1
LEFT
PRINT R
Input
2 1
R1
Output
PRINT R
RIGHT
PRINT 1
Input
6 4
GO?GO!
Output
RIGHT
RIGHT
PRINT !
LEFT
PRINT O
LEFT
PRINT G
LEFT
PRINT ?
LEFT
PRINT O
LEFT
PRINT G
Note
Note that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character. | def main():
n, k = map(int, input().split())
s = input()
if k - 1 <= n - k:
for i in range(k - 1):
print("LEFT")
for i in range(n - 1):
print("PRINT", s[i])
print("RIGHT")
print("PRINT", s[n - 1])
else:
for i in range(n - k):
print("RIGHT")
for i in range(n - 1, 0, -1):
print("PRINT", s[i])
print("LEFT")
print("PRINT", s[0])
main() | {
"input": [
"2 1\nR1\n",
"2 2\nR1\n",
"6 4\nGO?GO!\n"
],
"output": [
"PRINT R\nRIGHT\nPRINT 1\n",
"PRINT 1\nLEFT\nPRINT R\n",
"RIGHT\nRIGHT\nPRINT !\nLEFT\nPRINT O\nLEFT\nPRINT G\nLEFT\nPRINT ?\nLEFT\nPRINT O\nLEFT\nPRINT G\n"
]
} |
2,896 | 9 | Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?
Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).
If it is possible to partition the array, also give any possible way of valid partitioning.
Input
The first line will contain three space separated integers n, k, p (1 β€ k β€ n β€ 105; 0 β€ p β€ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 β€ ai β€ 109).
Output
In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes).
If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum.
As there can be multiple partitions, you are allowed to print any valid partition.
Examples
Input
5 5 3
2 6 10 5 9
Output
YES
1 9
1 5
1 10
1 6
1 2
Input
5 5 3
7 14 2 9 5
Output
NO
Input
5 3 1
1 2 3 7 5
Output
YES
3 5 1 3
1 7
1 2 | from sys import exit
def numline(f = int):
return map(f, input().split())
n, k, p = numline()
a = numline()
b = [[], []]
for i in a:
b[i % 2].append(i)
if (len(b[1]) + k - p) % 2 == 1 or len(b[1]) < k - p:
print("NO")
exit(0)
ol = [[] for i in range(p)] + [[b[1][i]] for i in range(k - p)]
cl = 0
for i in range(k - p, len(b[1]), 2):
ol[cl].append(b[1][i])
ol[cl].append(b[1][i + 1])
cl = (cl + 1) % k
for i in b[0]:
ol[cl].append(i)
cl = (cl + 1) % k
for i in ol:
if len(i) > 0:
continue
print("NO")
exit(0)
print("YES")
for i in ol:
print(" ".join(map(str, [len(i)] + i))) | {
"input": [
"5 5 3\n7 14 2 9 5\n",
"5 3 1\n1 2 3 7 5\n",
"5 5 3\n2 6 10 5 9\n"
],
"output": [
"NO\n",
"YES\n1 1\n1 3\n3 7 5 2\n",
"YES\n1 5\n1 9\n1 2\n1 6\n1 10 \n"
]
} |
2,897 | 10 | While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 β€ n β€ 2Β·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa | import sys
from collections import defaultdict, Counter
def q() :
print("NO")
exit()
N = int(sys.stdin.readline())
node = defaultdict(list)
counter = Counter()
for i in range(N) :
s = sys.stdin.readline()
n1,n2 = s[:2],s[1:3]
if i == 0 : start = n1
node[n1].append(n2)
counter[n1]+=1
counter[n2]-=1
st = en = False
for key, val in counter.items():
if val > 1: q()
if val == 1:
if st: q()
st, start = True, key
if val == -1:
if en: q()
en = True
if st != en: q()
S = [start]
ans = []
while S:
s = S[-1]
if node[s]:
S.append(node[s].pop())
else:
S.pop()
ans.append(s[1])
ans.append(start[0])
ans.reverse()
if len(ans) == N+2 :
print("YES")
print("".join(ans))
else :
print("NO") | {
"input": [
"4\nabc\nbCb\ncb1\nb13\n",
"7\naaa\naaa\naaa\naaa\naaa\naaa\naaa\n",
"5\naca\naba\naba\ncab\nbac\n"
],
"output": [
"NO\n",
"YES\naaaaaaaaa\n",
"YES\nabacaba\n"
]
} |
2,898 | 9 | The GCD table G of size n Γ n for an array of positive integers a of length n is defined by formula
<image>
Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:
<image>
Given all the numbers of the GCD table G, restore array a.
Input
The first line contains number n (1 β€ n β€ 500) β the length of array a. The second line contains n2 space-separated numbers β the elements of the GCD table of G for array a.
All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
Output
In the single line print n positive integers β the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
Examples
Input
4
2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
Output
4 3 6 2
Input
1
42
Output
42
Input
2
1 1 1 1
Output
1 1 | def gcd(a,b):
while b: a,b=b,a%b
return a
n=int(input())
l=list(map(int,input().split()))
m={}
ans=[]
for x in l: m[x]=m.get(x,0)+1
for x in sorted(m.keys())[::-1]:
while m[x]:
for y in ans: m[gcd(x,y)]-=2
ans+=[x]
m[x]-=1
print(' '.join(map(str,ans))) | {
"input": [
"2\n1 1 1 1\n",
"1\n42\n",
"4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2\n"
],
"output": [
"1 1 ",
"42",
"6 4 3 2 "
]
} |
2,899 | 9 | Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.
He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.
Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.
For example, suppose Mikhail is suggested to work on three projects and a1 = 6, b1 = 2, a2 = 1, b2 = 3, a3 = 2, b3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1Β·2.5 + a2Β·0 + a3Β·2.5 = 6Β·2.5 + 1Β·0 + 2Β·2.5 = 20 and b1Β·2.5 + b2Β·0 + b3Β·2.5 = 2Β·2.5 + 3Β·0 + 6Β·2.5 = 20.
Input
The first line of the input contains three integers n, p and q (1 β€ n β€ 100 000, 1 β€ p, q β€ 1 000 000) β the number of projects and the required number of experience and money.
Each of the next n lines contains two integers ai and bi (1 β€ ai, bi β€ 1 000 000) β the daily increase in experience and daily income for working on the i-th project.
Output
Print a real value β the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.
Examples
Input
3 20 20
6 2
1 3
2 6
Output
5.000000000000000
Input
4 1 1
2 3
3 2
2 3
3 2
Output
0.400000000000000
Note
First sample corresponds to the example in the problem statement. | from fractions import Fraction
def higher(x1, y1, x2, y2):
if x1 == 0:
if x2 == 0:
return
def min_days(p, q, pr):
ma = max(a for a, b in pr)
mb = max(b for a, b in pr)
pr.sort(key=lambda t: (t[0], -t[1]))
ch = [(0, mb)]
for a, b in pr:
if a == ch[-1][0]:
continue
while (
len(ch) >= 2
and ((b-ch[-2][1])*(ch[-1][0]-ch[-2][0])
>= (a-ch[-2][0])*(ch[-1][1]-ch[-2][1]))
):
ch.pop()
ch.append((a, b))
ch.append((ma, 0))
a1, b1 = None, None
for a2, b2 in ch:
if a1 is not None:
d = (a2-a1)*q + (b1-b2)*p
s = Fraction(b1*p-a1*q, d)
if 0 <= s <= 1:
return Fraction(d, a2*b1 - a1*b2)
a1, b1 = a2, b2
if __name__ == '__main__':
n, p, q = map(int, input().split())
pr = []
for _ in range(n):
a, b = map(int, input().split())
pr.append((a, b))
print("{:.7f}".format(float(min_days(p, q, pr))))
| {
"input": [
"3 20 20\n6 2\n1 3\n2 6\n",
"4 1 1\n2 3\n3 2\n2 3\n3 2\n"
],
"output": [
"5.0000000",
"0.4000000"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.