index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
0 | 11 | There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.
We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:
* Either this person does not go on the trip,
* Or at least k of his friends also go on the trip.
Note that the friendship is not transitive. That is, if a and b are friends and b and c are friends, it does not necessarily imply that a and c are friends.
For each day, find the maximum number of people that can go on the trip on that day.
Input
The first line contains three integers n, m, and k (2 β€ n β€ 2 β
10^5, 1 β€ m β€ 2 β
10^5, 1 β€ k < n) β the number of people, the number of days and the number of friends each person on the trip should have in the group.
The i-th (1 β€ i β€ m) of the next m lines contains two integers x and y (1β€ x, yβ€ n, xβ y), meaning that persons x and y become friends on the morning of day i. It is guaranteed that x and y were not friends before.
Output
Print exactly m lines, where the i-th of them (1β€ iβ€ m) contains the maximum number of people that can go on the trip on the evening of the day i.
Examples
Input
4 4 2
2 3
1 2
1 3
1 4
Output
0
0
3
3
Input
5 8 2
2 1
4 2
5 4
5 2
4 3
5 1
4 1
3 2
Output
0
0
0
3
3
4
4
5
Input
5 7 2
1 5
3 2
2 5
3 4
1 2
5 3
1 3
Output
0
0
0
0
3
4
4
Note
In the first example,
* 1,2,3 can go on day 3 and 4.
In the second example,
* 2,4,5 can go on day 4 and 5.
* 1,2,4,5 can go on day 6 and 7.
* 1,2,3,4,5 can go on day 8.
In the third example,
* 1,2,5 can go on day 5.
* 1,2,3,5 can go on day 6 and 7. | from collections import deque
def solve(adj, m, k, uv):
n = len(adj)
nn = [len(a) for a in adj]
q = deque()
for i in range(n):
if nn[i] < k:
q.append(i)
while q:
v = q.popleft()
for u in adj[v]:
nn[u] -= 1
if nn[u] == k-1:
q.append(u)
res = [0]*m
nk = len([1 for i in nn if i >= k])
res[-1] = nk
for i in range(m-1, 0, -1):
u1, v1 = uv[i]
if nn[u1] < k or nn[v1] < k:
res[i - 1] = nk
continue
if nn[u1] == k:
q.append(u1)
nn[u1] -= 1
if not q and nn[v1] == k:
q.append(v1)
nn[v1] -= 1
if not q:
nn[u1] -= 1
nn[v1] -= 1
adj[u1].remove(v1)
adj[v1].remove(u1)
while q:
v = q.popleft()
nk -= 1
for u in adj[v]:
nn[u] -= 1
if nn[u] == k - 1:
q.append(u)
res[i - 1] = nk
return res
n, m, k = map(int, input().split())
a = [set() for i in range(n)]
uv = []
for i in range(m):
u, v = map(int, input().split())
a[u - 1].add(v - 1)
a[v - 1].add(u - 1)
uv.append((u-1, v-1))
res = solve(a, m, k, uv)
print(str(res)[1:-1].replace(' ', '').replace(',', '\n')) | {
"input": [
"4 4 2\n2 3\n1 2\n1 3\n1 4\n",
"5 8 2\n2 1\n4 2\n5 4\n5 2\n4 3\n5 1\n4 1\n3 2\n",
"5 7 2\n1 5\n3 2\n2 5\n3 4\n1 2\n5 3\n1 3\n"
],
"output": [
"0\n0\n3\n3\n",
"0\n0\n0\n3\n3\n4\n4\n5\n",
"0\n0\n0\n0\n3\n4\n4\n"
]
} |
1 | 7 | Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have n cards with digits, and you want to use them to make as many phone numbers as possible. Each card must be used in at most one phone number, and you don't have to use all cards. The phone numbers do not necessarily have to be distinct.
Input
The first line contains an integer n β the number of cards with digits that you have (1 β€ n β€ 100).
The second line contains a string of n digits (characters "0", "1", ..., "9") s_1, s_2, β¦, s_n. The string will not contain any other characters, such as leading or trailing spaces.
Output
If at least one phone number can be made from these cards, output the maximum number of phone numbers that can be made. Otherwise, output 0.
Examples
Input
11
00000000008
Output
1
Input
22
0011223344556677889988
Output
2
Input
11
31415926535
Output
0
Note
In the first example, one phone number, "8000000000", can be made from these cards.
In the second example, you can make two phone numbers from the cards, for example, "80123456789" and "80123456789".
In the third example you can't make any phone number from the given cards. | n=int(input())
s=input()
def ct():
c=0
for d in s:
if d=='8':
c+=1
return c
c=ct()
m=n//11
print(min(m,c))
| {
"input": [
"22\n0011223344556677889988\n",
"11\n00000000008\n",
"11\n31415926535\n"
],
"output": [
"2\n",
"1\n",
"0\n"
]
} |
2 | 7 | You are given q queries in the following form:
Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].
Can you answer all the queries?
Recall that a number x belongs to segment [l, r] if l β€ x β€ r.
Input
The first line contains one integer q (1 β€ q β€ 500) β the number of queries.
Then q lines follow, each containing a query given in the format l_i r_i d_i (1 β€ l_i β€ r_i β€ 10^9, 1 β€ d_i β€ 10^9). l_i, r_i and d_i are integers.
Output
For each query print one integer: the answer to this query.
Example
Input
5
2 4 2
5 10 4
3 10 1
1 2 3
4 6 5
Output
6
4
1
3
10 | q=int(input())
def f(l,r,d):
if d<l or d>r:return d
return d*(int(r/d)+1)
for k in range(q):
l,r,d=map(int,input().split())
print(f(l,r,d)) | {
"input": [
"5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5\n"
],
"output": [
"6\n4\n1\n3\n10\n"
]
} |
3 | 10 | Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 β€ n β€ 10^5) β the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 β€ u, v β€ n, u β v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | def ii():
return int(input())
def ss():
return [x for x in input()]
def si():
return [int(x) for x in input().split()]
def mi():
return map(int, input().split())
a = ii()
s = [0 for i in range(a)]
for i in range(a - 1):
c, d = [int(x) - 1 for x in input().split()]
s[c] += 1
s[d] += 1
if 2 in s:
print("NO")
else:
print("YES") | {
"input": [
"2\n1 2\n",
"3\n1 2\n2 3\n",
"5\n1 2\n1 3\n1 4\n2 5\n",
"6\n1 2\n1 3\n1 4\n2 5\n2 6\n"
],
"output": [
"YES",
"NO",
"NO",
"YES"
]
} |
4 | 10 | An array of integers p_{1},p_{2}, β¦,p_{n} is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4].
There is a hidden permutation of length n.
For each index i, you are given s_{i}, which equals to the sum of all p_{j} such that j < i and p_{j} < p_{i}. In other words, s_i is the sum of elements before the i-th element that are smaller than the i-th element.
Your task is to restore the permutation.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^{5}) β the size of the permutation.
The second line contains n integers s_{1}, s_{2}, β¦, s_{n} (0 β€ s_{i} β€ (n(n-1))/(2)).
It is guaranteed that the array s corresponds to a valid permutation of length n.
Output
Print n integers p_{1}, p_{2}, β¦, p_{n} β the elements of the restored permutation. We can show that the answer is always unique.
Examples
Input
3
0 0 0
Output
3 2 1
Input
2
0 1
Output
1 2
Input
5
0 1 1 1 10
Output
1 4 3 2 5
Note
In the first example for each i there is no index j satisfying both conditions, hence s_i are always 0.
In the second example for i = 2 it happens that j = 1 satisfies the conditions, so s_2 = p_1.
In the third example for i = 2, 3, 4 only j = 1 satisfies the conditions, so s_2 = s_3 = s_4 = 1. For i = 5 all j = 1, 2, 3, 4 are possible, so s_5 = p_1 + p_2 + p_3 + p_4 = 10. | NN = 18
BIT=[0]*(2**NN+1)
def addbit(i, x):
while i <= 2**NN:
BIT[i] += x
i += i & (-i)
def getsum(i):
ret = 0
while i != 0:
ret += BIT[i]
i -= i&(-i)
return ret
def searchbit(x):
l, sl = 0, 0
d = 2**(NN-1)
while d:
m = l + d
sm = sl + BIT[m]
if sm <= x:
l, sl = m, sm
d //= 2
return l
N = int(input())
A = [int(a) for a in input().split()]
for i in range(1, N+1):
addbit(i, i)
ANS = []
for s in A[::-1]:
a = searchbit(s) + 1
addbit(a, -a)
ANS.append(a)
print(*ANS[::-1]) | {
"input": [
"3\n0 0 0\n",
"5\n0 1 1 1 10\n",
"2\n0 1\n"
],
"output": [
"3 2 1 ",
"1 4 3 2 5 ",
"1 2 "
]
} |
5 | 10 | This is the easier version of the problem. In this version 1 β€ n, m β€ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 β€ k β€ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 β€ t β€ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 β€ n β€ 100) β the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The third line contains an integer m (1 β€ m β€ 100) β the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j) β the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 β€ r_j β€ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,10]. | def main():
n = int(input())
a = list(enumerate(map(int, (input().split()))))
a.sort(key = lambda item: (item[1], -item[0]))
#print(a)
m = int(input())
for i in range(m):
k, pos = map(int, input().split())
s = a[-k:]
s = sorted(s)
print(s[pos - 1][1])
main() | {
"input": [
"3\n10 20 10\n6\n1 1\n2 1\n2 2\n3 1\n3 2\n3 3\n",
"7\n1 2 1 3 1 2 1\n9\n2 1\n2 2\n3 1\n3 2\n3 3\n1 1\n7 1\n7 7\n7 4\n"
],
"output": [
"20\n10\n20\n10\n20\n10\n",
"2\n3\n2\n3\n2\n3\n1\n1\n3\n"
]
} |
6 | 11 | 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": [
"3\n1 2 3\n",
"5\n5 4 3 2 1\n"
],
"output": [
"0 0 0\n",
"0 1 3 6 10\n"
]
} |
7 | 11 | There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1).
You're given k subsets A_1, β¦, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 β€ i_1 < i_2 < i_3 β€ k, A_{i_1} β© A_{i_2} β© A_{i_3} = β
.
In one operation, you can choose one of these k subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.
Let m_i be the minimum number of operations you have to do in order to make the i first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1 and n), they can be either off or on.
You have to compute m_i for all 1 β€ i β€ n.
Input
The first line contains two integers n and k (1 β€ n, k β€ 3 β
10^5).
The second line contains a binary string of length n, representing the initial state of each lamp (the lamp i is off if s_i = 0, on if s_i = 1).
The description of each one of the k subsets follows, in the following format:
The first line of the description contains a single integer c (1 β€ c β€ n) β the number of elements in the subset.
The second line of the description contains c distinct integers x_1, β¦, x_c (1 β€ x_i β€ n) β the elements of the subset.
It is guaranteed that:
* The intersection of any three subsets is empty;
* It's possible to make all lamps be simultaneously on using some operations.
Output
You must output n lines. The i-th line should contain a single integer m_i β the minimum number of operations required to make the lamps 1 to i be simultaneously on.
Examples
Input
7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
Output
1
2
3
3
3
3
3
Input
8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
Output
1
1
1
1
1
1
4
4
Input
5 3
00011
3
1 2 3
1
4
3
3 4 5
Output
1
1
1
1
1
Input
19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
Output
0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
Note
In the first example:
* For i = 1, we can just apply one operation on A_1, the final states will be 1010110;
* For i = 2, we can apply operations on A_1 and A_3, the final states will be 1100110;
* For i β₯ 3, we can apply operations on A_1, A_2 and A_3, the final states will be 1111111.
In the second example:
* For i β€ 6, we can just apply one operation on A_2, the final states will be 11111101;
* For i β₯ 7, we can apply operations on A_1, A_3, A_4, A_6, the final states will be 11111111. | from sys import stdin
input = stdin.readline
n , k = [int(i) for i in input().split()]
pairs = [i + k for i in range(k)] + [i for i in range(k)]
initial_condition = list(map(lambda x: x == '1',input().strip()))
data = [i for i in range(2*k)]
constrain = [-1] * (2*k)
h = [0] * (2*k)
L = [1] * k + [0] * k
dp1 = [-1 for i in range(n)]
dp2 = [-1 for i in range(n)]
for i in range(k):
input()
inp = [int(j) for j in input().split()]
for s in inp:
if dp1[s-1] == -1:dp1[s-1] = i
else:dp2[s-1] = i
pfsums = 0
ans = []
def remove_pfsum(s1):
global pfsums
if constrain[s1] == 1:
pfsums -= L[s1]
elif constrain[pairs[s1]] == 1:
pfsums -= L[pairs[s1]]
else:
pfsums -= min(L[s1],L[pairs[s1]])
def sh(i):
while i != data[i]:
i = data[i]
return i
def upd_pfsum(s1):
global pfsums
if constrain[s1] == 1:
pfsums += L[s1]
elif constrain[pairs[s1]] == 1:
pfsums += L[pairs[s1]]
else:
pfsums += min(L[s1],L[pairs[s1]])
def ms(i,j):
i = sh(i) ; j = sh(j)
cons = max(constrain[i],constrain[j])
if h[i] < h[j]:
data[i] = j
L[j] += L[i]
constrain[j] = cons
return j
else:
data[j] = i
if h[i] == h[j]:
h[i] += 1
L[i] += L[j]
constrain[i] = cons
return i
for i in range(n):
if dp1[i] == -1 and dp2[i] == -1:
pass
elif dp2[i] == -1:
s1 = sh(dp1[i])
remove_pfsum(s1)
constrain[s1] = 0 if initial_condition[i] else 1
constrain[pairs[s1]] = 1 if initial_condition[i] else 0
upd_pfsum(s1)
else:
s1 = sh(dp1[i]) ; s2 = sh(dp2[i])
if s1 == s2 or pairs[s1] == s2:
pass
else:
remove_pfsum(s1)
remove_pfsum(s2)
if initial_condition[i]:
new_s1 = ms(s1,s2)
new_s2 = ms(pairs[s1],pairs[s2])
else:
new_s1 = ms(s1,pairs[s2])
new_s2 = ms(pairs[s1],s2)
pairs[new_s1] = new_s2
pairs[new_s2] = new_s1
upd_pfsum(new_s1)
ans.append(pfsums)
for i in ans:
print(i)
| {
"input": [
"5 3\n00011\n3\n1 2 3\n1\n4\n3\n3 4 5\n",
"8 6\n00110011\n3\n1 3 8\n5\n1 2 5 6 7\n2\n6 8\n2\n3 5\n2\n4 7\n1\n2\n",
"19 5\n1001001001100000110\n2\n2 3\n2\n5 6\n2\n8 9\n5\n12 13 14 15 16\n1\n19\n",
"7 3\n0011100\n3\n1 4 6\n3\n3 4 7\n2\n2 3\n"
],
"output": [
"1\n1\n1\n1\n1\n",
"1\n1\n1\n1\n1\n1\n4\n4\n",
"0\n1\n1\n1\n2\n2\n2\n3\n3\n3\n3\n4\n4\n4\n4\n4\n4\n4\n5\n",
"1\n2\n3\n3\n3\n3\n3\n"
]
} |
8 | 12 | There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t β
v_i.
Consider two points i and j. Let d(i, j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points i and j coincide at some moment, the value d(i, j) will be 0.
Your task is to calculate the value β_{1 β€ i < j β€ n} d(i, j) (the sum of minimum distances over all pairs of points).
Input
The first line of the input contains one integer n (2 β€ n β€ 2 β
10^5) β the number of points.
The second line of the input contains n integers x_1, x_2, ..., x_n (1 β€ x_i β€ 10^8), where x_i is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct.
The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 β€ v_i β€ 10^8), where v_i is the speed of the i-th point.
Output
Print one integer β the value β_{1 β€ i < j β€ n} d(i, j) (the sum of minimum distances over all pairs of points).
Examples
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0 | # BIT
def add(bit, x, v):
while x < len(bit):
bit[x] += v
x += x & (-x)
def query(bit, x):
ans = 0
while x > 0:
ans += bit[x]
x -= x & (-x)
return ans
def relabel(arr):
srt = sorted(set(arr))
mp = {v:k for k, v in enumerate(srt, 1)}
arr = [mp[a] for a in arr]
return arr
# main
n = int(input())
x = list(map(int, input().split()))
v = relabel(list(map(int, input().split())))
arr = sorted(list(zip(x, v)));
ans = 0
bitSum = [0]*(n+1)
bitCnt = [0]*(n+1)
for x, v in arr:
ans += query(bitCnt, v)*x - query(bitSum, v)
add(bitSum, v, x)
add(bitCnt, v, 1)
print(ans)
| {
"input": [
"3\n1 3 2\n-100 2 3\n",
"2\n2 1\n-3 0\n",
"5\n2 1 4 3 5\n2 2 2 3 4\n"
],
"output": [
"3\n",
"0\n",
"19\n"
]
} |
9 | 10 | You are given a complete directed graph K_n with n vertices: each pair of vertices u β v in K_n have both directed edges (u, v) and (v, u); there are no self-loops.
You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices).
We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, ..., v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 β a visiting order, where each (v_i, v_{i + 1}) occurs exactly once.
Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.
Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, ..., v_r.
Input
The first line contains the single integer T (1 β€ T β€ 100) β the number of test cases.
Next T lines contain test cases β one per line. The first and only line of each test case contains three integers n, l and r (2 β€ n β€ 10^5, 1 β€ l β€ r β€ n(n - 1) + 1, r - l + 1 β€ 10^5) β the number of vertices in K_n, and segment of the cycle to print.
It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5.
Output
For each test case print the segment v_l, v_{l + 1}, ..., v_r of the lexicographically smallest cycle that visits every edge exactly once.
Example
Input
3
2 1 3
3 3 6
99995 9998900031 9998900031
Output
1 2 1
1 3 2 3
1
Note
In the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1.
In the third test case, it's quite obvious that the cycle should start and end in vertex 1. | def find(a):
global k, tot
if a > n * (n - 1):
return 1
while a > tot + (n - k) * 2:
tot += (n - k) * 2
k += 1
if a & 1:
return k
return (a - tot) // 2 + k
for _ in range(int(input())):
n, l, r = map(int, input().split())
global k, tot
k = 1
tot = 0
li = []
for i in range(l, r + 1):
li.append(find(i))
print(*li)
| {
"input": [
"3\n2 1 3\n3 3 6\n99995 9998900031 9998900031\n"
],
"output": [
"1 2 1 \n1 3 2 3 \n1 \n"
]
} |
10 | 12 | Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.
Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions can be summoned in any order.
Unfortunately, Polycarp cannot have more than k minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.
Polycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).
Help Polycarp to make up a plan of actions to summon the strongest possible army!
Input
The first line contains one integer T (1 β€ T β€ 75) β the number of test cases.
Each test case begins with a line containing two integers n and k (1 β€ k β€ n β€ 75) β the number of minions availible for summoning, and the maximum number of minions that can be controlled by Polycarp, respectively.
Then n lines follow, the i-th line contains 2 integers a_i and b_i (1 β€ a_i β€ 10^5, 0 β€ b_i β€ 10^5) β the parameters of the i-th minion.
Output
For each test case print the optimal sequence of actions as follows:
Firstly, print m β the number of actions which Polycarp has to perform (0 β€ m β€ 2n). Then print m integers o_1, o_2, ..., o_m, where o_i denotes the i-th action as follows: if the i-th action is to summon the minion x, then o_i = x, and if the i-th action is to destroy the minion x, then o_i = -x. Each minion can be summoned at most once and cannot be destroyed before being summoned (and, obviously, cannot be destroyed more than once). The number of minions in Polycarp's army should be not greater than k after every action.
If there are multiple optimal sequences, print any of them.
Example
Input
3
5 2
5 3
7 0
5 0
4 0
10 0
2 1
10 100
50 10
5 5
1 5
2 4
3 3
4 2
5 1
Output
4
2 1 -1 5
1
2
5
5 4 3 2 1
Note
Consider the example test.
In the first test case, Polycarp can summon the minion 2 with power level 7, then summon the minion 1, which will increase the power level of the previous minion by 3, then destroy the minion 1, and finally, summon the minion 5. After this, Polycarp will have two minions with power levels of 10.
In the second test case, Polycarp can control only one minion, so he should choose the strongest of them and summon it.
In the third test case, Polycarp is able to summon and control all five minions. | def read_int():
return int(input())
def read_ints():
return map(int, input().split(' '))
t = read_int()
for case_num in range(t):
n, k = read_ints()
p = []
for i in range(n):
ai, bi = read_ints()
p.append((bi, ai, i + 1))
p.sort()
dp = [[0 for j in range(k + 1)] for i in range(n + 1)]
use = [[False for j in range(k + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(min(i, k) + 1):
if i - 1 >= j:
dp[i][j] = dp[i - 1][j] + (k - 1) * p[i - 1][0]
if j > 0:
x = dp[i - 1][j - 1] + (j - 1) * p[i - 1][0] + p[i - 1][1]
if x > dp[i][j]:
dp[i][j] = x
use[i][j] = True
used = []
curr = k
for i in range(n, 0, -1):
if use[i][curr]:
used.append(p[i - 1][2])
curr -= 1
used.reverse()
seq = used[:-1]
st = set(used)
for i in range(1, n + 1):
if not i in st:
seq.append(i)
seq.append(-i)
seq.append(used[-1])
print(len(seq))
print(' '.join(map(str, seq)))
| {
"input": [
"3\n5 2\n5 3\n7 0\n5 0\n4 0\n10 0\n2 1\n10 100\n50 10\n5 5\n1 5\n2 4\n3 3\n4 2\n5 1\n"
],
"output": [
"8\n2 3 -3 4 -4 1 -1 5\n3\n1 -1 2\n5\n5 4 3 2 1\n"
]
} |
11 | 11 | Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.
Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.
There are n books in the family library. The i-th book is described by three integers: t_i β the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not).
So they need to choose some books from the given n books in such a way that:
* Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set;
* the total reading time of these books is minimized (they are children and want to play and joy as soon a possible).
The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set.
Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5).
The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 β€ t_i β€ 10^4, 0 β€ a_i, b_i β€ 1), where:
* t_i β the amount of time required for reading the i-th book;
* a_i equals 1 if Alice likes the i-th book and 0 otherwise;
* b_i equals 1 if Bob likes the i-th book and 0 otherwise.
Output
If there is no solution, print only one integer -1. Otherwise print one integer T β the minimum total reading time of the suitable set of books.
Examples
Input
8 4
7 1 1
2 1 1
4 0 1
8 1 1
1 0 1
1 1 1
1 0 1
3 0 0
Output
18
Input
5 2
6 0 0
9 0 0
1 0 1
2 1 1
5 1 0
Output
8
Input
5 3
3 0 0
2 1 0
3 1 0
5 0 1
3 0 1
Output
-1 | def read_ints():
line = input()
return [int(e) for e in line.strip().split(' ')]
n, k = read_ints()
a = []
b = []
t = []
for _ in range(n):
it, ia, ib = read_ints()
if ia == 1 and ib == 1:
t.append(it)
elif ia == 1:
a.append(it)
elif ib == 1:
b.append(it)
a.sort()
b.sort()
for i in range(min(len(a), len(b))):
t.append(a[i] + b[i])
t.sort()
print(-1 if len(t) < k else sum(t[:k]))
| {
"input": [
"8 4\n7 1 1\n2 1 1\n4 0 1\n8 1 1\n1 0 1\n1 1 1\n1 0 1\n3 0 0\n",
"5 2\n6 0 0\n9 0 0\n1 0 1\n2 1 1\n5 1 0\n",
"5 3\n3 0 0\n2 1 0\n3 1 0\n5 0 1\n3 0 1\n"
],
"output": [
"18\n",
"8\n",
"-1\n"
]
} |
12 | 7 | You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i β€ a_{i + 1}).
Find three indices i, j, k such that 1 β€ i < j < k β€ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains one integer n (3 β€ n β€ 5 β
10^4) β the length of the array a.
The second line of each test case contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ 10^9; a_{i - 1} β€ a_i) β the array a.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case print the answer to it in one line.
If there is a triple of indices i, j, k (i < j < k) such that it is impossible to construct a non-degenerate triangle having sides equal to a_i, a_j and a_k, print that three indices in ascending order. If there are multiple answers, print any of them.
Otherwise, print -1.
Example
Input
3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000
Output
2 3 6
-1
1 2 3
Note
In the first test case it is impossible with sides 6, 11 and 18. Note, that this is not the only correct answer.
In the second test case you always can construct a non-degenerate triangle. | def main():
for _ in range(int(input())):
s = int(input())
l = [int(i) for i in input().split()]
if l[0] + l[1] > l[-1]:
print(-1)
else:
print(1,2, s)
main()
# | {
"input": [
"3\n7\n4 6 11 11 15 18 20\n4\n10 10 10 11\n3\n1 1 1000000000\n"
],
"output": [
"1 2 7\n-1\n1 2 3\n"
]
} |
13 | 8 | Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.
Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.
For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)
The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).
We can show that there always exists a solution for the given constraints.
Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 50). Description of the test cases follows.
The first line of each test case contains one integers n (3 β€ n β€ 200).
The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.
The sum of values of n doesn't exceed 200.
Output
For each test case output on the first line an integer c (0 β€ c β€ 2) β the number of inverted cells.
In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).
Example
Input
3
4
S010
0001
1000
111F
3
S10
101
01F
5
S0101
00000
01111
11111
0001F
Output
1
3 4
2
1 2
2 1
0
Note
For the first test case, after inverting the cell, we get the following grid:
S010
0001
1001
111F
| T=int(input())
for Tid in range(T):
n=int(input())
a=[]
for i in range(n):
a.append(input())
a0,a1,a2=[],[],[]
def add(x,y,c):
if a[x][y]==c:
a0.append([x+1,y+1])
else:
a1.append([x+1,y+1])
add(0,1,'0')
add(1,0,'0')
add(n-1,n-2,'1')
add(n-2,n-1,'1')
if len(a0)<len(a1):
a2=a0
else:
a2=a1
print(len(a2))
for i in range(len(a2)):
print(a2[i][0],a2[i][1]) | {
"input": [
"3\n4\nS010\n0001\n1000\n111F\n3\nS10\n101\n01F\n5\nS0101\n00000\n01111\n11111\n0001F\n"
],
"output": [
"1\n3 4\n2\n1 2\n2 1\n0\n"
]
} |
14 | 7 | Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9. | def arr_inp():
return [int(x) for x in input().split()]
r, c, d = [arr_inp() for i in range(3)]
C=((c[0]-d[0]+r[1])/2)
if(C!=int(C)):
exit(print(-1))
C=int(C)
D=r[1]-C
A=d[0]-D
B=r[0]-A
arr=[A,B,C,D]
if(min(arr)<1 or max(arr)>9 or A==B or A==C or A==D or B==C or B==D or C==D ):
exit(print(-1))
print(A,B)
print(C,D)
| {
"input": [
"1 2\n3 4\n5 6\n",
"11 10\n13 8\n5 16\n",
"3 7\n4 6\n5 5\n",
"10 10\n10 10\n10 10\n"
],
"output": [
"-1\n",
"4 7\n9 1\n",
"1 2\n3 4\n",
"-1\n"
]
} |
15 | 12 | You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector. | import sys
input = sys.stdin.buffer.readline
def _find(s, u):
p = []
while s[u] != u:
p.append(u)
u = s[u]
for v in p: s[v] = u
return u
def _union(s, u, v):
su, sv = _find(s, u), _find(s, v)
if su != sv: s[su] = sv
n, m = map(int, input().split())
s, res = list(range(m+1)), []
for i in range(n):
p = list(map(int, input().split()))
if p[0] == 1:
u, v = 0, p[1]
else:
u, v = p[1], p[2]
su, sv = _find(s, u), _find(s, v)
if su != sv:
_union(s, su, sv)
res.append(i+1)
print(pow(2, len(res), 10**9+7), len(res))
print(*res)
| {
"input": [
"3 2\n1 1\n1 2\n2 2 1\n",
"3 5\n2 1 2\n1 3\n1 4\n",
"2 3\n2 1 3\n2 1 2\n"
],
"output": [
"\n4 2\n1 2 \n",
"\n8 3\n1 2 3 \n",
"\n4 2\n1 2 \n"
]
} |
16 | 9 | You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4. | import sys
def inp():
return sys.stdin.readline().rstrip()
p=1_000_000_007
t = int(inp())
rec = [1]*200_010
for i in range(10):
rec[i] = 1
for i in range(10,200_010):
rec[i] = (rec[i-9] + rec[i-10])%p
for z in range(t):
n,m = inp().split()
m = int(m)
res = 0
for c in n:
res = (res+rec[m+int(c)])%p
print(res)
| {
"input": [
"5\n1912 1\n5 6\n999 1\n88 2\n12 100\n"
],
"output": [
"\n5\n2\n6\n4\n2115\n"
]
} |
17 | 9 | This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2. | def putin():
return map(int, input().split())
def sol():
n = int(input())
C = list(putin())
B = list(putin())
q = int(input())
x = int(input())
min_arr = [x]
min_part_sums = [x]
part_sums = [C[0]]
for i in range(1, n):
part_sums.append(part_sums[-1] + C[i])
for elem in B:
min_arr.append(min_arr[-1] + elem)
min_part_sums.append(min_arr[-1] + min_part_sums[-1])
for i in range(n):
if min_part_sums[i] > part_sums[i]:
return 0
if min_part_sums[0] > C[0]:
return 0
answer = [1] * (part_sums[0] - max(0, min_part_sums[0]) + 1)
for k in range(1, n):
new_answer = [0] * (part_sums[k] - max(0, min_part_sums[k]) + 1)
cnt = 1
window = answer[-1]
new_answer[-1] = window
while cnt <= len(new_answer) - 1:
cnt += 1
if cnt <= len(answer):
window += answer[-cnt]
if C[k] + 1 < cnt:
window -= answer[C[k] + 1 - cnt]
new_answer[-cnt] = window
answer = new_answer.copy()
m = 10 ** 9 + 7
return sum(answer) % m
print(sol()) | {
"input": [
"3\n2 3 4\n2 1\n1\n-1\n"
],
"output": [
"56\n"
]
} |
18 | 7 | Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones. | def f(l):
n,x,y = l
return max((n*y+99)//100-x,0)
l = list(map(int,input().split()))
print(f(l))
| {
"input": [
"1000 352 146\n",
"10 1 14\n",
"20 10 50\n"
],
"output": [
"1108\n",
"1\n",
"0\n"
]
} |
19 | 8 | You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000 | from math import *
def kv():
q,w,e=map(int,input().split())
if (q==0) & (w==0) & (e==0):
print(-1)
elif (q==0) & (w==0):
print(0)
elif q==0:
print(1)
print("%.6f" % ((-e)/w))
else:
d=w*w-4*q*e
if d<0:
print('0')
elif d==0:
print('1')
print("%.6f" % ((-w)/(2*q)))
else:
print('2')
a=[((-w-sqrt(d))/(2*q)),((-w+sqrt(d))/(2*q))]
a.sort()
print("%.6f" % a[0])
print("%.6f" % a[1])
kv()
| {
"input": [
"1 -5 6\n"
],
"output": [
"2\n2.000000\n3.000000\n"
]
} |
20 | 8 | A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").
The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.
A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.
Notice, that any year between 2013 and 2015 is not a leap year.
Input
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
Output
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
Examples
Input
777-444---21-12-2013-12-2013-12-2013---444-777
Output
13-12-2013 | from re import compile
from collections import defaultdict
from time import strptime
def validDate(date):
try:
strptime(date, "%d-%m-%Y")
return True
except:
return False
myFormat = compile(r'(?=([0-2]\d|3[0-1])-(0\d|1[0-2])-(201[3-5]))' )
Dict = defaultdict(int)
for d in myFormat.finditer(input()):
temp = "-".join([d.group(1),d.group(2),d.group(3)])
if validDate (temp):
Dict[temp] = -~Dict[temp]
print(max(Dict, key=Dict.get)) | {
"input": [
"777-444---21-12-2013-12-2013-12-2013---444-777\n"
],
"output": [
"13-12-2013\n"
]
} |
21 | 8 | There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".
Find the number of cows that can currently show their hands without affecting any betting decisions.
Input
The first line contains a single integer, n (2 β€ n β€ 2Β·105). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".
Output
The first line should contain a single integer denoting the number of players that can currently show their hands.
Examples
Input
6
AFFAAA
Output
4
Input
3
AFI
Output
1
Note
In the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand. | from collections import Counter
def go():
n = int(input())
d = Counter()
for c in input():
d[c] += 1
if d['I'] == 0: return d['A']
elif d['I'] == 1: return 1
else: return 0
print(go())
| {
"input": [
"3\nAFI\n",
"6\nAFFAAA\n"
],
"output": [
"1",
"4"
]
} |
22 | 7 | Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
Input
The single line contains two integers, a and b (1 β€ a β€ 1000; 2 β€ b β€ 1000).
Output
Print a single integer β the number of hours Vasily can light up the room for.
Examples
Input
4 2
Output
7
Input
6 3
Output
8
Note
Consider the first sample. For the first four hours Vasily lights up new candles, then he uses four burned out candles to make two new ones and lights them up. When these candles go out (stop burning), Vasily can make another candle. Overall, Vasily can light up the room for 7 hours. | def f(a,b):
return (a-1)//(b-1)+a
if __name__ == '__main__':
a,b=map(int,input().split())
print(f(a,b))
| {
"input": [
"4 2\n",
"6 3\n"
],
"output": [
"7\n",
"8\n"
]
} |
23 | 8 | To celebrate the opening of the Winter Computer School the organizers decided to buy in n liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly a bottles 0.5 in volume, b one-liter bottles and c of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well).
Thus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly n liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer.
All the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind.
Input
The first line contains four integers β n, a, b, c (1 β€ n β€ 10000, 0 β€ a, b, c β€ 5000).
Output
Print the unique number β the solution to the problem. If it is impossible to buy exactly n liters of cola, print 0.
Examples
Input
10 5 5 5
Output
9
Input
3 0 0 2
Output
0 | def nik(rudy,pig,y,z):
temp = 0
for i in range(z+1):
for j in range(y+1):
t = rudy - i*2 -j
if t>=0 and pig*0.5 >= t:
temp+=1
print(temp)
rudy, pig, y, z = list(map(int,input().split()))
nik(rudy,pig,y,z)
| {
"input": [
"10 5 5 5\n",
"3 0 0 2\n"
],
"output": [
"9\n",
"0\n"
]
} |
24 | 8 | A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared β the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
Input
The first line of the input contains integer n (3 β€ n β€ 105) β the initial number of compilation errors.
The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the errors the compiler displayed for the first time.
The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 β the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.
The fourth line contains n - 2 space-separated integers Ρ1, Ρ2, ..., Ρn - 2 β the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.
Output
Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.
Examples
Input
5
1 5 8 123 7
123 7 5 1
5 1 7
Output
8
123
Input
6
1 4 3 3 5 7
3 7 5 4 3
4 3 7 5
Output
1
3
Note
In the first test sample B first corrects the error number 8, then the error number 123.
In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step. | input()
def d():
return sum(map(int, input().split()))
r = d(), d(), d()
print(r[0]-r[1])
print(r[1]-r[2])
| {
"input": [
"6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5\n",
"5\n1 5 8 123 7\n123 7 5 1\n5 1 7\n"
],
"output": [
"1\n3\n",
"8\n123\n"
]
} |
25 | 9 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of trees.
Next n lines contain pairs of integers xi, hi (1 β€ xi, hi β€ 109) β the coordinate and the height of the Ρ-th tree.
The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.
Output
Print a single number β the maximum number of trees that you can cut down by the given rules.
Examples
Input
5
1 2
2 1
5 10
10 9
19 1
Output
3
Input
5
1 2
2 1
5 10
10 9
20 1
Output
4
Note
In the first sample you can fell the trees like that:
* fell the 1-st tree to the left β now it occupies segment [ - 1;1]
* fell the 2-nd tree to the right β now it occupies segment [2;3]
* leave the 3-rd tree β it occupies point 5
* leave the 4-th tree β it occupies point 10
* fell the 5-th tree to the right β now it occupies segment [19;20]
In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | n=int(input())
l=[]
for _ in range(n):
l.append(list(map(int, input().split())))
def wood(l):
n=len(l)
a=float('-inf')
s=0
for i in range(n-1):
j=l[i]
if j[0]-j[1]>a:
s+=1
a=j[0]
elif j[0]+j[1]<l[i+1][0]:
s+=1
a=j[0]+j[1]
else:
a=j[0]
s+=1
return s
print(wood(l))
| {
"input": [
"5\n1 2\n2 1\n5 10\n10 9\n20 1\n",
"5\n1 2\n2 1\n5 10\n10 9\n19 1\n"
],
"output": [
"4\n",
"3\n"
]
} |
26 | 9 | Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.
Yesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as (xt = f(t), yt = g(t)), where argument t takes all integer values from 0 to 50. Moreover, f(t) and g(t) should be correct functions.
Assume that w(t) and h(t) are some correct functions, and c is an integer ranging from 0 to 50. The function s(t) is correct if it's obtained by one of the following rules:
1. s(t) = abs(w(t)), where abs(x) means taking the absolute value of a number x, i.e. |x|;
2. s(t) = (w(t) + h(t));
3. s(t) = (w(t) - h(t));
4. s(t) = (w(t) * h(t)), where * means multiplication, i.e. (w(t)Β·h(t));
5. s(t) = c;
6. s(t) = t;
Yesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate f(t) and g(t) for any set of at most 50 circles.
In each of the functions f(t) and g(t) you are allowed to use no more than 50 multiplications. The length of any function should not exceed 100Β·n characters. The function should not contain spaces.
Ruslan can't keep big numbers in his memory, so you should choose f(t) and g(t), such that for all integer t from 0 to 50 value of f(t) and g(t) and all the intermediate calculations won't exceed 109 by their absolute value.
Input
The first line of the input contains number n (1 β€ n β€ 50) β the number of circles Ruslan thinks of. Next follow n lines, each of them containing three integers xi, yi and ri (0 β€ xi, yi β€ 50, 2 β€ ri β€ 50) β the coordinates of the center and the raduis of the i-th circle.
Output
In the first line print a correct function f(t). In the second line print a correct function g(t). The set of the points (xt = f(t), yt = g(t)) (0 β€ t β€ 50) must satisfy the condition, that there is at least one point inside or on the border of each of the circles, Ruslan thinks of at the beginning.
Examples
Input
3
0 10 4
10 0 4
20 10 4
Output
t
abs((t-10))
Note
Correct functions:
1. 10
2. (1+2)
3. ((t-3)+(t*4))
4. abs((t-10))
5. (abs((((23-t)*(t*t))+((45+12)*(t*t))))*((5*t)+((12*t)-13)))
6. abs((t-(abs((t*31))+14))))
Incorrect functions:
1. 3+5+7 (not enough brackets, it should be ((3+5)+7) or (3+(5+7)))
2. abs(t-3) (not enough brackets, it should be abs((t-3))
3. 2+(2-3 (one bracket too many)
4. 1(t+5) (no arithmetic operation between 1 and the bracket)
5. 5000*5000 (the number exceeds the maximum)
<image> The picture shows one of the possible solutions | def ex(values):
e = None
for i, v in enumerate(values):
e_ = f'({v//2}*((1-abs((t-{i})))+abs((1-abs((t-{i}))))))'
if e is None:
e = e_
else:
e = f'({e}+{e_})'
return e
def solve(circles):
xs = [c[0] for c in circles]
ys = [c[1] for c in circles]
return ex(xs), ex(ys)
def pc(line):
t = tuple(map(int, line.split()))
assert len(t) == 3, f"Invalid circle: {line}"
return t
def main():
n = int(input())
circles = [pc(input()) for _ in range(n)]
f, g = solve(circles)
print(f)
print(g)
if __name__ == '__main__':
main()
| {
"input": [
"3\n0 10 4\n10 0 4\n20 10 4\n"
],
"output": [
"(((0*((1-abs((t-0)))+abs((abs((t-0))-1))))+(5*((1-abs((t-1)))+abs((abs((t-1))-1)))))+(10*((1-abs((t-2)))+abs((abs((t-2))-1)))))\n(((5*((1-abs((t-0)))+abs((abs((t-0))-1))))+(0*((1-abs((t-1)))+abs((abs((t-1))-1)))))+(5*((1-abs((t-2)))+abs((abs((t-2))-1)))))\n"
]
} |
27 | 7 | Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
Input
The first line of the input contains integers n and m (1 β€ n, m β€ 100) β the number of buttons and the number of bulbs respectively.
Each of the next n lines contains xi (0 β€ xi β€ m) β the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 β€ yij β€ m) β the numbers of these bulbs.
Output
If it's possible to turn on all m bulbs print "YES", otherwise print "NO".
Examples
Input
3 4
2 1 4
3 1 3 1
1 2
Output
YES
Input
3 3
1 1
1 2
1 1
Output
NO
Note
In the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp. | def read(): return list(map(int, input().split()))
n, m = read()
s = []
for _ in range(n):
s.extend(read()[1:])
print("YES" if len(set(s)) == m else "NO") | {
"input": [
"3 4\n2 1 4\n3 1 3 1\n1 2\n",
"3 3\n1 1\n1 2\n1 1\n"
],
"output": [
"YES\n",
"NO\n"
]
} |
28 | 9 | A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.
Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.
As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
Input
The first line contains five integers n, k, a, b, and q (1 β€ k β€ n β€ 200 000, 1 β€ b < a β€ 10 000, 1 β€ q β€ 200 000) β the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.
The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:
* 1 di ai (1 β€ di β€ n, 1 β€ ai β€ 10 000), representing an update of ai orders on day di, or
* 2 pi (1 β€ pi β€ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi?
It's guaranteed that the input will contain at least one query of the second type.
Output
For each query of the second type, print a line containing a single integer β the maximum number of orders that the factory can fill over all n days.
Examples
Input
5 2 2 1 8
1 1 2
1 5 3
1 2 1
2 2
1 4 2
1 3 2
2 1
2 3
Output
3
6
4
Input
5 4 10 1 6
1 1 5
1 5 5
1 3 2
1 5 2
2 1
2 2
Output
7
1
Note
Consider the first sample.
We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.
For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.
For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders. | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def add(a,x,v):
while x<len(a):
a[x] += v
x |= x+1
def get(a,x):
r = 0
while x>=0:
r += a[x]
x = (x&(x+1))-1
return r
n, k, a, b, q = mints()
h1 = [0]*n
h2 = [0]*n
z = [0]*n
for i in range(q):
t = tuple(mints())
if t[0] == 1:
p = z[t[1]-1]
pp = p + t[2]
add(h1, t[1]-1, min(a,pp)-min(a,p))
add(h2, t[1]-1, min(b,pp)-min(b,p))
z[t[1]-1] = pp
else:
print(get(h2,t[1]-2)+get(h1,n-1)-get(h1,t[1]+k-2))
| {
"input": [
"5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2\n",
"5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3\n"
],
"output": [
"7\n1\n",
"3\n6\n4\n"
]
} |
29 | 7 | You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.
Input
The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.
Output
The first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise.
If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.
Examples
Input
? + ? - ? + ? + ? = 42
Output
Possible
9 + 13 - 39 + 28 + 31 = 42
Input
? - ? = 1
Output
Impossible
Input
? = 1000000
Output
Possible
1000000 = 1000000 | def set_numbers(S, k):
ans = []
for i in range(k):
ans.append(S // k)
for i in range(S - k*(S // k)):
ans[i] += 1
return ans
s = input().split()
i = s.count('+') + 1
j = s.count('-')
n = int(s[-1])
if i-j*n <= n <= i*n-j:
print('Possible')
S1 = max(i, j + n)
l1 = [] if i == 0 else set_numbers(S1, i)
S2 = S1 - n
l2 = [] if j == 0 else set_numbers(S2, j)
p = 0
q = 0
for k in range(len(s)):
if k == 0:
s[k] = str(l1[p])
p += 1
elif s[k] == '?':
if s[k - 1] == '+':
s[k] = str(l1[p])
p += 1
else:
s[k] = str(l2[q])
q += 1
print(" ".join(s))
else:
print('Impossible') | {
"input": [
"? - ? = 1\n",
"? + ? - ? + ? + ? = 42\n",
"? = 1000000\n"
],
"output": [
"Impossible\n",
"Possible\n40 + 1 - 1 + 1 + 1 = 42\n",
"Possible\n1000000 = 1000000\n"
]
} |
30 | 7 | Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.
The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.
You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.
Input
First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 β€ n β€ 1000), the number of days.
Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.
The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.
Output
Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.
Examples
Input
ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler
Output
ross rachel
joey rachel
joey phoebe
joey monica
joey chandler
Input
icm codeforces
1
codeforces technex
Output
icm codeforces
icm technex
Note
In first example, the killer starts with ross and rachel.
* After day 1, ross is killed and joey appears.
* After day 2, rachel is killed and phoebe appears.
* After day 3, phoebe is killed and monica appears.
* After day 4, monica is killed and chandler appears. | def main():
a, b = map(str, input().split())
n = int(input())
print(a, b)
for i in range(n):
x, y = map(str, input().split())
if (x == a):
a = y
else:
b = y
print(a, b)
main() | {
"input": [
"icm codeforces\n1\ncodeforces technex\n",
"ross rachel\n4\nross joey\nrachel phoebe\nphoebe monica\nmonica chandler\n"
],
"output": [
"icm codeforces\nicm technex\n",
"ross rachel\njoey rachel\njoey phoebe\njoey monica\njoey chandler\n"
]
} |
31 | 8 | There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet β the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:
* alloc n β to allocate n bytes of the memory and return the allocated block's identifier x;
* erase x β to erase the block with the identifier x;
* defragment β to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order;
The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.
The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.
The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.
The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.
In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.
You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.
Input
The first line of the input data contains two positive integers t and m (1 β€ t β€ 100;1 β€ m β€ 100), where t β the amount of operations given to the memory manager for processing, and m β the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 β€ n β€ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.
Output
Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.
Examples
Input
6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6
Output
1
2
NULL
3 | t, m = map(int, input().split())
a, b = [0] * m, 1
def alloc(n):
global b
f = 0
for i in range(m):
if not a[i]:
f += 1
if f == n:
a[i - n + 1:i + 1] = [b] * n
b += 1
return b - 1
else:
f = 0
return 'NULL'
def erase(x):
f = 0
for i in range(m):
if x and a[i] == x:
a[i] = 0
f += 1
if f == 0:
print('ILLEGAL_ERASE_ARGUMENT')
def defragment():
f = 0
for i in range(m):
if f and a[i]:
a[i - f], a[i] = a[i], 0
elif not a[i]:
f += 1
for i in range(t):
c = input().split()
if c[0] == 'alloc':
print(alloc(int(c[1])))
elif c[0] == 'erase':
erase(int(c[1]))
else:
defragment() | {
"input": [
"6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6\n"
],
"output": [
"1\n2\nNULL\n3\n"
]
} |
32 | 10 | Some time ago Mister B detected a strange signal from the space, which he started to study.
After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.
Let's define the deviation of a permutation p as <image>.
Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.
Let's denote id k (0 β€ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example:
* k = 0: shift p1, p2, ... pn,
* k = 1: shift pn, p1, ... pn - 1,
* ...,
* k = n - 1: shift p2, p3, ... pn, p1.
Input
First line contains single integer n (2 β€ n β€ 106) β the length of the permutation.
The second line contains n space-separated integers p1, p2, ..., pn (1 β€ pi β€ n) β the elements of the permutation. It is guaranteed that all elements are distinct.
Output
Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.
Examples
Input
3
1 2 3
Output
0 0
Input
3
2 3 1
Output
0 1
Input
3
3 2 1
Output
2 1
Note
In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.
In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.
In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts. | def main():
n = int(input())
data = input().split()
#print(str(n) + " " + str(data))
data = list(map(lambda x: int(x), data))
res = 0
ires = 0
neg = 0
when = [0] * n
for i in range(n):
data[i] = i + 1 - data[i]
res += abs(data[i])
if data[i] <= 0:
neg += 1
a = -data[i]
if a < 0:
a = a + n
when[a] += 1
#print(when)
ares = res
#print(str(res) + " " + str(ires) + " " + str(neg))
for i in range(n):
neg -= when[i]
ares -= neg
ares += (n - neg)
x = data[n - i - 1] + i + 1
ares -= x
ares += n - x
#print(str(res) + " " + str(ires) + " " + str(ares) + " " + str(i) + " " + str(neg))
neg += 1
if ares < res:
res = ares
ires = i + 1
print(str(res) + " " + str(ires))
main()
| {
"input": [
"3\n3 2 1\n",
"3\n1 2 3\n",
"3\n2 3 1\n"
],
"output": [
"2 1\n",
"0 0\n",
"0 1\n"
]
} |
33 | 11 | Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.
Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.
Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 β€ i β€ n) there exist two numbers xi and ki that denote a possible transformation: ki kilograms of material xi can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material xi. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.
For each i (1 β€ i β€ n) Igor knows that the experiment requires ai kilograms of material i, and the laboratory contains bi kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?
Input
The first line contains one integer number n (1 β€ n β€ 105) β the number of materials discovered by Berland chemists.
The second line contains n integer numbers b1, b2... bn (1 β€ bi β€ 1012) β supplies of BerSU laboratory.
The third line contains n integer numbers a1, a2... an (1 β€ ai β€ 1012) β the amounts required for the experiment.
Then n - 1 lines follow. j-th of them contains two numbers xj + 1 and kj + 1 that denote transformation of (j + 1)-th material (1 β€ xj + 1 β€ j, 1 β€ kj + 1 β€ 109).
Output
Print YES if it is possible to conduct an experiment. Otherwise print NO.
Examples
Input
3
1 2 3
3 2 1
1 1
1 1
Output
YES
Input
3
3 2 1
1 2 3
1 1
1 2
Output
NO | import sys
# @profile
def main():
f = sys.stdin
# f = open('input.txt', 'r')
# fo = open('log.txt', 'w')
n = int(f.readline())
# b = []
# for i in range(n):
# b.append()
b = list(map(int, f.readline().strip().split(' ')))
a = list(map(int, f.readline().strip().split(' ')))
# return
b = [b[i] - a[i] for i in range(n)]
c = [[0, 0]]
for i in range(n - 1):
line = f.readline().strip().split(' ')
c.append([int(line[0]), int(line[1])])
# print(c)
for i in range(n - 1, 0, -1):
# print(i)
fa = c[i][0] - 1
if b[i] >= 0:
b[fa] += b[i]
else:
b[fa] += b[i] * c[i][1]
if b[fa] < -1e17:
print('NO')
return 0
# for x in b:
# fo.write(str(x) + '\n')
if b[0] >= 0:
print('YES')
else:
print('NO')
main()
| {
"input": [
"3\n3 2 1\n1 2 3\n1 1\n1 2\n",
"3\n1 2 3\n3 2 1\n1 1\n1 1\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
34 | 7 | As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.
Input
The first line contains two lowercase English letters β the password on the phone.
The second line contains single integer n (1 β€ n β€ 100) β the number of words Kashtanka knows.
The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct.
Output
Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise.
You can print each letter in arbitrary case (upper or lower).
Examples
Input
ya
4
ah
oy
to
ha
Output
YES
Input
hp
2
ht
tp
Output
NO
Input
ah
1
ha
Output
YES
Note
In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES".
In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring.
In the third example the string "hahahaha" contains "ah" as a substring. | a=input()
n=int(input())
s=[input() for i in range(n)]
def go():
print("YES")
exit()
for x in s:
if x == a: go()
for y in s:
if a in (x + y): go()
print("NO") | {
"input": [
"ah\n1\nha\n",
"ya\n4\nah\noy\nto\nha\n",
"hp\n2\nht\ntp\n"
],
"output": [
"YES",
"YES",
"NO"
]
} |
35 | 10 | Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.
She starts with 0 money on her account.
In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.
In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.
It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».
Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!
Input
The first line contains two integers n, d (1 β€ n β€ 105, 1 β€ d β€ 109) βthe number of days and the money limitation.
The second line contains n integer numbers a1, a2, ... an ( - 104 β€ ai β€ 104), where ai represents the transaction in i-th day.
Output
Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.
Examples
Input
5 10
-1 5 0 -5 3
Output
0
Input
3 4
-10 0 20
Output
-1
Input
5 10
-5 0 10 -11 0
Output
2 | def main():
n, d = map(int, input().split())
a = list(map(int, input().split()))
pref, mx, add, ans = [0] * n, [0] * n, 0, 0
for pos in range(n):
pref[pos] = a[pos] if not pos else a[pos] + pref[pos-1]
for pos in range(n-1, -1, -1):
mx[pos] = pref[pos] if pos == n - 1 else max(mx[pos + 1], pref[pos])
for i in range(n):
if pref[i] + add > d:
print("-1")
return
if a[i] == 0 and pref[i] + add < 0:
ans += 1
add += max(-(pref[i] + add), d - mx[i] - add)
print(ans)
if __name__ == "__main__":
main() | {
"input": [
"5 10\n-5 0 10 -11 0\n",
"5 10\n-1 5 0 -5 3\n",
"3 4\n-10 0 20\n"
],
"output": [
"2\n",
"0\n",
"-1\n"
]
} |
36 | 7 | Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.
Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length ai if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.
See the examples for better understanding.
Input
The first line of input contains two integer numbers n and k (1 β€ n, k β€ 100) β the number of buckets and the length of the garden, respectively.
The second line of input contains n integer numbers ai (1 β€ ai β€ 100) β the length of the segment that can be watered by the i-th bucket in one hour.
It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket.
Output
Print one integer number β the minimum number of hours required to water the garden.
Examples
Input
3 6
2 3 5
Output
2
Input
6 7
1 2 3 4 5 6
Output
7
Note
In the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden.
In the second test we can choose only the bucket that allows us to water the segment of length 1. | def main():
n, k = map(int, input().split())
arr = list(map(int, input().split()))
arr = [i for i in arr if k % i == 0]
print(k // max(arr))
main() | {
"input": [
"3 6\n2 3 5\n",
"6 7\n1 2 3 4 5 6\n"
],
"output": [
"2\n",
"7\n"
]
} |
37 | 8 | You and your friend are participating in a TV show "Run For Your Prize".
At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend β at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.
You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.
Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.
What is the minimum number of seconds it will take to pick up all the prizes?
Input
The first line contains one integer n (1 β€ n β€ 105) β the number of prizes.
The second line contains n integers a1, a2, ..., an (2 β€ ai β€ 106 - 1) β the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.
Output
Print one integer β the minimum number of seconds it will take to collect all prizes.
Examples
Input
3
2 3 9
Output
8
Input
2
2 999995
Output
5
Note
In the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.
In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5. | import sys
lines = sys.stdin.read().splitlines()
lincnt = -1
def input():
global lincnt
lincnt += 1
return lines[lincnt]
input()
l = map(int, input().split())
print(max(min(x - 1, 1000000 - x) for x in l))
| {
"input": [
"2\n2 999995\n",
"3\n2 3 9\n"
],
"output": [
"5\n",
"8\n"
]
} |
38 | 8 | You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges).
A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.
Destroy all vertices in the given tree or determine that it is impossible.
Input
The first line contains integer n (1 β€ n β€ 2Β·105) β number of vertices in a tree.
The second line contains n integers p1, p2, ..., pn (0 β€ pi β€ n). If pi β 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree.
Output
If it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes).
If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.
Examples
Input
5
0 1 2 1 2
Output
YES
1
2
3
5
4
Input
4
0 1 2 3
Output
NO
Note
In the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order.
<image> | from collections import defaultdict,deque
import sys
import bisect
import math
input=sys.stdin.readline
mod=1000000007
def bfs(root,count):
q=deque([root])
vis.add(root)
while q:
vertex=q.popleft()
for child in graph[vertex]:
if ans[child]==0:
ans[child]=count+1
count+=1
if child not in vis:
q.append(child)
vis.add(child)
graph=defaultdict(list)
n=int(input())
p=[int(i) for i in input().split() if i!='\n']
if n&1:
for i in range(n):
if p[i]!=0:
graph[p[i]].append(i+1)
graph[i+1].append(p[i])
length=[0]*(n+1)
for i in graph:
length[i]=len(graph[i])
CHECK,OBSERVE=1,0
stack=[(OBSERVE,1,0)]
ans=[0]*(n+1)
count=0
while stack:
state,vertex,parent=stack.pop()
if state==OBSERVE:
stack.append((CHECK,vertex,parent))
for child in graph[vertex]:
if child != parent:
stack.append((OBSERVE,child,vertex))
else:
if length[vertex]%2==0:
count+=1
ans[vertex]=count
length[parent]-=1
vis=set()
bfs(1,count)
out=[0]*(n)
for i in range(1,n+1):
out[ans[i]-1]=i
print('YES')
for i in out:
sys.stdout.write(str(i)+'\n')
else:
print('NO')
| {
"input": [
"5\n0 1 2 1 2\n",
"4\n0 1 2 3\n"
],
"output": [
"YES\n1\n2\n3\n5\n4\n",
"NO\n"
]
} |
39 | 11 | Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked and no post lamp can be placed there.
There are post lamps of different types which differ only by their power. When placed in position x, post lamp of power l illuminates the segment [x; x + l]. The power of each post lamp is always a positive integer number.
The post lamp shop provides an infinite amount of lamps of each type from power 1 to power k. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power l cost a_l each.
What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power 3 in position n - 1 (even though its illumination zone doesn't completely belong to segment [0; n]).
Input
The first line contains three integer numbers n, m and k (1 β€ k β€ n β€ 10^6, 0 β€ m β€ n) β the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available.
The second line contains m integer numbers s_1, s_2, ..., s_m (0 β€ s_1 < s_2 < ... s_m < n) β the blocked positions.
The third line contains k integer numbers a_1, a_2, ..., a_k (1 β€ a_i β€ 10^6) β the costs of the post lamps.
Output
Print the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street.
If illumintaing the entire segment [0; n] is impossible, print -1.
Examples
Input
6 2 3
1 3
1 2 3
Output
6
Input
4 3 4
1 2 3
1 10 100 1000
Output
1000
Input
5 1 5
0
3 3 3 3 3
Output
-1
Input
7 4 3
2 4 5 6
3 14 15
Output
-1 | import sys
from sys import stdin,stdout
n,m,k=map(int,stdin.readline().split(' '))
t22=stdin.readline()#;print(t22,"t2222")
bl=[]
if len(t22.strip())==0:
bl=[]
else:
bl=list(map(int,t22.split(' ')))
bd={}
for i in bl:
bd[i]=1
cost=list(map(int,stdin.readline().split(' ')))
dp=[-1 for i in range(n)]
dp[0]=0
def formdp():
global dp
for i in range(1,n):
if i in bd:
t1=i
while dp[t1]==-1:
t1-=1
dp[i]=dp[t1]
else:
dp[i]=i
def get(i):
#print("\t",i)
f=1;p=0
while p+i<n:
if dp[p+i]==p:
return -1
else:
p=dp[p+i];f+=1
#print(p,f)
return f
if True:
if 0 in bd:
print(-1)
else:
formdp()
#print(dp)
minf=[0 for i in range(k+1)]
for i in range(1,k+1):
minf[i]=get(i)
#print(minf)
ans=-1
for i in range(1,len(minf)):
if minf[i]!=-1:
if ans==-1:
ans=minf[i]*cost[i-1]
else:
ans=min(ans,minf[i]*cost[i-1])
if ans==-1:
print(-1)
else:
print(ans)
#except Exception as e:
# print(e)
#print(sys.maxsize) | {
"input": [
"5 1 5\n0\n3 3 3 3 3\n",
"4 3 4\n1 2 3\n1 10 100 1000\n",
"7 4 3\n2 4 5 6\n3 14 15\n",
"6 2 3\n1 3\n1 2 3\n"
],
"output": [
"-1\n",
"1000\n",
"-1\n",
"6\n"
]
} |
40 | 9 | At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector Π:
* Turn the vector by 90 degrees clockwise.
* Add to the vector a certain vector C.
Operations could be performed in any order any number of times.
Can Gerald cope with the task?
Input
The first line contains integers x1 ΠΈ y1 β the coordinates of the vector A ( - 108 β€ x1, y1 β€ 108). The second and the third line contain in the similar manner vectors B and C (their coordinates are integers; their absolute value does not exceed 108).
Output
Print "YES" (without the quotes) if it is possible to get vector B using the given operations. Otherwise print "NO" (without the quotes).
Examples
Input
0 0
1 1
0 1
Output
YES
Input
0 0
1 1
1 1
Output
YES
Input
0 0
1 1
2 2
Output
NO | import math
def ok(xa, ya):
x, y = xb - xa, yb - ya
d = math.gcd(abs(xc), abs(yc))
if xc == 0 and yc == 0:
return x == 0 and y == 0
if xc == 0:
return x % yc == 0 and y % yc == 0
if yc == 0:
return x % xc == 0 and y % xc == 0
if (x % d != 0) or (y % d != 0):
return 0
a, b, c1, c2 = xc // d, yc // d, x // d, -y // d
if a == 0 and b == 0:
return c1 == 0 and c2 == 0
if (c1 * b + c2 * a) % (a * a + b * b) != 0:
return 0
yy = (c1 * b + c2 * a) / (a * a + b * b)
if a == 0:
return (c2 - a * yy) % b == 0
else:
return (c1 - b * yy) % a == 0
xa, ya = map(int,input().split())
xb, yb = map(int,input().split())
xc, yc = map(int,input().split())
if ok(xa, ya) or ok(-ya, xa) or ok(-xa, -ya) or ok(ya, -xa):
print('YES')
else:
print('NO')
| {
"input": [
"0 0\n1 1\n1 1\n",
"0 0\n1 1\n0 1\n",
"0 0\n1 1\n2 2\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n"
]
} |
41 | 7 | Awruk is taking part in elections in his school. It is the final round. He has only one opponent β Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from this person. Of course 0 β€ k - a_i holds.
Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows a_1, a_2, ..., a_n β how many votes for Elodreip each student wants to give. Now he wants to change the number k to win the elections. Of course he knows that bigger k means bigger chance that somebody may notice that he has changed something and then he will be disqualified.
So, Awruk knows a_1, a_2, ..., a_n β how many votes each student will give to his opponent. Help him select the smallest winning number k. In order to win, Awruk needs to get strictly more votes than Elodreip.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of students in the school.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 100) β the number of votes each student gives to Elodreip.
Output
Output the smallest integer k (k β₯ max a_i) which gives Awruk the victory. In order to win, Awruk needs to get strictly more votes than Elodreip.
Examples
Input
5
1 1 1 5 1
Output
5
Input
5
2 2 3 2 2
Output
5
Note
In the first example, Elodreip gets 1 + 1 + 1 + 5 + 1 = 9 votes. The smallest possible k is 5 (it surely can't be less due to the fourth person), and it leads to 4 + 4 + 4 + 0 + 4 = 16 votes for Awruk, which is enough to win.
In the second example, Elodreip gets 11 votes. If k = 4, Awruk gets 9 votes and loses to Elodreip. | import sys
def main():
_, *l = map(int, sys.stdin.read().strip().split())
return max(max(l), int(2*sum(l)/len(l)) + 1)
print(main())
| {
"input": [
"5\n2 2 3 2 2\n",
"5\n1 1 1 5 1\n"
],
"output": [
"5\n",
"5\n"
]
} |
42 | 10 | You are given a binary matrix A of size n Γ n. Let's denote an x-compression of the given matrix as a matrix B of size n/x Γ n/x such that for every i β [1, n], j β [1, n] the condition A[i][j] = B[β i/x β][β j/x β] is met.
Obviously, x-compression is possible only if x divides n, but this condition is not enough. For example, the following matrix of size 2 Γ 2 does not have any 2-compression:
01 10
For the given matrix A, find maximum x such that an x-compression of this matrix is possible.
Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.
Input
The first line contains one number n (4 β€ n β€ 5200) β the number of rows and columns in the matrix A. It is guaranteed that n is divisible by 4.
Then the representation of matrix follows. Each of n next lines contains n/4 one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number B is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101.
Elements are not separated by whitespaces.
Output
Print one number: maximum x such that an x-compression of the given matrix is possible.
Examples
Input
8
E7
E7
E7
00
00
E7
E7
E7
Output
1
Input
4
7
F
F
F
Output
1
Note
The first example corresponds to the matrix:
11100111 11100111 11100111 00000000 00000000 11100111 11100111 11100111
It is easy to see that the answer on this example is 1. | from math import gcd
def D():
n = int(input())
matrix = [0 for _ in range(n)]
for i in range(n):
a = bin(int(input(), 16))[2:]
matrix[i] = '0'*(n-len(a))+ a
ans = 0
i = 0
while(i<n):
j = i+1
while(j<n and matrix[i]==matrix[j]): #Recorro por filas
j+=1
ans = gcd(ans,j-i)
col = 0
while(col<n):
l = col + 1
while(l<n and matrix[i][col]==matrix[i][l]): #Recorro por columnas
l+=1
ans = gcd(ans, col-l)
col = l
i = j
print(ans)
D() | {
"input": [
"8\nE7\nE7\nE7\n00\n00\nE7\nE7\nE7\n",
"4\n7\nF\nF\nF\n"
],
"output": [
"1",
"1"
]
} |
43 | 10 | At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | import sys
def read() : return sys.stdin.readline()
n, m = map(int, read().split())
p = [int(i) for i in read().split()]
gr = [0] * (n + 1)
for i in range(n + 1) :
gr[i] = []
for i in range(m) :
u, v = map(int, read().split())
gr[u].append(v)
can = [0] * (n + 1)
can[p[n-1]] = 1
idx = n-2; good = 1; ans = 0;
while (idx >= 0) :
cur = 0
for i in gr[p[idx]] :
cur += can[i]
if (cur == good) :
ans += 1
else :
good += 1
can[p[idx]] = 1
idx-=1
print(ans) | {
"input": [
"5 2\n3 1 5 4 2\n5 2\n5 4\n",
"3 3\n3 1 2\n1 2\n3 1\n3 2\n",
"2 1\n1 2\n1 2\n"
],
"output": [
"1\n",
"2\n",
"1\n"
]
} |
44 | 7 | You are given a string s consisting of n lowercase Latin letters.
Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from position l to position r is s[l; r] = s_l s_{l + 1} ... s_r.
You have to choose exactly one of the substrings of the given string and reverse it (i. e. make s[l; r] = s_r s_{r - 1} ... s_l) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.
If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.
String x is lexicographically less than string y, if either x is a prefix of y (and x β y), or there exists such i (1 β€ i β€ min(|x|, |y|)), that x_i < y_i, and for any j (1 β€ j < i) x_j = y_j. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languagesββ.
Input
The first line of the input contains one integer n (2 β€ n β€ 3 β
10^5) β the length of s.
The second line of the input contains the string s of length n consisting only of lowercase Latin letters.
Output
If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices l and r (1 β€ l < r β€ n) denoting the substring you have to reverse. If there are multiple answers, you can print any.
Examples
Input
7
abacaba
Output
YES
2 5
Input
6
aabcfg
Output
NO
Note
In the first testcase the resulting string is "aacabba". | def solve():
n = int(input())
s = input()
for i in range(n - 1):
if s[i] > s[i + 1]:
print('YES')
print(i + 1, i + 2)
return
print('NO')
solve()
| {
"input": [
"7\nabacaba\n",
"6\naabcfg\n"
],
"output": [
"YES\n2 3\n",
"NO\n"
]
} |
45 | 12 | You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.
The boss battle consists of n turns. During each turn, you will get several cards. Each card has two parameters: its cost c_i and damage d_i. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as the total cost of the cards you play during the turn does not exceed 3. After playing some (possibly zero) cards, you end your turn, and all cards you didn't play are discarded. Note that you can use each card at most once.
Your character has also found an artifact that boosts the damage of some of your actions: every 10-th card you play deals double damage.
What is the maximum possible damage you can deal during n turns?
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of turns.
Then n blocks of input follow, the i-th block representing the cards you get during the i-th turn.
Each block begins with a line containing one integer k_i (1 β€ k_i β€ 2 β
10^5) β the number of cards you get during i-th turn. Then k_i lines follow, each containing two integers c_j and d_j (1 β€ c_j β€ 3, 1 β€ d_j β€ 10^9) β the parameters of the corresponding card.
It is guaranteed that β _{i = 1}^{n} k_i β€ 2 β
10^5.
Output
Print one integer β the maximum damage you may deal.
Example
Input
5
3
1 6
1 7
1 5
2
1 4
1 3
3
1 10
3 5
2 3
3
1 15
2 4
1 10
1
1 100
Output
263
Note
In the example test the best course of action is as follows:
During the first turn, play all three cards in any order and deal 18 damage.
During the second turn, play both cards and deal 7 damage.
During the third turn, play the first and the third card and deal 13 damage.
During the fourth turn, play the first and the third card and deal 25 damage.
During the fifth turn, play the only card, which will deal double damage (200). | import sys
import math
import cProfile
DEBUG = False
def log(s):
if DEBUG and False:
print(s)
def calc_dmg(num, arr):
maximum = 0
if num - len(arr) < 0:
maximum = max(arr)
return sum(arr) + maximum
if DEBUG:
sys.stdin = open('input.txt')
pr = cProfile.Profile()
pr.enable()
n = sys.stdin.readline()
n = int(n)
dmg = [-sys.maxsize for _ in range(10)]
for i in range(n):
log(dmg)
cards = [_[:] for _ in [[-sys.maxsize] * 3] * 4]
k = sys.stdin.readline()
k = int(k)
for _ in range(k):
c, d = sys.stdin.readline().split()
c = int(c)
d = int(d)
cards[c].append(d)
cards[1].sort(reverse=True)
cards[2].sort(reverse=True)
cards[3].sort(reverse=True)
log(cards)
# dmg[j] = max(dmg[j],
# dmg[j - 1] + D(one card),
# dmg[j - 2] + D(two cards),
# dmg[j - 3] + D(three cards))
# Plus, if 1 <= j <= 3, dmg[j] = max(dmg[j], D(cards))
new_dmg = []
for j in range(10):
use1 = max(cards[1][0], cards[2][0], cards[3][0])
use2 = max(cards[1][0] + cards[1][1],
cards[1][0] + cards[2][0])
use3 = cards[1][0] + cards[1][1] + cards[1][2]
maximum = dmg[j]
if use1 > 0:
maximum = max(maximum, dmg[j - 1] + calc_dmg(j, [use1]))
if j == 1:
maximum = max(maximum, use1)
if use2 > 0:
maximum = max(maximum, dmg[j - 2] +
calc_dmg(j, [cards[1][0], cards[1][1]]
if cards[1][0] + cards[1][1] == use2
else [cards[1][0], cards[2][0]]))
if j == 2:
maximum = max(maximum, use2)
if use3 > 0:
maximum = max(maximum, dmg[j - 3] +
calc_dmg(j, [cards[1][0], cards[1][1], cards[1][2]]))
if j == 3:
maximum = max(maximum, use3)
new_dmg.append(maximum)
dmg = new_dmg
log(dmg)
print(max(dmg))
if DEBUG:
pr.disable()
pr.print_stats() | {
"input": [
"5\n3\n1 6\n1 7\n1 5\n2\n1 4\n1 3\n3\n1 10\n3 5\n2 3\n3\n1 15\n2 4\n1 10\n1\n1 100\n"
],
"output": [
"263\n"
]
} |
46 | 10 | This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n.
A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.
Let's denote a function that alternates digits of two numbers f(a_1 a_2 ... a_{p - 1} a_p, b_1 b_2 ... b_{q - 1} b_q), where a_1 ... a_p and b_1 ... b_q are digits of two integers written in the decimal notation without leading zeros.
In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.
For example: $$$f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212$$$
Formally,
* if p β₯ q then f(a_1 ... a_p, b_1 ... b_q) = a_1 a_2 ... a_{p - q + 1} b_1 a_{p - q + 2} b_2 ... a_{p - 1} b_{q - 1} a_p b_q;
* if p < q then f(a_1 ... a_p, b_1 ... b_q) = b_1 b_2 ... b_{q - p} a_1 b_{q - p + 1} a_2 ... a_{p - 1} b_{q - 1} a_p b_q.
Mishanya gives you an array consisting of n integers a_i, your task is to help students to calculate β_{i = 1}^{n}β_{j = 1}^{n} f(a_i, a_j) modulo 998 244 353.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of elements in the array. The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print the answer modulo 998 244 353.
Examples
Input
3
12 3 45
Output
12330
Input
2
123 456
Output
1115598 | mod=998244353
s=0
input()
d=[0]*11
def get(n,l,i):
if l<i: return (n,(d[i]*11*(int(n)%mod))%mod)
t=((int(n)%mod)*10)%mod
n=n[:-(2*i-1)]+'0'+n[-(2*i-1):]
return (n,(d[i]*(t+int(n)%mod)%mod)%mod)
l=input().split()
for i in l:
d[len(i)]+=1
for i in l:
n=i
x=len(n)
for j in range(1,11):
n,tmp=get(n,x,j)
s=(s+tmp)%mod
print(s) | {
"input": [
"3\n12 3 45\n",
"2\n123 456\n"
],
"output": [
"12330\n",
"1115598\n"
]
} |
47 | 7 | Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.
Each time she can do one of two operations:
1. take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);
2. take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).
She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has 0 stones. Can you help her?
Input
The first line contains one integer t (1 β€ t β€ 100) β the number of test cases. Next t lines describe test cases in the following format:
Line contains three non-negative integers a, b and c, separated by spaces (0 β€ a,b,c β€ 100) β the number of stones in the first, the second and the third heap, respectively.
In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.
Output
Print t lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer β the maximum possible number of stones that Alice can take after making some operations.
Example
Input
3
3 4 5
1 0 5
5 3 2
Output
9
0
6
Note
For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is 9. It is impossible to make some operations to take more than 9 stones, so the answer is 9. | def test():
a, b, c = map(int, input().split())
x1 = min(b, c//2)
b-=x1
x2 = min(a, b//2)
print((x1+x2)*3)
for _ in range(int(input())):test() | {
"input": [
"3\n3 4 5\n1 0 5\n5 3 2\n"
],
"output": [
"9\n0\n6\n"
]
} |
48 | 11 | There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland β they are held in two different cities a and b (1 β€ a, b β€ n; a β b).
Find the number of pairs of cities x and y (x β a, x β b, y β a, y β b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 β€ t β€ 4β
10^4) β the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 β€ n β€ 2β
10^5, n - 1 β€ m β€ 5β
10^5, 1 β€ a,b β€ n, a β b) β numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) β numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2β
10^5. The sum of the values of m for all sets of input data in the test does not exceed 5β
10^5.
Output
Print t integers β the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | def solve():
N, M, A, B = map(int, input().split())
roads = [list(map(lambda x:int(x)-1, input().split())) for _ in range(M)]
A -= 1
B -= 1
adj = [[] for _ in range(N)]
for a, b in roads:
adj[a].append(b)
adj[b].append(a)
def dfs(start, invalid):
Q = [start]
visited = set()
while Q:
q = Q.pop()
for next in adj[q]:
if next == invalid or next in visited:
continue
else:
visited.add(next)
Q.append(next)
return visited-{start}
set_A = dfs(A, B)
set_B = dfs(B, A)
print(len(set_A-set_B)*len(set_B-set_A))
T = int(input())
for _ in range(T):
solve()
| {
"input": [
"3\n7 7 3 5\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 5\n4 5 2 3\n1 2\n2 3\n3 4\n4 1\n4 2\n4 3 2 1\n1 2\n2 3\n4 1\n"
],
"output": [
"4\n0\n1\n"
]
} |
49 | 7 | You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero) elements. For example, [3,1] is a subsequence of [3,2,1] and [4,3,1], but not a subsequence of [1,3,3,7] and [3,10,4].
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 3t lines contain descriptions of test cases.
The first line of each test case contains two integers n and m (1β€ n,mβ€ 1000) β the lengths of the two arrays.
The second line of each test case contains n integers a_1,β¦,a_n (1β€ a_iβ€ 1000) β the elements of the first array.
The third line of each test case contains m integers b_1,β¦,b_m (1β€ b_iβ€ 1000) β the elements of the second array.
It is guaranteed that the sum of n and the sum of m across all test cases does not exceed 1000 (β_{i=1}^t n_i, β_{i=1}^t m_iβ€ 1000).
Output
For each test case, output "YES" if a solution exists, or "NO" otherwise.
If the answer is "YES", on the next line output an integer k (1β€ kβ€ 1000) β the length of the array, followed by k integers c_1,β¦,c_k (1β€ c_iβ€ 1000) β the elements of the array.
If there are multiple solutions with the smallest possible k, output any.
Example
Input
5
4 5
10 8 6 4
1 2 3 4 5
1 1
3
3
1 1
3
2
5 3
1000 2 2 2 3
3 1 5
5 5
1 2 3 4 5
1 2 3 4 5
Output
YES
1 4
YES
1 3
NO
YES
1 3
YES
1 2
Note
In the first test case, [4] is a subsequence of [10, 8, 6, 4] and [1, 2, 3, 4, 5]. This array has length 1, it is the smallest possible length of a subsequence of both a and b.
In the third test case, no non-empty subsequences of both [3] and [2] exist, so the answer is "NO". | def help():
input()
a=set(map(int,input().split()))&set(map(int,input().split()))
if a:
print("YES")
print(1,list(a)[0])
return
print("NO")
t=int(input())
for T in range(t):
help() | {
"input": [
"5\n4 5\n10 8 6 4\n1 2 3 4 5\n1 1\n3\n3\n1 1\n3\n2\n5 3\n1000 2 2 2 3\n3 1 5\n5 5\n1 2 3 4 5\n1 2 3 4 5\n"
],
"output": [
"YES\n1 4\nYES\n1 3\nNO\nYES\n1 3\nYES\n1 1\n"
]
} |
50 | 10 | Please note the non-standard memory limit.
There are n problems numbered with integers from 1 to n. i-th problem has the complexity c_i = 2^i, tag tag_i and score s_i.
After solving the problem i it's allowed to solve problem j if and only if IQ < |c_i - c_j| and tag_i β tag_j. After solving it your IQ changes and becomes IQ = |c_i - c_j| and you gain |s_i - s_j| points.
Any problem can be the first. You can solve problems in any order and as many times as you want.
Initially your IQ = 0. Find the maximum number of points that can be earned.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The first line of each test case contains an integer n (1 β€ n β€ 5000) β the number of problems.
The second line of each test case contains n integers tag_1, tag_2, β¦, tag_n (1 β€ tag_i β€ n) β tags of the problems.
The third line of each test case contains n integers s_1, s_2, β¦, s_n (1 β€ s_i β€ 10^9) β scores of the problems.
It's guaranteed that sum of n over all test cases does not exceed 5000.
Output
For each test case print a single integer β the maximum number of points that can be earned.
Example
Input
5
4
1 2 3 4
5 10 15 20
4
1 2 1 2
5 10 15 20
4
2 2 4 1
2 8 19 1
2
1 1
6 9
1
1
666
Output
35
30
42
0
0
Note
In the first test case optimal sequence of solving problems is as follows:
1. 1 β 2, after that total score is 5 and IQ = 2
2. 2 β 3, after that total score is 10 and IQ = 4
3. 3 β 1, after that total score is 20 and IQ = 6
4. 1 β 4, after that total score is 35 and IQ = 14
In the second test case optimal sequence of solving problems is as follows:
1. 1 β 2, after that total score is 5 and IQ = 2
2. 2 β 3, after that total score is 10 and IQ = 4
3. 3 β 4, after that total score is 15 and IQ = 8
4. 4 β 1, after that total score is 35 and IQ = 14
In the third test case optimal sequence of solving problems is as follows:
1. 1 β 3, after that total score is 17 and IQ = 6
2. 3 β 4, after that total score is 35 and IQ = 8
3. 4 β 2, after that total score is 42 and IQ = 12 | def nr():return int(input())
def nrs():return [int(i) for i in input().split()]
def f(n,t,s):
d=[0]*n
for i in range(1,n):
for j in range(i-1,-1,-1):
if t[i]==t[j]:continue
sc=abs(s[i]-s[j])
d[i],d[j]=max(d[i],d[j]+sc),max(d[j],d[i]+sc)
return max(d)
for _ in range(nr()):
n=nr()
t=nrs()
s=nrs()
print(f(n,t,s))
| {
"input": [
"5\n4\n1 2 3 4\n5 10 15 20\n4\n1 2 1 2\n5 10 15 20\n4\n2 2 4 1\n2 8 19 1\n2\n1 1\n6 9\n1\n1\n666\n"
],
"output": [
"\n35\n30\n42\n0\n0\n"
]
} |
51 | 9 | You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input
The first line contains the only integer q (1 β€ q β€ 1013).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer β his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Examples
Input
6
Output
2
Input
30
Output
1
6
Input
1
Output
1
0
Note
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. | import math
def prime(n):
b = int(math.sqrt(n))
l = []
while n % 2 == 0:
l.append(2)
n = n // 2
for i in range(3, b+1,2):
while n % i== 0:
l.append(i)
n = n // i
if n > 2:
l.append(n)
return l
n = int(input())
l = prime(n)
if len(l) > 2:
print(1)
print(l[0]*l[1])
elif len(l) == 0 or len(l) == 1:
print(1)
print(0)
else:
print(2) | {
"input": [
"1\n",
"6\n",
"30\n"
],
"output": [
"1\n0",
"2",
"1\n6"
]
} |
52 | 9 | Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.
It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.
Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.
Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.
Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.
Restore their common sequence of actions of length n + m such that all actions would be correct β there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's β subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.
Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).
Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.
Input
The first line contains an integer t (1 β€ t β€ 1000). Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first line contains three integers k, n, m (0 β€ k β€ 100, 1 β€ n, m β€ 100) β the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 300).
The third line contains m integers b_1, b_2, ..., b_m (0 β€ b_j β€ 300).
Output
For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.
Example
Input
5
3 2 2
2 0
0 5
4 3 2
2 0 5
0 6
0 2 2
1 0
2 3
5 4 4
6 0 8 0
0 7 0 9
5 4 1
8 7 8 0
0
Output
2 0 0 5
0 2 0 6 5
-1
0 6 0 7 0 8 0 9
-1 | def solve(k, n, m, arr1, arr2):
res = []
i = j = 0
while i != n or j != m:
if i != n and arr1[i] <= k:
res.append(arr1[i])
if arr1[i] == 0:
k += 1
i += 1
elif j != m and arr2[j] <= k:
res.append(arr2[j])
if arr2[j] == 0:
k += 1
j += 1
else:
res = [-1]
break
return ' '.join(map(str, res))
if __name__ == '__main__':
t = int(input())
for _ in range(t):
input()
k, n, m = map(int,input().split())
arr1 = list(map(int,input().split()))
arr2 = list(map(int,input().split()))
print(solve(k, n, m, arr1, arr2)) | {
"input": [
"5\n\n3 2 2\n2 0\n0 5\n\n4 3 2\n2 0 5\n0 6\n\n0 2 2\n1 0\n2 3\n\n5 4 4\n6 0 8 0\n0 7 0 9\n\n5 4 1\n8 7 8 0\n0\n"
],
"output": [
"0 2 0 5\n0 2 0 5 6\n-1\n0 6 0 7 0 8 0 9\n-1\n"
]
} |
53 | 7 | Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the size of downloaded data per second.
The guys want to watch the whole video without any pauses, so they have to wait some integer number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.
Let's suppose that video's length is c seconds and Valeric and Valerko wait t seconds before the watching. Then for any moment of time t0, t β€ t0 β€ c + t, the following condition must fulfill: the size of data received in t0 seconds is not less than the size of data needed to watch t0 - t seconds of the video.
Of course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses.
Input
The first line contains three space-separated integers a, b and c (1 β€ a, b, c β€ 1000, a > b). The first number (a) denotes the size of data needed to watch one second of the video. The second number (b) denotes the size of data Valeric and Valerko can download from the Net per second. The third number (c) denotes the video's length in seconds.
Output
Print a single number β the minimum integer number of seconds that Valeric and Valerko must wait to watch football without pauses.
Examples
Input
4 1 1
Output
3
Input
10 3 2
Output
5
Input
13 12 1
Output
1
Note
In the first sample video's length is 1 second and it is necessary 4 units of data for watching 1 second of video, so guys should download 4 Β· 1 = 4 units of data to watch the whole video. The most optimal way is to wait 3 seconds till 3 units of data will be downloaded and then start watching. While guys will be watching video 1 second, one unit of data will be downloaded and Valerik and Valerko will have 4 units of data by the end of watching. Also every moment till the end of video guys will have more data then necessary for watching.
In the second sample guys need 2 Β· 10 = 20 units of data, so they have to wait 5 seconds and after that they will have 20 units before the second second ends. However, if guys wait 4 seconds, they will be able to watch first second of video without pauses, but they will download 18 units of data by the end of second second and it is less then necessary. | def f(l):
a,b,c =l
return (c*(a-b)+b-1)//b
l = list(map(int,input().split()))
print(f(l))
| {
"input": [
"10 3 2\n",
"13 12 1\n",
"4 1 1\n"
],
"output": [
"5\n",
"1\n",
"3\n"
]
} |
54 | 7 | A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.
Input
The first input line contains integer k (1 β€ k β€ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 β€ |s| β€ 1000, where |s| is the length of string s.
Output
Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them.
If the solution doesn't exist, print "-1" (without quotes).
Examples
Input
2
aazz
Output
azaz
Input
3
abcabcabz
Output
-1 | def f(a,b):
for i in a:
if a[i]%b==0:a[i]//=b
else:return'-1'
c=''
for i in a:
c+=i*a[i]
return c*b
b=int(input())
d=input()
a={}
for i in d:
if i in a:a[i]+=1
else:a[i]=1
print(f(a,b)) | {
"input": [
"2\naazz\n",
"3\nabcabcabz\n"
],
"output": [
"azaz",
"-1\n"
]
} |
55 | 9 | The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).
You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai β€ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.
Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.
Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
Input
The first line contains four space-separated integers x0, y0, x1, y1 (1 β€ x0, y0, x1, y1 β€ 109), denoting the initial and the final positions of the king.
The second line contains a single integer n (1 β€ n β€ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 β€ ri, ai, bi β€ 109, ai β€ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.
It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.
Output
If there is no path between the initial and final position along allowed cells, print -1.
Otherwise print a single integer β the minimum number of moves the king needs to get from the initial position to the final one.
Examples
Input
5 7 6 11
3
5 3 8
6 7 11
5 2 5
Output
4
Input
3 4 3 10
3
3 1 4
4 5 9
3 10 10
Output
6
Input
1 1 2 10
2
1 1 3
2 6 10
Output
-1 | from collections import deque
def I(): return list(map(int, input().split()))
dic = {}
x0, y0, x1, y1 = I()
for i in range(int(input())):
r, a, b = I()
while a != b + 1:
tup = (r, a)
dic[tup] = -1
a += 1
x = [-1, -1, -1, 0, 0, 1, 1, 1]
y = [-1, 0, 1, -1, 1, -1, 0, 1]
dic[(x0, y0)] = 0
queue = deque([(x0, y0)])
while len(queue) > 0:
popped = queue.popleft()
for i in range(8):
new_square = (popped[0] + x[i], popped[1] + y[i])
if new_square in dic and dic[new_square] == -1:
queue.append(new_square)
dic[new_square] = dic[popped] + 1
print(dic[(x1, y1)])
| {
"input": [
"3 4 3 10\n3\n3 1 4\n4 5 9\n3 10 10\n",
"1 1 2 10\n2\n1 1 3\n2 6 10\n",
"5 7 6 11\n3\n5 3 8\n6 7 11\n5 2 5\n"
],
"output": [
"6\n",
"-1\n",
"4\n"
]
} |
56 | 7 | Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are n teams taking part in the national championship. The championship consists of nΒ·(n - 1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
Input
The first line contains an integer n (2 β€ n β€ 30). Each of the following n lines contains a pair of distinct space-separated integers hi, ai (1 β€ hi, ai β€ 100) β the colors of the i-th team's home and guest uniforms, respectively.
Output
In a single line print the number of games where the host team is going to play in the guest uniform.
Examples
Input
3
1 2
2 4
3 4
Output
1
Input
4
100 42
42 100
5 42
100 5
Output
5
Input
2
1 2
1 2
Output
0
Note
In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.
In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first). | a=int(input())
A=[]
B=[]
c=0
for i in range(a):
b=input().split()
A.append(b[0])
B.append(b[1])
def cz(x,Y):
d=0
for i in Y:
if i==x:
d+=1
return d
e=0
for i in A:
e+=cz(i,B)
print(e) | {
"input": [
"2\n1 2\n1 2\n",
"4\n100 42\n42 100\n5 42\n100 5\n",
"3\n1 2\n2 4\n3 4\n"
],
"output": [
"0\n",
"5\n",
"1\n"
]
} |
57 | 8 | In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | def f(x, p):
q = []
while x:
q.append(x)
x = p[x]
return q
from collections import defaultdict
n, k = map(int, input().split())
t = list(map(int, input().split()))
p = [0] * (n + 1)
for i, j in enumerate(t, 1):
p[j] = i
p = [f(i, p) for i, j in enumerate(t, 1) if j == 0]
s = defaultdict(int)
for i in p:
if k in i: t = {i.index(k) + 1}
else: s[len(i)] += 1
s = [list(range(i, k * i + 1, i)) for i, k in s.items()]
for q in s:
t |= {x + y for x in q for y in t}
print('\n'.join(map(str, sorted(list(t))))) | {
"input": [
"6 2\n2 3 0 5 6 0\n",
"6 2\n0 0 1 0 4 5\n",
"6 1\n2 0 4 0 6 0\n",
"4 1\n0 0 0 0\n"
],
"output": [
"2\n5\n",
"1\n3\n4\n6\n",
"2\n4\n6\n",
"1\n2\n3\n4\n"
]
} |
58 | 7 | Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
Input
The first line contains a non-empty string s β the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.
Output
Print the new sum that Xenia can count.
Examples
Input
3+2+1
Output
1+2+3
Input
1+1+3+1+3
Output
1+1+1+3+3
Input
2
Output
2 | pl='+'
def tr(s):
v=s.split(pl)
v.sort()
return pl.join(v)
print(tr(input())) | {
"input": [
"2\n",
"3+2+1\n",
"1+1+3+1+3\n"
],
"output": [
"2\n",
"1+2+3\n",
"1+1+1+3+3\n"
]
} |
59 | 9 | Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li β€ j β€ ri.
2. Find the maximum of elements from li to ri. That is, calculate the value <image>.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input
The first line contains two integers n and m (1 β€ n, m β€ 5000) β the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 β€ ti β€ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 β€ li β€ ri β€ n, - 104 β€ di β€ 104) β the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 β€ li β€ ri β€ n, - 5Β·107 β€ mi β€ 5Β·107) β the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
Output
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| β€ 109) β the recovered array.
Examples
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO | 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
n,m = Ri()
lis = []
for i in range(m):
lis.append(Ri())
ans = [10**9]*n
for i in range(m-1,-1,-1):
if lis[i][0] == 2:
for j in range(lis[i][1]-1,lis[i][2]):
ans[j] = min(ans[j], lis[i][3])
else:
for j in range(lis[i][1]-1,lis[i][2]):
if ans[j] != 10**9:
ans[j]-=lis[i][3]
for i in range(n):
if ans[i] == 10**9:
ans[i] = -10**9
temp = ans[:]
# print(temp)
flag = True
for i in range(m):
if lis[i][0] == 2:
t= -10**9
for j in range(lis[i][1]-1,lis[i][2]):
t = max(t, temp[j])
if t != lis[i][3]:
flag = False
break
else:
for j in range(lis[i][1]-1,lis[i][2]):
temp[j]+=lis[i][3]
# print(temp, ans)
if flag :
YES()
print(*ans)
else:
NO()
# print(-1) | {
"input": [
"4 5\n1 2 3 1\n2 1 2 8\n2 3 4 7\n1 1 3 3\n2 3 4 8\n",
"4 5\n1 2 3 1\n2 1 2 8\n2 3 4 7\n1 1 3 3\n2 3 4 13\n"
],
"output": [
"YES\n8 7 4 7 ",
"NO\n"
]
} |
60 | 7 | The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 β€ i β€ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for c kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day d (1 β€ d < n), lent a barrel of honey and immediately (on day d) sell it according to a daily exchange rate. The next day (d + 1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day d + 1) give his friend the borrowed barrel of honey as well as c kilograms of raspberry for renting the barrel.
The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.
Input
The first line contains two space-separated integers, n and c (2 β€ n β€ 100, 0 β€ c β€ 100), β the number of days and the number of kilos of raspberry that the bear should give for borrowing the barrel.
The second line contains n space-separated integers x1, x2, ..., xn (0 β€ xi β€ 100), the price of a honey barrel on day i.
Output
Print a single integer β the answer to the problem.
Examples
Input
5 1
5 10 7 3 20
Output
3
Input
6 2
100 1 10 40 10 40
Output
97
Input
3 0
1 2 3
Output
0
Note
In the first sample the bear will lend a honey barrel at day 3 and then sell it for 7. Then the bear will buy a barrel for 3 and return it to the friend. So, the profit is (7 - 3 - 1) = 3.
In the second sample bear will lend a honey barrel at day 1 and then sell it for 100. Then the bear buy the barrel for 1 at the day 2. So, the profit is (100 - 1 - 2) = 97. | def main():
n, c = map(int, input().split())
l = list(map(int, input().split()))
print(max(0, max(a - b for a, b in zip(l, l[1:])) - c))
main()
| {
"input": [
"6 2\n100 1 10 40 10 40\n",
"5 1\n5 10 7 3 20\n",
"3 0\n1 2 3\n"
],
"output": [
"97\n",
"3\n",
"0\n"
]
} |
61 | 11 | Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.
Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.
For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.
<image>
You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
Input
The first line of input contains two space-separated integers n and m (1 β€ n, m β€ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.
If it is impossible to cut the given graph, print "No solution" (without quotes).
Examples
Input
8 12
1 2
2 3
3 4
4 1
1 3
2 4
3 5
3 6
5 6
6 7
6 8
7 8
Output
1 2 4
1 3 2
1 4 3
5 3 6
5 6 8
6 7 8
Input
3 3
1 2
2 3
3 1
Output
No solution
Input
3 2
1 2
2 3
Output
1 2 3 | import sys
input = sys.stdin.readline
print = sys.stdout.write
def get_input():
n, m = [int(x) for x in input().split(' ')]
graph = [[] for _ in range(n + 1)]
for _ in range(m):
c1, c2 = [int(x) for x in input().split(' ')]
graph[c1].append(c2)
graph[c2].append(c1)
if m % 2 != 0:
print("No solution")
exit(0)
return graph
def dfs(graph):
n = len(graph)
w = [0] * n
pi = [None] * n
visited = [False] * n
finished = [False] * n
adjacency = [[] for _ in range(n)]
stack = [1]
while stack:
current_node = stack[-1]
if visited[current_node]:
stack.pop()
if finished[current_node]:
w[current_node] = 0
continue
# print(current_node, adjacency[current_node])
finished[current_node] = True
unpair = []
for adj in adjacency[current_node]:
if w[adj] == 0:
# print('unpaired ->', adj, w[adj])
unpair.append(adj)
else:
print(' '.join([str(current_node), str(adj), str(w[adj]), '\n']))
while len(unpair) > 1:
print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n']))
w[current_node] = unpair.pop() if unpair else 0
continue
visited[current_node] = True
not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]]
stack += not_blocked_neighbors
adjacency[current_node] = not_blocked_neighbors
# print('stack:', stack, current_node)
# def recursive_dfs(graph):
# n = len(graph)
# visited = [False] * n
# recursive_dfs_visit(graph, 1, visited)
# def recursive_dfs_visit(graph, root, visited):
# unpair = []
# visited[root] = True
# adjacency = [x for x in graph[root] if not visited[x]]
# for adj in adjacency:
# w = recursive_dfs_visit(graph, adj, visited)
# if w == 0:
# unpair.append(adj)
# else:
# print(' '.join([str(root), str(adj), str(w), '\n']))
# while len(unpair) > 1:
# print(' '.join([str(unpair.pop()), str(root), str(unpair.pop()), '\n']))
# if unpair:
# return unpair.pop()
# return 0
if __name__ == "__main__":
graph = get_input()
dfs(graph)
| {
"input": [
"3 2\n1 2\n2 3\n",
"3 3\n1 2\n2 3\n3 1\n",
"8 12\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n3 5\n3 6\n5 6\n6 7\n6 8\n7 8\n"
],
"output": [
"1 2 3\n",
"No solution\n",
"6 7 8 5 6 8 4 3 5 2 3 6 1 2 4 4 1 3 "
]
} |
62 | 7 | Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.
But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of apples. The second line contains n integers w1, w2, ..., wn (wi = 100 or wi = 200), where wi is the weight of the i-th apple.
Output
In a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).
Examples
Input
3
100 200 100
Output
YES
Input
4
100 100 100 200
Output
NO
Note
In the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa. | from collections import Counter
def main():
n = int(input())
c = Counter(input().split())
print(('YES', 'NO')[c['100'] & 1 if c['100'] else c['200'] & 1])
if __name__ == '__main__':
main()
| {
"input": [
"4\n100 100 100 200\n",
"3\n100 200 100\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
63 | 7 | There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size b of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins b in the initial bet.
Input
The input consists of a single line containing five integers c1, c2, c3, c4 and c5 β the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0 β€ c1, c2, c3, c4, c5 β€ 100).
Output
Print the only line containing a single positive integer b β the number of coins in the initial bet of each player. If there is no such value of b, then print the only value "-1" (quotes for clarity).
Examples
Input
2 5 4 0 4
Output
3
Input
4 5 9 2 1
Output
-1
Note
In the first sample the following sequence of operations is possible:
1. One coin is passed from the fourth player to the second player;
2. One coin is passed from the fourth player to the fifth player;
3. One coin is passed from the first player to the third player;
4. One coin is passed from the fourth player to the second player. | s = sum(list(map(int,input().split())))
def ans():
for i in range(1,101):
if 5*i == s:
return i
return -1
print(ans()) | {
"input": [
"2 5 4 0 4\n",
"4 5 9 2 1\n"
],
"output": [
"3\n",
"-1\n"
]
} |
64 | 9 | New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 β€ i β€ n) book is wi.
As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.
1. He lifts all the books above book x.
2. He pushes book x out of the stack.
3. He puts down the lifted books without changing their order.
4. After reading book x, he puts book x on the top of the stack.
<image>
He decided to read books for m days. In the j-th (1 β€ j β€ m) day, he will read the book that is numbered with integer bj (1 β€ bj β€ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.
After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?
Input
The first line contains two space-separated integers n (2 β€ n β€ 500) and m (1 β€ m β€ 1000) β the number of books, and the number of days for which Jaehyun would read books.
The second line contains n space-separated integers w1, w2, ..., wn (1 β€ wi β€ 100) β the weight of each book.
The third line contains m space separated integers b1, b2, ..., bm (1 β€ bj β€ n) β the order of books that he would read. Note that he can read the same book more than once.
Output
Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.
Examples
Input
3 5
1 2 3
1 3 2 3 1
Output
12
Note
Here's a picture depicting the example. Each vertical column presents the stacked books.
<image> | def f(s):
return int(s) - 1
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(f, input().split()))
c = [[0] * n for i in range(n)]
o = 0
for i in range(m):
for j in range(n):
if j != b[i]:
c[j][b[i]] = 1
for j in range(n):
if c[b[i]][j] == 1:
o += a[j]
c[b[i]][j] = 0
print(o) | {
"input": [
"3 5\n1 2 3\n1 3 2 3 1\n"
],
"output": [
"12\n"
]
} |
65 | 7 | In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.
<image>
An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.
A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.
One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i1, he can make a sequence of jumps through the platforms i1 < i2 < ... < ik, if i2 - i1 = i3 - i2 = ... = ik - ik - 1. Of course, all segments i1, i2, ... ik should be exactly the platforms, not pits.
Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i1, i2, ..., i5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of segments on the level.
Next line contains the scheme of the level represented as a string of n characters '*' and '.'.
Output
If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).
Examples
Input
16
.**.*..*.***.**.
Output
yes
Input
11
.*.*...*.*.
Output
no
Note
In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14. | def main():
n, s = int(input()), input()
for step in range(1, (n + 3) // 4):
for start in range(step):
if "*****" in s[start::step]:
print("yes")
return
print("no")
if __name__ == '__main__':
main() | {
"input": [
"16\n.**.*..*.***.**.\n",
"11\n.*.*...*.*.\n"
],
"output": [
"yes",
"no"
]
} |
66 | 8 | Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.
GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.
GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?
Input
The first line contains string a, the second line contains string b, and the third line contains string c (1 β€ |a|, |b|, |c| β€ 105, where |s| denotes the length of string s).
All three strings consist only of lowercase English letters.
It is possible that b and c coincide.
Output
Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.
Examples
Input
aaa
a
b
Output
aaa
Input
pozdravstaklenidodiri
niste
dobri
Output
nisteaadddiiklooprrvz
Input
abbbaaccca
ab
aca
Output
ababacabcc
Note
In the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 β 2 (ab), 3 β 4 (ab), 5 β 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc. | from collections import Counter
from collections import defaultdict
def get_single(a, b):
res = 2 ** 32
for s in b.keys():
res = min(res, a[s] // b[s])
return res
def get_count(a, b, c):
best = 0, get_single(a, c)
r1 = 0
while a & b == b:
r1 += 1
a = a - b
r2 = get_single(a, c)
if r1 + r2 > sum(best):
best = r1, r2
return best
a = input()
b = input()
c = input()
aa = Counter(a)
bb = Counter(b)
cc = Counter(c)
r = get_count(Counter(a), bb, cc)
res = b * r[0] + c * r[1]
rest = aa - Counter(res)
res += ''.join(list(rest.elements()))
print(res)
| {
"input": [
"pozdravstaklenidodiri\nniste\ndobri\n",
"aaa\na\nb\n",
"abbbaaccca\nab\naca\n"
],
"output": [
"nisteaadddiiklooprrvz\n",
"aaa\n",
"ababacabcc\n"
]
} |
67 | 9 | You are given a sequence of n integers a1, a2, ..., an.
Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.
The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.
The poorness of a segment is defined as the absolute value of sum of the elements of segment.
Input
The first line contains one integer n (1 β€ n β€ 200 000), the length of a sequence.
The second line contains n integers a1, a2, ..., an (|ai| β€ 10 000).
Output
Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.
Examples
Input
3
1 2 3
Output
1.000000000000000
Input
4
1 2 3 4
Output
2.000000000000000
Input
10
1 10 2 9 3 8 4 7 5 6
Output
4.500000000000000
Note
For the first case, the optimal value of x is 2 so the sequence becomes - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case.
For the second sample the optimal value of x is 2.5 so the sequence becomes - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case. | n = int(input())
a = list(map(int, input().split()))
def f(x):
mx, cur = 0, 0
for i in range(n):
cur = max(cur, 0) + a[i] - x
mx = max(mx, cur)
cur = 0
for i in range(n):
cur = max(cur, 0) + x - a[i]
mx = max(mx, cur)
return mx
L, R = min(a), max(a) + 1
for t in range(100):
d = (R - L) / 3
x1, x2 = L + d, R - d
if f(x1) > f(x2):
L = x1
else:
R = x2
print('{:.10f}'.format(f(L)))
| {
"input": [
"10\n1 10 2 9 3 8 4 7 5 6\n",
"4\n1 2 3 4\n",
"3\n1 2 3\n"
],
"output": [
"4.500000000000024\n",
"2.000000000000003\n",
"1.000000000000000\n"
]
} |
68 | 7 | Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a person to the chat ('Add' command).
* Remove a person from the chat ('Remove' command).
* Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).
Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.
Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.
As Polycarp has no time, he is asking for your help in solving this problem.
Input
Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:
* +<name> for 'Add' command.
* -<name> for 'Remove' command.
* <sender_name>:<message_text> for 'Send' command.
<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.
It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.
All names are case-sensitive.
Output
Print a single number β answer to the problem.
Examples
Input
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate
Output
9
Input
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate
Output
14 | def readln(): return tuple(map(int, input().split()))
cnt = ans = 0
while True:
try:
inp = input()
if inp[0] == '+':
cnt += 1
elif inp[0] == '-':
cnt -= 1
else:
ans += cnt * len(inp.split(':')[1])
except:
break
print(ans)
| {
"input": [
"+Mike\nMike:hello\n+Kate\n+Dmitry\n-Dmitry\nKate:hi\n-Kate\n",
"+Mike\n-Mike\n+Mike\nMike:Hi I am here\n-Mike\n+Kate\n-Kate\n"
],
"output": [
"9\n",
"14\n"
]
} |
69 | 10 | Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.
Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options:
1. a1 = xyz;
2. a2 = xzy;
3. a3 = (xy)z;
4. a4 = (xz)y;
5. a5 = yxz;
6. a6 = yzx;
7. a7 = (yx)z;
8. a8 = (yz)x;
9. a9 = zxy;
10. a10 = zyx;
11. a11 = (zx)y;
12. a12 = (zy)x.
Let m be the maximum of all the ai, and c be the smallest index (from 1 to 12) such that ac = m. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that ac.
Input
The only line of the input contains three space-separated real numbers x, y and z (0.1 β€ x, y, z β€ 200.0). Each of x, y and z is given with exactly one digit after the decimal point.
Output
Find the maximum value of expression among xyz, xzy, (xy)z, (xz)y, yxz, yzx, (yx)z, (yz)x, zxy, zyx, (zx)y, (zy)x and print the corresponding expression. If there are many maximums, print the one that comes first in the list.
xyz should be outputted as x^y^z (without brackets), and (xy)z should be outputted as (x^y)^z (quotes for clarity).
Examples
Input
1.1 3.4 2.5
Output
z^y^x
Input
2.0 2.0 2.0
Output
x^y^z
Input
1.9 1.8 1.7
Output
(x^y)^z | from math import log, inf
from itertools import product, permutations
def comp_key(p, A, mode):
a = log(A[p[0][1]])*A[p[0][2]] if p[1] else log(A[p[0][1]]) + log(A[p[0][2]])
k = A[p[0][0]] if mode else 1/A[p[0][0]]
return a + log(log(k)) if k > 1 else -inf
def solve(A):
mode = any((x > 1 for x in A))
c = (max if mode else min)(((x,y) for y in [True, False] for x in permutations(range(3))), key = lambda p: comp_key(p, A, mode))
k = 'xyz'
return ('{0}^{1}^{2}' if c[1] else '({0}^{1})^{2}').format(k[c[0][0]], k[c[0][1]], k[c[0][2]])
A = [float(s) for s in input().split()]
print(solve(A))
| {
"input": [
"1.1 3.4 2.5\n",
"1.9 1.8 1.7\n",
"2.0 2.0 2.0\n"
],
"output": [
"z^y^x\n",
"(x^y)^z\n",
"x^y^z\n"
]
} |
70 | 8 | Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
* There is no road between a and b.
* There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.
On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.
Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.
Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input
The first line of the input contains two integers n and k (4 β€ n β€ 1000, n - 1 β€ k β€ 2n - 2) β the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers a, b, c and d (1 β€ a, b, c, d β€ n).
Output
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.
Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
Examples
Input
7 11
2 4 7 3
Output
2 7 1 3 6 5 4
7 1 5 4 6 2 3
Input
1000 999
10 20 30 40
Output
-1
Note
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
<image> | def main():
n, k = [int(i) for i in input().strip().split()]
a, b, c, d = [int(i) for i in input().strip().split()]
if k <= n or n <= 4:
print(-1)
return
s = [a, b, c, d]
others = [i for i in range(1, n + 1) if i not in s]
print(" ".join(map(str, [a, c] + others + [d, b])))
print(" ".join(map(str, [c, a] + others + [b, d])))
if __name__ == "__main__":
main() | {
"input": [
"1000 999\n10 20 30 40\n",
"7 11\n2 4 7 3\n"
],
"output": [
"-1",
"2 7 1 5 6 3 4 \n7 2 1 5 6 4 3 "
]
} |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 18