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 " ] }
71
8
In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier β€” an integer from 1 to 109. At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier. Your task is to determine the k-th identifier to be pronounced. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ min(2Β·109, nΒ·(n + 1) / 2). The second line contains the sequence id1, id2, ..., idn (1 ≀ idi ≀ 109) β€” identifiers of roborts. It is guaranteed that all identifiers are different. Output Print the k-th pronounced identifier (assume that the numeration starts from 1). Examples Input 2 2 1 2 Output 1 Input 4 5 10 4 18 3 Output 4 Note In the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k = 2, the answer equals to 1. In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k = 5, the answer equals to 4.
def I(): return list(map(int, input().split())) n, k = I() i = 0 while i < k: k -= i i += 1 print(I()[k-1])
{ "input": [ "4 5\n10 4 18 3\n", "2 2\n1 2\n" ], "output": [ "4", "1" ] }
72
10
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj). At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get? Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≀ i ≀ n exists, so pk = qk for 1 ≀ k < i and pi < qi. Input The first line contains two integers n and m (1 ≀ n, m ≀ 106) β€” the length of the permutation p and the number of pairs of positions. The second line contains n distinct integers pi (1 ≀ pi ≀ n) β€” the elements of the permutation p. Each of the last m lines contains two integers (aj, bj) (1 ≀ aj, bj ≀ n) β€” the pairs of positions to swap. Note that you are given a positions, not the values to swap. Output Print the only line with n distinct integers p'i (1 ≀ p'i ≀ n) β€” the lexicographically maximal permutation one can get. Example Input 9 6 1 2 3 4 5 6 7 8 9 1 4 4 7 2 5 5 8 3 6 6 9 Output 7 8 9 4 5 6 1 2 3
import sys input=sys.stdin.readline def make_set(v): parent[v]=v def find_set(v): if v == parent[v]: return v else: parent[v]=find_set(parent[v]) return parent[v] def union_sets(a,b): a = find_set(a) b = find_set(b) if a != b: if rank[a]<rank[b]: a,b=b,a parent[b] = a if rank[a]==rank[b]: rank[a]+=1 n,m=list(map(int,input().split())) arr=list(map(int,input().split())) parent=[i for i in range(n)] rank=[0]*(n) for i in range(m): a,b=list(map(int,input().split())) a=a-1 b=b-1 union_sets(a,b) b={} for i in range(n): if find_set(i) not in b.keys(): b[find_set(i)]=[] b[find_set(i)].append(i) e=[0]*n for i in b: b[i].sort() c=[] for j in range(len(b[i])): c.append(arr[b[i][j]]) c.sort(reverse=True) for j in range(len(b[i])): e[b[i][j]]=c[j] print(*e)
{ "input": [ "9 6\n1 2 3 4 5 6 7 8 9\n1 4\n4 7\n2 5\n5 8\n3 6\n6 9\n" ], "output": [ "7 8 9 4 5 6 1 2 3 \n" ] }
73
10
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him? Input The first line contains five integers n, m, L, s, t (2 ≀ n ≀ 1000, 1 ≀ m ≀ 10 000, 1 ≀ L ≀ 109, 0 ≀ s, t ≀ n - 1, s β‰  t) β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≀ ui, vi ≀ n - 1, ui β‰  vi, 0 ≀ wi ≀ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L. If there are multiple solutions, print any of them. Examples Input 5 5 13 0 4 0 1 5 2 1 2 3 2 3 1 4 0 4 3 4 Output YES 0 1 5 2 1 2 3 2 3 1 4 8 4 3 4 Input 2 1 123456789 0 1 0 1 0 Output YES 0 1 123456789 Input 2 1 999999999 1 0 0 1 1000000000 Output NO Note Here's how the graph in the first sample case looks like : <image> In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
import heapq from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[from_node, to_node] = distance self.distances[to_node, from_node] = distance def dijkstra(graph, initial): visited = {initial: 0} path = {} h = [(0, initial)] nodes = set(graph.nodes) while nodes and h: current_weight, min_node = heapq.heappop(h) try: while min_node not in nodes: current_weight, min_node = heapq.heappop(h) except IndexError: break nodes.remove(min_node) for v in graph.edges[min_node]: weight = current_weight + graph.distances[min_node, v] if v not in visited or weight < visited[v]: visited[v] = weight heapq.heappush(h, (weight, v)) path[v] = min_node return visited, path n, m, L, s, t = map(int, input().split()) min_g = Graph(n) max_g = Graph(n) g = Graph(n) for _ in range(m): u, v, w = map(int, input().split()) if w == 0: min_w = 1 max_w = int(1e18) else: min_w = max_w = w min_g.add_edge(u, v, min_w) max_g.add_edge(u, v, max_w) g.add_edge(u, v, w) min_ls, min_p = dijkstra(min_g, s) try: min_l = min_ls[t] max_l = dijkstra(max_g, s)[0][t] except KeyError: min_l = 0 max_l = -1 if min_l <= L <= max_l: while min_l < L: a = s b = z = t while z != s: if g.distances[z, min_p[z]] == 0: max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]] max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]] a = z b = min_p[z] z = min_p[z] new_dist = min_g.distances[a, b] + L - min_l max_g.distances[a, b] = new_dist max_g.distances[b, a] = new_dist min_g = max_g min_ls, min_p = dijkstra(min_g, s) min_l = min_ls[t] if min_l == L: print('YES') print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in min_g.distances.items() if u < v)) else: print('NO') else: print('NO')
{ "input": [ "5 5 13 0 4\n0 1 5\n2 1 2\n3 2 3\n1 4 0\n4 3 4\n", "2 1 123456789 0 1\n0 1 0\n", "2 1 999999999 1 0\n0 1 1000000000\n" ], "output": [ "YES\n0 1 5\n2 1 2\n3 2 3\n1 4 8\n4 3 4\n", "YES\n0 1 123456789\n", "NO" ] }
74
7
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s. There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly. There are n cars in the rental service, i-th of them is characterized with two integers ci and vi β€” the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service. Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times. Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially. Input The first line contains four positive integers n, k, s and t (1 ≀ n ≀ 2Β·105, 1 ≀ k ≀ 2Β·105, 2 ≀ s ≀ 109, 1 ≀ t ≀ 2Β·109) β€” the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≀ ci, vi ≀ 109) β€” the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≀ gi ≀ s - 1) β€” the positions of the gas stations on the road in arbitrary order. Output Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1. Examples Input 3 1 8 10 10 8 5 7 11 9 3 Output 10 Input 2 2 10 18 10 4 20 6 5 3 Output 20 Note In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
import sys input = sys.stdin.readline N = int(2e5+1) n, k, s, t = map(int, input().split()) car = [list(map(int, input().split())) for _ in range(n)] g = sorted(list(map(int, input().split()))) + [0] g[k] = s - g[k - 1] for i in range(k-1, 0, -1): g[i] -= g[i - 1] def is_valid(g, k, v, t): need = 0 for i in range(k+1): need += max(g[i], 3 * g[i] - v) return need <= t def binary_search(g, k): l, r = max(g), int(2e9) while l < r: v = l + (r - l) // 2 if is_valid(g, k, v, t): r = v else: l = v + 1 return l l = binary_search(g, k) res = int(2e9) for i in range(n): if car[i][1] >= l: res = min(res, car[i][0]) print(-1 if res == int(2e9) else res)
{ "input": [ "3 1 8 10\n10 8\n5 7\n11 9\n3\n", "2 2 10 18\n10 4\n20 6\n5 3\n" ], "output": [ "10\n", "20\n" ] }
75
8
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it? Input The input contains a single integer n (0 ≀ n ≀ 2000000000). Output Output a single integer. Examples Input 11 Output 2 Input 14 Output 0 Input 61441 Output 2 Input 571576 Output 10 Input 2128506 Output 3
def f(i): if i in '0964ad': return 1 if i in '8b': return 2 return 0 n=sum([f(i) for i in hex(int(input()))[2:]]) print(n) #print(' '.join([str(i) for i in a]))
{ "input": [ "14\n", "2128506\n", "11\n", "571576\n", "61441\n" ], "output": [ "0", "3", "2", "10", "2" ] }
76
7
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times. Solve the problem to show that it's not a NP problem. Input The first line contains two integers l and r (2 ≀ l ≀ r ≀ 109). Output Print single integer, the integer that appears maximum number of times in the divisors. If there are multiple answers, print any of them. Examples Input 19 29 Output 2 Input 3 6 Output 3 Note Definition of a divisor: <https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html> The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}. The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}.
def solve(): n,k = map(int, input().split()) if n==k: return n return 2 print(solve())
{ "input": [ "19 29\n", "3 6\n" ], "output": [ "2\n", "2\n" ] }
77
7
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it. Input The first line contains three integers n, k and p (1 ≀ n ≀ 1 000, n ≀ k ≀ 2 000, 1 ≀ p ≀ 109) β€” the number of people, the number of keys and the office location. The second line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” positions in which people are located initially. The positions are given in arbitrary order. The third line contains k distinct integers b1, b2, ..., bk (1 ≀ bj ≀ 109) β€” positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point. Output Print the minimum time (in seconds) needed for all n to reach the office with keys. Examples Input 2 4 50 20 100 60 10 40 80 Output 50 Input 1 2 10 11 15 7 Output 7 Note In the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.
def read(): return [int(x) for x in input().split()] n,k,p = read() a = read() b = read() a.sort() b.sort() ans = 2e9+1 ans = int(ans) for i in range(k-n+1): tmp = 0 for j in range(n): tmp = max(tmp,abs(a[j]-b[i+j])+abs(b[i+j]-p)) ans = min(ans,tmp) print(ans)
{ "input": [ "1 2 10\n11\n15 7\n", "2 4 50\n20 100\n60 10 40 80\n" ], "output": [ "7", "50" ] }
78
8
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c. Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not. Input The only line contains six integers ax, ay, bx, by, cx, cy (|ax|, |ay|, |bx|, |by|, |cx|, |cy| ≀ 109). It's guaranteed that the points are distinct. Output Print "Yes" if the problem has a solution, "No" otherwise. You can print each letter in any case (upper or lower). Examples Input 0 1 1 1 1 0 Output Yes Input 1 1 0 0 1000 1000 Output No Note In the first sample test, rotate the page around (0.5, 0.5) by <image>. In the second sample test, you can't find any solution.
def d(x,y,xx,yy):return ((x-xx)**2+(y-yy)**2) x1,y1,x2,y2,x3,y3=map(int,input().split()) print(['NO','YES'][d(x1,y1,x2,y2)==d(x2,y2,x3,y3)and(y2-y1)*(x3-x2)!=(y3-y2)*(x2-x1)])
{ "input": [ "0 1 1 1 1 0\n", "1 1 0 0 1000 1000\n" ], "output": [ "Yes\n", "No\n" ] }
79
11
You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
def Solution(G): unvisited = { i for i in range(len(G)) } sol = [] while unvisited: l = len(unvisited) a = next(iter(unvisited)) unvisited.discard(a) stack = [a] while stack: v = stack.pop() s = unvisited & G[v] stack.extend(unvisited - s) unvisited = s sol.append(l - len(unvisited)) sol.sort() print(len(sol)) print(" ".join(map("{0}".format,sol))) pass def main(): s = input().split(" ") n = int(s[0]) m = int(s[1]) G=[ {i} for i in range(n) ] for _ in range(m): s =input().split(" ") n1 = int(s[0])-1 n2 = int(s[1])-1 G[n2].add(n1) G[n1].add(n2) Solution(G) main()
{ "input": [ "5 5\n1 2\n3 4\n3 2\n4 2\n2 5\n" ], "output": [ "2\n1 4 \n" ] }
80
9
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!). Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers. For each of m company clients, let us denote indices of two different data centers storing this client data as ci, 1 and ci, 2. In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day. Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer uj (0 ≀ uj ≀ h - 1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance. Summing up everything above, the condition uci, 1 β‰  uci, 2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance. Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if uj = h - 1, then the new maintenance hour would become 0, otherwise it would become uj + 1). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed. Such an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees. Input The first line of input contains three integers n, m and h (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000, 2 ≀ h ≀ 100 000), the number of company data centers, number of clients and the day length of day measured in hours. The second line of input contains n integers u1, u2, ..., un (0 ≀ uj < h), j-th of these numbers is an index of a maintenance hour for data center j. Each of the next m lines contains two integers ci, 1 and ci, 2 (1 ≀ ci, 1, ci, 2 ≀ n, ci, 1 β‰  ci, 2), defining the data center indices containing the data of client i. It is guaranteed that the given maintenance schedule allows each client to access at least one copy of his data at any moment of day. Output In the first line print the minimum possible number of data centers k (1 ≀ k ≀ n) that have to be included in an experiment in order to keep the data available for any client. In the second line print k distinct integers x1, x2, ..., xk (1 ≀ xi ≀ n), the indices of data centers whose maintenance time will be shifted by one hour later. Data center indices may be printed in any order. If there are several possible answers, it is allowed to print any of them. It is guaranteed that at there is at least one valid choice of data centers. Examples Input 3 3 5 4 4 0 1 3 3 2 3 1 Output 1 3 Input 4 5 4 2 1 0 3 4 3 3 2 1 2 1 4 1 3 Output 4 1 2 3 4 Note Consider the first sample test. The given answer is the only way to conduct an experiment involving the only data center. In such a scenario the third data center has a maintenance during the hour 1, and no two data centers storing the information of the same client have maintenance at the same hour. On the other hand, for example, if we shift the maintenance time on hour later for the first data center, then the data of clients 1 and 3 will be unavailable during the hour 0.
from collections import deque import sys input = sys.stdin.readline n, m, MOD = map(int, input().split()) u = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(m)] graph = [[] for i in range(n)] rev_graph = [[] for i in range(n)] set_ = set() INF = 10 ** 9 for a, b in info: a -= 1 b -= 1 if (u[a] + 1) % MOD == u[b]: if a * INF + b not in set_: graph[a].append(b) rev_graph[b].append(a) set_.add(a * INF + b) if (u[b] + 1) % MOD == u[a]: if b * INF + a not in set_: graph[b].append(a) rev_graph[a].append(b) set_.add(b * INF + a) def scc(N, G, RG): order = [] used = [0]*N group = [None]*N def dfs(s): used[s] = 1 q = deque([s]) tmp = deque([s]) while q: s = q.pop() for t in G[s]: if not used[t]: used[t] = 1 q.append(t) tmp.append(t) while tmp: order.append(tmp.pop()) def rdfs(s, col): group[s] = col used[s] = 1 q = deque([s]) while q: s = q.pop() for t in RG[s]: if not used[t]: q.append(t) used[t] = 1 group[t] = col for i in range(N): if not used[i]: dfs(i) used = [0]*N label = 0 for s in reversed(order): if not used[s]: rdfs(s, label) label += 1 return label, group def construct(N, G, label, group): G0 = [set() for i in range(label)] GP = [[] for i in range(label)] for v in range(N): lbs = group[v] for w in G[v]: lbt = group[w] if lbs == lbt: continue G0[lbs].add(lbt) GP[lbs].append(v + 1) return G0, GP min_ans = 10 ** 9 ind_ans = -1 label, group = scc(n, graph, rev_graph) new_graph, element = construct(n, graph, label, group) for i in range(len(new_graph)): if len(new_graph[i]) == 0 and min_ans > len(element[i]): min_ans = len(element[i]) ind_ans = i print(min_ans) print(*element[ind_ans])
{ "input": [ "3 3 5\n4 4 0\n1 3\n3 2\n3 1\n", "4 5 4\n2 1 0 3\n4 3\n3 2\n1 2\n1 4\n1 3\n" ], "output": [ "1\n3 \n", "4\n1 2 3 4 \n" ] }
81
8
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β€” three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string s = "BBAABBBA" the answer is two-gram "BB", which contained in s three times. In other words, find any most frequent two-gram. Note that occurrences of the two-gram can overlap with each other. Input The first line of the input contains integer number n (2 ≀ n ≀ 100) β€” the length of string s. The second line of the input contains the string s consisting of n capital Latin letters. Output Print the only line containing exactly two capital Latin letters β€” any two-gram contained in the given string s as a substring (i.e. two consecutive characters of the string) maximal number of times. Examples Input 7 ABACABA Output AB Input 5 ZZZAA Output ZZ Note In the first example "BA" is also valid answer. In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times.
import collections def main(): n, s = int(input()), input() two_grams = [s[i] + s[i+1] for i in range(len(s)-1)] print(collections.Counter(two_grams).most_common()[0][0]) main()
{ "input": [ "5\nZZZAA\n", "7\nABACABA\n" ], "output": [ "ZZ\n", "AB\n" ] }
82
8
Innopolis University scientists continue to investigate the periodic table. There are nΒ·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≀ r ≀ n, 1 ≀ c ≀ m) in the table. Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 β‰  r2 and c1 β‰  c2, then we can produce element (r2, c2). <image> Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions. Innopolis University scientists already have samples of q elements. They want to obtain samples of all nΒ·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase. Input The first line contains three integers n, m, q (1 ≀ n, m ≀ 200 000; 0 ≀ q ≀ min(nΒ·m, 200 000)), the chemical table dimensions and the number of elements scientists already have. The following q lines contain two integers ri, ci (1 ≀ ri ≀ n, 1 ≀ ci ≀ m), each describes an element that scientists already have. All elements in the input are different. Output Print the minimal number of elements to be purchased. Examples Input 2 2 3 1 2 2 2 2 1 Output 0 Input 1 5 3 1 3 1 1 1 5 Output 2 Input 4 3 6 1 2 1 3 2 2 2 3 3 1 3 3 Output 1 Note For each example you have a picture which illustrates it. The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially. The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced. Test 1 We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything. <image> Test 2 We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements. <image> Test 3 There are several possible solutions. One of them is illustrated below. Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions. <image>
n,m,q = map(int,input().split()) f = [-1]*(n+m+1) def find(x): if f[x]==-1: return x else: f[x] = find(f[x]) return f[x] ans = n+m-1 for i in range(q): r,c = map(int,input().split()) c+=n R = find(r) C = find(c) if R!=C : ans-=1 f[R]=C print(ans)
{ "input": [ "1 5 3\n1 3\n1 1\n1 5\n", "2 2 3\n1 2\n2 2\n2 1\n", "4 3 6\n1 2\n1 3\n2 2\n2 3\n3 1\n3 3\n" ], "output": [ "2\n", "0\n", "1\n" ] }
83
8
You are given an array a of n integers and an integer s. It is guaranteed that n is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s. The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array 6, 5, 8 is equal to 6, since if we sort this array we will get 5, 6, 8, and 6 is located on the middle position. Input The first line contains two integers n and s (1≀ n≀ 2β‹… 10^5-1, 1≀ s≀ 10^9) β€” the length of the array and the required value of median. The second line contains n integers a_1, a_2, …, a_n (1≀ a_i ≀ 10^9) β€” the elements of the array a. It is guaranteed that n is odd. Output In a single line output the minimum number of operations to make the median being equal to s. Examples Input 3 8 6 5 8 Output 2 Input 7 20 21 15 12 11 20 19 12 Output 6 Note In the first sample, 6 can be increased twice. The array will transform to 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8. In the second sample, 19 can be increased once and 15 can be increased five times. The array will become equal to 21, 20, 12, 11, 20, 20, 12. If we sort this array we get 11, 12, 12, 20, 20, 20, 21, this way the median is 20.
def go(): n, s = [int(i) for i in input().split(' ')] a = [int(i) for i in input().split(' ')] a.sort() x = 0 for i in range(n // 2): x += max(0, a[i] - s) x += max(0, s - a[n - i - 1]) x += abs(a[n // 2] - s) return x print(go())
{ "input": [ "3 8\n6 5 8\n", "7 20\n21 15 12 11 20 19 12\n" ], "output": [ "2\n", "6\n" ] }
84
9
Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res). Each item belongs to one class. In this problem we will only consider three of such classes: weapon, armor, orb. Besides, there's a whole new world hidden inside each item. We can increase an item's level travelling to its world. We can also capture the so-called residents in the Item World Residents are the creatures that live inside items. Each resident gives some bonus to the item in which it is currently located. We will only consider residents of types: gladiator (who improves the item's atk), sentry (who improves def) and physician (who improves res). Each item has the size parameter. The parameter limits the maximum number of residents that can live inside an item. We can move residents between items. Within one moment of time we can take some resident from an item and move it to some other item if it has a free place for a new resident. We cannot remove a resident from the items and leave outside β€” any of them should be inside of some item at any moment of time. Laharl has a certain number of items. He wants to move the residents between items so as to equip himself with weapon, armor and a defensive orb. The weapon's atk should be largest possible in the end. Among all equipping patterns containing weapon's maximum atk parameter we should choose the ones where the armor’s def parameter is the largest possible. Among all such equipment patterns we should choose the one where the defensive orb would have the largest possible res parameter. Values of the parameters def and res of weapon, atk and res of armor and atk and def of orb are indifferent for Laharl. Find the optimal equipment pattern Laharl can get. Input The first line contains number n (3 ≀ n ≀ 100) β€” representing how many items Laharl has. Then follow n lines. Each line contains description of an item. The description has the following form: "name class atk def res size" β€” the item's name, class, basic attack, defense and resistance parameters and its size correspondingly. * name and class are strings and atk, def, res and size are integers. * name consists of lowercase Latin letters and its length can range from 1 to 10, inclusive. * class can be "weapon", "armor" or "orb". * 0 ≀ atk, def, res ≀ 1000. * 1 ≀ size ≀ 10. It is guaranteed that Laharl has at least one item of each class. The next line contains an integer k (1 ≀ k ≀ 1000) β€” the number of residents. Then k lines follow. Each of them describes a resident. A resident description looks like: "name type bonus home" β€” the resident's name, his type, the number of points the resident adds to the item's corresponding parameter and the name of the item which currently contains the resident. * name, type and home are strings and bonus is an integer. * name consists of lowercase Latin letters and its length can range from 1 to 10, inclusive. * type may be "gladiator", "sentry" or "physician". * 1 ≀ bonus ≀ 100. It is guaranteed that the number of residents in each item does not exceed the item's size. The names of all items and residents are pairwise different. All words and numbers in the input are separated by single spaces. Output Print on the first line the name of the weapon in the optimal equipping pattern; then print the number of residents the weapon contains; then print the residents' names. Print on the second and third lines in the same form the names of the armor and defensive orb as well as the residents they contain. Use single spaces for separation. If there are several possible solutions, print any of them. Examples Input 4 sword weapon 10 2 3 2 pagstarmor armor 0 15 3 1 iceorb orb 3 2 13 2 longbow weapon 9 1 2 1 5 mike gladiator 5 longbow bobby sentry 6 pagstarmor petr gladiator 7 iceorb teddy physician 6 sword blackjack sentry 8 sword Output sword 2 petr mike pagstarmor 1 blackjack iceorb 2 teddy bobby Input 4 sword weapon 10 2 3 2 pagstarmor armor 0 15 3 1 iceorb orb 3 2 13 2 longbow weapon 9 1 2 1 6 mike gladiator 5 longbow bobby sentry 6 pagstarmor petr gladiator 7 iceorb teddy physician 6 sword blackjack sentry 8 sword joe physician 6 iceorb Output longbow 1 mike pagstarmor 1 bobby iceorb 2 petr joe Note In the second sample we have no free space inside the items, therefore we cannot move the residents between them.
# written with help of failed tests def searchBest(iType, number, rType, countResidents): global items, equipped best = 0 ret = None for item, params in items.items(): if params[0] == iType: val = int(params[number]) if countResidents: for resid in equipped[item]: if resid[1] == rType: val += int(resid[2]) if val > best: best = val ret = item return ret def printItem(item): global equipped print(item, len(equipped[item]), ' '.join([x[0] for x in equipped[item]])) def searchFor(iType, number, might): global items, equipped, liesIn pSum = [0] for x in might: pSum.append(pSum[-1] + int(x[2])) while len(pSum) < 11: pSum.append(pSum[-1]) bestVal = 0 for item, params in items.items(): if params[0] == iType: val = int(params[number]) + pSum[int(params[4])] if val > bestVal: bestVal = val for item, params in items.items(): if params[0] == iType: val = int(params[number]) + pSum[int(params[4])] if val == bestVal: for i in range(min(int(params[4]), len(might))): want = might[i] equipped[liesIn[want[0]]].remove(want) liesIn[want[0]] = item if len(equipped[item]) == int(params[4]): rm = equipped[item][0] liesIn[rm[0]] = want[3] equipped[want[3]] = [rm] + equipped[want[3]] equipped[item].remove(rm) equipped[item].append(want) return item def rel(item): global liesIn, equipped, items while len(equipped[item]) > int(items[item][4]): toDelete = equipped[item][0] for other in items: if len(equipped[other]) < int(items[other][4]): liesIn[toDelete[0]] = other equipped[other].append(toDelete) break equipped[item] = equipped[item][1:] n = int(input()) items = dict() equipped = dict() for i in range(n): t = tuple(input().split()) items[t[0]] = t[1:] equipped[t[0]] = [] k = int(input()) residents = [None for i in range(k)] glads = dict() liesIn = dict() for i in range(k): residents[i] = tuple(input().split()) equipped[residents[i][3]] = equipped.get(residents[i][3], []) + [residents[i]] liesIn[residents[i][0]] = residents[i][3] canSwap = False for name, val in equipped.items(): if len(val) < int(items[name][4]): canSwap = True if canSwap: glads = sorted([x for x in residents if x[1] == 'gladiator'], key = lambda x: -int(x[2])) sentries = sorted([x for x in residents if x[1] == 'sentry'], key = lambda x: -int(x[2])) phys = sorted([x for x in residents if x[1] == 'physician'], key = lambda x: -int(x[2])) wp = searchFor('weapon', 1, glads) ar = searchFor('armor', 2, sentries) orb = searchFor('orb', 3, phys) rel(wp) rel(ar) rel(orb) printItem(wp) printItem(ar) printItem(orb) else: printItem(searchBest('weapon', 1, 'gladiator', True)) printItem(searchBest('armor', 2, 'sentry', True)) printItem(searchBest('orb', 3, 'physician', True))
{ "input": [ "4\nsword weapon 10 2 3 2\npagstarmor armor 0 15 3 1\niceorb orb 3 2 13 2\nlongbow weapon 9 1 2 1\n6\nmike gladiator 5 longbow\nbobby sentry 6 pagstarmor\npetr gladiator 7 iceorb\nteddy physician 6 sword\nblackjack sentry 8 sword\njoe physician 6 iceorb\n", "4\nsword weapon 10 2 3 2\npagstarmor armor 0 15 3 1\niceorb orb 3 2 13 2\nlongbow weapon 9 1 2 1\n5\nmike gladiator 5 longbow\nbobby sentry 6 pagstarmor\npetr gladiator 7 iceorb\nteddy physician 6 sword\nblackjack sentry 8 sword\n" ], "output": [ "longbow 1 mike\npagstarmor 1 bobby\niceorb 2 petr joe\n", "sword 2 petr mike \npagstarmor 1 blackjack \niceorb 2 teddy bobby \n" ] }
85
10
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago. You are given a connected undirected graph with n vertices and m weighted edges. There are k special vertices: x_1, x_2, …, x_k. Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them. For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them. The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him. Input The first line contains three integers n, m and k (2 ≀ k ≀ n ≀ 10^5, n-1 ≀ m ≀ 10^5) β€” the number of vertices, the number of edges and the number of special vertices. The second line contains k distinct integers x_1, x_2, …, x_k (1 ≀ x_i ≀ n). Each of the following m lines contains three integers u, v and w (1 ≀ u,v ≀ n, 1 ≀ w ≀ 10^9), denoting there is an edge between u and v of weight w. The given graph is undirected, so an edge (u, v) can be used in the both directions. The graph may have multiple edges and self-loops. It is guaranteed, that the graph is connected. Output The first and only line should contain k integers. The i-th integer is the distance between x_i and the farthest special vertex from it. Examples Input 2 3 2 2 1 1 2 3 1 2 2 2 2 1 Output 2 2 Input 4 5 3 1 2 3 1 2 5 4 2 1 2 3 2 1 4 4 1 3 3 Output 3 3 3 Note In the first example, the distance between vertex 1 and 2 equals to 2 because one can walk through the edge of weight 2 connecting them. So the distance to the farthest node for both 1 and 2 equals to 2. In the second example, one can find that distance between 1 and 2, distance between 1 and 3 are both 3 and the distance between 2 and 3 is 2. The graph may have multiple edges between and self-loops, as in the first example.
def g(): return map(int,input().split()) n,m,k=g() p=list(range(n+1)) z=[0]*(n+1) for x in g(): z[x]=1 e=[] for i in range(m): u,v,w=g() e+=[(w,u,v)] e=sorted(e) def q(x): if x!=p[x]: p[x]=q(p[x]) return p[x] for w,u,v in e: u=q(u);v=q(v) if u!=v: if u%5==3: u,v=v,u p[u]=v;z[v]+=z[u] if z[v]==k: print((str(w)+' ')*k);exit(0)
{ "input": [ "4 5 3\n1 2 3\n1 2 5\n4 2 1\n2 3 2\n1 4 4\n1 3 3\n", "2 3 2\n2 1\n1 2 3\n1 2 2\n2 2 1\n" ], "output": [ "3 3 3 ", "2 2 " ] }
86
7
Alice received a set of Toy Trainβ„’ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≀ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described. Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≀ i ≀ m), now at station a_i, should be delivered to station b_i (a_i β‰  b_i). <image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible. Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 5 000; 1 ≀ m ≀ 20 000) β€” the number of stations and the number of candies, respectively. The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≀ a_i, b_i ≀ n; a_i β‰  b_i) β€” the station that initially contains candy i and the destination station of the candy, respectively. Output In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i. Examples Input 5 7 2 4 5 1 2 3 3 4 4 1 5 3 3 5 Output 10 9 10 10 9 Input 2 3 1 2 1 2 1 2 Output 5 6 Note Consider the second sample. If the train started at station 1, the optimal strategy is as follows. 1. Load the first candy onto the train. 2. Proceed to station 2. This step takes 1 second. 3. Deliver the first candy. 4. Proceed to station 1. This step takes 1 second. 5. Load the second candy onto the train. 6. Proceed to station 2. This step takes 1 second. 7. Deliver the second candy. 8. Proceed to station 1. This step takes 1 second. 9. Load the third candy onto the train. 10. Proceed to station 2. This step takes 1 second. 11. Deliver the third candy. Hence, the train needs 5 seconds to complete the tasks. If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.
# import numpy as np def dist(a, b): return (b - a) % n n, m = list(map(int, input().split(" "))) sweets = {i: [] for i in range(n)} for i in range(m): s, t = list(map(int, input().split(" "))) sweets[s - 1].append(t - 1) t = {i: -1e6 for i in range(n)} for i in range(n): sweets[i] = sorted(sweets[i], key=lambda x: -dist(i, x)) if len(sweets[i]): t[i] = (len(sweets[i]) - 1) * n + dist(i, sweets[i][-1]) # t = np.array([t[i] for i in range(n)], dtype=int) # raise ValueError("") # print(t) result = [] m_max, i_max = 0, 0 for i, v in t.items(): if v + i > m_max + i_max: m_max, i_max = v, i result.append(m_max + i_max) for s in range(1, n): old_max = t[i_max] + dist(s, i_max) new_max = t[s - 1] + dist(s, s - 1) if new_max > old_max: result.append(new_max) i_max = s - 1 else: result.append(old_max) print(" ".join(map(str, result)))
{ "input": [ "2 3\n1 2\n1 2\n1 2\n", "5 7\n2 4\n5 1\n2 3\n3 4\n4 1\n5 3\n3 5\n" ], "output": [ "5 6 ", "10 9 10 10 9 " ] }
87
8
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters. The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: 1, 2, 3, so that each character is painted in at most one color, and the description of the i-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color i. The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace. Input The first line of the input contains two integers n, q (1 ≀ n ≀ 100 000, 1 ≀ q ≀ 1000) β€” the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe β€” a string of length n consisting of lowercase English characters. Each of the following line describes a single evolution and is in one of the following formats: * + i c (i ∈ \{1, 2, 3\}, c ∈ \{a, b, ..., z\}: append the character c to the end of i-th religion description. * - i (i ∈ \{1, 2, 3\}) – remove the last character from the i-th religion description. You can assume that the pattern is non-empty. You can assume that no religion will have description longer than 250 characters. Output Write q lines. The i-th of them should be YES if the religions could coexist in peace after the i-th evolution, or NO otherwise. You can print each character in any case (either upper or lower). Examples Input 6 8 abdabc + 1 a + 1 d + 2 b + 2 c + 3 a + 3 b + 1 c - 2 Output YES YES YES YES YES YES NO YES Input 6 8 abbaab + 1 a + 2 a + 3 a + 1 b + 2 b + 3 b - 1 + 2 z Output YES YES YES YES YES NO YES NO Note In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe: <image>
n, q = map(int, input().split()) s = '!' + input() nxt = [[n + 1] * (n + 2) for _ in range(26)] for i in range(n - 1, -1, -1): c = ord(s[i + 1]) - 97 for j in range(26): nxt[j][i] = nxt[j][i + 1] nxt[c][i] = i + 1 w = [[-1], [-1], [-1]] idx = lambda i, j, k: i * 65536 + j * 256 + k dp = [0] * (256 * 256 * 256) def calc(fix=None): r = list(map(range, (len(w[0]), len(w[1]), len(w[2])))) if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix])) for i in r[0]: for j in r[1]: for k in r[2]: dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1, nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1, nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1) if i == j == k == 0: dp[idx(i, j, k)] = 0 out = [] for _ in range(q): t, *r = input().split() if t == '+': i, c = int(r[0]) - 1, ord(r[1]) - 97 w[i].append(c) calc(i) else: i = int(r[0]) - 1 w[i].pop() req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)] out.append('YES' if req <= n else 'NO') print(*out, sep='\n')
{ "input": [ "6 8\nabdabc\n+ 1 a\n+ 1 d\n+ 2 b\n+ 2 c\n+ 3 a\n+ 3 b\n+ 1 c\n- 2\n", "6 8\nabbaab\n+ 1 a\n+ 2 a\n+ 3 a\n+ 1 b\n+ 2 b\n+ 3 b\n- 1\n+ 2 z\n" ], "output": [ "YES\nYES\nYES\nYES\nYES\nYES\nNO\nYES\n", "YES\nYES\nYES\nYES\nYES\nNO\nYES\nNO\n" ] }
88
7
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem. Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For example, 1, 101, 0000 are good, while 01, 1001, and 111000 are not good. We are given a string s of length n consisting of only zeroes and ones. We need to cut s into minimal possible number of substrings s_1, s_2, …, s_k such that all of them are good. More formally, we have to find minimal by number of strings sequence of good strings s_1, s_2, …, s_k such that their concatenation (joining) equals s, i.e. s_1 + s_2 + ... + s_k = s. For example, cuttings 110010 into 110 and 010 or into 11 and 0010 are valid, as 110, 010, 11, 0010 are all good, and we can't cut 110010 to the smaller number of substrings as 110010 isn't good itself. At the same time, cutting of 110010 into 1100 and 10 isn't valid as both strings aren't good. Also, cutting of 110010 into 1, 1, 0010 isn't valid, as it isn't minimal, even though all 3 strings are good. Can you help Keanu? We can show that the solution always exists. If there are multiple optimal answers, print any. Input The first line of the input contains a single integer n (1≀ n ≀ 100) β€” the length of the string s. The second line contains the string s of length n consisting only from zeros and ones. Output In the first line, output a single integer k (1≀ k) β€” a minimal number of strings you have cut s into. In the second line, output k strings s_1, s_2, …, s_k separated with spaces. The length of each string has to be positive. Their concatenation has to be equal to s and all of them have to be good. If there are multiple answers, print any. Examples Input 1 1 Output 1 1 Input 2 10 Output 2 1 0 Input 6 100011 Output 2 100 011 Note In the first example, the string 1 wasn't cut at all. As it is good, the condition is satisfied. In the second example, 1 and 0 both are good. As 10 isn't good, the answer is indeed minimal. In the third example, 100 and 011 both are good. As 100011 isn't good, the answer is indeed minimal.
input() s = input() def good(s) : return s.count("0") == s.count("1") if not good(s) : print(1) print(s) else : print(2) print(s[0], s[1:])
{ "input": [ "1\n1\n", "6\n100011\n", "2\n10\n" ], "output": [ "1\n1\n", "2\n1 00011\n", "2\n1 0\n" ] }
89
7
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: * f(0) = a; * f(1) = b; * f(n) = f(n-1) βŠ• f(n-2) when n > 1, where βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). You are given three integers a, b, and n, calculate f(n). You have to answer for T independent test cases. Input The input contains one or more independent test cases. The first line of input contains a single integer T (1 ≀ T ≀ 10^3), the number of test cases. Each of the T following lines contains three space-separated integers a, b, and n (0 ≀ a, b, n ≀ 10^9) respectively. Output For each test case, output f(n). Example Input 3 3 4 2 4 5 0 325 265 1231232 Output 7 4 76 Note In the first example, f(2) = f(0) βŠ• f(1) = 3 βŠ• 4 = 7.
def solve(): x,y,z=map(int,input().split()) s=[x,y,x^y] print(s[z%3]) for n in range(int(input())): solve()
{ "input": [ "3\n3 4 2\n4 5 0\n325 265 1231232\n" ], "output": [ "7\n4\n76\n" ] }
90
7
Your math teacher gave you the following problem: There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], …, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l ≀ x ≀ r. The length of the segment [l; r] is equal to r - l. Two segments [a; b] and [c; d] have a common point (intersect) if there exists x that a ≀ x ≀ b and c ≀ x ≀ d. For example, [2; 5] and [3; 10] have a common point, but [5; 6] and [1; 4] don't have. You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given n segments. In other words, you need to find a segment [a; b], such that [a; b] and every [l_i; r_i] have a common point for each i, and b-a is minimal. Input The first line contains integer number t (1 ≀ t ≀ 100) β€” the number of test cases in the input. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 10^{5}) β€” the number of segments. The following n lines contain segment descriptions: the i-th of them contains two integers l_i,r_i (1 ≀ l_i ≀ r_i ≀ 10^{9}). The sum of all values n over all the test cases in the input doesn't exceed 10^5. Output For each test case, output one integer β€” the smallest possible length of the segment which has at least one common point with all given segments. Example Input 4 3 4 5 5 9 7 7 5 11 19 4 17 16 16 3 12 14 17 1 1 10 1 1 1 Output 2 4 0 0 Note In the first test case of the example, we can choose the segment [5;7] as the answer. It is the shortest segment that has at least one common point with all given segments.
def iinput(): return [int(i) for i in input().split()] t = int(input()) for _ in range(t): n = int(input()) max_l = 0 min_r = 10**9 + 1 for _ in range(n): l, r = iinput() min_r = min(min_r, r) max_l = max(max_l, l) print(max(0, max_l - min_r))
{ "input": [ "4\n3\n4 5\n5 9\n7 7\n5\n11 19\n4 17\n16 16\n3 12\n14 17\n1\n1 10\n1\n1 1\n" ], "output": [ "2\n4\n0\n0\n" ] }
91
10
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≑ 0 (mod 2a), * |x - y| ≑ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 β€” the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≀ a, b ≀ 109 and |x1|,|y1|,|x2|,|y2| ≀ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number β€” the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
def f(a,b,x,y,z,w): c=(x+y) // (2*a) d=(z+w) // (2*a) e=(x-y) // (2*b) f=(z-w) // (2*b) return max(abs(c-d),abs(e-f)) a,b,x,y,z,w=map(int,input().split()) print(f(a,b,x,y,z,w))
{ "input": [ "2 2 1 0 0 1\n", "2 2 10 11 0 1\n", "2 4 3 -1 3 7\n" ], "output": [ "1", "5", "2" ] }
92
8
You are given a positive integer m and two integer sequence: a=[a_1, a_2, …, a_n] and b=[b_1, b_2, …, b_n]. Both of these sequence have a length n. Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [0], [1,1], [2,3]. You need to find the non-negative integer x, and increase all elements of a_i by x, modulo m (i.e. you want to change a_i to (a_i + x) mod m), so it would be possible to rearrange elements of a to make it equal b, among them you need to find the smallest possible x. In other words, you need to find the smallest non-negative integer x, for which it is possible to find some permutation p=[p_1, p_2, …, p_n], such that for all 1 ≀ i ≀ n, (a_i + x) mod m = b_{p_i}, where y mod m β€” remainder of division of y by m. For example, if m=3, a = [0, 0, 2, 1], b = [2, 0, 1, 1], you can choose x=1, and a will be equal to [1, 1, 0, 2] and you can rearrange it to make it equal [2, 0, 1, 1], which is equal to b. Input The first line contains two integers n,m (1 ≀ n ≀ 2000, 1 ≀ m ≀ 10^9): number of elemens in arrays and m. The second line contains n integers a_1, a_2, …, a_n (0 ≀ a_i < m). The third line contains n integers b_1, b_2, …, b_n (0 ≀ b_i < m). It is guaranteed that there exists some non-negative integer x, such that it would be possible to find some permutation p_1, p_2, …, p_n such that (a_i + x) mod m = b_{p_i}. Output Print one integer, the smallest non-negative integer x, such that it would be possible to find some permutation p_1, p_2, …, p_n such that (a_i + x) mod m = b_{p_i} for all 1 ≀ i ≀ n. Examples Input 4 3 0 0 2 1 2 0 1 1 Output 1 Input 3 2 0 0 0 1 1 1 Output 1 Input 5 10 0 0 0 1 2 2 1 0 0 0 Output 0
def solve(a,b,m,n): ans=m for i in range(n): x=(m+b[i]-a[0])%m for j in range(n): if (a[j]+x)%m!=b[(i+j)%n]:break else:ans=min(ans,x) return ans n,m=map(int,input().split()) a=sorted(list(map(int,input().split())));b=sorted(list(map(int,input().split())));print(solve(a,b,m,n))
{ "input": [ "3 2\n0 0 0\n1 1 1\n", "4 3\n0 0 2 1\n2 0 1 1\n", "5 10\n0 0 0 1 2\n2 1 0 0 0\n" ], "output": [ "1", "1", "0" ] }
93
8
You're given an array a_1, …, a_n of n non-negative integers. Let's call it sharpened if and only if there exists an integer 1 ≀ k ≀ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: * The arrays [4], [0, 1], [12, 10, 8] and [3, 11, 15, 9, 7, 4] are sharpened; * The arrays [2, 8, 2, 8, 6, 5], [0, 1, 1, 0] and [2, 5, 6, 9, 8, 8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any i (1 ≀ i ≀ n) such that a_i>0 and assign a_i := a_i - 1. Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 15\ 000) β€” the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer n (1 ≀ n ≀ 3 β‹… 10^5). The second line of each test case contains a sequence of n non-negative integers a_1, …, a_n (0 ≀ a_i ≀ 10^9). It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise. Example Input 10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 Output Yes Yes Yes No No Yes Yes Yes Yes No Note In the first and the second test case of the first test, the given array is already sharpened. In the third test case of the first test, we can transform the array into [3, 11, 15, 9, 7, 4] (decrease the first element 97 times and decrease the last element 4 times). It is sharpened because 3 < 11 < 15 and 15 > 9 > 7 > 4. In the fourth test case of the first test, it's impossible to make the given array sharpened.
def f(a): for i in range(len(a)): if a[i] < i: return i-1 return len(a)-1 def solve(a): i = f(a) j = len(a) - 1 - f(a[::-1]) return "Yes" if i >= j else "No" n = int(input()) for i in range(n): input() a = list(map(int, input().strip().split())) print(solve(a))
{ "input": [ "10\n1\n248618\n3\n12 10 8\n6\n100 11 15 9 7 8\n4\n0 1 1 0\n2\n0 0\n2\n0 1\n2\n1 0\n2\n1 1\n3\n0 1 0\n3\n1 0 1\n" ], "output": [ "Yes\nYes\nYes\nNo\nNo\nYes\nYes\nYes\nYes\nNo\n" ] }
94
9
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again. You know that you will spend m wrong tries to perform the combo and during the i-th try you will make a mistake right after p_i-th button (1 ≀ p_i < n) (i.e. you will press first p_i buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1-th try you press all buttons right and finally perform the combo. I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'. Your task is to calculate for each button (letter) the number of times you'll press it. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains two integers n and m (2 ≀ n ≀ 2 β‹… 10^5, 1 ≀ m ≀ 2 β‹… 10^5) β€” the length of s and the number of tries correspondingly. The second line of each test case contains the string s consisting of n lowercase Latin letters. The third line of each test case contains m integers p_1, p_2, ..., p_m (1 ≀ p_i < n) β€” the number of characters pressed right during the i-th try. It is guaranteed that the sum of n and the sum of m both does not exceed 2 β‹… 10^5 (βˆ‘ n ≀ 2 β‹… 10^5, βˆ‘ m ≀ 2 β‹… 10^5). It is guaranteed that the answer for each letter does not exceed 2 β‹… 10^9. Output For each test case, print the answer β€” 26 integers: the number of times you press the button 'a', the number of times you press the button 'b', ..., the number of times you press the button 'z'. Example Input 3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 Output 4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 Note The first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is 4, 'b' is 2 and 'c' is 2. In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 9, 'd' is 4, 'e' is 5, 'f' is 3, 'o' is 9, 'r' is 3 and 's' is 1.
def func(x): return ord(x) - ord('a') t = int(input()) while(t): t -= 1 n, m = list(map(int, input().split())) a = list(map(func, list(input()))) p = sorted(list(map(int, input().split()))) count = [0] * 26 j = 0 c = m+1 for i in range(n): while(j < m and p[j] == i): c -= 1 j += 1 count[a[i]] += c print(*count)
{ "input": [ "3\n4 2\nabca\n1 3\n10 5\ncodeforces\n2 8 3 2 9\n26 10\nqwertyuioplkjhgfdsazxcvbnm\n20 10 1 2 3 5 10 5 9 4\n" ], "output": [ "4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n\n0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 \n\n2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 \n\n" ] }
95
7
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level. All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by 1. If he manages to finish the level successfully then the number of clears increases by 1 as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears). Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be. So he peeked at the stats n times and wrote down n pairs of integers β€” (p_1, c_1), (p_2, c_2), ..., (p_n, c_n), where p_i is the number of plays at the i-th moment of time and c_i is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down). Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level. Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct. Help him to check the correctness of his records. For your convenience you have to answer multiple independent test cases. Input The first line contains a single integer T (1 ≀ T ≀ 500) β€” the number of test cases. The first line of each test case contains a single integer n (1 ≀ n ≀ 100) β€” the number of moments of time Polycarp peeked at the stats. Each of the next n lines contains two integers p_i and c_i (0 ≀ p_i, c_i ≀ 1000) β€” the number of plays and the number of clears of the level at the i-th moment of time. Note that the stats are given in chronological order. Output For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower). Example Input 6 3 0 0 1 1 1 2 2 1 0 1000 3 4 10 1 15 2 10 2 15 2 1 765 432 2 4 4 4 3 5 0 0 1 0 1 0 1 0 1 0 Output NO YES NO YES NO YES Note In the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened. The second test case is a nice example of a Super Expert level. In the third test case the number of plays decreased, which is impossible. The fourth test case is probably an auto level with a single jump over the spike. In the fifth test case the number of clears decreased, which is also impossible. Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.
from sys import stdin def main(): inp=stdin.readline for _ in range(int(inp())): n=int(inp()) pp,cp=0,0 ans="YES" for i in range(n): p,c=map(int, inp().split()) if p>=pp and c<=p and c >=cp and c-cp<=p-pp: pp=p cp=c continue else: ans="NO" pp=p cp=c print(ans) main()
{ "input": [ "6\n3\n0 0\n1 1\n1 2\n2\n1 0\n1000 3\n4\n10 1\n15 2\n10 2\n15 2\n1\n765 432\n2\n4 4\n4 3\n5\n0 0\n1 0\n1 0\n1 0\n1 0\n" ], "output": [ "NO\nYES\nNO\nYES\nNO\nYES\n" ] }
96
9
The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 β‹… n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon. Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square. You can rotate 2n-gon and/or the square. Input The first line contains a single integer T (1 ≀ T ≀ 200) β€” the number of test cases. Next T lines contain descriptions of test cases β€” one per line. Each line contains single odd integer n (3 ≀ n ≀ 199). Don't forget you need to embed 2n-gon, not an n-gon. Output Print T real numbers β€” one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}. Example Input 3 3 5 199 Output 1.931851653 3.196226611 126.687663595
import math as np def fun(): n = int(input()) print(1/(2*np.sin(np.pi/(4*n)))) T = int(input()) for _ in range(1,T+1): fun()
{ "input": [ "3\n3\n5\n199\n" ], "output": [ "1.931851653\n3.196226611\n126.687663797\n" ] }
97
8
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 2 β‹… 10^4) β€” the number of test cases. Then t test cases follow. The only line of the test case contains one integer n (1 ≀ n ≀ 10^9). Output For each test case, print the answer β€” the minimum number of moves needed to obtain 1 from n if it's possible to do that or -1 if it's impossible to obtain 1 from n. Example Input 7 1 2 3 12 12345 15116544 387420489 Output 0 -1 2 -1 -1 12 36 Note Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer 15116544: 1. Divide by 6 and get 2519424; 2. divide by 6 and get 419904; 3. divide by 6 and get 69984; 4. divide by 6 and get 11664; 5. multiply by 2 and get 23328; 6. divide by 6 and get 3888; 7. divide by 6 and get 648; 8. divide by 6 and get 108; 9. multiply by 2 and get 216; 10. divide by 6 and get 36; 11. divide by 6 and get 6; 12. divide by 6 and get 1.
n=int(input()) def f(a): res=0 while a%6==0: a/=6 res+=1 while a%3==0: a/=3 res+=2 if a==1: return res else: return -1 for i in range(n): num=int(input()) print(f(num))
{ "input": [ "7\n1\n2\n3\n12\n12345\n15116544\n387420489\n" ], "output": [ "0\n-1\n2\n-1\n-1\n12\n36\n" ] }
98
9
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of a equal to zero. Input The first line contains one integer n (1 ≀ n ≀ 100 000): the number of elements of the array. The second line contains n elements of an array a separated by spaces: a_1, a_2, ..., a_n (-10^9 ≀ a_i ≀ 10^9). Output The output should contain six lines representing three operations. For each operation, print two lines: * The first line contains two integers l, r (1 ≀ l ≀ r ≀ n): the bounds of the selected segment. * The second line contains r-l+1 integers b_l, b_{l+1}, ..., b_r (-10^{18} ≀ b_i ≀ 10^{18}): the numbers to add to a_l, a_{l+1}, …, a_r, respectively; b_i should be divisible by r - l + 1. Example Input 4 1 3 2 4 Output 1 1 -1 3 4 4 2 2 4 -3 -6 -6
mod = 10**9 + 7 def solve(): n = int(input()) a = list(map(int, input().split())) if n == 1: print(1, 1) print(0) else: print(1, n - 1) for i in range(0, n - 1): print(a[i] * (n - 1), end = ' ') a[i] = a[i] * n print() print(n, n) print(-a[n - 1]) a[n - 1] = 0 print(1, n) for i in range(n): a[i] = -a[i] print(*a) t = 1 while t > 0: solve() t -= 1
{ "input": [ "4\n1 3 2 4\n" ], "output": [ "1 1\n-1\n2 4\n9 6 12 \n1 4\n0 -12 -8 -16 \n" ] }
99
10
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened. Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door. There are n lamps with Spirit Tree's light. Sein knows the time of turning on and off for the i-th lamp β€” l_i and r_i respectively. To open the door you have to choose k lamps in such a way that there will be a moment of time when they all will be turned on. While Sein decides which of the k lamps to pick, Ori is interested: how many ways there are to pick such k lamps that the door will open? It may happen that Sein may be wrong and there are no such k lamps. The answer might be large, so print it modulo 998 244 353. Input First line contains two integers n and k (1 ≀ n ≀ 3 β‹… 10^5, 1 ≀ k ≀ n) β€” total number of lamps and the number of lamps that must be turned on simultaneously. Next n lines contain two integers l_i ans r_i (1 ≀ l_i ≀ r_i ≀ 10^9) β€” period of time when i-th lamp is turned on. Output Print one integer β€” the answer to the task modulo 998 244 353. Examples Input 7 3 1 7 3 8 4 5 6 7 1 3 5 10 8 9 Output 9 Input 3 1 1 1 2 2 3 3 Output 3 Input 3 2 1 1 2 2 3 3 Output 0 Input 3 3 1 3 2 3 3 3 Output 1 Input 5 2 1 3 2 4 3 5 4 6 5 7 Output 7 Note In first test case there are nine sets of k lamps: (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (2, 3, 6), (2, 4, 6), (2, 6, 7). In second test case k=1, so the answer is 3. In third test case there are no such pairs of lamps. In forth test case all lamps are turned on in a time 3, so the answer is 1. In fifth test case there are seven sets of k lamps: (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5).
from sys import stdin import math m = 998244353 def put(): return map(int, stdin.readline().split()) def inv(a,b): return (pow(b, m-2, m)*(a%m))%m n, k = put() C = [0]*(n+1) C[k-1] = 1 for i in range(k, n+1): C[i] = inv(C[i-1]*i,i-k+1) l,r = [],[] for _ in range(n): a,b = put() l.append(a) r.append(b) l.sort() r.sort() i,j = 0,0 count = 0 ans = 0 while i<n and j<n: if l[i]<=r[j]: ans += C[count] count+=1 i+=1 else: count-=1 j+=1 print(ans%m)
{ "input": [ "3 3\n1 3\n2 3\n3 3\n", "3 1\n1 1\n2 2\n3 3\n", "7 3\n1 7\n3 8\n4 5\n6 7\n1 3\n5 10\n8 9\n", "3 2\n1 1\n2 2\n3 3\n", "5 2\n1 3\n2 4\n3 5\n4 6\n5 7\n" ], "output": [ "1\n", "3\n", "9\n", "0\n", "7\n" ] }