src_uid
stringlengths
32
32
prob_desc_description
stringlengths
63
2.99k
tags
stringlengths
6
159
source_code
stringlengths
29
58.4k
lang_cluster
stringclasses
1 value
categories
listlengths
1
5
desc_length
int64
63
3.13k
code_length
int64
29
58.4k
games
int64
0
1
geometry
int64
0
1
graphs
int64
0
1
math
int64
0
1
number theory
int64
0
1
probabilities
int64
0
1
strings
int64
0
1
trees
int64
0
1
labels_dict
dict
__index_level_0__
int64
0
4.98k
d4b6bea78b80b0a94646cbaf048b473f
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer q independent test cases.
['greedy']
n=int(input()) for i in range(n): n,k=map(int,input().split(' ')) stri=input() result=['1']*n t=0 for j in range(n): if(stri[j]=='0'): s=min(k,j-t) k-=s result[j-s]='0' t+=1 print("".join(result))
Python
[ "other" ]
599
276
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,239
be12bb8148708f9ad3dc33b83b55eb1e
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
['data structures', 'constructive algorithms', 'sortings', 'greedy']
n = int(input()) b = list(map(int, input().split())) from collections import Counter from itertools import accumulate cum = list(accumulate(b)) cnt = Counter(cum) print (n - cnt.most_common(1)[0][1])
Python
[ "other" ]
887
201
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,685
9fd09b05d0e49236dca45615e684ad85
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by units.Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.
['binary search']
n, k = map(int, input().split()) A = list(map(int, input().split())) def f(x): over = 0 need = 0 for a in A: if a > x: over += (a - x) else: need += (x - a) return need <= (over * (1 - k/100)) left = 0 right = 1000 while right - left > 1e-12: m = (left + right) / 2 if f(m): left = m else: right = m print(round(right, 8))
Python
[ "other" ]
754
409
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,075
ed5bf2596ec33a1a044ffd7952cdb897
Sereja has a sequence that consists of n positive integers, a1, a2, ..., an. First Sereja took a piece of squared paper and wrote all distinct non-empty non-decreasing subsequences of sequence a. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exceed it.A sequence of positive integers x = x1, x2, ..., xr doesn't exceed a sequence of positive integers y = y1, y2, ..., yr, if the following inequation holds: x1 ≤ y1, x2 ≤ y2, ..., xr ≤ yr.Now Sereja wonders, how many sequences are written on the lines piece of paper. Help Sereja, find the required quantity modulo 1000000007 (109 + 7).
['data structures', 'dp']
M=10**9+7 N=2**20 v,w=[0]*N,[0]*N def S(y): s=0 while y>0: s+=w[y] y-=y&-y return s input() for x in map(int,raw_input().split()): s=1+S(x) d=((s*x-v[x])%M+M)%M v[x]+=d y=x while y<N: w[y]=(w[y]+d)%M y+=y&-y print S(N-1)%M
Python
[ "other" ]
659
255
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,342
c249103153c5006e9b37bf15a51fe261
You are given a following process. There is a platform with n columns. 1 \times 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the n columns have at least one square in them, the bottom row is being removed. You will receive 1 point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.
['implementation']
#JMD #Nagendra Jha-4096 #a=list(map(int,sys.stdin.readline().split(' '))) #n,k,s= map(int, sys.stdin.readline().split(' ')) import sys import math #import fractions #import numpy ###Defines...### mod=1000000007 ###FUF's...### def nospace(l): ans=''.join(str(i) for i in l) return ans ##### Main #### n,m= map(int, sys.stdin.readline().split(' ')) a=list(map(int,sys.stdin.readline().split(' '))) li=[0 for i in range(n)] for aa in a:li[aa-1]+=1 li.sort() print(li[0])
Python
[ "other" ]
576
484
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,775
c4929ec631caae439ccb9bc6882ed816
You have an array of integers a of size n. Initially, all elements of the array are equal to 1. You can perform the following operation: choose two integers i (1 \le i \le n) and x (x &gt; 0), and then increase the value of a_i by \left\lfloor\frac{a_i}{x}\right\rfloor (i.e. make a_i = a_i + \left\lfloor\frac{a_i}{x}\right\rfloor).After performing all operations, you will receive c_i coins for all such i that a_i = b_i.Your task is to determine the maximum number of coins that you can receive by performing no more than k operations.
['dp', 'greedy']
def quotient(n): li = set() for i in range(1, n + 1): li.add(n // i) return list(li) def main(): seen = {} for i in range(1, 1001): seen[i] = False tree = [[] for i in range(13)] tree[0] = [1] seen[1] = True for i in range(1, 13): cand = set() for el in tree[i - 1]: for q in quotient(el): if el + q <= 1000: if seen[el + q] == False: cand.add(q + el) for el in cand: seen[el] = True tree[i] = list(cand) cost = [0] * 1001 for i in range(13): for el in tree[i]: cost[el] = i t = int(input()) for _ in range(t): n, k = map(int, input().split()) b = list(map(int, input().split())) c = list(map(int, input().split())) b = [cost[b[i]] for i in range(n)] N = n W = k w = b v = c if sum(b) <= k: print(sum(c)) else: dp = [[0] * (W + 1) for j in range(N + 1)] for i in range(N): for j in range(W + 1): if j < w[i]: dp[i + 1][j] = dp[i][j] else: dp[i + 1][j] = max(dp[i][j], dp[i][j - w[i]] + v[i]) print(dp[N][W]) if __name__ == '__main__': main()
Python
[ "other" ]
622
1,155
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,670
09faf19627d2ff00c3821d4bc2644b63
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, \dots, a_n, where a_i is the price of berPhone on the day i.Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if n=6 and a=[3, 9, 4, 6, 7, 5], then the number of days with a bad price is 3 — these are days 2 (a_2=9), 4 (a_4=6) and 5 (a_5=7).Print the number of days with a bad price.You have to answer t independent data sets.
['data structures', 'implementation']
t = int(input()) for _ in range(t): n = int(input()) lis = list(map(int, input().split())) stack = [] bad = 0 for i in range(len(lis)): if len(stack) == 0 or stack[-1] <= lis[i]: stack.append(lis[i]) else: while(len(stack) > 0 and stack[-1] > lis[i]): stack.pop() bad += 1 stack.append(lis[i]) print (bad)
Python
[ "other" ]
623
418
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,186
99d2b0386d101da802ac508ef8f7325b
There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).Let's simplify this game a bit. Formally, there are n participants, the i-th participant chose the number a_i. The winner of the game is such a participant that the number he chose is unique (i. e. nobody else chose this number except him) and is minimal (i. e. among all unique values of a the minimum one is the winning one).Your task is to find the index of the participant who won the game (or -1 if there is no winner). Indexing is 1-based, i. e. the participants are numbered from 1 to n.You have to answer t independent test cases.
['implementation']
import math for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) d,dd={},{} for ii in range(0,n): dd[a[ii]]=ii+1 for i in a: if i in d: d[i]+=1 else:d[i]=1 f,m=1,100000000 for j in d: # print(j,m) if d[j]==1: f=0 if m>j: ans=j m=j if f:print(-1) else:print(dd[ans]) # print(d)
Python
[ "other" ]
768
472
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,459
9a6ee18e144a38935d7c06e73f2e6384
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.Help the Beaver to write a program that will encrypt messages in the described manner.
['data structures']
n,m,c = map(int,input().split()) a = list(input().split()) b = list(input().split()) sum = 0 for i in range(n): if i<m: sum = sum + int(b[i]) sum = sum%c if i >= n - m + 1: sum = c - int(b[i-n+m-1]) + sum sum = sum%c print((int(a[i])+sum)%c,end = ' ')
Python
[ "other" ]
1,048
300
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,387
516ed4dbe4da9883c88888b134d6621f
Sonya was unable to think of a story for this problem, so here comes the formal description.You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.
['dp', 'sortings']
from heapq import * class Maxheap: def __init__(_): _.h = [] def add(_, v): heappush(_.h, -v) def top(_): return -_.h[0] def pop(_): return -heappop(_.h) class Graph: def __init__(_): _.change = Maxheap() # increment slope at ... _.change.add(-10**18) _.a = _.y = 0 # last line has slope a, starts from y _.dx = 0 # the whole graph is shifted right by ... def __repr__(_): return f"<{[x+_.dx for x in _.change]}; {_.a} {_.y}>" def shiftx(_, v): _.dx+= v def shifty(_, v): _.y+= v def addleft(_, v): if _.change.top() < v-_.dx: dx = v-_.dx - _.change.top() _.y+= _.a*dx _.change.add(v-_.dx) def addright(_, v): if _.change.top() < v-_.dx: dx = v-_.dx - _.change.top() _.y+= _.a*dx; _.a+= 1 _.change.add(v-_.dx) return _.change.add(v-_.dx) _.a+= 1; _.y+= _.change.top()-(v-_.dx) def cutright(_): dx = _.change.pop()-_.change.top() _.a-= 1; _.y-= _.a*dx n = int(input()) G = Graph() for x in map(int,input().split()): G.shiftx(1) G.addleft(x) G.addright(x) while G.a > 0: G.cutright() print(G.y)
Python
[ "other" ]
409
1,225
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,168
bf6e2310e4f808ca4c8ff28ba8a51a68
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1end repeatHere y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value.
['constructive algorithms']
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w = map(int, input().split()) a = [0] + list(map(int, input().split())) total = sum(a) def ng(): print('No') exit() def ok(a): print('Yes') print(*a) exit() if w < 1 or total < w: ng() if n == 1: if w == a[1]: ok([1] * (a[1] * 2)) else: ng() if w == 1: if min(a[1:]) > 1: ng() min_i = a.index(1) ans = [] for i in range(1, n + 1): if i == min_i: continue ans += [i] * (a[i] * 2) ok([min_i] + ans + [min_i]) ans1, ans2, ans3 = [], [], [] w -= 2 if w: for i in range(1, 3): x = min(a[i] - 1, w) w -= x a[i] -= x ans3 += [i] * (2 * x) for i in range(3, n + 1): x = min(a[i], w) w -= x a[i] -= x ans3 += [i] * (2 * x) ans1 = [2] * ((a[2] - 1) * 2) for i in range(3, n + 1): ans1 += [i] * (a[i] * 2) ans1 = [1] + ans1 + [1] a[1] -= 1 ans2 = [2] + [1] * (a[1] * 2) + [2] if w == 0: ok(ans1 + ans2 + ans3) else: ng()
Python
[ "other" ]
730
1,137
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
477
92b6ab47c306a15631f045d624a1bf37
You are given an array a consisting of n integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.You may choose at most one consecutive subarray of a and multiply all values contained in this subarray by x. You want to maximize the beauty of array after applying at most one such operation.
['dp', 'greedy', 'divide and conquer', 'data structures', 'brute force']
n, x = map(int, raw_input().split()) A = map(int, raw_input().split()) dpm = [0] * (n+1) dp = [0] * (n+1) dpn = [0] * (n+1) ans = 0 for i in xrange(1, n+1): dpm[i] = A[i-1]*x + max(dpm[i-1], dpn[i-1], 0) dp[i] = A[i-1] + max(dpm[i-1], dp[i-1], dpn[i-1], 0) dpn[i] = A[i-1] + max(dpn[i-1], 0) ans = max(ans, dpm[i], dp[i], dpn[i]) print ans
Python
[ "other" ]
486
344
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
128
6bb26991c9ea70e51a6bda5653de8131
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.
['implementation']
n, k = map(int, raw_input().split()) t = 0 for a in raw_input().split(): if a.count('4') + a.count('7') <= k: t += 1 print t
Python
[ "other" ]
443
127
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
923
0ea79b2a7ddf3d4da9c7a348e61933a7
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that: the cashier needs 5 seconds to scan one item; after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.
['implementation']
import fileinput f = fileinput.input() n = int(f.readline()) ks = [] line = f.readline() ks = map(int, line.split()) ms = [] for i in range(n): ms.append(map(int, f.readline().split())) def time(n): return sum(ms[n]) * 5 + ks[n] * 15 print min(map(time, range(n)))
Python
[ "other" ]
823
276
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,567
1985566215ea5a7f22ef729bac7205ed
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?
['data structures', 'implementation', 'sortings']
n=int(input()) s1=input().split() s1=sorted(s1) s2=input().split() s2=sorted(s2) s2.append(0) s3=input().split() s3=sorted(s3) s3.append(0) for i in range(len(s1)): if int(s1[i])-int(s2[i])!=0: print(s1[i]) break for i in range(len(s2)): if int(s2[i])-int(s3[i])!=0: print(s2[i]) break
Python
[ "other" ]
852
353
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
787
6c165390c7f9fee059ef197ef40ae64f
Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0 to T, inclusive.All problems are divided into two types: easy problems — Petya takes exactly a minutes to solve any easy problem; hard problems — Petya takes exactly b minutes (b &gt; a) to solve any hard problem. Thus, if Petya starts solving an easy problem at time x, then it will be solved at time x+a. Similarly, if at a time x Petya starts to solve a hard problem, then it will be solved at time x+b.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time t_i (0 \le t_i \le T) at which it will become mandatory (required). If Petya leaves the exam at time s and there is such a problem i that t_i \le s and he didn't solve it, then he will receive 0 points for the whole exam. Otherwise (i.e if he has solved all such problems for which t_i \le s) he will receive a number of points equal to the number of solved problems. Note that leaving at time s Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if n=2, T=5, a=2, b=3, the first problem is hard and t_1=3 and the second problem is easy and t_2=2. Then: if he leaves at time s=0, then he will receive 0 points since he will not have time to solve any problems; if he leaves at time s=1, he will receive 0 points since he will not have time to solve any problems; if he leaves at time s=2, then he can get a 1 point by solving the problem with the number 2 (it must be solved in the range from 0 to 2); if he leaves at time s=3, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time s=4, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time s=5, then he can get 2 points by solving all problems. Thus, the answer to this test is 2.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
['two pointers', 'sortings', 'greedy']
import sys t = int(input()) ans = [0]*t for pi in range(t): n, T, a, b = map(int, sys.stdin.readline().split()) a1 = list(map(int, sys.stdin.readline().split())) a2 = list(map(int, sys.stdin.readline().split())) easy_count = a1.count(0) hard_count = n - easy_count tasks = sorted((t, x) for x, t in zip(a1, a2)) solved = 0 req_easy, req_hard = 0, 0 for i, (t, is_hard) in enumerate(tasks, start=1): rem = t-1 - req_easy*a - req_hard*b if rem >= 0: c = min(easy_count-req_easy, rem//a) c += min(hard_count-req_hard, (rem-c*a) // b) solved = max(solved, c+req_easy+req_hard) if is_hard == 1: req_hard += 1 else: req_easy += 1 if easy_count*a + hard_count*b <= T: solved = n ans[pi] = solved print(*ans, sep='\n')
Python
[ "other" ]
2,543
862
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,898
30c4f155336cf762699a1bbc55a60d27
School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.
['implementation']
n,m = map(int,raw_input().split()) a = [0]*n for _ in xrange(m): b,c = map(int,raw_input().split()) for i in xrange(b,c+1,1): a[i-1]+=1 for i in xrange(n): if a[i]<>1: print i+1,a[i] exit(0) print 'OK'
Python
[ "other" ]
766
210
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
189
072fe39ccec85497af67cf46551a5920
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
['dp', 'two pointers', 'divide and conquer', 'data structures', 'binary search']
import sys from collections import defaultdict as di range = range input = raw_input class LazySegmentTree: def __init__(self, data, default=0, func=max): """initialize the lazy segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self._lazy = [0] * (2 * _size) self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __len__(self): return self._len def _push(self, idx): """push query on idx to its children""" # Let the children know of the queries q, self._lazy[idx] = self._lazy[idx], 0 self._lazy[2 * idx] += q self._lazy[2 * idx + 1] += q self.data[2 * idx] += q self.data[2 * idx + 1] += q def _update(self, idx): """updates the node idx to know of all queries applied to it via its ancestors""" for i in reversed(range(1, idx.bit_length())): self._push(idx >> i) def _build(self, idx): """make the changes to idx be known to its ancestors""" idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx] idx >>= 1 def add(self, start, stop, value): """lazily add value to [start, stop)""" start = start_copy = start + self._size stop = stop_copy = stop + self._size while start < stop: if start & 1: self._lazy[start] += value self.data[start] += value start += 1 if stop & 1: stop -= 1 self._lazy[stop] += value self.data[stop] += value start >>= 1 stop >>= 1 # Tell all nodes above of the updated area of the updates self._build(start_copy) self._build(stop_copy - 1) def query(self, start, stop, default=0): """func of data[start, stop)""" start += self._size stop += self._size # Apply all the lazily stored queries self._update(start) self._update(stop - 1) res = default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "LazySegmentTree({0})".format(self.data) n, k = [int(x) for x in input().split()] A = [int(x) for x in input().split()] last_occ = [-1]*(n + 1) update = [] for i in range(n): a = A[i] update.append(last_occ[a]) last_occ[a] = i oldDP = [0]*(n+1) for _ in range(k): seg = LazySegmentTree(oldDP) DP = [0] for i in range(1,n+1): #for j in range(update[i - 1] + 1, i): # oldDP[j] += 1 seg.add(update[i - 1] + 1, i, 1) #DP.append(max(oldDP[:i+1])) DP.append(seg.query(0,i+1)) oldDP = DP print max(oldDP)
Python
[ "other" ]
1,039
3,296
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
852
88e6651e1b0481d711e89c8071be1edf
Today the «Z» city residents enjoy a shell game competition. The residents are gathered on the main square to watch the breath-taking performance. The performer puts 3 non-transparent cups upside down in a row. Then he openly puts a small ball under one of the cups and starts to shuffle the cups around very quickly so that on the whole he makes exactly 3 shuffles. After that the spectators have exactly one attempt to guess in which cup they think the ball is and if the answer is correct they get a prize. Maybe you can try to find the ball too?
['implementation']
fil = open("input.txt","r") start = int(fil.readline().strip()) for i in range(3): a,b = list(map(int, fil.readline().strip().split(" "))) if a == start: start = b elif b == start: start = a fil2 = open("output.txt","w") fil2.write(str(start))
Python
[ "other" ]
549
247
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,373
5312a505bd59b55a6c5487f67a33d81a
At the store, the salespeople want to make all prices round. In this problem, a number that is a power of 10 is called a round number. For example, the numbers 10^0 = 1, 10^1 = 10, 10^2 = 100 are round numbers, but 20, 110 and 256 are not round numbers. So, if an item is worth m bourles (the value of the item is not greater than 10^9), the sellers want to change its value to the nearest round number that is not greater than m. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly 10^k bourles, where the value of k — is the maximum possible (k — any non-negative integer).For example, let the item have a value of 178-bourles. Then the new price of the item will be 100, and the answer will be 178-100=78.
['constructive algorithms']
import math for _ in [0] * int(input()): number = int(input()) k = 1 if number == 1 or math.log(number, 10) == int(math.log(number, 10)): print(0) elif number < 10: print(number - 1) else: while k <= (number // 10): k *= 10 print(number - k)
Python
[ "other" ]
853
330
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,297
7372994c95acc3b999dd9657abd35a24
Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya.n athletes participate in the tournament, numbered from 1 to n. Burenka determined the strength of the i-th athlete as an integer a_i, where 1 \leq a_i \leq n. All the strength values are different, that is, the array a is a permutation of length n. We know that in a fight, if a_i &gt; a_j, then the i-th participant always wins the j-th.The tournament goes like this: initially, all n athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.Burenka decided to ask Tonya q questions. In each question, Burenka asks how many victories the i-th participant gets in the first k rounds of the competition for some given numbers i and k. Tonya is not very good at analytics, so he asks you to help him answer all the questions.
['binary search', 'data structures', 'implementation', 'two pointers']
import sys, threading import math from os import path from collections import defaultdict, Counter, deque from bisect import * from string import ascii_lowercase from functools import cmp_to_key import heapq def readInts(): x = list(map(int, (sys.stdin.readline().rstrip().split()))) return x[0] if len(x) == 1 else x def readList(type=int): x = sys.stdin.readline() x = list(map(type, x.rstrip('\n\r').split())) return x def readStr(): x = sys.stdin.readline().rstrip('\r\n') return x write = sys.stdout.write read = sys.stdin.readline MAXN = 1123456 class mydict: def __init__(self, func): self.random = randint(0, 1 << 32) self.default = func self.dict = {} def __getitem__(self, key): mykey = self.random ^ key if mykey not in self.dict: self.dict[mykey] = self.default() return self.dict[mykey] def get(self, key, default): mykey = self.random ^ key if mykey not in self.dict: return default return self.dict[mykey] def __setitem__(self, key, item): mykey = self.random ^ key self.dict[mykey] = item def getkeys(self): return [self.random ^ i for i in self.dict] def __str__(self): return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}' def lcm(a, b): return (a*b)//(math.gcd(a,b)) def mod(n): return n%(998244353) def upper_bound(a, num): l = 0 r = len(a)-1 ans = -1 while l <= r: mid = (l+r)//2 if a[mid] >= num: ans = mid r = mid-1 else: l = mid+1 return ans def solve(t): # print(f'Case #{t}: ', end = '') n, q = readInts() ar = readList() mr = [] m = ar[0] mp = {} for i in range(n): m = max(ar[i], m) mp[m] = i mr.append(m) # print(mp) for _ in range(q): ind, r = readInts() ind -= 1 if r < ind: print(0) continue if ar[ind] == n: print(max(0, r-max(0, (ind-1)))) continue ans = 0 r -= max(0, ind-1) if ind > 0 and mr[ind-1] > ar[ind]: print(0) continue if ind > 0 and r > 0: ans = 1 r -= 1 if r > 0: if ar[ind] in mp: # print(mp[ar[ind]]) tmp = mp[ar[ind]] - ind if r >= tmp: ans += tmp else: ans += r print(ans) def main(): t = 1 if path.exists("F:/Comp Programming/input.txt"): sys.stdin = open("F:/Comp Programming/input.txt", 'r') sys.stdout = open("F:/Comp Programming/output1.txt", 'w') # sys.setrecursionlimit(10**6) t = readInts() for i in range(t): solve(i+1) if __name__ == '__main__': main()
Python
[ "other" ]
1,168
3,136
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,566
a440099306ef411a4deca7fe3305c08b
Vasya collects coins: he has exactly one coin for every year from 1 to n. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order. That is, he took a certain segment [l, r] and reversed it. At that the segment's endpoints did not coincide. For example, if n = 8, then initially Vasya's coins were kept in the order 1 2 3 4 5 6 7 8. If Vasya's younger brother chose the segment [2, 6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Vasya suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 ... n using exactly one segment reversal. If it is possible, find the segment itself.
['implementation']
def main(): num = int(input()) data = [int(x) for x in input().split()] left = 0 right = 0 sign = True i = 0 j = 0 if len(data)<2: sign = False #find left for i in range(len(data)): if data[i] != i+1: break left = i+1 #check left if left>num: sign = False #find right for j in range(num-1, i,-1): if data[j] != j+1: break right = j+1 #check left if right<1: sign = False if left > right: sign = False #check data from left to right for i in range(left-1, right-1): if data[i]!= data[i+1]+1: sign = False break if sign: print(left,right) else: print("0 0\n") main()
Python
[ "other" ]
917
855
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,503
1392daad6638b7a93e84dd474cdf916a
You are a paparazzi working in Manhattan.Manhattan has r south-to-north streets, denoted by numbers 1, 2,\ldots, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,\ldots,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the intersection between the x-th south-to-north street and the y-th west-to-east street is denoted by (x, y). In order to move from the intersection (x,y) to the intersection (x', y') you need |x-x'|+|y-y'| minutes.You know about the presence of n celebrities in the city and you want to take photos of as many of them as possible. More precisely, for each i=1,\dots, n, you know that the i-th celebrity will be at the intersection (x_i, y_i) in exactly t_i minutes from now (and he will stay there for a very short time, so you may take a photo of him only if at the t_i-th minute from now you are at the intersection (x_i, y_i)). You are very good at your job, so you are able to take photos instantaneously. You know that t_i &lt; t_{i+1} for any i=1,2,\ldots, n-1.Currently you are at your office, which is located at the intersection (1, 1). If you plan your working day optimally, what is the maximum number of celebrities you can take a photo of?
['dp']
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 r = inp[ii]; ii += 1 n = inp[ii]; ii += 1 T = inp[ii + 0: ii + 3 * n: 3] X = inp[ii + 1: ii + 3 * n: 3] Y = inp[ii + 2: ii + 3 * n: 3] big = 501 DP = [0] * n DPmax = [0] * n for i in range(n): x = X[i] y = Y[i] t = T[i] d = 0 reachall = t - (max(x, big - x) + max(y, big - y)) for j in reversed(range(i)): if T[j] <= reachall: d = max(d, DPmax[j]) break if d < DP[j] and abs(x - X[j]) + abs(y - Y[j]) <= t - T[j]: d = DP[j] if d > 0 or abs(x - 1) + abs(y - 1) <= t: d += 1 DP[i] = d DPmax[i] = max(d, DPmax[i - 1]) print DPmax[-1]
Python
[ "other" ]
1,403
754
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,623
1cd295e204724335c63e685fcc0708b8
The Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ≤ r.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 ≤ i &lt; n) ai ≤ ai + 1 holds.
['greedy', 'brute force']
n = int(input()) l = list(map(int,input().split())) l.append(max(l)) m,ans = l[0],0 for i in range(1,n) : if l[i-1]>l[i] : ans += l[i-1]-l[i] print(ans)
Python
[ "other" ]
585
164
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
730
d197a682b956f000422aeafd874816ce
Vasya has a sequence a consisting of n integers a_1, a_2, \dots, a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (\dots 00000000110_2) into 3 (\dots 00000000011_2), 12 (\dots 000000001100_2), 1026 (\dots 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to 0.For the given sequence a_1, a_2, \ldots, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 \le l \le r \le n and sequence a_l, a_{l + 1}, \dots, a_r is good.
['dp', 'bitmasks']
#!/usr/bin/env python3 from __future__ import absolute_import import sys from itertools import imap def rint(): return imap(int, sys.stdin.readline().split()) #lines = stdin.readlines() def get_num1(i): cnt = 0 while i: if i%2: cnt +=1 i //=2 return cnt n = int(raw_input()) a = list(rint()) b = [get_num1(aa) for aa in a] ans = 0 #S0[i] : 1 if sum of 1s in ragne (0, i) is odd, else 0 S0 = [0]*n S0[0] = b[0]%2 for i in xrange(1, n): S0[i] = (S0[i-1] + b[i])%2 #total even pairs in (0, n) even_cnt = S0.count(0) ans = even_cnt # check total even pairs in (i, n) for i in xrange(1, n): if b[i-1] %2: even_cnt = n - i - even_cnt else: even_cnt -= 1 ans += even_cnt for i in xrange(n): max_value = 0 sum_value = 0 for j in xrange(1, 62): if i + j > n: break sum_value += b[i+j-1] max_value = max(max_value, b[i+j-1]) if 2 * max_value > sum_value and sum_value%2 == 0: ans -= 1 print ans
Python
[ "other" ]
896
1,040
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,851
0d586ba7d304902caaeb7cd9e6917cd6
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle n \times m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell: if there is a digit k in the cell, then exactly k neighboring cells have bombs. if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).
['implementation']
n, m = map(int, input().split()) maps = [] for i in range(n): s = [ i for i in input()] maps.append(s) import sys for i in range(n): for j in range(m): ans = 0 if i-1 >=0 : if maps[i-1][j] == '*': ans += 1 if j-1 >= 0 and maps[i-1][j-1] == '*': ans += 1 if j+1 < m and maps[i-1][j+1] == '*': ans += 1 if i+1 <n : if maps[i+1][j] == '*': ans += 1 if j-1 >= 0 and maps[i+1][j-1] == '*': ans += 1 if j+1 < m and maps[i+1][j+1] == '*': ans += 1 if j-1 >=0 and maps[i][j-1] == '*': ans += 1 if j+1 <m and maps[i][j+1] == '*': ans += 1 if maps[i][j] in '12345678': if ans != int(maps[i][j]): print("NO") sys.exit(0) elif maps[i][j] == '.' and ans!=0: print("NO") sys.exit(0) print("YES")
Python
[ "other" ]
953
1,013
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,610
e30085b163c820cff68fb24b94088ec1
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence s is called correct if: s is empty; s is equal to "(t)", where t is correct bracket sequence; s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.
['data structures', 'greedy']
n = int(input()) start = 0 tmp = 0 wrong = 0 for b in input(): if b == '(': start += 1 else: if start > 0: start -= 1 else: wrong += 1 if wrong == 1: if start == 1: print('Yes') else: print('No') elif wrong == 0: if start == 0: print('Yes') else: print('No') else: print('No')
Python
[ "other" ]
951
390
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,994
a1ea9eb8db25289958a6f730c555362f
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
['constructive algorithms', 'sortings']
def cmp(x): return x[1] n,m=map(int,input().split()) q=[[] for i in range(m)] for i in range(n): name,r,b=input().split() q[int(r)-1].append([name,int(b)]) for i in q: i=sorted(i,key=cmp) if len(i)==2: print(i[-1][0],i[-2][0]) elif i[-1][1]==i[-2][1]==i[-3][1] or i[-2][1]==i[-3][1]: print('?') else: print(i[-1][0],i[-2][0])
Python
[ "other" ]
1,379
351
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
42
0135818c10fae9fc9efcc724fa43181f
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).It is possible that some students not be included in any team at all.Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
['dp', 'two pointers', 'sortings']
n, k = map(int, raw_input().split()) a = sorted(map(int, raw_input().split())) dp = [[0] * k for i in range(n)] dp[0][0] = 1 for i in range(1, n): l = i while l >= 0 and (a[i] - a[l]) <= 5: l -= 1 # print a[i], i - l, l for j in range(min(k, i + 1)): if j == 0: dp[i][j] = max(i - l, dp[i - 1][j]) else: if l >= 0: dp[i][j] = max(i - l + dp[l][j - 1], dp[i - 1][j]) else: dp[i][j] = max(i - l, dp[i - 1][j]) # print dp print max(dp[-1])
Python
[ "other" ]
1,097
540
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,065
fbde86a29f416b3d83bcc63fb3776776
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
['constructive algorithms']
s = ['a', 'a', 'b', 'b'] n = int(input()) q = [] for i in range(n): q.append(s[i % 4]) print(*q, sep="")
Python
[ "other" ]
488
108
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,717
16c54cf7d8b484b5e22a7d391fdc5cd3
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?
['implementation']
from collections import Counter as c x=int(input()) l=[] for i in range(x): l=l+list(map(int,input().split()))[1:] l=dict(c(l)) for a,b in l.items(): if b==x: print(a,end=' ')
Python
[ "other" ]
532
192
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,148
4585419ab2b7200770cfe1e607161e9f
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative integer a_i to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of a to help out students like Mishka: a was sorted in non-decreasing order (a_1 \le a_2 \le \dots \le a_n); n was even; the following sequence b, consisting of \frac n 2 elements, was formed and given out to students: b_i = a_i + a_{n - i + 1}. Professor also mentioned that any sequence a, which produces sequence b with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence a of non-negative integers, which produces sequence b with the presented technique. It is guaranteed that there exists at least one correct sequence a, which produces the given sequence b.
['greedy']
def read_input(): n = int(input()) line = input() line = line.strip().split() b = [int(num) for num in line] return n, b def mishka_and_the_last_exam(n, b): l = [0] * n half = n // 2 for i, sum_ in enumerate(b[::-1]): if i == 0: l[half - 1 - i] = sum_ // 2 l[half + i] = sum_ - (sum_ // 2) elif i < half - 1: l[half -1 - i] = l[half - 1 - i + 1] l[half + i] = sum_ - l[half -1 - i] if l[half + i - 1] > l[half + i]: diff = l[half + i - 1] - l[half + i] l[half -1 - i] -= diff l[half + i] += diff else: l[0] = 0 l[-1] = sum_ return l def print_results(result): result = [str(el) for el in result] print(" ".join(result)) if __name__ == "__main__": n, b = read_input() result = mishka_and_the_last_exam(n, b) print_results(result)
Python
[ "other" ]
1,299
958
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,089
6e7c2c0d7d4ce952c53285eb827da21d
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 &gt; 19.
['brute force']
n = int(raw_input()) lis = [] for i in range(n): l = [] parts = [int(x) for x in raw_input().split()] for p in parts: l.append(p) lis.append(l) rows = [] columns = [] for i in range(n): sum = 0 for j in range(n): sum += lis[i][j] rows.append(sum) for i in range(n): sum = 0 for j in range(n): sum += lis[j][i] columns.append(sum) total = 0 for i in range(n): for j in range(n): if columns[j] - rows[i] > 0: total += 1 print total
Python
[ "other" ]
975
501
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,711
2a6c457012f7ceb589b3dea6b889f7cb
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.
['implementation']
import sys n = int(sys.stdin.readline().split()[0]) rooms = [[0 for x in range(2)] for y in range(n)] row = 0 for line in sys.stdin: column = 0 for word in line.split(): rooms[row][column] = int(word) column += 1 row += 1 rooms_acceptable = 0 for room in rooms: if room[0] + 2 <= room[1]: rooms_acceptable += 1 print(rooms_acceptable)
Python
[ "other" ]
461
382
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,713
bac276604d67fa573b61075c1024865a
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.Help Pashmak, print the number of edges in the required path.
['dp', 'sortings']
from sys import stdin from itertools import repeat, groupby from operator import itemgetter def main(): n, m = map(int, stdin.readline().split()) d = [[] for _ in xrange(100001)] IN = stdin.read().split() IN = map(int, IN, repeat(10, len(IN))) for i in xrange(0, 3*m, 3): d[IN[i+2]].append((IN[i+1], IN[i])) dp = [0] * (n + 10) for dd in d: dd.sort() for u, v in [(x, max(dp[y[1]] for y in l)) for x, l in groupby(dd, key=itemgetter(0))]: dp[u] = max(dp[u], v + 1) print max(dp) main()
Python
[ "other" ]
593
553
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,720
994bfacedc61a4a67c0997011cadb333
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.
['data structures', 'greedy']
from heapq import heappush as hpush, heappop as hpop INF = float('inf') n = input() p = map(int, raw_input().strip().split()) free = [] sold = [] hpush(free, p[0]) ans = 0 for i in xrange(1, n): try: p1 = hpop(free) except: p1 = INF try: p2 = hpop(sold) except: p2 = INF if p1 < p2: if p2 != INF: hpush(sold, p2) if p1 < p[i]: hpush(sold, p[i]) ans += (p[i] - p1) else: hpush(free, p1) hpush(free, p[i]) else: if p1 != INF: hpush(free, p1) if p2 < p[i]: hpush(free, p2) hpush(sold, p[i]) ans += (p[i] - p2) else: hpush(sold, p2) hpush(free, p[i]) print ans
Python
[ "other" ]
445
789
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,144
7bb5df614d1fc8323eba51d04ee7bf2a
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows. Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1. Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.
['dp']
n = int(input()) P = list(map(int, input().split())) dp = [0] * (n + 2) dp[1] = 0 M = 10 ** 9 + 7 for i in range(2, n + 2): dp[i] = 2 * dp[i - 1] + 2 - dp[P[i - 2]] dp[i] %= M print(dp[-1])
Python
[ "other" ]
1,017
197
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,779
848ead2b878f9fd8547e1d442e2f85ff
Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?
['implementation', 'greedy']
def main(): n, v = map(int, input().split()) l = [0] * 3002 for _ in range(n): a, b = map(int, input().split()) l[a] += b a = res = 0 for b in l: x = a + b if x < v: res += x a = 0 else: res += v if a < v: a = x - v else: a = b print(res) if __name__ == '__main__': main()
Python
[ "other" ]
658
434
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,763
585bb4a040144da39ed240366193e705
The robot is located on a checkered rectangular board of size n \times m (n rows, m columns). The rows in the board are numbered from 1 to n from top to bottom, and the columns — from 1 to m from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands s executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in s. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board 3 \times 3, if the robot starts a sequence of actions s="RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell (2, 1) (second row, first column) then all commands will be executed successfully and the robot will stop at the cell (1, 2) (first row, second column). The robot starts from cell (2, 1) (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell (1, 2) (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
['implementation']
t = int(input()) for case in range(t): n, m = map(int, input().split()) s = input() x, y = 1, 1 x_max_r, x_max_l, y_max_u, y_max_d = 0, 0, 0, 0 x_last, y_last = 1, 1 x_mov, y_mov = 0, 0 # First find longest path for i in s: if i == "R": x_mov += 1 elif i == "L": x_mov -= 1 elif i == "D": y_mov += 1 elif i == "U": y_mov -= 1 if x_max_r < x_mov: x_max_r = x_mov elif x_max_l > x_mov: x_max_l = x_mov if y_max_d < y_mov: y_max_d = y_mov elif y_max_u > y_mov: y_max_u = y_mov if x + x_mov < 1 and x+1 <= m: x += 1 elif x + x_mov > m and x-1 > 0: x -= 1 if y + y_mov < 1 and y+1 <= n: y += 1 elif y + y_mov > n and y-1 > 0: y -= 1 if x + x_max_r > m or x + x_max_l < 1: x = x_last break elif y + y_max_d > n or y + y_max_u < 1: y = y_last break else: x_last, y_last = x, y print(y, x) """ 1 4 3 RDDDUDDUDLRLDDLLLDD 1 1 -3 1 1 3 2 ULURRLLRD 3 1 3 2 """
Python
[ "other" ]
1,724
1,284
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
680
d5fc2bc618dd9d453a5e7ae30ccb73f3
Polycarp is playing a new computer game. This game has n stones in a row. The stone on the position i has integer power a_i. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if n = 5 and a = [1, 5, 4, 3, 2], then Polycarp could make the following moves: Destroy the leftmost stone. After this move a = [5, 4, 3, 2]; Destroy the rightmost stone. After this move a = [5, 4, 3]; Destroy the leftmost stone. After this move a = [4, 3]. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example: Destroy the leftmost stone. After this move a = [5, 4, 3, 2]; Destroy the leftmost stone. After this move a = [4, 3, 2]. Polycarp destroyed the stones with the greatest and least power, so he can end the game.
['brute force', 'dp', 'greedy']
t = int(input()) for p in range(t): n = int(input()) a = list(map(int, input().rstrip().split())) x = max(a) j = a.index(x) y = min(a) i = a.index(y) mid = n // 2 a1 = 0 a2 = 0 a3 = 0 for k in range(n): if a[k] == y or a[k] == x: a1 = k + 1 for l in range(n - 1, -1, -1): if a[l] == y or a[l] == x: a2 = (n - l) if n % 2 == 0: for m in range(int(n / 2)): if a[m] == y or a[m] == x: a3 += m+1 #print(a3) #break for o in range(n - 1, int(n / 2)-1, -1): if a[o] == y or a[o] == x: a3 += (n - o) #print(a3) #break else: for q in range(n // 2 + 1): if a[q] == y or a[q] == x: a3 += q+1 for r in range(n - 1, n // 2, -1): if a[r] == y or a[r] == x: a3 += (n - r) print(min(a1, a2, a3)) #print(a1) #print(a2) #print(a3)
Python
[ "other" ]
1,349
1,075
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,950
5fa2af185c4e3c8a1ce3df0983824bad
Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.Tenten keeps a record for all events, and she ends up with a list of the following types of records: + means that she placed another shuriken on the showcase; - x means that the shuriken of price x was bought. Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!
['data structures', 'implementation', 'greedy']
def read_seq(v): seq = [] for i in range(2 * v): s = input().split() if len(s) == 2: s[1] = int(s[1]) seq.append(s) return seq def solve(): n = int(input()) pos = [-1] * (2 * n) stack = [] seq = read_seq(n) for i, act in enumerate(seq): if act[0] == '+': stack.append(i) else: if not stack: return None else: v = stack.pop() pos[v] = act[1] if stack: return None stack = [] for i, act in enumerate(seq): if act[0] == '+': if stack and stack[-1] < pos[i]: return None else: stack.append(pos[i]) else: stack.pop() return [x for x in pos if x != -1] def main(): res = solve() if res: print('YES') print(' '.join(map(str, res))) else: print('NO') if __name__ == '__main__': main()
Python
[ "other" ]
946
1,001
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,940
4d743a00e11510c824080ad7f1804021
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square.Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly k drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits.
['implementation', 'sortings', 'greedy']
n, k = map(int, raw_input().split()) squares = map(int, raw_input().split()) squares.sort(reverse=True) if k > n: print -1 else: print squares[k - 1], print 0
Python
[ "other" ]
590
170
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,292
cc928c02b337f2b5ad7aed37bb83d139
Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations. The total number of stations equals to n. One can fuel the car at the i-th station with no more than ai liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the 1-st and the 2-nd station is b1 kilometers, the distance between the 2-nd and the 3-rd one is b2 kilometers, ..., between the (n - 1)-th and the n-th ones the distance is bn - 1 kilometers and between the n-th and the 1-st one the distance is bn kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all ai is equal to the sum of all bi. The i-th gas station and i-th post office are very close, so the distance between them is 0 kilometers.Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.
['data structures', 'dp']
##[1,7,2,3] ## ##[8,1,1,3] ## ##[1,8,10,13] ## ##[8,9,10,13] ## ##[-7,-1,0,0] n=int(input()) A=list(map(int,input().split())) B=list(map(int,input().split())) Sa=[0]*n Sb=[0]*n Sa[0]=A[0] Sb[0]=B[0] for i in range(1,n): Sa[i]=Sa[i-1]+A[i] Sb[i]=Sb[i-1]+B[i] D=[0]*n for i in range(n): D[i]=Sa[i]-Sb[i] m=min(D) ans=[] for i in range(n): if(D[i]==m): ans.append(i+1) if(ans[-1]==n): ans[-1]=0 Sa[n-1]=A[n-1] B=[B[-1]]+B[:n-1] Sb[n-1]=B[n-1] for i in range(n-2,-1,-1): Sa[i]=Sa[i+1]+A[i] Sb[i]=Sb[i+1]+B[i] for i in range(n): D[i]=Sa[i]-Sb[i] m=min(D) for i in range(n): if(D[i]==m): ans.append(i-1) if(ans[-1]==-1): ans[-1]=n-1 ans=sorted(set(ans)) print(len(ans)) for item in ans: print(item+1,end=" ")
Python
[ "other" ]
1,934
800
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,407
4d24aaf5ebf70265b027a6af86e09250
You are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string b that consists of n characters such that: b is a regular bracket sequence; if for some i and j (1 \le i, j \le n) a_i=a_j, then b_i=b_j. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string b exists.
['bitmasks', 'brute force', 'implementation']
f=int(input()) for i in range(f): li=input() if li[0] == li[-1]: print("NO") continue x=0 y=0 z=0 a1=li[0] a2=li[-1] open1=0 close1=0 summ=0 for i in range(len(li)): if li[i]==a1: open1+=1 elif li[i]==a2: close1+=1 else: summ+=1 c1=0 c2=0; if open1+summ==close1: for i in range(len(li)): if li[i]==a2: c2+=1 else: c1+=1 if c2>c1: break elif open1==summ+close1: for i in range(len(li)): if li[i]==a1: c1+=1 else: c2+=1 if c2>c1: break else: print("NO") continue if c2>c1: print("NO") else: print("YES")
Python
[ "other" ]
1,055
910
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,361
e702594a8e993e135ea8ca78eb3ecd66
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.
['implementation', 'sortings']
def main(): number = int(raw_input()) min0 = -1 max0 = -1 covn = -1 for k in range(0, number): line = raw_input() words = line.split(' ', 1) l0 = int(words[0]) r0 = int(words[1]) if min0 == -1 or l0 < min0: min0 = l0 covn = -1 if max0 == -1 or r0 > max0: max0 = r0 covn = -1 if min0 == l0 and max0 == r0: covn = k+1 print(covn) main()
Python
[ "other" ]
585
475
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
616
c1e51cc003cbf60a617fc11de9c73bcf
Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate x_i-1, x_i+1 or stay at x_i. Each friend is allowed to move no more than once.For all friends 1 \le x_i \le n holds, however, they can come to houses with coordinates 0 and n+1 (if their houses are at 1 or n, respectively).For example, let the initial positions be x = [1, 2, 4, 4]. The final ones then can be [1, 3, 3, 4], [0, 2, 3, 3], [2, 2, 5, 5], [2, 1, 3, 5] and so on. The number of occupied houses is the number of distinct positions among the final ones.So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?
['dp', 'greedy']
# cook your dish here n = int(input()) f = list(map(int, input().split())) f.sort() f1 = [] for i in range(n): f1.append(f[i]) if (f1[0] > 0): f1[0] -= 1 for i in range(1, n): if (f1[i]-f1[i-1] > 1): f1[i] -= 1 elif (f1[i] == f1[i-1]): if (i == n-1 or f1[i+1] > f1[i]): f1[i] += 1 for i in range(1, n): if (f[i]-f[i-1] <= 2): f[i] = f[i-1] max_count = 1 min_count = 1 for i in range(1, n): if (f1[i] != f1[i-1]): max_count += 1 if (f[i] != f[i-1]): min_count += 1 print(min_count, max_count)
Python
[ "other" ]
1,068
609
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,502
88d56c1e3a7ffa94354ce0c70d8e958f
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.
['implementation', 'brute force']
n=input() a,b=map(str,raw_input().split(':')) if(int(a)>[n-1,n][n==12]):a='0'+a[1] if(int(b)>59):b='0'+b[1] print ''.join([[a,'10'][a=='00' and n==12],':',b])
Python
[ "other" ]
763
158
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
34
fdd60d5cde436c2f274fae89f4abf556
You are given a circular array with n elements. The elements are numbered from some element with values from 1 to n in clockwise order. The i-th cell contains the value ai. The robot Simba is in cell s.Each moment of time the robot is in some of the n cells (at the begin he is in s). In one turn the robot can write out the number written in current cell or move to the adjacent cell in clockwise or counterclockwise direction. To write out the number from the cell Simba doesn't spend any time, but to move to adjacent cell Simba spends one unit of time.Simba wants to write the number from each cell one time, so the numbers will be written in a non decreasing order. Find the least number of time units to write out all numbers.
['dp']
from heapq import heappush, heappop from collections import defaultdict def solve(start, lt): n = len(lt) ii = list(sorted(set(lt))) maxlt = max(ii) right = {} left = {} leftn = {} rightn = {} last = {} for i in range(2 * n): l = lt[i % n] if l in last: right[last[l]] = i % n left[i % n] = last[l] last[l] = i % n hole = defaultdict(lambda: - 10**10) _mindst = {} mindstb = {} mindste = {} for i in range(n): hole[lt[i]] = max(hole[lt[i]], (right[i] - i) % n) for i in range(n): _mindst[lt[i]] = n - hole[lt[i]] last = 0 for i in reversed(ii): mindste[i] = last last += _mindst[i] mindstb[i] = last def np(state): pos, boe = state if boe == 'begin': if left[pos] == pos: yield (0, (pos, 'end'), (('>', pos),)) l = pos while True: ll = left[l] if ll == pos: break distance = 2 * ((pos - l) % n) + (ll - pos) % n path = (('<', l), ('>', ll)) yield (distance, (ll, 'end'), path) l = left[l] r = pos while True: rr = right[r] if rr == pos: break distance = 2 * ((r - pos) % n) + (pos - rr) % n path = (('>', r), ('<', rr)) yield (distance, (rr, 'end'), path) r = right[r] if boe == 'end' or boe == 'start': if boe == 'start': nxtl = ii[0] else: nxtl = ii[ii.index(lt[pos]) + 1] p = pos while lt[p] != nxtl: p = (p + 1) % n yield ((p - pos) % n, (p, 'begin'), (('up', '>', p),)) p = pos while lt[p] != nxtl: p = (p - 1) % n yield ((pos - p) % n, (p, 'begin'), (('up', '<', p),)) def dijkstra(beg): border = [] heappush(border, (mindstb[lt[beg[0]]], 0, beg, None, None)) fin = {} while True: asd, verd, ver, parent, path = heappop(border) if ver not in fin: fin[ver] = verd, parent, path pos, boe = ver if boe == 'end' and lt[pos] == maxlt: cur = ver gpath = [] while cur != beg: _, parent, path = fin[cur] gpath.extend(reversed(path)) cur = parent return verd, list(reversed(gpath)) for d, neigh, path in np(ver): pos, boe = neigh if boe == 'start' or boe == 'begin': asd = d + verd + mindstb[lt[pos]] else: asd = d + verd + mindste[lt[pos]] heappush(border, (asd,(d + verd), neigh, ver, path)) def reconstruct(path): cur = start res = [] done = set() for ps in path: #print('ps', ps, 'cur', cur) if len(ps) == 3: _, direction, pos = ps dst = (pos - cur) % n if direction == '>' else (cur - pos) % n sign = '+' if dst == 0 or direction == '>' else '-' res.append('%s%d'%(sign, dst)) cur = pos done.add(pos) else: direction, pos = ps if direction == '>': last = cur while cur != pos: cur = right[cur] if cur not in done: done.add(cur) res.append('+%d'%((cur-last)%n)) last = cur if direction == '<': last = cur while cur != pos: cur = left[cur] if cur not in done: done.add(cur) res.append('-%d'%((last-cur)%n)) last = cur return res dst, path = dijkstra((start, 'start')) return dst, reconstruct(path) def check(start, lt, sol, dst): cmp_dst, path = sol ltcur = -10**10 n = len(lt) assert(cmp_dst == dst) done = set() cur = start for move in path: cur += {'+': 1, '-': -1}[move[0]] * int(move[1:]) cur %= n assert(cur not in done) done.add(cur) assert(lt[cur] >= ltcur) ltcur = lt[cur] assert(len(done) == len(lt)) n, start = tuple(map(int, raw_input().split())) lt = tuple(map(int, raw_input().split())) dst, rpath = solve(start - 1, lt) print(dst) for p in rpath: print(p)
Python
[ "other" ]
732
4,896
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,480
0a157c97599c2240ca916317524c67e5
Even if you just leave them be, they will fall to pieces all by themselves. So, someone has to protect them, right?You find yourself playing with Teucer again in the city of Liyue. As you take the eccentric little kid around, you notice something interesting about the structure of the city.Liyue can be represented as a directed graph containing n nodes. Nodes are labeled from 1 to n. There is a directed edge from node a to node b if and only if a &lt; b.A path between nodes a and b is defined as a sequence of edges such that you can start at a, travel along all of these edges in the corresponding direction, and end at b. The length of a path is defined by the number of edges. A rainbow path of length x is defined as a path in the graph such that there exists at least 2 distinct colors among the set of x edges.Teucer's favorite number is k. You are curious about the following scenario: If you were to label each edge with a color, what is the minimum number of colors needed to ensure that all paths of length k or longer are rainbow paths?Teucer wants to surprise his older brother with a map of Liyue. He also wants to know a valid coloring of edges that uses the minimum number of colors. Please help him with this task!
['bitmasks', 'constructive algorithms', 'divide and conquer']
# LUOGU_RID: 93245551 n,k=map(int,input().split()) cnt=0 sum=1 while sum<n: sum=sum*k cnt=cnt+1 print(cnt) for i in range(0,n): for j in range(i+1,n): u=i v=j ans=0 while u!=v: u//=k v//=k ans=ans+1 print(ans,end=' ')
Python
[ "other" ]
1,319
321
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,902
3efc451a0fd5b67d58812eff774b3c6a
Student Dima from Kremland has a matrix a of size n \times m filled with non-negative integers.He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!Formally, he wants to choose an integers sequence c_1, c_2, \ldots, c_n (1 \leq c_j \leq m) so that the inequality a_{1, c_1} \oplus a_{2, c_2} \oplus \ldots \oplus a_{n, c_n} &gt; 0 holds, where a_{i, j} is the matrix element from the i-th row and the j-th column.Here x \oplus y denotes the bitwise XOR operation of integers x and y.
['dp', 'constructive algorithms', 'bitmasks', 'brute force']
n, m = map(int, raw_input().split()) a = [] for i in range(n): a.append(map(int, raw_input().split())) z = 'NIE' l = 0 r = 0 for i in range(n): for j in range(m): x = 0 for k in range(n): if k != i: x = x ^ a[k][0] else: x = x ^ a[k][j] if x > 0: z = 'TAK' l = i r = j break if z == 'TAK': break print z if z == 'TAK': p = [] for i in range(n): if i == l: p.append(r + 1) else: p.append(1) print ' '.join(map(str, p))
Python
[ "other" ]
661
556
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,814
d24c7d022efd1425876e6b45150362be
John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N.John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules.To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey.He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey.In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7.
['dp']
n = int(input()) cnt = [[] for _ in range(n)] for i in range (n - 1): fr, to = map(int, input().split()) cnt[fr - 1].append(to - 1); cnt[to - 1].append(fr - 1); l = 0 for i in range(n): if (len(cnt[i]) == 1): l += 1 ans = (n - l) * pow(2, n - l, 10 ** 9 + 7) ans += l * pow(2, n - l + 1, 10 ** 9 + 7) print (ans % (10 ** 9 + 7))
Python
[ "other" ]
1,329
353
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
204
b0446162c528fbd9c13f3e9d5c70d076
As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to n, then we can formalize the popular model of abduction, known as the (a, b)-Cowavan Raid: first they steal a cow number a, then number a + b, then — number a + 2·b, and so on, until the number of an abducted cow exceeds n. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made p scenarios of the (a, b)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen.
['data structures', 'sortings', 'brute force']
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()] ii = 0 n = inp[ii] ii += 1 A = [float(x) for x in inp[ii:ii + n]] ii += n queries = [[] for _ in range(n)] q = inp[ii] ii += 1 m = 500 ans = [0]*q B = [] for _ in range(q): a = inp[ii] - 1 ii += 1 b = inp[ii] ii += 1 B.append(b) if b >= m: i = a s = 0.0 while i < n: s += A[i] i += b ans[_] = s else: queries[a].append(_) buckets = [[0.0]*i for i in range(1, m)] modvals = [n%b for b in range(1, m)] for a in reversed(range(n)): val = A[a] for b in range(m - 1): if modvals[b] == 0: modvals[b] += b else: modvals[b] -= 1 buckets[b][modvals[b]] += val #for b,bucket in enumerate(buckets): # bucket[a % (b + 1)] += val for qind in queries[a]: ans[qind] = buckets[B[qind] - 1][a % B[qind]] print '\n'.join(str(int(x)) for x in ans)
Python
[ "other" ]
1,377
1,015
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,777
cc1b29b49711131d4790d91d0fae4a5a
Recently Monocarp got a job. His working day lasts exactly m minutes. During work, Monocarp wants to drink coffee at certain moments: there are n minutes a_1, a_2, \dots, a_n, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute a_i, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least d minutes pass between any two coffee breaks. Monocarp also wants to take these n coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than d minutes pass between the end of any working day and the start of the following working day.For each of the n given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.
['data structures', 'two pointers', 'binary search', 'greedy']
from collections import Counter, defaultdict, deque read = lambda: list(map(int,input().split())) def solve(a,d,df): cnt = 1 res = [0] * n Q = deque([(a[0], cnt)]) res[df[a[0]]] = 1 for i in range(1,n): if a[i] > Q[0][0] + d: val, day = Q.popleft() res[df[a[i]]] = day Q.append((a[i], day)) else: cnt += 1 res[df[a[i]]] = cnt Q.append((a[i], cnt)) print(cnt) print(' '.join(map(str, res))) n,m,d = read() a = read() df = {v:i for i,v in enumerate(a)} a.sort() solve(a,d,df)
Python
[ "other" ]
1,156
591
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,975
4cc5a6975d33cee60e53e8f648ec30de
You are given two strings s and t, both consisting only of lowercase Latin letters.The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, \dots, s_r without changing the order.Each of the occurrences of string a in a string b is a position i (1 \le i \le |b| - |a| + 1) such that b[i..i + |a| - 1] = a (|a| is the length of string a).You are asked q queries: for the i-th query you are required to calculate the number of occurrences of string t in a substring s[l_i..r_i].
['implementation', 'brute force']
a1 = list(map(int, input().split(' ')[:3])) bigString = input() littleString = input() all = 0 left = [0]*len(bigString) right = [0]*len(bigString) leftCount = 0 rightCount = 0 for i in range(len(bigString)): left[i] = leftCount if bigString.find(littleString,i,i + len(littleString)) != -1: leftCount += 1 for i in range(len(bigString) - 1, -1, -1): #print(i) right[i] = rightCount if bigString.find(littleString,i - len(littleString) + 1, i + 1) != -1: rightCount += 1 for i in range(len(bigString)): if bigString.find(littleString,i,i + len(littleString)) != -1: all += 1 #print(left) #print(right) #print(all, "all") for s in range(a1[2]): a2 = list(map(int, input().split(' ')[:2])) a2[0] -= 1 a2[1] -= 1 if a2[1] - a2[0] < len(littleString) - 1: print(0) else: result = all - right[a2[1]] - left[a2[0]] print(result)
Python
[ "other" ]
599
915
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,450
ed0a8a10e03de931856e287f9e650e1a
Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: If i ≠ n, move from pile i to pile i + 1; If pile located at the position of student is not empty, remove one box from it.GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed.
['binary search', 'greedy']
N, M = map(int, input().split()) books_list = list(map(int, input().split())) while books_list[-1] == 0: books_list.pop() books_list.insert(0, 0) def check(Time): piles = books_list[:] last_pile_no = len(piles) - 1 for i in range(M): #student i_time = Time - last_pile_no while True: if i_time >= piles[last_pile_no]: i_time -= piles[last_pile_no] last_pile_no -= 1 if last_pile_no == 0: return True else: piles[last_pile_no] -= i_time break return False l = 0 r = int(sum(books_list)/M) + len(books_list) + 1 while r-l > 1: mid = int((l+r)/2) if check(mid): r = mid else: l = mid print(r)
Python
[ "other" ]
1,150
783
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
265
6c35a8bcee2e29142108c9a0da7a74eb
Masha and Grisha like studying sets of positive integers.One day Grisha has written a set A containing n different integers ai on a blackboard. Now he asks Masha to create a set B containing n different integers bj such that all n2 integers that can be obtained by summing up ai and bj for all possible pairs of i and j are different.Both Masha and Grisha don't like big numbers, so all numbers in A are from 1 to 106, and all numbers in B must also be in the same range.Help Masha to create the set B that satisfies Grisha's requirement.
['constructive algorithms', 'brute force']
from random import randint def solve(): n, a = int(input()), list(map(int, input().split())) bb, ab = set(), set() while True: b = randint(1, 1000000) for i in a: if i + b in ab: break else: bb.add(b) if len(bb) == n: break for i in a: ab.add(b + i) print('YES') print(' '.join(map(str, bb))) T = int(input()) for i in range(T): solve()
Python
[ "other" ]
538
372
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,465
97bbbf864fafcf95794db671deb6924b
Bob came to a cash &amp; carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.
['dp']
n=input() t=[0] a=[0] for i in range(n): v1,v2=map(int,raw_input().split(" ")) v1+=1 t.append(v1) a.append(v2) ans=[10**15 for j in range(n+1)] #print ans ans[0]=0 for i in range(1,n+1): for j in range(n,0,-1): ans[j]=min(ans[j],ans[max(0,j-t[i])]+a[i]) print ans[n]
Python
[ "other" ]
554
313
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,169
b9dacff0cab78595296d697d22dce5d9
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.
['implementation']
n = input() man = '' mas = -3000 for i in xrange(n): ss = raw_input().split() curm = sum(map(int,ss[3:]),0) curm += int(ss[1])*100 - int(ss[2])*50 if curm>mas: man = ss[0] mas = curm print man
Python
[ "other" ]
902
203
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,977
35dccda260cfdaea651d1950df452e7a
The only difference between the two versions is that in this version n \leq 2 \cdot 10^5 and the sum of n over all test cases does not exceed 2 \cdot 10^5.A terminal is a row of n equal segments numbered 1 to n in order. There are two terminals, one above the other. You are given an array a of length n. For all i = 1, 2, \dots, n, there should be a straight wire from some point on segment i of the top terminal to some point on segment a_i of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if n=7 and a=[4,1,4,6,7,7,5]. A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.What is the maximum number of crossings there can be if you place the wires optimally?
['data structures', 'divide and conquer', 'sortings']
from array import array for _ in range(int(input())): n = int(input()) a = array('i', map(int, input().split())) ans = 0 # Codeforces 1676H2 Maximum Crossings # https://codeforces.com/contest/1676/problem/H2 def mergeSort(arr): global ans if len(arr) < 2: return arr mid = len(arr)//2 L = arr[:mid] R = arr[mid:] mergeSort(L) mergeSort(R) pL = pR = 0 for i in range(len(arr)): if pR == len(R) or pL<len(L) and L[pL]<R[pR]: arr[i], ans, pL = L[pL], ans + pR, pL + 1 else: arr[i], pR = R[pR], pR+1 return arr mergeSort(a) print(ans)
Python
[ "other" ]
878
754
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,149
7c1f7740bdac042147e969a98897f594
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≤ i &lt; j ≤ n), such that an inequality ai &gt; aj holds.Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
['greedy']
n = int(input()) inp = input() seq = inp.split(' ') seq = [ abs(int(x)) for x in seq ] Max = max(seq) nxt = [0] * n cnt = [0] * n pos = [n] * (Max+1) for i in range(n-1, -1, -1): nxt[i] = pos[seq[i]] pos[seq[i]] = i for i in range(0, Max+1): j = pos[i] while(j<n): front = sum(cnt[0:j]) back = sum(cnt[j+1:n]) if(front < back): seq[j] = 0 - seq[j] j = nxt[j] j = pos[i] while(j < n): cnt[j] = 1 j = nxt[j] #for i in range(0, n-1): # print(seq[i], sep=' ') #print(seq[n-1]) inv = 0 for i in range(len(seq)): for j in range(i+1, len(seq)): if(seq[i] > seq[j]): inv += 1 print(inv)
Python
[ "other" ]
516
691
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,216
7b806b9a402a83a5b8943e7f3436cc9a
Berland annual chess tournament is coming!Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.Thus, organizers should divide all 2·n players into two teams with n people each in such a way that the first team always wins.Every chess player has its rating ri. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.After teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.Is it possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?
['implementation', 'sortings']
n = int(input()) l = sorted(map(int, input().split())) l2 = l[n:] for a in l[:n]: if a in l2: print('NO') exit() print('YES')
Python
[ "other" ]
1,063
133
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,617
b06d5b48525cd386a0141bdf44579a5c
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 \leq j \leq n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the right of player n.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either 0, 1, or 2 other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly 1 other player, then they should logically attack that player in response. If instead a player is being attacked by 0 or 2 other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the n players in the game to make them instead attack another player — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.
['dp', 'greedy']
for _ in range(int(input())): n=int(input()) a=list(str(input())) ans=0 flag=0 c=1 for i in range(1,n): if a[i]!=a[i-1]: flag=1 break if i==n-1 and flag==0: if a[0]=='R': a[0]='L' else: a[0]='R' ans=1 else: a=a[i:n]+a[:i] for i in range(1,n): if a[i]==a[i-1]: c+=1 else: ans+=c//3 c=1 print(ans+c//3)
Python
[ "other" ]
1,769
490
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
307
5ccef7fbfd5e85d7fc7ef92f9ebc4088
You are given two arrays a and b of n elements, each element is either 0 or 1.You can make operations of 2 kinds. Pick an index i and change a_i to 1-a_i. Rearrange the array a however you want. Find the minimum number of operations required to make a equal to b.
['brute force', 'greedy', 'sortings']
n = int(input()) for i in range(n): index = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) ans = abs(sum(a)-sum(b)) cnt = ans for x in range(index): if cnt <= 0: break if a[x] != b[x]: a[x] = 1- a[x] cnt -= 1 if a == b: print(ans) else: print(ans+1)
Python
[ "other" ]
338
427
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,443
14959b7266ceebe96c33bfa1791e26b4
You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either grass or weeds. For example, a 4 × 5 garden may look as follows (empty cells denote grass): You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1, 1). At any moment of time you are facing a certain direction — either left or right. And initially, you face right.In one move you can do either one of these:1) Move one cell in the direction that you are facing. if you are facing right: move from cell (r, c) to cell (r, c + 1) if you are facing left: move from cell (r, c) to cell (r, c - 1) 2) Move one cell down (that is, from cell (r, c) to cell (r + 1, c)), and change your direction to the opposite one. if you were facing right previously, you will face left if you were facing left previously, you will face right You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.What is the minimum number of moves required to mow all the weeds?
['sortings', 'greedy']
#------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now---------------------------------------------------- m,n=map(int,input().split()) arr=[] s=[] e=[] t=[] move=0 row=0 cur=0 for i in range(m): a=input() arr.append(a) for i in range(m): if 'W' in arr[i]: s.append(arr[i].find('W')) e.append(arr[i].rfind('W')) t.append(i%2) row=i for i in range(len(t)): if t[i]==0: move+=abs(e[i]-min(s[i],cur))+max(0,cur-s[i]) cur=e[i] else: move+=abs(max(cur,e[i])-s[i])+max(0,e[i]-cur) cur=s[i] print(move+row)
Python
[ "other" ]
1,426
2,390
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,970
b17eaccfd447b11c4f9297e3276a3ca9
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.At any time moment t when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id i, then it is being tested on the first test from time moment t till time moment t + 1, then on the second test till time moment t + 2 and so on. This solution is fully tested at time moment t + a_i, and after that the testing process immediately starts testing another solution.Consider some time moment, let there be exactly m fully tested solutions by this moment. There is a caption "System testing: d%" on the page with solutions, where d is calculated asd = round\left(100\cdot\frac{m}{n}\right),where round(x) = \lfloor{x + 0.5}\rfloor is a function which maps every real to the nearest integer.Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test q, and the caption says "System testing: q%". Find the number of interesting solutions.Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
['implementation']
n, k = map(int, input().split()) a = list(map(int, input().split())) p = [[0, 0, 0] for i in range(k)] j = 0 m = 0 ans = [0] * n flag = True while flag: flag = False t = 0 for i in range(k): p[i][0] += 1 if p[i][0] == int(m / n * 100 + 0.5): ans[p[i][2]] = 1 if p[i][0] >= p[i][1]: if p[i][1] != 0: t += 1 if j >= n: p[i] = [0, 0, 0] else: p[i][0] = 0 p[i][1] = a[j] p[i][2] = j j += 1 if p[i][1] != 0: flag = True m += t print(sum(ans))
Python
[ "other" ]
1,783
641
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
712
4a48b828e35efa065668703edc22bf9b
It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are n displays placed along a road, and the i-th of them can display a text with font size s_i only. Maria Stepanovna wants to rent such three displays with indices i &lt; j &lt; k that the font size increases if you move along the road in a particular direction. Namely, the condition s_i &lt; s_j &lt; s_k should be held.The rent cost is for the i-th display is c_i. Please determine the smallest cost Maria Stepanovna should pay.
['dp', 'implementation', 'brute force']
from operator import __gt__, __lt__ def helper(op): xx = list(map(float, input().split())) le, ri, a = [], [], xx[0] for b in xx: if a > b: a = b le.append(a) for a in reversed(xx): if op(b, a): b = a ri.append(b) ri.reverse() return xx, le, ri n, res = int(input()), 9e9 ss, sLe, sRi = helper(__lt__) cc, cLe, cRi = helper(__gt__) for j in sorted(range(1, n - 1), key=cc.__getitem__): s, c = ss[j], cc[j] if cLe[j - 1] + c + cRi[j + 1] < res and sLe[j - 1] < s < sRi[j + 1]: a = b = 9e9 for i in range(j): if ss[i] < s and a > cc[i]: a = cc[i] for k in range(j + 1, n): if s < ss[k] and b > cc[k]: b = cc[k] if res > a + b + c: res = a + b + c print(int(res) if res < 9e9 else -1)
Python
[ "other" ]
654
871
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,865
11fabde93815c1805369bbbc5a40e2d8
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
['implementation', 'greedy']
c1, c2, c3, c4 = map(int, input().split()) n, m = map(int, input().split()) lst1 = list(map(int, input().split())) lst2 = list(map(int, input().split())) buss = 0 for i in lst1: buss += min(c1 * i, c2) buss = min(buss, c3) tr = 0 for i in lst2: tr += min(c1 * i, c2) tr = min(tr, c3) print(min(c4, buss + tr))
Python
[ "other" ]
831
320
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,988
c091ca39dd5708f391b52de63faac6b9
This is an interactive problem.Homer likes arrays a lot and he wants to play a game with you. Homer has hidden from you a permutation a_1, a_2, \dots, a_n of integers 1 to n. You are asked to find any index k (1 \leq k \leq n) which is a local minimum. For an array a_1, a_2, \dots, a_n, an index i (1 \leq i \leq n) is said to be a local minimum if a_i &lt; \min\{a_{i-1},a_{i+1}\}, where a_0 = a_{n+1} = +\infty. An array is said to be a permutation of integers 1 to n, if it contains all integers from 1 to n exactly once.Initially, you are only given the value of n without any other information about this permutation.At each interactive step, you are allowed to choose any i (1 \leq i \leq n) and make a query with it. As a response, you will be given the value of a_i. You are asked to find any index k which is a local minimum after at most 100 queries.
['binary search', 'interactive', 'ternary search']
#import io, os #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline import math n=int(input()) hi=n lo=1 if n==1: print("!",n) else: print("?",1,flush=True) a=int(input()) print("?",2,flush=True) b=int(input()) print("?",n,flush=True) c=int(input()) print("?",n-1,flush=True) d=int(input()) if c<d: print("!",n) elif a<b: print("!",1) else: while lo<hi: mid=lo+((hi-lo)//2) print("?",mid-1,flush=True) a=int(input()) print("?",mid,flush=True) b=int(input()) print("?",mid+1,flush=True) c=int(input()) if b<a and b<c: print("!",mid) break elif a<b: hi=mid elif c<b: lo=lo+(math.ceil((hi-lo)/2))
Python
[ "other" ]
981
790
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
512
79d8943cb9a9f63b008cb38ee51ae41e
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?Let a_i be how many numbers i (1 \le i \le k) you have.An n \times n matrix is called beautiful if it contains all the numbers you have, and for each 2 \times 2 submatrix of the original matrix is satisfied: The number of occupied cells doesn't exceed 3; The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size.
['binary search', 'constructive algorithms', 'dp', 'greedy']
import sys I=lambda:[*map(int,sys.stdin.readline().split())] def totalcells(n): return n*n-(n//2)*(n//2) def maxfreq(n): return n*((n+1)//2) t, = I() for _ in range(t): m, k = I() a = I() mf = max(a) n = 0 while totalcells(n) < m or maxfreq(n) < mf: n += 1 print(n) ans = [[0]*n for _ in range(n)] gone = set() for (sx, sy) in ((1, 0), (0, 1)): spots = ((n+1)//2)*(n//2) vals = [] z = max(range(k), key=lambda i: a[i]) if z not in gone: c = min(spots, a[z]) if c > 0: vals += [z]*c gone.add(z) a[z] -= c for i in range(k): if i not in gone: c = min(spots-len(vals), a[i]) if c > 0: vals += [i]*c a[i] -= c gone.add(i) v = 0 for i in range(sx, n, 2): for j in range(sy, n, 2): if v < len(vals): ans[i][j] = vals[v]+1 v += 1 vals = [] for i in range(k): vals += [i]*a[i] vals.sort(key=lambda x: x not in gone) v = 0 for (sx, sy) in ((0, 0), (1, 0), (0, 1)): for i in range(sx, n, 2): for j in range(sy, n, 2): if v < len(vals) and ans[i][j] == 0: ans[i][j] = vals[v]+1 v += 1 for row in ans: print(*row)
Python
[ "other" ]
489
1,468
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,508
ad242f98f1c8eb8d30789ec672fc95a0
Tokitsukaze has a sequence a of length n. For each operation, she selects two numbers a_i and a_j (i \ne j; 1 \leq i,j \leq n). If a_i = a_j, change one of them to 0. Otherwise change both of them to \min(a_i, a_j). Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to 0. It can be proved that the answer always exists.
['implementation']
for _ in range(int(input())): a=int(input()) b=list(map(int,input().split())) if 0 in b: c=b.count(0) print(a-c) else: r=list(set(b)) if len(r)==len(b): print(a+1) elif len(r)<a: print(a)
Python
[ "other" ]
429
300
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
580
d5be4e2cd91df0cd8866d46a979be4b1
You have been invited as a production process optimization specialist to some very large company. The company has n machines at its factory, standing one behind another in the production chain. Each machine can be described in one of the following two ways: (+,~a_i) or (*,~a_i).If a workpiece with the value x is supplied to the machine of kind (+,~a_i), then the output workpiece has value x + a_i.If a workpiece with the value x is supplied to the machine of kind (*,~a_i), then the output workpiece has value x \cdot a_i.The whole production process is as follows. The workpiece with the value 1 is supplied to the first machine, then the workpiece obtained after the operation of the first machine is supplied to the second machine, then the workpiece obtained after the operation of the second machine is supplied to the third machine, and so on. The company is not doing very well, so now the value of the resulting product does not exceed 2 \cdot 10^9.The directors of the company are not satisfied with the efficiency of the production process and have given you a budget of b coins to optimize it.To optimize production you can change the order of machines in the chain. Namely, by spending p coins, you can take any machine of kind (+,~a_i) and move it to any place in the chain without changing the order of other machines. Also, by spending m coins, you can take any machine of kind (*,~a_i) and move it to any place in the chain.What is the maximum value of the resulting product that can be achieved if the total cost of movements that are made should not exceed b coins?
['binary search', 'brute force', 'greedy']
from bisect import bisect import sys input = sys.stdin.readline n, b, p, m = map(int, input().split()) adds = [] curr = [] mults = [] i = 0 for _ in range(n): t, v = input().split() v = int(v) if t == '*': if v == 1: continue curr.sort() adds.append(curr) mults.append(v) curr = [] else: curr.append(v) curr.sort() adds.append(curr) pref = [] for l in adds: np = [0] for v in l[::-1]: np.append(v + np[-1]) pref.append(np) y = len(mults) un_m = sorted(set(mults)) z = len(un_m) ct_m = [0] * z for v in mults: for i in range(z): if un_m[i] == v: ct_m[i] += 1 from itertools import product poss = [] assert len(adds) == y + 1 for tup in product(*[range(ct + 1) for ct in ct_m]): rem_adds = (b - m * sum(tup))//p if rem_adds < 0: continue d = {} for i in range(z): d[un_m[i]] = tup[i] end = 1 used = [0] * y for i in range(y): if d[mults[i]]: used[i] = 1 d[mults[i]] -= 1 end *= mults[i] seg_mult = [1] for i in range(y - 1, -1, -1): if used[i] == 0: seg_mult.append(seg_mult[-1] * mults[i]) else: seg_mult.append(seg_mult[-1]) seg_mult.reverse() exc = [seg_mult[0] - v for v in seg_mult] init_tot = 0 for j in range(y + 1): if exc[j] != 0: init_tot += len(adds[j]) lo = 0 #Ct value provided >= lo >= rem_adds hi = 10 ** 18 + 100 #Too high while hi - lo > 1: mid = lo + (hi - lo) // 2 tot = init_tot for j in range(y + 1): if exc[j] == 0: continue limit = (mid - 1) // exc[j] #ct = len(adds[j]) - bisect(adds[j], limit - 1) #tot += ct diff = bisect(adds[j], limit) tot -= diff #print(mid, j, diff) if tot >= rem_adds: lo = mid else: hi = mid tot = seg_mult[0] ct = 0 for j in range(y + 1): tot += pref[j][-1] * seg_mult[j] if exc[j] == 0: continue limit = (lo - 1) // exc[j] s_ct = len(adds[j]) - bisect(adds[j], limit) tot += pref[j][s_ct] * exc[j] ct += s_ct if lo != 0: assert ct >= rem_adds tot -= lo * (ct - rem_adds) #print(tup, lo, tot, end) poss.append(tot * end) #break print(max(poss))
Python
[ "other" ]
1,688
2,692
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,382
97e149fe5933bf1c9dbe8d958c1b2e05
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint — black and white.There is a tool named eraser in cfpaint. The eraser has an integer size k (1 \le k \le n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 \le i, j \le n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i \le i' \le i + k - 1 and j \le j' \le j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.A white line is a row or a column without any black cells.Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
['dp', 'two pointers', 'implementation', 'data structures', 'brute force']
import fileinput def D(a):print(a) def S(s,I):return int(s.split(" ")[I]) def sm(I,B,E): if(B==0):return S[I][E] return S[I][E]-S[I][B-1] def main(): global S z=0 A=0 N=0 K=0 C=0 for l in fileinput.input(): z+=1 if(z<2): N=S(l,0) K=S(l,1) A=[0]*N S=[0]*N C=[0]*N for i in range(N): A[i]=[0]*N S[i]=[0]*N C[i]=[0]*N continue for i in range(N): if(l[i]=='B'): A[z-2][i]=1 for i in range(N): S[i][0]=A[i][0] for j in xrange(1,N): S[i][j]=S[i][j-1]+A[i][j] for i in range(N-K+1): T=0 for j in range(N): if(S[j][N-1]==0): T+=1 for j in range(K-1): if(S[j][N-1]!=0 and sm(j,i,i+K-1)==S[j][N-1]): T+=1 for j in xrange(K-1,N): if(S[j][N-1]!=0 and sm(j,i,i+K-1)==S[j][N-1]): T+=1 C[i][j-K+1]+=T if(S[j-K+1][N-1]!=0 and sm(j-K+1,i,i+K-1)==S[j-K+1][N-1]): T-=1 for i in range(N): S[i][0]=A[0][i] for j in xrange(1,N): S[i][j]=S[i][j-1]+A[j][i] for i in range(N-K+1): T=0 for j in range(N): if(S[j][N-1]==0): T+=1 for j in range(K-1): if(S[j][N-1]!=0 and sm(j,i,i+K-1)==S[j][N-1]): T+=1 for j in xrange(K-1,N): if(S[j][N-1]!=0 and sm(j,i,i+K-1)==S[j][N-1]): T+=1 C[j-K+1][i]+=T if(S[j-K+1][N-1]!=0 and sm(j-K+1,i,i+K-1)==S[j-K+1][N-1]): T-=1 X=0 for i in range(N): for j in range(N): X=max(X,C[i][j]) D(X) main()
Python
[ "other" ]
1,236
1,837
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,643
7e678f141f411d3872f25559e2c1f17c
You are given an array a of n non-negative integers. In one operation you can change any number in the array to any other non-negative integer.Let's define the cost of the array as \operatorname{DIFF}(a) - \operatorname{MEX}(a), where \operatorname{MEX} of a set of non-negative integers is the smallest non-negative integer not present in the set, and \operatorname{DIFF} is the number of different numbers in the array.For example, \operatorname{MEX}(\{1, 2, 3\}) = 0, \operatorname{MEX}(\{0, 1, 2, 4, 5\}) = 3.You should find the minimal cost of the array a if you are allowed to make at most k operations.
['binary search', 'brute force', 'constructive algorithms', 'data structures', 'greedy', 'two pointers']
import os, sys from io import BytesIO, IOBase from array import array 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, 8192)) 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, 8192)) 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") class segmenttree: def __init__(self, n, default=0, func=lambda a, b: a + b): self.tree, self.n, self.func, self.default = [default] * (2 * n), n, func, default def fill(self, arr): self.tree[self.n:] = arr for i in range(self.n - 1, 0, -1): self.tree[i] = self.func(self.tree[i << 1], self.tree[(i << 1) + 1]) # get interval[l,r) def query(self, l, r): res = self.default l += self.n r += self.n while l < r: if l & 1: res = self.func(res, self.tree[l]) l += 1 if r & 1: r -= 1 res = self.func(res, self.tree[r]) l >>= 1 r >>= 1 return res def __setitem__(self, ix, val): ix += self.n self.tree[ix] = val while ix > 1: self.tree[ix >> 1] = self.func(self.tree[ix], self.tree[ix ^ 1]) ix >>= 1 def __getitem__(self, item): return self.tree[item + self.n] sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: [dtype(x) for x in input().split()] ceil1, out = lambda a, b: (a + b - 1) // b, [] for _ in range(int(input())): n, k = inp(int) a = array('i', sorted(inp(int))) coun = segmenttree(n + 2) coun2 = segmenttree(n + 2) ix, ans = n - 1, n cum = array('i', [0] * (n + 3)) for i in range(n): if a[i] <= n: cum[a[i]] = 1 for i in range(1, n + 1): cum[i] += cum[i - 1] for mex in range(n, -1, -1): mmex = 0 while ix > -1 and a[ix] >= mex: mmex += 1 if ix == 0 or a[ix] != a[ix - 1]: coun[mmex] += mmex coun2[mmex] += 1 mmex = 0 ix -= 1 if ix < n - 1 and a[ix + 1] != mex: mmex = 0 k_ = k - mmex rem = max(mex - cum[mex - 1] - mmex, 0) if rem > k_: continue coun2[mmex] -= 1 coun[mmex] -= mmex if coun.query(1, n + 1) <= rem: ans = 0 else: be, en = 0, n while be < en: md = (be + en + 1) >> 1 if coun.query(0, md + 1) <= k_: be = md else: en = md - 1 k_ -= coun.query(1, be + 1) ans = min(ans, coun2.query(1, n + 1) - (coun2.query(1, be + 1) + k_ // (be + 1))) coun2[mmex] += 1 coun[mmex] += mmex out.append(f'{ans}') print('\n'.join(out))
Python
[ "other" ]
663
4,361
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,023
b7aef95015e326307521fd59d4fccb64
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
['implementation']
n = int(input()) l = list(map(int,input().split())) d1 = {l[i]:i+1 for i in range(n)} m = int(input()) queries = list(map(int,input().split())) count1 = 0 count2 = 0 k1 = set({}) k2 = set({}) for i in queries: count1 = count1 + d1[i] count2 = count2 + n+1-d1[i] print(count1,count2)
Python
[ "other" ]
1,781
284
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,278
8a6953a226abef41a44963c9b4998a25
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least x.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.
['dp', 'greedy', 'implementation', 'sortings', 'brute force']
import sys def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s); sys.stdout.write('\n') def wi(n): sys.stdout.write(str(n)); sys.stdout.write('\n') def wia(a, sep=' '): sys.stdout.write(sep.join([str(x) for x in a])); sys.stdout.write('\n') def can(t, n, x, a): cnt = 0 mx = 10**9 + 1 c = 0 mn = mx for i in range(n): c += 1 mn = min(mn, a[i]) if c * mn >= x: cnt += 1 c = 0 mn = mx if cnt >= t: return True return False def solve(n, x, a): a = sorted(a, reverse=True) lo = 0 hi = n + 1 while hi > lo + 1: mid = (lo + hi) // 2 if can(mid, n, x, a): lo = mid else: hi = mid return lo def main(): for _ in range(ri()): n, x = ria() a = ria() wi(solve(n, x, a)) if __name__ == '__main__': main()
Python
[ "other" ]
518
1,045
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,094
ec1a29826209a0820e8183cccb2d2f01
You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.
['greedy']
n, k = map(int, input().split()) temp = [int(x) for x in input().split()] if k > 2: print(max(temp)) elif k == 1: print(min(temp)) else: print(max(temp[0], temp[-1]))
Python
[ "other" ]
382
179
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,572
d497431eb37fafdf211309da8740ece6
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 &gt; a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
['implementation', 'greedy']
[h1, a1, c1] = map(int, raw_input().strip().split(' ')) [h2, a2] = map(int, raw_input().strip().split(' ')) total = 0 s = "" while h2 > 0: total += 1 if h2 - a1 <= 0: s += "STRIKE\n" break if h1 - a2 <= 0: s += "HEAL\n" h1 += c1 h1 -= a2 else: s += "STRIKE\n" h1 -= a2 h2 -= a1 print total print s
Python
[ "other" ]
1,465
320
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
519
d8a93129cb5e7f05a5d6bbeedbd9ef1a
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.
['implementation', 'brute force']
from itertools import combinations n = int(input()) a = [input() for _ in range(n)] ans = 0 for (c, d) in combinations('abcdefghijklmnopqrstuvwxyz', 2): t = 0 for s in a: if len(s) == s.count(c) + s.count(d): t += len(s) ans = max(ans, t) print(ans)
Python
[ "other" ]
699
295
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,405
bc1587d3affd867804e664fdb38ed765
The hero is addicted to glory, and is fighting against a monster. The hero has n skills. The i-th skill is of type a_i (either fire or frost) and has initial damage b_i. The hero can perform all of the n skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows: If the current skill immediately follows another skill of a different type, then its damage is doubled. In other words, If a skill of type fire and with initial damage c is performed immediately after a skill of type fire, then it will deal c damage; If a skill of type fire and with initial damage c is performed immediately after a skill of type frost, then it will deal 2c damage; If a skill of type frost and with initial damage c is performed immediately after a skill of type fire, then it will deal 2c damage; If a skill of type frost and with initial damage c is performed immediately after a skill of type frost , then it will deal c damage. Your task is to find the maximum damage the hero can deal.
['greedy', 'implementation', 'sortings']
nn = int(input()) for _ in range(nn): n = int(input()) fire_or_frost=input()#[0,0,0,1,1,1]#[randint(0,1) for x in range(n_skills)] fire_or_frost = fire_or_frost.split(' ') skills = [int(x) for x in fire_or_frost] scores = input()#[3,4,5,6,7,8]#[randint(1,10) for x in range(n_skills)] scores = scores.split(' ') damage = [int(x) for x in scores] if sum(skills)==0 or sum(skills)==len(skills): print(sum(damage)) else: a_damage = [] b_damage = [] for i in range(len(skills)): if skills[i]==0: a_damage.append(damage[i]) else: b_damage.append(damage[i]) a_damage.sort(reverse=True) b_damage.sort(reverse=True) if len(a_damage)==len(b_damage): result = sum(damage)*2-min(damage) print(result) else: n_len = min(len(a_damage),len(b_damage)) #result = sum(a_damage[:n_len])*2+sum(b_damage[:n_len])*2+\ # sum(a_damage[n_len:])+sum(b_damage[n_len:]) result = sum(a_damage[:n_len]+b_damage[:n_len])*2+sum(a_damage[n_len:]+b_damage[n_len:]) print(result)
Python
[ "other" ]
1,128
1,012
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
346
66daa3864875e48d32a7acd23bd7a829
There are n traps numbered from 1 to n. You will go through them one by one in order. The i-th trap deals a_i base damage to you.Instead of going through a trap, you can jump it over. You can jump over no more than k traps. If you jump over a trap, it does not deal any damage to you. But there is an additional rule: if you jump over a trap, all next traps damages increase by 1 (this is a bonus damage).Note that if you jump over a trap, you don't get any damage (neither base damage nor bonus damage). Also, the bonus damage stacks so, for example, if you go through a trap i with base damage a_i, and you have already jumped over 3 traps, you get (a_i + 3) damage.You have to find the minimal damage that it is possible to get if you are allowed to jump over no more than k traps.
['constructive algorithms', 'greedy', 'sortings']
def get_minimum_damage(trap_count: int, base_damage: list, jumps: int): # check if all the traps can be jumped across if trap_count <= jumps: return 0 # store idx, val, profit/loss if jumped across = [(idx, value, profit)] damage_loss_pairs = [(idx, val, val - (trap_count - idx) + 1) for idx, val in enumerate(base_damage)] # sort based on profit damage_loss_pairs.sort(key=lambda x: x[2], reverse=True) # find the indices to be jumped across jumbed_trap = damage_loss_pairs[:jumps] other_trap = damage_loss_pairs[jumps:] total_penalty = sum([trap_count - trap[0] - (jumps - idx ) for idx, trap in enumerate(jumbed_trap)]) # for i in range(jumps): # idx, _, _ = damage_loss_pairs.pop(0) # pop the ones which give maximum profit # total_penalty += trap_count - idx - (jumps - i) # # skip_indices.add(idx) damage_gained = sum(map(lambda x: x[1], other_trap)) + total_penalty return damage_gained no_test = int(input()) for _ in range(no_test): num, no_of_jumsps = map(int, input().split()) numbers = list(map(int, input().split())) damages = get_minimum_damage(num, numbers, no_of_jumsps) print(damages)
Python
[ "other" ]
856
1,208
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,782
74095fe82bd22257eeb97e1caf586499
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.
['dp', 'implementation', 'data structures']
n, k = map(int, raw_input().split()) x = map(int, raw_input().split()) sum = [0] for i in range(1, n + 1): sum.append(sum[i - 1] + x[i - 1]) ksum = [0] for i in range(1, n - k + 2): ksum.append(sum[i + k - 1] - sum[i - 1]) right = [0 for i in ksum] pos = [0 for i in ksum] right[len(ksum) - 1] = ksum[len(ksum) - 1] pos[len(ksum) - 1] = len(ksum) - 1 for i in range(len(ksum) - 2, 0, -1): if ksum[i] >= right[i + 1]: right[i] = ksum[i] pos[i] = i else: right[i] = right[i + 1] pos[i] = pos[i + 1] ans = -1 a = -1 for i in range(1, len(ksum) - k): if (ksum[i] + right[i + k] > ans): ans = ksum[i] + right[i + k] a = i b = pos[a + k] print(str(a) + " " + str(b))
Python
[ "other" ]
1,109
730
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,683
1378b4c9ba8029d310f07a1027a8c7a6
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
['implementation']
f = open('input.txt', 'r') n, k = map(int, f.readline().split()) a, k = list(map(int, f.readline().split())), k - 1 while not a[k]: k = (k + 1) % n print(k + 1, file=open('output.txt', 'w'))
Python
[ "other" ]
1,153
195
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,930
7e6a2329633ee283e3327413114901d1
You are given a grid, consisting of 2 rows and n columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells A and B belong to the same component if they are neighbours, or if there is a neighbour of A that belongs to the same component with B.Let's call some bicoloring beautiful if it has exactly k components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo 998244353.
['dp', 'bitmasks']
n,k = map(int,input().split()) mod = 998244353 dp = [[[0,0]for j in range(2*n+1)] for i in range(n)] dp[0][0][0] = dp[0][1][1] = 1 for i in range(1,n): for j in range(2*n-1): dp[i][j][0] += (dp[i-1][j][0] + dp[i-1][j][1] + dp[i-1][j][1]) %mod dp[i][j+1][0] += dp[i-1][j][0] % mod dp[i][j+1][1] += (dp[i-1][j][0] + dp[i-1][j][0])%mod dp[i][j][1] += dp[i-1][j][1] %mod dp[i][j+2][1] += dp[i-1][j][1] %mod print(sum(dp[n-1][k-1])*2%mod)
Python
[ "other" ]
583
456
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,417
9f8660190134606194cdd8db891a3d46
You are given a non-empty string s=s_1s_2\dots s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j (1 \le j \le n-2), that s_{j}s_{j+1}s_{j+2}="one" or s_{j}s_{j+1}s_{j+2}="two".For example: Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"), Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like s="onetwone", then if Polycarp selects two indices 3 and 6, then "onetwone" will be selected and the result is "ontwne".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?
['dp', 'greedy']
from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter import itertools from itertools import permutations,combinations import sys import bisect import string import math import time #import random def I(): return int(input()) def MI(): return map(int,input().split()) def LI(): return [int(i) for i in input().split()] def LI_(): return [int(i)-1 for i in input().split()] def StoI(): return [ord(i)-97 for i in input()] def ItoS(nn): return chr(nn+97) def GI(V,E,Directed=False,index=0): org_inp=[] g=[[] for i in range(n)] for i in range(E): inp=LI() org_inp.append(inp) if index==0: inp[0]-=1 inp[1]-=1 if len(inp)==2: a,b=inp g[a].append(b) if not Directed: g[b].append(a) elif len(inp)==3: a,b,c=inp aa=(inp[0],inp[2]) bb=(inp[1],inp[2]) g[a].append(bb) if not Directed: g[b].append(aa) return g,org_inp def show(*inp,end='\n'): if show_flg: print(*inp,end=end) YN=['Yes','No'] mo=10**9+7 inf=float('inf') l_alp=string.ascii_lowercase u_alp=string.ascii_uppercase #sys.setrecursionlimit(10**5) input=lambda: sys.stdin.readline().rstrip() show_flg=False show_flg=True t=I() for _ in range(t): s=input() n=len(s) ''' import random K=list('twone')+['two','one','twone']*3+['o']*5 n=50 s=''.join([K[random.randint(0,18)] for i in range(n)]) s+=['two','one','twone'][random.randint(0,2)] n=len(s) ''' ans=[] i=0 while i<n: if s[i]=='o': if i<n-1 and s[i+1]=='n': if i<n-2 and s[i+2]=='e': ans+=[i+1 +1] elif s[i]=='t': if i<n-1 and s[i+1]=='w': if i<n-2 and s[i+2]=='o': if i<n-3 and s[i+3]=='n': if i<n-4 and s[i+4]=='e': ans+=[i+2 +1] i=i+4 else: ans+=[i+1 +1] i=i+1 else: ans+=[i+1 +1] i=i+1 i+=1 print(len(ans)) print(*ans) ''' tmp='' for i in range(len(s)): if i+1 not in ans: tmp+=s[i] else: tmp+=' ' if 'two' in ''.join(tmp.split()) or 'one' in ''.join(tmp.split()): print('Error') show(tmp) show(s) #show(s,tmp) '''
Python
[ "other" ]
1,134
2,624
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
655
1d55d31320368ddb1439ee086d40b57c
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.
['dp', 'bitmasks', 'brute force']
# -*- coding: utf-8 -*- import sys def make_string(k, k2string, s1, s2): if k in k2string: return k2string[k] if k == 1: k2string[k] = s1 elif k == 2: k2string[k] = s2 else: k2string[k] = make_string(k-2, k2string, s1, s2) + make_string(k-1, k2string, s1, s2) return k2string[k] def count_comb(k, k2comb): if k in k2comb: return k2comb[k] if k == 1: k2comb[k] = ([0, 0, 0, 0, 1, 0], ('1', '1')) elif k == 2: k2comb[k] = ([0, 0, 0, 0, 0, 1], ('2', '2')) else: r_2 = count_comb(k-2, k2comb) r_1 = count_comb(k-1, k2comb) r = ([x+y for (x,y) in zip(r_2[0],r_1[0])], (r_2[1][0], r_1[1][1])) ss = r_2[1][1] + r_1[1][0] if ss == '11': r[0][0] += 1 elif ss == '12': r[0][1] += 1 elif ss == '21': r[0][2] += 1 elif ss == '22': r[0][3] += 1 k2comb[k] = r return k2comb[k] def max_independent_ac(l, cStart, aEnd): if l <= 1: return 0 elif (cStart and not aEnd) or (not cStart and aEnd): return (l-1) // 2 elif cStart and aEnd: return (l-2) // 2 else: return l // 2 def print_sequence(l, ac, cStart, aEnd): cStart = 1 if cStart else 0 aEnd = 1 if aEnd else 0 if cStart: print('C', end='') for i in range(ac): print('AC', end='') for i in range(l - 2*ac - cStart - aEnd): print('B', end='') if aEnd: print('A', end='') print() def run_test(k, x, n, m): comb = count_comb(k, {})[0] for mask in range(16): v = [0, 0, 0, 0, 0, 0] if (mask & 1) and (mask & 2): v[0] = 1 if (mask & 2) and (mask & 4): v[1] = 1 if (mask & 1) and (mask & 8): v[2] = 1 if (mask & 4) and (mask & 8): v[3] = 1 if (n == 1 and v[0]) or (m == 1 and v[3]): continue max1 = max_independent_ac(n, mask & 1, mask & 2) max2 = max_independent_ac(m, mask & 4, mask & 8) for p in range(max1+1): for q in range(max2+1): v[4] = p v[5] = q if sum([x*y for (x,y) in zip(v,comb)]) == x: print_sequence(n, p, mask&1, mask&2) print_sequence(m, q, mask&4, mask&8) return print('Happy new year!') k, x, n, m = (int(x) for x in sys.stdin.readline().split(' ')) run_test(k, x, n, m)
Python
[ "other" ]
1,217
2,075
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,298
56535017d012fdfcc13695dfd5b33084
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.
['implementation', 'brute force']
L=lambda x,y:2*y>=x>=y D=lambda x,y:2*y<x>=y a,b,c,d=map(int,raw_input().split()) for i in range(199): for j in range(i): for k in range(j): if L(i,a) and L(j,b) and L(k,c) and D(i,d) and D(j,d) and L(k,d): print i,'\n',j,'\n',k exit(0) print -1
Python
[ "other" ]
772
301
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,215
b9bafdc49709b4fc4b5fe786d5aa99a3
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store. Remember, that in this problem k=2.Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by a_i — the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary: Vasya can buy one good with the index i if he currently has enough coins (i.e p \ge a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i). Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p \ge a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i). Please note that each good can be bought no more than once.For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.
['dp', 'sortings', 'greedy']
t = int(input()) answer = [] for i in range(t): n, p, k = [int(j) for j in input().split()] a = [int(j) for j in input().split()] a.sort() j = 2 if p - a[0] < 0: v = 0 else: v = 1 p -= a[0] while v and j < n and p - a[j] >= 0: p -= a[j] v += 2 j += 2 if j - 1 < n and v != 0: for k in range(j): if k % 2 == 0: p += a[k] else: p -= a[k] if p >= 0: v += 1 answer.append(v) for i in answer: print(i)
Python
[ "other" ]
1,969
571
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,449
cd6bc23ea61c43b38c537f9e04ad11a6
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.
['implementation']
from sys import stdin n, m = map(int, stdin.readline().strip().split()) u = float('inf') d = -float('inf') l = float('inf') r = -float('inf') num_blacks = 0 for i in xrange(n): row = stdin.readline().strip() for j in xrange(m): if row[j] == 'B': if i <= u: u = i if i >= d: d = i if j <= l: l = j if j >= r: r = j num_blacks += 1 if num_blacks == 0: print 1 else: s = max(d-u, r-l)+1 if s > m or s > n: print -1 else: print s*s - num_blacks
Python
[ "other" ]
560
619
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
786
c5c048a25ca6b63f00b20f23f0adcda6
Let's look at the following process: initially you have an empty stack and an array s of the length l. You are trying to push array elements to the stack in the order s_1, s_2, s_3, \dots s_{l}. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack. If after this process the stack remains empty, the array s is considered stack exterminable.There are samples of stack exterminable arrays: [1, 1]; [2, 1, 1, 2]; [1, 1, 2, 2]; [1, 3, 3, 1, 2, 2]; [3, 1, 3, 3, 1, 3]; [3, 3, 3, 3, 3, 3]; [5, 1, 2, 2, 1, 4, 4, 5]; Let's consider the changing of stack more details if s = [5, 1, 2, 2, 1, 4, 4, 5] (the top of stack is highlighted). after pushing s_1 = 5 the stack turn into [\textbf{5}]; after pushing s_2 = 1 the stack turn into [5, \textbf{1}]; after pushing s_3 = 2 the stack turn into [5, 1, \textbf{2}]; after pushing s_4 = 2 the stack turn into [5, \textbf{1}]; after pushing s_5 = 1 the stack turn into [\textbf{5}]; after pushing s_6 = 4 the stack turn into [5, \textbf{4}]; after pushing s_7 = 4 the stack turn into [\textbf{5}]; after pushing s_8 = 5 the stack is empty. You are given an array a_1, a_2, \ldots, a_n. You have to calculate the number of its subarrays which are stack exterminable.Note, that you have to answer q independent queries.
['data structures', 'dp']
# encoding: utf-8 from sys import stdin def solve(a): # root node of tries denotes empty stack stack = [None] node_stack = [[1, {}]] trie = node_stack[-1] counter = 0 for i in range(len(a)): el = a[i] if len(stack) == 0 or stack[-1] != el: current_node = node_stack[-1] stack.append(el) if el not in current_node[1]: current_node[1][el] = [0, {}] next_node = current_node[1][el] next_node[0] += 1 node_stack.append(next_node) else: # just go up in trie stack.pop() node_stack.pop() node_stack[-1][0] += 1 value = node_stack[-1][0] counter -= (((value - 1) * (value - 2)) // 2) counter += (((value) * (value - 1)) // 2) return counter q = int(stdin.readline().strip()) for _ in range(q): n = int(stdin.readline().strip()) a = [int(i) for i in stdin.readline().strip().split()] print(solve(a))
Python
[ "other" ]
1,672
1,027
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,197
6a260fc32ae8153a2741137becc6cfb4
This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java — call System.out.flush(), and in Pascal — flush(output).Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers — the number of "bulls" and the number of "cows". A try can contain equal digits.More formally, let's the secret string is s and the second player are trying to guess it with a string x. The number of "bulls" is a number of such positions i (1 ≤ i ≤ 4) where s[i] = x[i]. The number of "cows" is a number of such digits c that s contains c in the position i (i.e. s[i] = c), x contains c, but x[i] ≠ c.For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.In this problem you are to guess the string s that the system has chosen. You only know that the chosen string consists of 4 distinct digits.You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons — the program either guessed the number x or made an invalid action (for example, printed letters instead of digits).Your program is allowed to do at most 50 queries.You can hack solutions of other participants providing a 4-digit string containing distinct digits — the secret string.
['constructive algorithms', 'implementation', 'brute force']
ans=[] for i in range(10): print(str(i)*4) A=input() if A!='0 0':ans.append(i) import itertools A=list(itertools.permutations(ans)) for i in A: print(''.join(map(str,list(i)))) a=input() if a=='4 0':break
Python
[ "other" ]
2,553
230
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,121
f13f27a131b9315ebbb8688e2f43ddde
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.
['binary search']
n = int(input()) xs = list(map(int, input().split())) vs = list(map(int, input().split())) l = 0 r = max(xs) - min(xs) + 1 for i in range(50): m = (r + l) / 2 lev = 0 prav = 1000000000 for j in range(n): prav = min(prav, xs[j] + vs[j] * m) lev = max(lev, xs[j] - vs[j] * m) if prav < lev: break if prav < lev: l = m else: r = m print((l + r) / 2)
Python
[ "other" ]
568
423
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,188
41bdb08253cf5706573f5d469ab0a7b3
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.
['implementation']
def Golden_Boys_Girls(students,subjects,matrix): The_Best = []; results = [] for i in range(subjects): Current_Max_Score = 0 for j in range(students): if matrix[j][i] > Current_Max_Score: if j in results: The_Best = [] elif j not in The_Best and j not in results: The_Best = [] The_Best.append(j) Current_Max_Score = matrix[j][i] elif matrix[j][i] == Current_Max_Score: if j not in The_Best and j not in results: The_Best.append(j) if The_Best: results.extend(The_Best) The_Best = [] if len(results) == students: break print len(results) students,subjects = map(int,raw_input().split()) ; matrix = [] for i in range (students): matrix.append(list(map(int, raw_input()))) Golden_Boys_Girls(students,subjects,matrix)
Python
[ "other" ]
538
967
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,203
b856eafe350fccaabd39b97fb18d9c2f
There are n pieces of cake on a line. The i-th piece of cake has weight a_i (1 \leq i \leq n).The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., \max(a_1+a_2,\, a_2+a_3,\, \ldots,\, a_{n-1} + a_{n})).You want to maximize the tastiness of the cake. You are allowed to do the following operation at most once (doing more operations would ruin the cake): Choose a contiguous subsegment a[l, r] of pieces of cake (1 \leq l \leq r \leq n), and reverse it. The subsegment a[l, r] of the array a is the sequence a_l, a_{l+1}, \dots, a_r.If you reverse it, the array will become a_1, a_2, \dots, a_{l-2}, a_{l-1}, \underline{a_r}, \underline{a_{r-1}}, \underline{\dots}, \underline{a_{l+1}}, \underline{a_l}, a_{r+1}, a_{r+2}, \dots, a_{n-1}, a_n.For example, if the weights are initially [5, 2, 1, 4, 7, 3], you can reverse the subsegment a[2, 5], getting [5, \underline{7}, \underline{4}, \underline{1}, \underline{2}, 3]. The tastiness of the cake is now 5 + 7 = 12 (while before the operation the tastiness was 4+7=11).Find the maximum tastiness of the cake after doing the operation at most once.
['greedy', 'implementation', 'sortings']
t = int(input()) for arrow in range(t): n = int(input()) a = list(map(int, input().split())) mx1, mx2 = 0, 0 for i in a: if mx1 <= i: mx2 = mx1 mx1 = i if i < mx1: mx2 = max(i, mx2) print(mx1 + mx2)
Python
[ "other" ]
1,233
285
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,377
0870110338a84f76d4870d06dc9da2df
Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.
['implementation']
from collections import Counter as cnt def dis(ls, shifts, z): x, y = ls[0], ls[1] ans = [] for shift in shifts: x1, y1 = shift[0], shift[1] a = (x - x1) ** 2 b = (y - y1) ** 2 d = (a + b) ** 0.5 if d > z: ans.append(True) else: ans.append(False) if False in ans: return False else: return True n, m, z = map(int, input().split()) keys = [] shifts = [] for x in range(n): row = input() keys.append(row) if 'S' in row: for y, val in enumerate(row): if val == 'S': shifts.append([x+1, y+1]) move = dict() for x, row in enumerate(keys): for y, key in enumerate(row): d = dis([x+1, y+1], shifts, z) if key in move and move[key] is False: pass else: move[key] = d all_keys = [] all_keys += [key for key in keys] all_keys = ''.join(all_keys) all_keys = all_keys.replace('S', '') q = int(input()) a = input() count = cnt(a) uppa = 0 ans = 0 for key in count: if key.lower() not in all_keys: ans = -1 break if key.isupper(): uppa += 1 if move[key.lower()]: ans += count[key] shifts = len(shifts) if shifts == 0 and uppa > 0: ans = -1 print(ans)
Python
[ "other" ]
1,121
1,307
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
323
3d6151b549bd52f95ab7fdb972e6fb98
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.
['two pointers', 'implementation', 'sortings', 'greedy']
a, b, c = map(int, raw_input().split()) m = int(raw_input()) u = [] p = [] for _ in xrange(m) : s = list(raw_input().split()) if s[1] == "USB" : u.append(int(s[0])) else : p.append(int(s[0])) u.sort() p.sort() a = min(a, len(u)) b = min(b, len(p)) um = sorted(u[a:] + p[b:]) c = min(c, len(um)) cost = sum(um[:c]) + sum(p[:b]) + sum(u[:a]) print a + b + c , cost
Python
[ "other" ]
920
394
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,005
fa7a44fd24fa0a8910cb7cc0aa4f2155
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.
['greedy']
# FILE: caseOfZerosAndOnes.py # CodeForces 556A def main(): length = int(input()) string = input() countZero = 0 countOne = 0 for i in range(length): if(string[i] == '0'): countZero += 1 else: countOne += 1 min = countZero if(countOne < countZero): min = countOne print(length - (2 * min)) main()
Python
[ "other" ]
638
386
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,514
dc93c41e70c7eb82af407359b194d28a
In the evening Polycarp decided to analyze his today's travel expenses on public transport.The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop to the other and back. There is at most one bus running between a pair of stops.Polycarp made n trips on buses. About each trip the stop where he started the trip and the the stop where he finished are known. The trips follow in the chronological order in Polycarp's notes.It is known that one trip on any bus costs a burles. In case when passenger makes a transshipment the cost of trip decreases to b burles (b &lt; a). A passenger makes a transshipment if the stop on which he boards the bus coincides with the stop where he left the previous bus. Obviously, the first trip can not be made with transshipment.For example, if Polycarp made three consecutive trips: "BerBank" "University", "University" "BerMall", "University" "BerBank", then he payed a + b + a = 2a + b burles. From the BerBank he arrived to the University, where he made transshipment to the other bus and departed to the BerMall. Then he walked to the University and returned to the BerBank by bus.Also Polycarp can buy no more than k travel cards. Each travel card costs f burles. The travel card for a single bus route makes free of charge any trip by this route (in both directions). Once purchased, a travel card can be used any number of times in any direction.What is the smallest amount of money Polycarp could have spent today if he can buy no more than k travel cards?
['implementation', 'sortings', 'greedy']
def main(): trips, reg, cheap, cards, card_cost = map(int, input().split()) costs = [] indexes = {} total = 0 last = "" for i in range(trips): a, b = input().split() pair = (min(a, b), max(a, b)) if pair in indexes: index = indexes[pair] else: costs.append(0) indexes[pair] = len(costs) - 1 index = len(costs) - 1 total += (cheap if a == last else reg) costs[index] += (cheap if a == last else reg) last = b costs = sorted(costs, reverse = True) for c in costs: if c < card_cost or cards <= 0: break total -= c total += card_cost cards -= 1 print(total) main()
Python
[ "other" ]
1,668
661
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
911
337b6d2a11a25ef917809e6409f8edef
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.
['dp', 'implementation', 'greedy', 'brute force']
from io import StringIO import sys data = sys.stdin def score_line(row): score = 0 max_score = 0 combo = False for b in row: if b == 1: if combo: score += 1 else: score = 1 combo = True else: score = 0 combo = False max_score = max(score, max_score) return max_score rows = [] n, m, q = map(int, data.readline().split(' ')) for i in range(n): rows.append(list(map(int, data.readline().split(' ')))) row_scores = list(map(score_line, rows)) for i in range(q): r, c = map(int, data.readline().split(' ')) rows[r-1][c-1] = 1 - rows[r-1][c-1] row_scores[r-1] = score_line(rows[r-1]) print(max(row_scores))
Python
[ "other" ]
916
789
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,739
9b277feec7952947357b133a152fd599
After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of 7 because its subribbon a appears 7 times, and the ribbon abcdabc has the beauty of 2 because its subribbon abc appears twice.The rules are simple. The game will have n turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after n turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?
['greedy']
n = int(input()) scores = [] for _ in range(3): letters = {} word = input() if n >= len(word) - 1 and n > 1: print("Draw") exit(0) for c in word: if c in letters: letters[c] += 1 else: letters[c] = 1 scores.append(max(letters.values()) + n) if scores[_] > len(word): scores[_] = len(word) if len(letters) == 1 and n == 1: scores[_] = len(word) - 1 if sorted(scores)[2] == sorted(scores)[1]: print("Draw") else: if scores[0] == max(scores): print("Kuro") elif scores[1] == max(scores): print("Shiro") else: print("Katie")
Python
[ "other" ]
1,530
663
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
183
99e5c907b623c310d6f1599f485ca21d
n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i.Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by 1.The winner of the tournament is the first hero that wins in at least 100^{500} fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.Calculate the number of possible winners among n heroes.
['implementation', 'sortings']
m=int(input()) for i in range(m): n=int(input()) ar=[int(x) for x in input().split()] c=0 for i in range(0,len(ar)): for j in range(0,len(ar)): if(ar[i]>ar[j]): c+=1 break print(c)
Python
[ "other" ]
874
230
0
0
0
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,009