Unnamed: 0
int64
0
999
name
stringlengths
9
60
description
stringlengths
168
5.26k
solution
stringlengths
38
20.8k
0
1037_E. Trips
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'))
1
1060_A. Phone Numbers
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() k = s.count("8") l = n - k if k <= l//10: print(k) else: while k > l//10: k -= 1 l += 1 print(min(k, l//10))
2
1101_A. Minimum Integer
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
n = int(input()) A = [] for i in range(n): A = A+[input().split()] for a in A: if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]): print(a[2]) else: print(int(a[2])*(int(a[1])//int(a[2])+1))
3
1189_D1. Add on a Tree
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>
m = int(input()) l = [0 for _ in range(m + 1)] for _ in range(m - 1): a,b = map(int, input().split()) l[a] += 1 l[b] += 1 if 2 in l: print("NO") else: print("YES")
4
1208_D. Restore Permutation
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.
from sys import stdin,stdout class Tree(object): def __init__(self,n): self.tree=[0]*(4*n+10) self.b=[0]*(n+10) self.a=list(map(int,stdin.readline().split())) self.n=n def update(self,L,C,l,r,rt): if l==r: self.tree[rt]+=C return mid=(l+r)//2 if L<=mid: self.update(L,C,l,mid,rt<<1) else: self.update(L,C,mid+1,r,rt<<1|1) self.tree[rt]=self.tree[rt<<1]+self.tree[rt<<1|1] def query(self,s,l,r,rt): if l==r: return l mid=(l+r)//2 if self.tree[rt<<1]>s: return self.query(s,l,mid,rt<<1) else: return self.query(s-self.tree[rt<<1],mid+1,r,rt<<1|1) def slove(self): for i in range(n): self.update(i+1,i+1,1,n,1) for i in range(n,0,-1): self.b[i]=self.query(self.a[i-1],1,n,1) self.update(self.b[i],-self.b[i],1,n,1) for i in range(n): stdout.write('%d '%(self.b[i+1])) if __name__ == '__main__': n=int(stdin.readline()) seg=Tree(n) seg.slove()
5
1227_D1. Optimal Subsequences (Easy Version)
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].
# class SegmentTree(): # adapted from https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ # def __init__(self,arr,func,initialRes=0): # self.f=func # self.N=len(arr) # self.tree=[0 for _ in range(2*self.N)] # self.initialRes=initialRes # for i in range(self.N): # self.tree[self.N+i]=arr[i] # for i in range(self.N-1,0,-1): # self.tree[i]=self.f(self.tree[i<<1],self.tree[i<<1|1]) # def updateTreeNode(self,idx,value): #update value at arr[idx] # self.tree[idx+self.N]=value # idx+=self.N # i=idx # while i>1: # self.tree[i>>1]=self.f(self.tree[i],self.tree[i^1]) # i>>=1 # def query(self,l,r): #get sum (or whatever function) on interval [l,r] inclusive # r+=1 # res=self.initialRes # l+=self.N # r+=self.N # while l<r: # if l&1: # res=self.f(res,self.tree[l]) # l+=1 # if r&1: # r-=1 # res=self.f(res,self.tree[r]) # l>>=1 # r>>=1 # return res # def getMaxSegTree(arr): # return SegmentTree(arr,lambda a,b:max(a,b),initialRes=-float('inf')) # def getMinSegTree(arr): # return SegmentTree(arr,lambda a,b:min(a,b),initialRes=float('inf')) # def getSumSegTree(arr): # return SegmentTree(arr,lambda a,b:a+b,initialRes=0) from collections import Counter def main(): # mlogn solution n=int(input()) a=readIntArr() b=sorted(a,reverse=True) m=int(input()) allans=[] for _ in range(m): k,pos=readIntArr() cnt=Counter(b[:k]) totalCnts=0 for x in a: if cnt[x]>0: cnt[x]-=1 totalCnts+=1 if totalCnts==pos: allans.append(x) break multiLineArrayPrint(allans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(i,j): print('? {} {}'.format(i,j)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(' '.join([str(x) for x in ans]))) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 for _abc in range(1): main()
6
1269_E. K Integers
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=" ")
7
1291_E. Prefix Enlightenment
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)
8
1334_D. Minimum Euler Cycle
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.
# -*- coding:utf-8 -*- """ created by shuangquan.huang at 2020/7/1 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(n, l, r): # 1, 2, 1, 3, ..., 1, n # 2, 3, 2, 4, ..., 2, n # ... # n-1, n # 1 lo, hi = 1, n while lo <= hi: k = (lo + hi) // 2 s = k * (2*n-1-k) if s < l: lo = k + 1 else: hi = k - 1 k = lo s = k * (2*n-1-k) b = k # [b, b+1, b, b+2, ..., b, n] row = [] for i in range(b+1, n+1): row.append(b) row.append(i) ans = row[l-s-1:] d = r-l+1 if len(ans) >= d: return ans[:d] while len(ans) < d: b += 1 row = [] for i in range(b + 1, n + 1): row.append(b) row.append(i) if not row: break ans += row ans.append(1) # print(ans[:d]) return ans[:d] if __name__ == '__main__': T = int(input()) ans = [] for ti in range(T): N, L, R = map(int, input().split()) ans.append(solve(N, L, R)) print('\n'.join([' '.join(map(str, v)) for v in ans]))
9
1374_E1. Reading Books (easy version)
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
import sys input=sys.stdin.readline f=lambda :list(map(int, input().strip('\n').split())) n, k=f() _11=[] _01=[] _10=[] for _ in range(n): t, a, b=f() if a and b: _11.append(t) elif a: _10.append(t) elif b: _01.append(t) _01.sort(); _10.sort(); _11.sort() for i in range(1, len(_01)): _01[i]+=_01[i-1] for i in range(1, len(_10)): _10[i]+=_10[i-1] for i in range(1, len(_11)): _11[i]+=_11[i-1] ans=3*1e9 if len(_01)>=k and len(_10)>=k: ans=min(ans, _01[k-1]+_10[k-1]) for i in range(len(_11)): if i+1<k and (len(_01)>=k-i-1) and (len(_10)>=k-i-1): ans=min(ans, _11[i]+_01[k-i-2]+_10[k-i-2]) else: if len(_11)>=k: ans=min(ans, _11[k-1]) break print(-1 if ans==3*1e9 else ans)
10
1421_B. Putting Bricks in the Wall
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
l=[] for _ in range(int(input())): n=int(input()) a=[] for i in range(n): a.append(list(input())) if a[0][1]==a[1][0]: if a[n-1][n-2]==a[n-2][n-1]: if a[n-1][n-2]==a[0][1]: l.append("2") l.append("1 2") l.append("2 1") else: l.append("0") else: if a[n-1][n-2]!=a[0][1]: l.append("1") l.append(str(n-1)+" "+str(n)) else: l.append("1") l.append(str(n)+" "+str(n-1)) else: if a[n-1][n-2]==a[n-2][n-1]: if a[n-1][n-2]!=a[0][1]: l.append("1") l.append("2 1") else: l.append("1") l.append("1 2") else: if a[0][1]!=a[n-2][n-1]: l.append("2") l.append("1 2") l.append(str(n-1)+" "+str(n)) else: l.append("2") l.append("2 1") l.append(str(n - 1)+" "+ str(n)) for i in l: print(i)
11
143_A. Help Vasilisa the Wise 2
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.
inn = list(map(int, input().split(" "))) r1 = inn[0] r2 = inn[1] inn = list(map(int, input().split(" "))) c1 = inn[0] c2 = inn[1] inn = list(map(int, input().split(" "))) d1 = inn[0] d2 = inn[1] x = int((d1+c1-r2)/2) y = int(((2*r1)-d1-c1+r2)/2) a = int(((2*c1)-d1-c1+r2)/2) b = int((r2-(2*c1)+d1+c1)/2) if x == y or x == a or x == b or y == a or y == b or a == b or x < 1 or x > 9 or y < 1 or y > 9 or a < 1 or a > 9 or b < 1 or b > 9: print(-1) else: print(x, y) print(a, b)
12
1466_F. Euclid's nightmare
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 return su != sv n, m = map(int, input().split()) s, solo = list(range(m+1)), [0]*(m+1) res, pos = [], set() for i in range(n): p = list(map(int, input().split())) if p[0] == 1: pos.add(p[1]) p1 = _find(s, p[1]) if not solo[p1]: res.append(i+1) solo[p1] = 1 else: pos.add(p[1]) pos.add(p[2]) p1, p2 = _find(s, p[1]), _find(s, p[2]) if not (p1 == p2 or (solo[p1] and solo[p2])): _union(s, p1, p2) res.append(i+1) if solo[p1] or solo[p2]: solo[_find(s, p1)] = 1 cc = 0 for u in pos: su = _find(s, u) cc += 1 if not solo[su] and su == u: cc -= 1 print(pow(2, cc, 10**9+7), len(res)) print(*res)
13
1513_C. Add One
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.
from os import path import sys,time from math import ceil, floor,gcd,log,log2 ,factorial from collections import defaultdict ,Counter , OrderedDict , deque from heapq import heapify , heappush , heappop from bisect import * # from functools import reduce from operator import mul from itertools import permutations maxx, mod = float('inf') , int(1e9 + 7) localsys ,start_time = 0 , time.time() if (path.exists('input.txt')): localsys = 1;sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w'); #left shift --- num*(2**k) --(k - shift) input = sys.stdin.readline N = int(2e5 + 10) dp =[1]*N for i in range(10 , N): dp[i] = (dp[i-9] + dp[i-10])%mod for _ in range(int(input())): n , m = map(int , input().split()) ; ans =0 while n : i = n%10 ; n//=10 ans = (ans + dp[i + m])%mod print(ans) if localsys: print("\n\n\nTime Elased :",time.time() - start_time,"seconds")
14
1540_C1. Converging Array (Easy Version)
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())
15
168_A. Wizards and Demonstration
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.
num,wiz,per = map(int,input().split()) k = 0 while (k+wiz)/num*100 < per: k += 1 print(k)
16
260_B. Ancient Prophesy
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
s=input() n=len(s) l=list("0987654321") cnt={} for i in range(n-9): t=s[i:i+10] if t[0] in l and t[1] in l and t[2]=="-" and t[3] in l and t[4] in l and t[5]=="-" and t[6] in l and t[7] in l and t[8] in l and t[9] in l: if 2013<=int(t[6:11])<=2015 and 1<=int(t[3:5])<=12: if int(t[3:5]) in [1,3,5,7,8,10,12] and 1<=int(t[0:2])<=31: if not t in cnt: cnt[t]=1 else: cnt[t]+=1 elif int(t[3:5]) in [4,6,9,11] and 1<=int(t[0:2])<=30: if not t in cnt: cnt[t]=1 else: cnt[t]+=1 elif int(t[3:5])==2 and 1<=int(t[0:2])<=28: if not t in cnt: cnt[t]=1 else: cnt[t]+=1 print(max(cnt,key=cnt.get))
17
284_B. Cows and Poker Game
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.
#!/bin/python # -*- coding: utf-8 -*- n = int(input()) s = input() print(int(s.count('I') == 1) if 'I' in s else s.count('A'))
18
379_A. New Year Candles
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.
a, b = map(int, input().split()) c, s = a, 0 while a >= b: s += a // b a = (a // b) + (a % b) print(s + c)
19
39_H. Multiplication Table
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action β€” multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix k. Input The first line contains a single integer k (2 ≀ k ≀ 10) β€” the radix of the system. Output Output the multiplication table for the system of notations with the radix k. The table must contain k - 1 rows and k - 1 columns. The element on the crossing of the i-th row and the j-th column is equal to the product of i and j in the system of notations with the radix k. Each line may have any number of spaces between the numbers (the extra spaces in the samples are put for clarity). Examples Input 10 Output 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81 Input 3 Output 1 2 2 11
k=int(input()) for i in range(1,k): z,a=i,[] for j in range(k-1): p,s=z,"" while p: s=str(p%k)+s p//=k z+=i a.append(s) print(*a)
20
44_B. Cola
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,x,y,z,cot): for i in range(z+1): for j in range(y+1): t = rudy - i*2 -j if t>=0 and x*0.5 >= t: cot+=1 return cot rudy, x, y, z = list(map(int,input().split())) cot = 0 print(nik(rudy,x,y,z,cot))
21
519_B. A and B and Compilation Errors
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.
n = int(input()) a_sum = sum(map(int, input().split())) b_sum = sum(map(int, input().split())) c_sum = sum(map(int, input().split())) print(a_sum - b_sum) print(b_sum - c_sum)
22
545_C. Woodcutters
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].
ll=lambda:map(int,input().split()) t=lambda:int(input()) ss=lambda:input() #from math import log10 ,log2,ceil,factorial as f,gcd #from itertools import combinations_with_replacement as cs #from functools import reduce #from bisect import bisect_right as br #from collections import Counter n=t() x,h=[],[] for _ in range(n): a,b=ll() x.append(a) h.append(b) if n>=2: c=2 tx=x[0] for i in range(1,n-1): if x[i]-tx>h[i]: tx=x[i] c+=1 elif x[i+1]-x[i]>h[i]: tx=x[i]+h[i] c+=1 else: tx=x[i] print(c) else: print(1)
23
615_A. Bulbs
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.
import math nm = input().split() n = int(nm[0]) m = int(nm[1]) lis = [ 0 for i in range(m+1)] for _ in range(n) : inp = list(map(int, input().split())) inp.pop(0) for i in inp: lis[i]=1 prev = i if sum(lis)==m: print("YES") else: print("NO")
24
634_C. Factory Repairs
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.
from functools import reduce class SegmentTree(): def __init__(self, L, function = lambda x,y: x+y, initilizer = None): self.function = function self.initilizer = initilizer N = self.size = len(L) M = 1 << N.bit_length() self.margin = 2*M - N self.L = [None for i in range(self.margin)] + L for i in range(M-1, 0, -1): x, y = self.L[i<<1], self.L[i<<1|1] self.L[i] = None if x is None or y is None else function(x, y) def modify(self, pos, value): p = pos + self.margin self.L[p] = value while p > 1: x, y = self.L[p], self.L[p^1] if p&1: x, y = y, x self.L[p>>1] = None if x is None or y is None else self.function(x, y) p>>=1 def query(self, left, right): l, r = left + self.margin, right + self.margin stack = [] void = True if self.initilizer is not None: void = False result = self.initilizer while l < r: if l&1: if void: result = self.L[l] void = False else: result = self.function(result, self.L[l]) l+=1 if r&1: r-=1 stack.append(self.L[r]) l>>=1 r>>=1 init = stack.pop() if void else result return reduce(self.function, reversed(stack), init) import sys n, k, a, b, q = [int(x) for x in input().split()] orders = [0]*(n+2) a_tree, b_tree = SegmentTree(orders, initilizer = 0), SegmentTree(orders, initilizer = 0) for line in sys.stdin: s = [int(x) for x in line.split()] if s[0] == 1: orders[s[1]] += s[2] a_tree.modify(s[1], min(a, orders[s[1]])) b_tree.modify(s[1], min(b, orders[s[1]])) else: query = b_tree.query(0, s[1]) + a_tree.query(s[1]+k, n+1) print(query)
25
663_A. Rebus
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
s = input().split() plus = 1 minus = 0 for ch in s: if (ch == '+') : plus += 1 if (ch == '-') : minus += 1 n = int(s[len(s) - 1]) maxx = plus * n - 1 * minus minn = plus - n * minus now = n - (plus - minus) if (n>maxx or n<minn): print("Impossible") else: pre = '+' print("Possible") for ch in s: if (ch == '?'): if (pre == '+') : val = 1 if (now > 0) : val = min(n - 1,now) + 1 now -= (val - 1) print(val,end = " ") if (pre == '-'): val = 1 if (now < 0) : val = min(abs(n) - 1,abs(now)) + 1 now += (val - 1) print(val,end = " ") else : print(ch,end = " ") pre = ch
26
730_J. Bottles
Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda ai and bottle volume bi (ai ≀ bi). Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda from one bottle to another. Nick asks you to help him to determine k β€” the minimal number of bottles to store all remaining soda and t β€” the minimal time to pour soda into k bottles. A bottle can't store more soda than its volume. All remaining soda should be saved. Input The first line contains positive integer n (1 ≀ n ≀ 100) β€” the number of bottles. The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 100), where ai is the amount of soda remaining in the i-th bottle. The third line contains n positive integers b1, b2, ..., bn (1 ≀ bi ≀ 100), where bi is the volume of the i-th bottle. It is guaranteed that ai ≀ bi for any i. Output The only line should contain two integers k and t, where k is the minimal number of bottles that can store all the soda and t is the minimal time to pour the soda into k bottles. Examples Input 4 3 3 4 3 4 7 6 5 Output 2 6 Input 2 1 1 100 100 Output 1 1 Input 5 10 30 5 6 24 10 41 7 8 24 Output 3 11 Note In the first example Nick can pour soda from the first bottle to the second bottle. It will take 3 seconds. After it the second bottle will contain 3 + 3 = 6 units of soda. Then he can pour soda from the fourth bottle to the second bottle and to the third bottle: one unit to the second and two units to the third. It will take 1 + 2 = 3 seconds. So, all the soda will be in two bottles and he will spend 3 + 3 = 6 seconds to do it.
f = lambda: list(map(int, input().split())) n = int(input()) a, b = f(), f() d = [[None] * 10001 for i in range(n)] def g(i, s): if s <= 0: return (0, s) if i == n: return (1e7, 0) if not d[i][s]: x, y = g(i + 1, s - b[i]) d[i][s] = min(g(i + 1, s), (x + 1, y + b[i] - a[i])) return d[i][s] x, y = g(0, sum(a)) print(x, y)
27
776_A. A Serial Killer
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(): l = input().split() print(*l) for _ in range(int(input())): a, b = input().split() l[a == l[1]] = b print(*l) if __name__ == '__main__': main()
28
7_B. Memory Manager
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()) disk = [False] * m req = 0 for i in range(t): inp = input().split() if inp[0][0] == "a": c = 0 inp[1] = int(inp[1]) for j in range(m): if disk[j]: c = 0 else: c += 1 if c == inp[1]: req += 1 print(req) for j in range(j - inp[1] + 1, j + 1): disk[j] = req break if c < inp[1]: print("NULL") elif inp[0][0] == "e": inp[1] = int(inp[1]) if inp[1] > req: print("ILLEGAL_ERASE_ARGUMENT") continue if not inp[1] in disk: print("ILLEGAL_ERASE_ARGUMENT") continue if inp[1] < 1: print("ILLEGAL_ERASE_ARGUMENT") continue for j in range(m): if disk[j] == inp[1]: disk[j] = False elif inp[0][0] == "d": for j in range(m): if disk[j]: _j = j while _j > 0 and not disk[_j - 1]: disk[_j - 1] = disk[_j] disk[_j] = False _j -= 1
29
820_D. Mister B and PR Shifts
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.
from sys import stdin def main(): n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) inf = [0] * (n + 1) curr = 0 d = 0 for i in range(n): curr += abs(i + 1 - a[i]) if a[i] > i + 1: d += 1 inf[a[i] - i - 1] += 1 elif a[i] <= i + 1: d -= 1 if a[i] == i + 1: inf[0] += 1 else: inf[a[i] + n - i - 1] += 1 best = curr num = 0 for i in range(n): curr -= d curr -= 1 curr = curr - abs(a[n - i - 1] - n) + abs(a[n - i - 1] - 1) d += 2 d -= inf[i + 1] * 2 if curr < best: best = curr num = i + 1 print(best, num) main()
30
846_E. Chemistry in Berland
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()
31
868_A. Bark to Unlock
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.
one=input() num=int(input()) twos=[] for i in range(num): twos.append(input()) if (one in twos) or (one[::-1] in twos): print("YES") else: flag1,flag2=False,False for i in range(num): if twos[i][0]==one[1]: flag1=True if twos[i][1]==one[0]: flag2=True if(flag1 and flag2): print("YES") else: print("NO")
32
893_D. Credit Card
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
#Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue, bisect #sys.stdin = open("input.txt", "r") MOD = 10**9+7 sys.setrecursionlimit(1000000) n, d = map(int, input().split()) a = list(map(int, input().split())) p = [0 for i in range(n)] for i in range(n): p[i] = p[i-1]+a[i] mx = [-1 for i in range(n)] mx[-1] = p[-1] for i in range(n-2, -1, -1): mx[i] = max(mx[i+1], p[i]) c = 0 ans = 0 for i in range(n): p[i] += c if p[i] > d: print(-1) exit() if a[i] != 0 or p[i] >= 0: continue av = d-(mx[i]+c) if -p[i] > av: print(-1) exit() ans += 1 c = d-mx[i] print(ans)
33
915_A. Garden
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 is_prime(a): return all(a % i for i in range(2, a)) n, k = map(int, input().split()) l = [int(x) for x in input().split()] if is_prime(k): if k in l: print(1) else: print(k) else: ll = [] for i in range(len(l)): if k % l[i] == 0: ll.append(l[i]) print(k // max(ll))
34
938_B. Run For Your Prize
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.
input() a=list(map(int,input().split())) ans=0 for x in a: z=min(x-1,1000000-x) ans=max(z,ans) print(ans)
35
990_E. Post Lamps
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 array import array n, m, k = map(int, input().split()) block = list(map(int, input().split())) a = [0] + list(map(int, input().split())) if block and block[0] == 0: print(-1) exit() prev = array('i', list(range(n))) for x in block: prev[x] = -1 for i in range(1, n): if prev[i] == -1: prev[i] = prev[i-1] inf = ans = 10**18 for i in range(1, k+1): s = 0 cost = 0 while True: cost += a[i] t = s+i if t >= n: break if prev[t] == s: cost = inf break s = prev[t] ans = min(ans, cost) print(ans if ans < inf else -1)
36
101_C. Vectors
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')
37
1043_A. Elections
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 math n = int(input()) l= list(map(int,input().split())) s = 2*sum(l) z= s/n p = max(l) an = int(z+1) print(max(p,an))
38
1107_D. Compression
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.
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(a ,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left)/ 2) # Check if middle element is # less than or equal to key if (arr[mid]<=key): count = mid+1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def countGreater( arr,n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ ind=defaultdict(list) ind['1']=[0,0,0,1] ind['0']=[0,0,0,0] ind['2']=[0,0,1,0] ind['3']=[0,0,1,1] ind ['4']=[0,1,0,0] ind ['5']=[0,1,0,1] ind ['6']=[0,1,1,0] ind ['7']=[0,1,1,1] ind ['8']=[1,0,0,0] ind ['9']=[1,0,0,1] ind['A']=[1,0,1,0] ind ['B']=[1,0,1,1] ind ['C']=[1,1,0,0] ind ['D']=[1,1,0,1] ind ['E']=[1,1,1,0] ind ['F']=[1,1,1,1] n=int(input()) l=[[] for i in range(n)] for i in range(n): s=input() for j in s: for u in ind[j]: l[i].append(u) a=[] c=1 for i in range(1,n): f=0 for j in range(n): if l[i-1][j]!=l[i][j]: f=1 a.append(c) c=1 break if f==0: c+=1 a.append(c) c=1 for i in range(1,n): f=0 for j in range(n): if l[j][i-1]!=l[j][i]: f=1 a.append(c) c=1 break if f==0: c+=1 a.append(c) ans=0 for i in a: ans=math.gcd(i,ans) print(ans)
39
1136_D. Nastya Is Buying Lunch
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 import math import bisect from math import sqrt def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) mod = int(1e9)+7 n, m = rinput() p = [0] + get_list() d = {i:set() for i in range(1, n+1)} for _ in range(m): u, v = rinput() d[u].add(v) last = p[n] target = n for i in range(n-1, 0, -1): for j in range(i, target): if p[j+1] in d[p[j]]: p[j], p[j+1] = p[j+1], p[j] else: break if p[target]!=last: target -= 1 print(n-target) # 3 1 4 5 2
40
1155_A. Reverse a Substring
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".
''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' def main(): n = input() s = input() for i in range(len(s)-1): if s[i]>s[i+1]: print('YES') print(i+1, i+2) return print('NO') main()
41
1176_F. Destroy it!
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()
42
1195_D2. Submarine in the Rybinsk Sea (hard edition)
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
from collections import Counter n = int(input()) a = list(map(int, input().split())) l = [len(str(i)) for i in a] c = Counter(l) cl = [c[i] for i in range(1,11)] M = 998244353 pad = lambda a, d: a%d + (a - a%d) * 10 #print(a, l, c, cl) ans = 0 for i in a: il = len(str(i)) # let's calculate it again to avoid zip and enumerate #print('processing', i, ans) t = i for p in range(10): #if not cl[p]: continue i = pad(i, 100**p) #print('top pad', p, 'is', i, 'there are', cl[p]) ans = (ans + i * cl[p]) % M i = t # restore for p in range(10): #if not cl[p]: continue i = pad(i, 10 * 100**p) #print('bottom pad', p, 'is', i, 'there are', cl[p]) ans = (ans + i * cl[p]) % M print(ans)
43
1236_A. Stones
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.
t = int(input()) while t>0: x, y, z = [int(i) for i in input().split()] s = 0 f = -1 z = z//2 if y >= z: y = y - z s = z*2 + z else: s = y*2 + y f = 1 if f == -1: y = y//2 if x >= y: s = s + 2*y + y else: s = s + 2*x + x print(s) t-=1
44
1382_A. Common Subsequence
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".
#!/usr/bin/env python3 import io import os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_str(): return input().decode().strip() def rint(): return map(int, input().split()) def oint(): return int(input()) t = oint() for _ in range(t): n, m = rint() a = set(rint()) b = set(rint()) c = a&b if c: print('YES') print(1, list(c)[0]) else: print('NO')
45
151_C. Win or Freeze
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 sys line = sys.stdin.readline() N = int(line) tmp = N factor = [] i = 2 while i**2 <= tmp: if tmp % i == 0: tmp //= i factor.append(i) else: i += 1 if tmp != 1: factor.append(i) if len(factor) == 2: print(2) else: print(1) if len(factor) <= 1: print(0) else: print(factor[0] * factor[1])
46
195_A. Let's Watch Football
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.
from math import ceil a,b,c = map(int,input().split()) t = (a*c - c*b)/b print(ceil(t))
47
219_A. k-String
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
from collections import Counter import string import math import sys def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(number_of_variables): if number_of_variables==1: return int(sys.stdin.readline()) if number_of_variables>=2: return map(int,sys.stdin.readline().split()) def makedict(var): return dict(Counter(var)) mod=100000007 k=vary(1) s=input() tt=makedict(list(s)) ans='' for i in tt: if tt[i]%k!=0: print(-1) exit() else: ans+=i*(tt[i]//k) print(ans*k)
48
242_C. King's Path
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 x0,y0,x1,y1=list(map(int, input().split())) n=int(input()) allowed={} for i in range(n): r,a,b=list(map(int,input().split())) for j in range(a,b+1): allowed[(r,j)]=True visited={} q=deque() q.append((x0,y0)) visited[(x0,y0)]=0 dire=[(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,1),(1,-1)] result=-1; while len(q)>0: x,y=q.popleft() original_dist=visited[(x,y)] if x==x1 and y==y1: result=original_dist; break; for i in range(len(dire)): dx,dy=dire[i] nx,ny=x+dx,y+dy if (nx,ny) in allowed and (nx,ny) not in visited: q.append((nx,ny)) visited[(nx,ny)]=original_dist+1 print(result)
49
268_A. Games
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).
n=int(input()) mat=[] for i in range(n): mat.append(list(map(int, input().rstrip().split()))) b=0 for i in range (n): for j in range (n): if mat[i][0]==mat[j][1]: b=b+1 print(b)
50
290_D. Orange
<image> Input The first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase. The second line of the input is an integer between 0 and 26, inclusive. Output Output the required string. Examples Input AprilFool 14 Output AprILFooL
text = input().lower() caps = int(input())+97 for letter in text: print(letter.upper(), end='')if letter < chr(caps) else print(letter, end='') print()
51
316_B2. EKG
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)))))
52
339_A. Helpful Maths
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
x=input() x=x.replace("+","") x=sorted(x) for i in range(1,2*len(x)-1,2): x.insert(i,"+") x=''.join(x) print(x)
53
361_C. Levko and Array Recovery
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)
54
385_A. Bear and Raspberry
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.
n, c = map(int, input().split()) l = list(map(int, input().split())) ans = 0 for i in range(n - 1): d = l[i] - l[i + 1] - c ans = max(ans, d) print(ans)
55
433_A. Kitahara Haruki's Gift
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.
n = int(input()) a = list(input().split(' ')) a = list(int(x) for x in a) one, two = 0, 0 for i in range(n): if a[i] == 100: one += 1 else: two += 1 flag = False if one%2 == 0 and two%2 == 0 or one > two and two % 2 == 1 and one % 2 == 0 and one >= 2 \ or one < two and two%2 == 1 and one%2 == 0 and one >= 2: flag = True if not flag: print('NO') else: print('YES')
56
478_A. Initial Bet
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.
l=list(map(int,input().split())) x=sum(l) if(x%5==0 and x!=0): print(int(x/5)) else: print(-1)
57
500_C. New Year Book Reading
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>
n,m=map(int,input().split()) weight=[int(i) for i in input().split()] order=[int(i) for i in input().split()] stack=[] for i in order: if i-1 not in stack: stack.append(i-1) #print(stack) ans=0 for i in order: #i=i-1 currlift=sum(weight[i] for i in stack[0:stack.index(i-1)]) ans+=currlift temp=i-1 stack.remove(i-1) stack.insert(0,temp) #print(currlift) #print(stack) print(ans)
58
526_A. King of Thieves
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.
#!/usr/bin/env python # jump.py - Codeforces <!!! NNNA !!!> quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ 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 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). """ # Standard libraries import unittest import sys import re import random # Additional libraries ############################################################################### # Jump Class ############################################################################### class Jump: """ Jump representation """ def __init__(self, args): """ Default constructor """ self.args = args self.size = args[0] self.maze = args[1] self.dist = [] self.cur_dist = [] self.calc_dist() def calc_dist(self): distance = 0 start = 0 for m in self.maze: if not start: if m: start = 1 continue distance += 1 if m: self.dist.append(distance) distance = 0 def next(self): self.cur_dist[1] = self.cur_dist[0] + self.cur_dist[1] del(self.cur_dist[0]) def iterate(self): len = self.cur_dist[0] hop_len = 0 hops = 0 for m in self.cur_dist: hop_len += m if hop_len == len: hop_len = 0 hops += 1 if hops == 4: return 1 if hop_len > len: return 0 return 0 def iterate_all(self): while len(self.cur_dist) > 1: if self.iterate(): return 1 self.next() return 0 def calculate(self): """ Main calcualtion function of the class """ for i in range(len(self.dist)): self.cur_dist = list(self.dist[i:]) if self.iterate_all(): return "yes" return "no" ############################################################################### # Executable code ############################################################################### def decode_inputs(inputs): """ Decoding input string tuple into base class args tuple """ # Decoding first input into an integer size = int(inputs[0]) # Decoding second input into a list of ints maze = [0 if i == "." else 1 for i in inputs[1]] args = (size, maze) return args def calculate(inputs): """ Base class calculate method wrapper """ return Jump(decode_inputs(inputs)).calculate() def main(): """ Main function. Not called by unit tests """ # Read test input string tuple inputs = (input(), input()) # Print the result print(calculate(inputs)) ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_decode_inputs(self): """ Input string decoding testing """ self.assertEqual(decode_inputs(("4", ".*.*")), (4, [0, 1, 0, 1])) def test_Jump_class__basic_functions(self): """ Jump class basic functions testing """ d = Jump((7, [0, 1, 0, 1, 1, 0, 1])) self.assertEqual(d.size, 7) # Distance listb self.assertEqual(d.dist, [2, 1, 2]) # Next dist merge with the next one d.cur_dist = [2, 1, 2] d.next() self.assertEqual(d.cur_dist, [3, 2]) # Iterate function, 1 - success d.cur_dist = [2, 2, 2, 2] self.assertEqual(d.iterate(), 1) d.cur_dist = [2, 1, 1, 2, 2] self.assertEqual(d.iterate(), 1) d.cur_dist = [2, 3] self.assertEqual(d.iterate(), 0) # Iterate all possible cur_dist d.cur_dist = [2, 1, 3, 3, 3] self.assertEqual(d.iterate_all(), 1) d.cur_dist = [2, 1, 3, 3, 2] self.assertEqual(d.iterate_all(), 0) # Calculate d.dist = [20, 2, 2, 2, 2] # self.assertEqual(d.calculate(), "yes") def test_calculate(self): """ Main calculation function """ # Sample test 1 self.assertEqual(calculate(("16", ".**.*..*.***.**.")), "yes") # Sample test2 self.assertEqual(calculate(("11", ".*.*...*.*.")), "no") if __name__ == "__main__": if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) main()
59
5_A. Chat Server's Outgoing Traffic
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
import sys n=0 ans=0 while True: i=sys.stdin.readline().strip() if len(i)<=1: break if i[0]=="+": n+=1 elif i[0]=="-": n-=1 else: ans+=(len(i.split(':')[1]))*n print(ans)
60
621_D. Rat Kwesh and Cheese
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 decimal import * getcontext().prec = 700 x, y, z = map(Decimal, input().split()) a = [] a.append((y**z * x.ln(), -1, 'x^y^z')) a.append((z**y * x.ln(), -2, 'x^z^y')) a.append((y *z * x.ln(), -3, '(x^y)^z')) a.append((x**z * y.ln(), -5, 'y^x^z')) a.append((z**x * y.ln(), -6, 'y^z^x')) a.append((x *z * y.ln(), -7, '(y^x)^z')) a.append((x**y * z.ln(), -9, 'z^x^y')) a.append((y**x * z.ln(), -10, 'z^y^x')) a.append((x *y * z.ln(), -11, '(z^x)^y')) print(max(a)[2])
61
643_B. Bear and Two Paths
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>
import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, k = map(int, input().split()) a, b, c, d = map(int, input().split()) if k < n + 1 or n == 4: print("-1") exit(0) l = [_ for _ in range(1, n + 1)] l.remove(a) l.remove(b) l.remove(c) l.remove(d) print(a, end = ' ') print(c, end = ' ') for x in l: print(x, end = ' ') print(d, end = ' ') print(b, end = ' ') print("") print(c, end = ' ') print(a, end = ' ') for x in l: print(x, end = ' ') print(b, end = ' ') print(d, end = ' ')
62
670_B. Game of Robots
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.
n, k = input().split(' ') n = int(n) k = int(k) d = input().split(' ') i = 0 while True: i += 1 p = int((i) * (i+1) / 2) if k <= p : print(d[k-(p-i)-1]) break
63
691_D. Swaps in Permutation
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
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def solve(n,p,path): se, x, fin = [1] * (n + 1), 1, [0] * n while x != len(se): se[x], jj, curr, inde, vals = 0, 0, [x], [x - 1], [p[x - 1]] while jj != len(curr): zz = curr[jj] for y in path[zz]: if se[y]: curr.append(y) inde.append(y-1) vals.append(p[y-1]) se[y] = 0 jj += 1 inde.sort() vals.sort() for ind, i in enumerate(inde): fin[i] = vals[-ind - 1] while x != n + 1 and not se[x]: x += 1 for i in fin: print(i, end=' ') def main(): n, m = map(int, input().split()) p = list(map(int, input().split())) path = [[] for _ in range(n + 1)] for _ in range(m): u1, v1 = map(int, input().split()) path[u1].append(v1) path[v1].append(u1) solve(n,p,path) #Fast IO Region 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") if __name__ == '__main__': main()
64
737_A. Road to Cinema
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.
# Question B. Road to Cinema import sys def roadToCinema(V, S, T, stations): # O(M) """ V : volume of fuel tank S : total distance T : time limit stations: fuel stations' locations rtype : boolean, whether this aircraft can travel within the time limit """ m = len(stations) t = 0 stations.append(S) # destination prev = 0 for cur in stations: dis = cur - prev # let Sa, Sb as the distance of accelerated mode/ normal mode respectively # then the task is: # min t = (Sa + 2 * Sb) # s.t. Sa + Sb = dis # 2 * Sa + Sb <= V if dis > V: # Sa <= V - dis < 0 return False else: # t = Sa + 2Sb = 3(Sa + Sb) - (2Sa + Sb) # >= 3 * dis - V # on the other hand, Sb is non-negative # Sb = t - dis t += max(dis * 3 - V, dis) if t > T: return False prev = cur return True def binSearch(S, T, stations): # O(logS * M) """ to find the least tank volume to enable the aircraft to complete the journey the fastest way is to complete the whole journey with the speed of 2km/min, at 2L/km V <= 2S """ l = 0 r = S * 2 if T < S: return float("inf") while l + 1 < r: m = l + (r - l) // 2 if roadToCinema(m, S, T, stations) == True: r = m else: l = m return r if __name__ == "__main__": # O(logS * M + N) line = sys.stdin.readline() [N, M, S, T] = list(map(int, line.split(" "))) aircrafts = [] for i in range(N): [c, v] = list(map(int, sys.stdin.readline().split(" "))) aircrafts.append([c, v]) stations = list(map(int, sys.stdin.readline().split(" "))) stations.sort() minVolume = binSearch(S, T, stations) if minVolume == float("inf"): # no aircraft can complete the journey print(-1) else: res = float("inf") for i in range(N): if aircrafts[i][1] >= minVolume: res = min(res, aircrafts[i][0]) if res == float('inf'): # no given aircraft can complete the journey print(-1) else: print(res)
65
784_B. Kids' Riddle
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
a=str(hex(int(input()))) b=0 for i in range(2,len(a)): if a[i]=="0" or a[i]=="4" or a[i]=="6" or a[i]=="9" or a[i]=="a" or a[i]=="d": b+=1 elif a[i]=="8" or a[i]=="b": b+=2 print(b)
66
805_A. Fake NP
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}.
n, k=map(int ,input().split()) if n==k and n%2==1: print(n) else: print(2)
67
830_A. Office Keys
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.
o=lambda:[int(f)for f in input().split()] n,k,p=o() a=sorted(o()) b=sorted(o()) print(min(max(abs(b[i + d] - a[i]) + abs(b[i + d] - p) for i in range(n)) for d in range(k - n + 1)))
68
851_B. Arpa and an exam about geometry
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.
ax,ay,bx,by,cx,cy=map(int,input().split()) ab=(ax-bx)**2+(ay-by)**2 bc=(bx-cx)**2+(by-cy)**2 if ab==bc and (ay-by)*(bx-cx)!=(by-cy)*(ax-bx): print("Yes") else: print("No")
69
920_E. Connected Components?
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
n,m=map(int,input().split()) non=[{i} for i in range(n)] for i in range(m): u,v=map(int,input().split()) u,v=u-1,v-1 non[u].add(v) non[v].add(u) vertex=set(range(n)) ans=[] while(vertex): a=next(iter(vertex)) vertex.remove(a) stk=[a] cou=1 while(stk): v=stk.pop() s=vertex-non[v] cou+=len(s) stk.extend(s) vertex&=non[v] ans.append(cou) ans.sort() print(len(ans)) print(" ".join(map(str,ans)))
70
977_B. Two-gram
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.
n = int(input()) k = str(input()) Max = 0 for i in range(n-1): t=k[i]+k[i+1] z=0 for j in range(0,n-1): s=k[j]+k[j+1] if (s==t): z=z+1 #print(z) if (z>Max): Max=z res=t print(res)
71
1012_B. Chemical table
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>
class UnionFind: def __init__(self, n): self.par = [-1]*n self.rank = [0]*n def Find(self, x): if self.par[x] < 0: return x else: self.par[x] = self.Find(self.par[x]) return self.par[x] def Unite(self, x, y): x = self.Find(x) y = self.Find(y) if x != y: if self.rank[x] < self.rank[y]: self.par[y] += self.par[x] self.par[x] = y else: self.par[x] += self.par[y] self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1 def Same(self, x, y): return self.Find(x) == self.Find(y) def Size(self, x): return -self.par[self.Find(x)] import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m, q = map(int, input().split()) uf = UnionFind(n+m) for i in range(q): r, c = map(int, input().split()) r, c = r-1, c-1 uf.Unite(r, c+n) S = set() for i in range(n+m): S.add(uf.Find(i)) print(len(S)-1)
72
1037_B. Reach Median
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.
# -*- coding: utf-8 -*- # @Date : 2018-09-03 08:46:01 # @Author : raj lath (oorja.halt@gmail.com) # @Link : http://codeforces.com/contest/1037/problem/B # @Version : 1.0.0 import os from sys import stdin max_val=int(10e12) min_val=int(-10e12) def read_int() : return int(stdin.readline()) def read_ints() : return [int(x) for x in stdin.readline().split()] def read_str() : return input() def read_strs() : return [x for x in stdin.readline().split()] def read_str_list(): return [x for x in stdin.readline().split().split()] nb_elemets, value_needed = read_ints() elements = sorted(read_ints()) mid = nb_elemets//2 ans = abs(elements[mid] - value_needed) ans += sum( max(0, (a - value_needed)) for a in elements[:mid] ) ans += sum( max(0, (value_needed - a)) for a in elements[mid+1:] ) print(ans)
73
1081_D. Maximum Distance
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.
""" @author: phamv """ ####Function Definition def find(x): while f[x] != x : f[x] = f[f[x]] x = f[x] return x def merge(u, v) : u, v = map(find, (u, v)) f[u] = v; if u == v: return False ret = s[u] > 0 and s[v] > 0 s[v] += s[u] return ret ############### n, m, k = map(int, input().split()) x = list(map(int, input().split())) lst = list() for i in range(m): lst.append(tuple(map(int, input().split()))) lst.sort(key = lambda x: x[2]) f = list(range(n + 1)) s = [0] * (n + 1) for j in x: s[j] += 1 for h in lst: if merge(h[0], h[1]): answer = h[2] print(*[answer]*k)
74
1129_A2. Toy Train
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.
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- mii=lambda:map(int,input().split()) n,m=mii() a=[0 for _ in range(n)] c=[123456 for _ in range(n)] for _ in range(m): u,v=mii() u%=n v%=n if v<u: v+=n a[u]+=1 if c[u]>v: c[u]=v ans=[] for i in list(range(1,n))+[0]: out=0 for j in range(i,n): if not a[j]: continue tmp=(j-i)+(a[j]-1)*n+(c[j]-j) out=max(out,tmp) #print(1,i,j,tmp) for j in range(i): if not a[j]: continue tmp=(j+n-i)+(a[j]-1)*n+(c[j]-j) out=max(out,tmp) #print(2,i,j,tmp) ans.append(out) print(" ".join(map(str,ans)))
75
1149_B. Three Religions
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')
76
1208_A. XORinacci
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.
import sys from collections import defaultdict as dd from collections import deque from functools import * from fractions import Fraction as f from copy import * from bisect import * from heapq import * from math import * from itertools import permutations ,product def eprint(*args): print(*args, file=sys.stderr) zz=1 #sys.setrecursionlimit(10**6) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') def inc(d,c): d[c]=d[c]+1 if c in d else 1 def bo(i): return ord(i)-ord('A') def li(): return [int(xx) for xx in input().split()] def fli(): return [float(x) for x in input().split()] def comp(a,b): if(a>b): return 2 return 2 if a==b else 0 def gi(): return [xx for xx in input().split()] def fi(): return int(input()) def pro(a): return reduce(lambda a,b:a*b,a) def swap(a,i,j): a[i],a[j]=a[j],a[i] def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def isvalid(i,j): return 0<=i<n and 0<=j<n def bo(i): return ord(i)-ord('a') def graph(n,m): for i in range(m): x,y=mi() a[x].append(y) a[y].append(x) t=fi() while t>0: t-=1 a,b,n=mi() n+=1 if n%3==0: print(a^b) elif n%3==1: print(a) else: print(b)
77
1227_A. Math Problem
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.
t = int(input()) for i in range(t): n = int(input()) x = [] y = [] for i in range(n): a, b = map(int, input().split()) x.append(a) y.append(b) if n == 1: print(0) elif min(y) > max(x): print(0) else: print(abs(max(x)-min(y)))
78
124_D. Squares
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.
#!/usr/bin/python3 def cds(a, b, x, y): return (x + y) // (2 * a), (x - y) // (2 * b) def norm(x, y): return max(x, y) a, b, x1, y1, x2, y2 = map(int, input().split()) xp1, yp1 = cds(a, b, x1, y1) xp2, yp2 = cds(a, b, x2, y2) print(norm(abs(xp1 - xp2), abs(yp1 - yp2)))
79
1269_B. Modulo Equality
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
import sys input=sys.stdin.readline from collections import deque n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() b.sort() a=deque(a) b=deque(b) ans=0 for _ in range(n): if a==b: break f=1 for j in range(n-1): if b[j+1]-a[j+1]!=b[j]-a[j]: f=0 break if f: if b[0]>a[0]: print(ans+b[0]-a[0]) exit() else: print(ans+b[0]-a[0]+m) exit() p=m-a[-1] ans+=p ww=0 for j in range(n): a[j]+=p if a[j]==m: ww=n-j break for j in range(ww): a.pop() a.appendleft(0) print(ans)
80
1311_C. Perform the Combo
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.
from sys import stdin from bisect import bisect_left from collections import Counter for k in range(int(stdin.readline())): n,m=[int(x) for x in stdin.readline().split()] s=input() d=Counter(s) l=list(map(int,stdin.readline().split())) l.sort() ans=[0 for j in range(0,26)] for j in range(0,len(s)): n=len(l)-bisect_left(l,j+1) ans[ord(s[j])-97]+=(n) e=list(d.keys()) try: for i in range(0,len(e)): ans[ord(e[i])-97]+=(d[e[i]]) except(Exception): pass print(*ans)
81
1334_A. Level Statistics
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.
T=int(input()) list=[] c=-1 d=-1 for i in range(T): n=int(input()) k="Yes" for j in range(n): a,b=map(int,input().split()) if a>=b and c<=a and d<=b and (b-d)<=(a-c): g=0 else: k="No" c=a d=b c=-1 d=-1 list.append(k) for i in range(len(list)): print(list[i])
82
1374_B. Multiply by 2, divide by 6
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.
t=int(input()) for i in range(t): n=int(input()) if n==1: print(0) else: if n%3!=0: print(-1) else: threes=0 twos=0 while n%3==0: threes+=1 n=n//3 while n%2==0: twos+=1 n=n//2 if n!=1 or twos>threes: print(-1) else: print(2*threes-twos)
83
1420_D. Rescue Nibel!
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).
import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)] def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10**19 MOD = 998244353 EPS = 10**-10 def compress(S): zipped, unzipped = {}, {} for i, a in enumerate(sorted(S)): zipped[a] = i unzipped[i] = a return zipped, unzipped class ModTools: def __init__(self, MAX, MOD): MAX += 1 self.MAX = MAX self.MOD = MOD factorial = [1] * MAX factorial[0] = factorial[1] = 1 for i in range(2, MAX): factorial[i] = factorial[i-1] * i % MOD inverse = [1] * MAX inverse[MAX-1] = pow(factorial[MAX-1], MOD-2, MOD) for i in range(MAX-2, -1, -1): inverse[i] = inverse[i+1] * (i+1) % MOD self.fact = factorial self.inv = inverse def nCr(self, n, r): if n < r: return 0 r = min(r, n-r) numerator = self.fact[n] denominator = self.inv[r] * self.inv[n-r] % self.MOD return numerator * denominator % self.MOD N, K = MAP() LR = [] S = set() for i in range(N): l, r = MAP() r += 1 LR.append((l, r)) S.add(l) S.add(r) zipped, _ = compress(S) M = len(zipped) lcnt = [0] * M rcnt = [0] * M for i in range(N): LR[i] = (zipped[LR[i][0]], zipped[LR[i][1]]) lcnt[LR[i][0]] += 1 rcnt[LR[i][1]] += 1 cur = 0 ans = 0 mt = ModTools(N, MOD) for i in range(M): cur -= rcnt[i] while lcnt[i]: if cur >= K-1: ans += mt.nCr(cur, K-1) ans %= MOD cur += 1 lcnt[i] -= 1 print(ans)
84
167_C. Wizards and Numbers
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it β€” a and b. The order of the numbers is not important. Let's consider a ≀ b for the sake of definiteness. The players can cast one of the two spells in turns: * Replace b with b - ak. Number k can be chosen by the player, considering the limitations that k > 0 and b - ak β‰₯ 0. Number k is chosen independently each time an active player casts a spell. * Replace b with b mod a. If a > b, similar moves are possible. If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses. To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second. Input The first line contains a single integer t β€” the number of input data sets (1 ≀ t ≀ 104). Each of the next t lines contains two integers a, b (0 ≀ a, b ≀ 1018). The numbers are separated by a space. 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 For any of the t input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input. Examples Input 4 10 21 31 10 0 1 10 30 Output First Second Second First Note In the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win. In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win. In the third sample, the first player has no moves. In the fourth sample, the first player wins in one move, taking 30 modulo 10.
def solve(a, b): if a == 0: return False if solve(b % a, a): b //= a return not (b % (a + 1) & 1) return True n = int(input()) for _ in range(n): a, b = [int(x) for x in input().split()] if a > b: a, b = b, a if solve(a, b): print("First") else: print("Second")
85
209_B. Pixels
Flatland is inhabited by pixels of three colors: red, green and blue. We know that if two pixels of different colors meet in a violent fight, only one of them survives the fight (that is, the total number of pixels decreases by one). Besides, if pixels of colors x and y (x β‰  y) meet in a violent fight, then the pixel that survives the fight immediately changes its color to z (z β‰  x; z β‰  y). Pixels of the same color are friends, so they don't fight. The King of Flatland knows that his land will be peaceful and prosperous when the pixels are of the same color. For each of the three colors you know the number of pixels of this color that inhabit Flatland. Help the king and determine whether fights can bring peace and prosperity to the country and if it is possible, find the minimum number of fights needed to make the land peaceful and prosperous. Input The first line contains three space-separated integers a, b and c (0 ≀ a, b, c ≀ 231; a + b + c > 0) β€” the number of red, green and blue pixels, correspondingly. Output Print a single number β€” the minimum number of pixel fights before the country becomes peaceful and prosperous. If making the country peaceful and prosperous is impossible, print -1. Examples Input 1 1 1 Output 1 Input 3 1 0 Output 3 Note In the first test sample the country needs only one fight to achieve peace and prosperity. Besides, it can be any fight whatsoever. For example, let's assume that the green and the blue pixels fight, then the surviving pixel will be red. As a result, after the fight there are two red pixels. There won't be other pixels. In the second sample the following sequence of fights is possible: red and blue, green and red, red and blue. As a result, after all fights there is one green pixel left.
a = list(map(int,input().split())) def calc(a): return int((((a[1]-a[0])+(a[1]+a[0]))/2)) a.sort() if a[1] % 2 == 0 and a[0] % 2 == 0: print(calc(a)) elif a[1] % 2 == 0 or a[0] % 2 == 0: print(a[2]) else: print(calc(a))
86
235_A. LCM Challenge
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find the maximum possible least common multiple of these three integers? Input The first line contains an integer n (1 ≀ n ≀ 106) β€” the n mentioned in the statement. Output Print a single integer β€” the maximum possible LCM of three not necessarily distinct positive integers that are not greater than n. Examples Input 9 Output 504 Input 7 Output 210 Note The least common multiple of some positive integers is the least positive integer which is multiple for each of them. The result may become very large, 32-bit integer won't be enough. So using 64-bit integers is recommended. For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7Β·6Β·5 = 210. It is the maximum value we can get.
import sys, math input = sys.stdin.readline def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) import collections as col import math def solve(): N = getInt() if N == 1: return 1 if N == 2: return 2 if N % 2 == 1: return N*(N-1)*(N-2) return max(N*(N-1)*(N-2)//2,(N-1)*(N-2)*(N-3), N*(N-1)*(N-3) if N % 3 > 0 else 0) #can we make a bigger number using N? N*(N-1), we can't use (N-2), we could use N-3 print(solve())
87
25_D. Roads not only in Berland
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones. Input The first line contains integer n (2 ≀ n ≀ 1000) β€” amount of cities in Berland and neighboring countries. Next n - 1 lines contain the description of roads. Each road is described by two space-separated integers ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi) β€” pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself. Output Output the answer, number t β€” what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output t lines β€” the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v β€” it means that road between cities i and j became closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any. Examples Input 2 1 2 Output 0 Input 7 1 2 2 3 3 1 4 5 5 6 6 7 Output 1 3 1 3 7
''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input().rstrip() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' mod=1000000007 # mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('a') file=1 def solve(): n = ii() par = [i for i in range(n+1)] freq = [1 for i in range(n+1)] def find(i): if i==par[i]: return i par[i] = find(par[i]) return par[i] def union(x,y): x = find(x) y = find(y) if x==y: return 0 if freq[x] < freq[y]: par[x] = y freq[y] += 1 else: par[y] = x freq[x] += 1 return 1 erase = [] for i in range(n-1): x,y = mi() x1 = find(x) y1 = find(y) if x1==y1: erase.append([x,y]) continue union(x,y) add = [] x = list(set(par[1:])) for i in range(1,len(x)): if(union(x[0],x[i])): add.append([x[0],x[i]]) print(len(add)) for i in range(len(add)): print(*erase[i],end=" ") print(*add[i],end=" ") print() if __name__ =="__main__": if(file): if path.exists('input.txt'): sys.stdin=open('input.txt', 'r') sys.stdout=open('output.txt','w') else: input=sys.stdin.readline solve()
88
306_C. White, Black and White Again
Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to take place during each day. As each day is unequivocally characterizes as a part of a white or a black stripe, then each day is going to have events of the same type only (ether good or not-so-good). What is the number of distinct ways this scenario can develop over the next n days if Polycarpus is in for a white stripe (a stripe that has good events only, the stripe's length is at least 1 day), the a black stripe (a stripe that has not-so-good events only, the stripe's length is at least 1 day) and a white stripe again (a stripe that has good events only, the stripe's length is at least 1 day). Each of n days will belong to one of the three stripes only. Note that even the events of the same type are distinct from each other. Even if some events occur on the same day, they go in some order (there are no simultaneous events). Write a code that prints the number of possible configurations to sort the events into days. See the samples for clarifications on which scenarios should be considered distinct. Print the answer modulo 1000000009 (109 + 9). Input The single line of the input contains integers n, w and b (3 ≀ n ≀ 4000, 2 ≀ w ≀ 4000, 1 ≀ b ≀ 4000) β€” the number of days, the number of good events and the number of not-so-good events. It is guaranteed that w + b β‰₯ n. Output Print the required number of ways modulo 1000000009 (109 + 9). Examples Input 3 2 1 Output 2 Input 4 2 2 Output 4 Input 3 2 2 Output 4 Note We'll represent the good events by numbers starting from 1 and the not-so-good events β€” by letters starting from 'a'. Vertical lines separate days. In the first sample the possible ways are: "1|a|2" and "2|a|1". In the second sample the possible ways are: "1|a|b|2", "2|a|b|1", "1|b|a|2" and "2|b|a|1". In the third sample the possible ways are: "1|ab|2", "2|ab|1", "1|ba|2" and "2|ba|1".
import sys MOD = int(1e9) + 9 def inv(n): return pow(n, MOD - 2, MOD) def combo(n): rv = [0 for __ in range(n + 1)] rv[0] = 1 for k in range(n): rv[k + 1] = rv[k] * (n - k) % MOD * inv(k + 1) % MOD return rv with sys.stdin as fin, sys.stdout as fout: n, w, b = map(int, next(fin).split()) combw = combo(w - 1) combb = combo(b - 1) ans = 0 for black in range(max(1, n - w), min(n - 2, b) + 1): ans = (ans + (n - 1 - black) * combw[n - black - 1] % MOD * combb[black - 1]) % MOD for f in w, b: for k in range(1, f + 1): ans = k * ans % MOD print(ans, file=fout)
89
39_E. What Has Dirichlet Got to Do with That?
You all know the Dirichlet principle, the point of which is that if n boxes have no less than n + 1 items, that leads to the existence of a box in which there are at least two items. Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. There are a different boxes and b different items, and each turn a player can either add a new box or a new item. The player, after whose turn the number of ways of putting b items into a boxes becomes no less then a certain given number n, loses. All the boxes and items are considered to be different. Boxes may remain empty. Who loses if both players play optimally and Stas's turn is first? Input The only input line has three integers a, b, n (1 ≀ a ≀ 10000, 1 ≀ b ≀ 30, 2 ≀ n ≀ 109) β€” the initial number of the boxes, the number of the items and the number which constrains the number of ways, respectively. Guaranteed that the initial number of ways is strictly less than n. Output Output "Stas" if Masha wins. Output "Masha" if Stas wins. In case of a draw, output "Missing". Examples Input 2 2 10 Output Masha Input 5 5 16808 Output Masha Input 3 1 4 Output Stas Input 1 4 10 Output Missing Note In the second example the initial number of ways is equal to 3125. * If Stas increases the number of boxes, he will lose, as Masha may increase the number of boxes once more during her turn. After that any Stas's move will lead to defeat. * But if Stas increases the number of items, then any Masha's move will be losing.
a, b, L = list(map(int, input().split())) memo = {} #10^9 rougly equals 31700 * 31700 memo[(31701, 1)] = ((L - 31701) + 1)% 2 #2**30 > 10^9 memo[(1, 30)] = -1 for i in range(31700, a - 1, -1): for j in range(29, b - 1, -1): if i**j>=L: continue s = set() if (i + 1) ** j < L: s.add(memo[(i + 1, j)]) if i ** (j + 1) < L: s.add(memo[(i, j + 1)]) if 0 not in s and -1 in s: memo[(i, j)] = -1 else: mex = 0 while mex in s: mex += 1 memo[(i, j)] = mex if memo[(a, b)] > 0: print("Masha") elif memo[(a, b)] == -1: print("Missing") else: print("Stas")
90
425_A. Sereja and Swaps
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation: <image> A swap operation is the following sequence of actions: * choose two indexes i, j (i β‰  j); * perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations? Input The first line contains two integers n and k (1 ≀ n ≀ 200; 1 ≀ k ≀ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 ≀ a[i] ≀ 1000). Output In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations. Examples Input 10 2 10 -1 2 2 2 2 2 2 -1 10 Output 32 Input 5 10 -1 -1 -1 -1 -1 Output -1
#!/usr/local/bin/python3 n, k = map(int, input().split()) a = list(map(int, input().split())) r_sum = a[0] for l in range(n): for r in range(l, n): inside = sorted(a[l:r+1]) outside = sorted(a[:l] + a[r+1:], reverse=True) t_sum = sum(inside) for i in range(min(k, len(inside), len(outside))): if outside[i] > inside[i]: t_sum += (outside[i] - inside[i]) else: break if t_sum > r_sum: r_sum = t_sum print(r_sum)
91
449_D. Jzzhu and Numbers
Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≀ i1 < i2 < ... < ik ≀ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≀ k ≀ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers. Input The first line contains a single integer n (1 ≀ n ≀ 106). The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 106). Output Output a single integer representing the number of required groups modulo 1000000007 (109 + 7). Examples Input 3 2 3 3 Output 0 Input 4 0 1 2 3 Output 10 Input 6 5 2 0 5 2 1 Output 53
import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) # zeta mebius def zeta_super(val, n): # len(val)==2^n out = val[:] for i in range(n): for j in range(1<<n): if not j>>i&1: out[j] += out[j^(1<<i)] return out n = int(input()) a = list(map(int, input().split())) m = max(a).bit_length() M = 10**9+7 v = [0]*(1<<m) for item in a: v[item] += 1 v2 = [1] for i in range(n+1): v2.append(v2[-1]*2%M) nv = zeta_super(v, m) ans = 0 for b in range(1<<m): ans += (v2[nv[b]]-1)*pow(-1, bin(b).count("1")) ans %= M print(ans%M)
92
494_A. Treasure
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≀ i ≀ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with. Input The first line of the input contains a string s (1 ≀ |s| ≀ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character. Output If there is no way of replacing '#' characters which leads to a beautiful string print - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them. Examples Input (((#)((#) Output 1 2 Input ()((#((#(#() Output 2 2 1 Input # Output -1 Input (#) Output -1 Note |s| denotes the length of the string s.
#!/usr/bin/env python3 s = input() count = 0 res = [] last = s.rfind("#") for i, c in enumerate(s): if c == '(': count += 1 elif c == ')': count -= 1 else: if i < last: res.append(1) count -= 1 else: num = max(1, 1 + s.count("(") - s.count("#") - s.count(")")) res.append(num) count -= num if count < 0: res = [] print(-1) break for i in res: print(i)
93
544_E. Remembering Strings
You have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i. For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because: * the first string is the only string that has character c in position 3; * the second string is the only string that has character d in position 2; * the third string is the only string that has character s in position 2. You want to change your multiset a little so that it is easy to remember. For aij coins, you can change character in the j-th position of the i-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember. Input The first line contains two integers n, m (1 ≀ n, m ≀ 20) β€” the number of strings in the multiset and the length of the strings respectively. Next n lines contain the strings of the multiset, consisting only of lowercase English letters, each string's length is m. Next n lines contain m integers each, the i-th of them contains integers ai1, ai2, ..., aim (0 ≀ aij ≀ 106). Output Print a single number β€” the answer to the problem. Examples Input 4 5 abcde abcde abcde abcde 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output 3 Input 4 3 abc aba adc ada 10 10 10 10 1 10 10 10 10 10 1 10 Output 2 Input 3 3 abc ada ssa 1 1 1 1 1 1 1 1 1 Output 0
from sys import stdin n,m=map(int,stdin.readline().strip().split()) s=[] for i in range(n): s.append(list(map(ord,list(stdin.readline().strip())))) for j in range(m): s[-1][j]=s[-1][j]-97 ct=[tuple(map(int,stdin.readline().strip().split())) for i in range(n)] mc=[[0 for i in range(22)] for j in range(22)] c=[[0 for i in range(22)] for i in range(22)] maxmask=1<<n maxx=10**8 dp=[maxx for i in range(maxmask)] for i in range(n): for j in range(m): mx=0 for k in range(n): if s[i][j]==s[k][j]: mc[i][j]|=(1<<k) c[i][j]+=ct[k][j] mx=max(mx,ct[k][j]) c[i][j]-=mx dp[0]=0 for i in range(1,maxmask): for j in range(n): if i & (1<<j): lb=j break mask=i for j in range(m): dp[mask]=min(dp[mask],dp[mask ^(1<<lb)]+ct[lb][j],dp[mask & (mask ^ mc[lb][j])]+c[lb][j]) print(dp[(1<<n)-1])
94
571_B. Minimization
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n. You need to permute the array elements so that value <image> became minimal possible. In particular, it is allowed not to change order of elements at all. Input The first line contains two integers n, k (2 ≀ n ≀ 3Β·105, 1 ≀ k ≀ min(5000, n - 1)). The second line contains n integers A[1], A[2], ..., A[n] ( - 109 ≀ A[i] ≀ 109), separate by spaces β€” elements of the array A. Output Print the minimum possible value of the sum described in the statement. Examples Input 3 2 1 2 4 Output 1 Input 5 2 3 -5 3 -5 3 Output 0 Input 6 3 4 3 4 3 2 5 Output 3 Note In the first test one of the optimal permutations is 1 4 2. In the second test the initial order is optimal. In the third test one of the optimal permutations is 2 3 4 4 3 5.
f = lambda: map(int, input().split()) n, k = f() p = sorted(f()) m, d = n // k, n % k u, v = d + 1, k - d + 1 g = [0] * u * v i = 0 for a in range(u): j = a * m + a - 1 for b in range(v): x = g[i - 1] + p[j] - p[j - m + 1] if b else 9e9 y = g[i - v] + p[j] - p[j - m] if a else 9e9 if i: g[i] = min(x, y) i += 1 j += m print(g[-1])
95
614_C. Peter and Snow Blower
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path. Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine. Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him. Input The first line of the input contains three integers β€” the number of vertices of the polygon n (<image>), and coordinates of point P. Each of the next n lines contains two integers β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value. Output Print a single real value number β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 3 0 0 0 1 -1 2 1 2 Output 12.566370614359172464 Input 4 1 -1 0 0 1 2 2 0 1 1 Output 21.991148575128551812 Note In the first sample snow will be removed from that area: <image>
import math import sys def calculate_area(n, x, y, vertices): r_max = -sys.maxsize r_min = sys.maxsize last_d = -1 for v in vertices: d = distance_two_points(v, (x, y)) if d > r_max: r_max = d if d < r_min: r_min = d last_v = vertices[0] for i in range(1,n): d_min, i_point = distance_point_to_line(last_v, vertices[i], (x, y)) if d_min < r_min and is_in_range(i_point, last_v, vertices[i]): r_min = d_min last_v = vertices[i] d_min, i_point = distance_point_to_line(last_v, vertices[0], (x, y)) if d_min < r_min and is_in_range(i_point, last_v, vertices[0]): r_min = d_min return math.pi * (r_max**2 - r_min**2) def distance_two_points(p1, p2): return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2) def distance_point_to_line(p1, p2, p0): a = p2[1] - p1[1] b = p1[0] - p2[0] c = p2[0]*p1[1] - p2[1]*p1[0] dist = math.fabs(a*p0[0] + b*p0[1] + c) / math.sqrt(a**2 + b**2) x_int = (b*(b*p0[0]-a*p0[1]) - a*c)/(a**2 + b**2) y_int = (a*(-b*p0[0]+a*p0[1]) - b*c)/(a**2 + b**2) return dist, (x_int, y_int) def is_in_range(i_point, p1, p2): x_min = p1[0] if p1[0] <= p2[0] else p2[0] x_max = p1[0] if p1[0] > p2[0] else p2[0] y_min = p1[1] if p1[1] <= p2[1] else p2[1] y_max = p1[1] if p1[1] > p2[1] else p2[1] return x_min <= i_point[0] <= x_max and y_min <= i_point[1] <= y_max if __name__ == "__main__": n, x, y = input().split() n, x, y = int(n), int(x), int(y) vertices = [None]*n for i in range(n): x_i, y_i = input().split() vertices[i] = (int(x_i), int(y_i)) area = calculate_area(n, x, y, vertices) print(area)
96
730_G. Car Repair Shop
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order they came. The i-th request is characterized by two values: si β€” the day when a client wants to start the repair of his car, di β€” duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on. Polycarp is making schedule by processing requests in the order from the first to the n-th request. He schedules the i-th request as follows: * If the car repair shop is idle for di days starting from si (si, si + 1, ..., si + di - 1), then these days are used to repair a car of the i-th client. * Otherwise, Polycarp finds the first day x (from 1 and further) that there are di subsequent days when no repair is scheduled starting from x. In other words he chooses the smallest positive x that all days x, x + 1, ..., x + di - 1 are not scheduled for repair of any car. So, the car of the i-th client will be repaired in the range [x, x + di - 1]. It is possible that the day x when repair is scheduled to start will be less than si. Given n requests, you are asked to help Polycarp schedule all of them according to the rules above. Input The first line contains integer n (1 ≀ n ≀ 200) β€” the number of requests from clients. The following n lines contain requests, one request per line. The i-th request is given as the pair of integers si, di (1 ≀ si ≀ 109, 1 ≀ di ≀ 5Β·106), where si is the preferred time to start repairing the i-th car, di is the number of days to repair the i-th car. The requests should be processed in the order they are given in the input. Output Print n lines. The i-th line should contain two integers β€” the start day to repair the i-th car and the finish day to repair the i-th car. Examples Input 3 9 2 7 3 2 4 Output 9 10 1 3 4 7 Input 4 1000000000 1000000 1000000000 1000000 100000000 1000000 1000000000 1000000 Output 1000000000 1000999999 1 1000000 100000000 100999999 1000001 2000000
t, p = 1, [] for i in range(int(input())): l, d = map(int, input().split()) if t > l: for i, q in enumerate(p, 1): if q[0] <= l <= q[1] - d: p.insert(i, [l + d, q[1]]) q[1] = l break else: for q in p: if q[0] <= q[1] - d: l = q[0] q[0] += d break else: l = t t += d else: p.append([t, l]) t = l + d print(l, l + d - 1)
97
754_B. Ilya and tic-tac-toe game
Ilya is an experienced player in tic-tac-toe on the 4 Γ— 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not. The rules of tic-tac-toe on the 4 Γ— 4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal). Input The tic-tac-toe position is given in four lines. Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn. Output Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise. Examples Input xx.. .oo. x... oox. Output YES Input x.ox ox.. x.o. oo.x Output NO Input x..x ..oo o... x.xo Output YES Input o.x. o... .x.. ooxx Output NO Note In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row. In the second example it wasn't possible to win by making single turn. In the third example Ilya could have won by placing X in the last row between two existing Xs. In the fourth example it wasn't possible to win by making single turn.
from sys import exit l1 = input() l2 = input() l3 = input() l4 = input() grid = [[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,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,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]] cross = 0 dots = [] for i in range(0, 4): if l1[i] == ".": dots += [[0+2, i+2]] elif l1[i] == "x": cross += 1 grid[0+2][i+2] = 1 if l2[i] == ".": dots += [[1+2, i+2]] elif l2[i] == "x": cross += 1 grid[1+2][i+2] = 1 if l3[i] == ".": dots += [[2+2, i+2]] elif l3[i] == "x": cross += 1 grid[2+2][i+2] = 1 if l4[i] == ".": dots += [[3+2, i+2]] elif l4[i] == "x": cross += 1 grid[3+2][i+2] = 1 def check(dot, dir, delta): global grid grid[dot[0]][dot[1]] = 1 acc = 1 if dir == 0: #horizontal for i in range(delta, delta+3): acc *= grid[dot[0]+i][dot[1]] elif dir == 1: #vertical for i in range(delta, delta+3): acc *= grid[dot[0]][dot[1]+i] elif dir == 2: #diag1 for i in range(delta, delta+3): acc *= grid[dot[0]+i][dot[1]+i] elif dir == 3: #diag2 for i in range(delta, delta+3): acc *= grid[dot[0]+i][dot[1]-i] grid[dot[0]][dot[1]] = 0 return acc if cross < 2 or len(dots) == 0: print("NO") else: for dot in dots: for dir in range(0, 4): for delta in range(-2, 1): if check(dot, dir, delta) == 1: print("YES") exit(0) print("NO")
98
774_K. Stepan and Vowels
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa". Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y". There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon". Sergey is very busy and asks you to help him and write the required program. Input The first line contains the integer n (1 ≀ n ≀ 100 000) β€” the number of letters in the word written by Stepan. The second line contains the string s which has length that equals to n and contains only lowercase English letters β€” the word written by Stepan. Output Print the single string β€” the word written by Stepan converted according to the rules described in the statement. Examples Input 13 pobeeeedaaaaa Output pobeda Input 22 iiiimpleeemeentatiioon Output implemeentatioon Input 18 aeiouyaaeeiioouuyy Output aeiouyaeeioouy Input 24 aaaoooiiiuuuyyyeeeggghhh Output aoiuyeggghhh
import math from sys import stdin, stdout fin = stdin fout = stdout n = int(fin.readline().strip()) s = fin.readline().strip() ans = [] gl = frozenset({'a', 'e', 'i', 'y', 'o', 'u'}) met = False cdel = False for i in range(n): if i > 0: if s[i] != s[i - 1]: met = False cdel = False ans.append(s[i]) else: if s[i] in gl: if s[i] == 'e' or s[i] == 'o': if not met: ans.append(s[i]) elif not cdel: ans.pop() cdel = True met = True else: ans.append(s[i]) else: ans.append(s[i]) fout.write(''.join(ans))
99
820_A. Mister B and Book Reading
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second β€” v0 + a pages, at third β€” v0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v1 pages per day. Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time. Help Mister B to calculate how many days he needed to finish the book. Input First and only line contains five space-separated integers: c, v0, v1, a and l (1 ≀ c ≀ 1000, 0 ≀ l < v0 ≀ v1 ≀ 1000, 0 ≀ a ≀ 1000) β€” the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading. Output Print one integer β€” the number of days Mister B needed to finish the book. Examples Input 5 5 10 5 4 Output 1 Input 12 4 12 4 1 Output 3 Input 15 1 100 0 0 Output 15 Note In the first sample test the book contains 5 pages, so Mister B read it right at the first day. In the second sample test at first day Mister B read pages number 1 - 4, at second day β€” 4 - 11, at third day β€” 11 - 12 and finished the book. In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.
c,v0,v1,a,l = list(map(int, input().split(" "))) count=1 sum=v0 while sum<c: sum+=min(v0+count*a-l,v1-l) count+=1 print(count)