Unnamed: 0
int64
0
999
name
stringlengths
9
60
description
stringlengths
168
5.26k
solution
stringlengths
38
20.8k
200
591_C. Median Smoothing
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi...
def main(): n = int(input()) a = [int(i) for i in input().split()] flag = 0 now_begin = 0 kek = 0 ans = [[-1] * 2 for i in range(n)] for i in range(1, n - 1): if a[i] != a[i - 1] and a[i] != a[i + 1]: kek += 1 else: flag = max((kek + 1) // 2, flag) ...
201
633_A. Ebony and Ivory
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of dama...
a, b, c = map(int, input().split()) h = 0 if c % a == 0: k = c // a else: k = c // a + 1 if c % b == 0: m = c // b else: m = c // b + 1 if c - a*k < 0 and c - b*m < 0 and ((c < 2 * a) and c < 2*b): print('No') else: for i in range(k+1): if (c - a*i) % b == 0 and (h == 0): pri...
202
774_D. Lie or Truth
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an. While Vasya was walking, his little brother Stepan played with Vasya's cubes and chan...
n,l,r = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) if(a[:l - 1] == b[:l - 1] and a[r:] == b[r:]): print("TRUTH") else: print("LIE")
203
799_D. Field expansion
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Ar...
def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x) def listr...
204
845_B. Luba And The Ticket
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of las...
def main(): s = input() print(solver(s)) def solver(s): L1 = [int(x) for x in s[0:3]] L2 = [int(x) for x in s[3:6]] diff = sum(L2) - sum(L1) if diff == 0: return 0 elif diff < 0: L1, L2 = L2, L1 diff = -diff changes = [9 - L1[i] for i in range(3)] + [L2[i] - 0 for i in range(3)] changes.sort(reverse =...
205
865_D. Buy Low Sell High
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...
from heapq import * N = int(input()) price = [int(i) for i in input().split()] total = 0 inf = (10**6) + 1 h = [inf] #Assume we bought and sold optimally for the first k prices. #We adjust our answer for the (k+1)th price that comes up. for p in price: if p > h[0]: total += (p - heappop(h)) #We p...
206
1016_C. Vasya And The Mushrooms
Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends...
n = int(input()) u1 = list(map(int, input().split())) u2 = list(map(int, input().split())) a1 = u1[:n] a2 = u2[:n] for i in range(1, n): a1[i] += a1[i - 1] a2[i] += a2[i - 1] q1 = [0] * (2 * n) q2 = [0] * (2 * n) for i in range(1, n): q1[i] = u1[i] * (i) + q1[i - 1] q2[i] = u2[i] * (i) + q2[i - 1] for i...
207
103_C. Russian Roulette
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha se...
#!/usr/bin/env python3 n, k, p = map(int, input().strip().split()) if k == 0: ak = 0 an = n else: ak = k - 1 if n % 2 == 1 else k an = n - (n % 2) ans = '' for i in range(p): v = int(input().rstrip()) if k == 0: print('.', end='') else: if v == n: print('X', en...
208
1062_D. Fun with Integers
You are given a positive integer n greater or equal to 2. For every pair of integers a and b (2 ≤ |a|, |b| ≤ n), you can transform a into b if and only if there exists an integer x such that 1 < |x| and (a ⋅ x = b or b ⋅ x = a), where |x| denotes the absolute value of x. After such a transformation, your score increas...
i = input() i = int(i) v = 0 g = 2 s = 4 while g <= i: while s <= i: v = v + int(s / g * 4) s = s + g g = g + 1 s = g * 2 print(str(v))
209
1084_C. The Fair Nut and String
The Fair Nut found a string s. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences p_1, p_2, …, p_k, such that: 1. For each i (1 ≤ i ≤ k), s_{p_i} = 'a'. 2. For each i (1 ≤ i < k), there is such j that p_i < j < p_{i + 1} and s...
s=input() sss='' for i in s: if i in ['a','b']: sss+=i from itertools import groupby xxx=[''.join(g) for _, g in groupby(sss)] xxx=[len(i)+1 for i in xxx if 'a' in i] ans=1 if len(xxx)==1: print((xxx[0]-1)%1000000007) else: for i in xxx: ans*=i print((ans-1)%1000000007)
210
1131_E. String Multiplication
Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings s of length m an...
ALPH = 'abcdefghijklmnopqrstuvwxyz' MAX = 10 ** 9 def cnt(s): c = {ch : 0 for ch in ALPH} i = 0 while i < len(s): j = i + 1 while j < len(s) and s[i] == s[j]: j += 1 c[s[i]] = max(c[s[i]], j - i) i = j return c def nxt(c, t): nc = cnt(t) for ch in AL...
211
1152_A. Neko Finds Grapes
On a random day, Neko found n treasure chests and m keys. The i-th chest has an integer a_i written on it and the j-th key has an integer b_j on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible. The j-th key can be used to unlock the ...
n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) aeven = 0 aodd = 0 beven = 0 bodd = 0 for i in range(n): if a[i] % 2 == 0: aeven += 1 else: aodd += 1 for i in range(m): if b[i] % 2 == 0: beven += 1 else: bodd += 1 ...
212
1191_C. Tokitsukaze and Discard Items
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them. These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o...
from collections import deque n,m,k=list(map(int,input().split())) arr=list(map(int,input().split())) d=deque() for i in arr: d.append(i) chances=curr=tot=0 # print("WORKING") while tot<m: # print("S") if (d[0]-curr)%k==0: p=(d[0]-curr)//k else:p=((d[0]-curr)//k)+1 temp=curr while tot<m...
213
1230_A. Dawid and Bags of Candies
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
list1 = list(map(int, input().split())) list1.sort() if list1[0] + list1[3] == list1[1] + list1[2]: print("YES") elif list1[0] + list1[2] +list1[1] == list1[3]: print("YES") else: print("NO")
214
1271_C. Shawarma Tent
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes. The main school of the capital is located in (s_x, ...
n,x,y=map(int,input().split()) lu=0 ld=0 ru=0 rd=0 u=0 d=0 l=0 r=0 for i in range(n): a,b=map(int,input().split()) if(a<x and b<y): ld+=1 elif(a<x and b>y): lu+=1 elif(a==x and b!=y): if(b>y): u+=1 else: d+=1 elif(a>x and b<y): rd+=1 ...
215
1315_D. Recommendations
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications. The latest A/B test suggests that users are reading recommended publications more actively ...
# Код программы написал на языке Python 3 import sys from heapq import heappush, heappop def main(): n = int(sys.stdin.readline()) h = sorted(list(zip([int(i) for i in sys.stdin.readline().split()], [int(i) for i in sys.stdin.readline().split()]))) z, w, o, res = [], 0, 0, 0 while o < n: ...
216
1359_D. Yet Another Yet Another Task
Alice and Bob are playing yet another card game. This time the rules are the following. There are n cards lying in a row in front of them. The i-th card has value a_i. First, Alice chooses a non-empty consecutive segment of cards [l; r] (l ≤ r). After that Bob removes a single card j from that segment (l ≤ j ≤ r). Th...
import math import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(31): s = 0 for j in a: if j <= i: s = max(0, s + j) else: s = 0 ans = max(ans, s - i) print(ans)
217
139_D. Digits Permutations
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly. Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so o...
import itertools def countZeroes(s): ret = 0 for i in s: if i != '0': break ret += 1 return ret def stupid(n): ansMax = 0 bn1 = n bn2 = n for n1 in itertools.permutations(n): for n2 in itertools.permutations(n): val = str(int(''.join(n1)) + i...
218
1493_C. K-beautiful Strings
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is...
#!/usr/bin/python import sys from sys import stdin def solve(N, K, S): if N % K != 0: print(-1) return cnt_dict = {} for s in S: cnt_dict[s] = 0 for s in S: cnt_dict[s] += 1 bea = True for k in cnt_dict: if cnt_dict[k] % K != 0: bea = Fal...
219
171_C. A Piece of Cake
How to make a cake you'll never eat. Ingredients. * 2 carrots * 0 calories * 100 g chocolate spread * 1 pack of flour * 1 egg Method. 1. Put calories into the mixing bowl. 2. Take carrots from refrigerator. 3. Chop carrots. 4. Take chocolate spread from refrigerator. 5. Put chocolate spread ...
a = input().split() s = 0 for i in range(int(a[0])): s += (i + 1) * int(a[i + 1]) print(s)
220
191_A. Dynasty Puzzles
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the...
from sys import stdin, stdout fst = 97 sze = 26 values = [[0 for i in range(sze)] for j in range(sze)] n = int(stdin.readline()) challengers = [] for i in range(n): s = stdin.readline().strip() challengers.append((ord(s[0]) - fst, ord(s[-1]) - fst)) for i in range(sze): if values[i][challeng...
221
215_A. Bicycle Chain
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t...
n = int(input()) a = list(map(int,input().split())) m = int(input()) b = list(map(int,input().split())) count = [] for i in range(n): for j in range(m): if((b[j]/a[i])==int(b[j]/a[i])): count.append(int(b[j]/a[i])) o = max(count) print(count.count(o))
222
239_A. Two Bags of Potatoes
Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater ...
""" author - Sayan Bose Brooklyn 99 is love! """ y, k, n = map(int, input().split()) if n-y == 0: print(-1) else: y1 = y res = [] f, f1 = 0, 0 while y <= n: if not y%k: f = 1 if y-y1: f1 = 1 print(y-y1, end = ' ') if not f: temp = y//k + 1 y = k * temp else: y += k if not f1:...
223
358_B. Dima and Text Messages
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. ...
def werify_message(words, message): true_message = ''.join(['<3', '<3'.join(words), '<3']) # index in true_message i = 0 for litera in message: if len(true_message) != i: if litera == true_message[i]: i += 1 else: # Дошли до конца исходного сообще...
224
381_A. Sereja and Dima
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
n = int(input("")) cards=list(map(int,input().split())) sereja = 0 dima = 0 temp = 0 turn = 1 while cards != []: nMax=max(cards[0],cards[-1]) if turn==1: temp = sereja + nMax sereja+=nMax turn=2 else: temp = dima + nMax dima+=nMax turn=1 cards.remo...
225
451_D. Count Good Substrings
We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba". Given a string, you have to find two values: 1. the number of good substrings of even length; 2. the number of good ...
s = input() blocks = [] evenA = [0] oddA = [0] evenB = [0] oddB = [0] even = True for x in s: evenA.append(evenA[-1]) oddA.append(oddA[-1]) evenB.append(evenB[-1]) oddB.append(oddB[-1]) if x == 'a': if even: evenA[-1] += 1 else: oddA[-1] += 1 else: ...
226
474_C. Captain Marmot
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles. Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments com...
#a+b-y #x+b-a #1 - import sys input=sys.stdin.readline def distSq(p1,p2): return (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1]) def isSquare(p1, p2, p3, p4): d2 = distSq(p1, p2) # from p1 to p2 d3 = distSq(p1, p3) # from p1 to p3 d4 = distSq(p1, p4) # from p1 to p4 # If length...
227
521_C. Pluses everywhere
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no ...
n, k = map(int, input().split()) t = list(map(int, input())) p, d = 1, 10 ** 9 + 7 s, f = 0, [1] * n for i in range(2, n): f[i] = (i * f[i - 1]) % d c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b - a], d - 2, d)) % d if k: u = [0] * (n + 1) p = [1] * (n + 1) for i in range(n): u[i...
228
618_B. Guess the Permutation
Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n. Bob gave you all the values of ai, j that he wro...
# from pprint import pprint n = int(input()) a = [] for i in range(n): row = [int(k) for k in input().split()] a.append(row) result = [0] * n for k in range(1, n): # print('k=', k) for i in range(n): countK = 0 countNonK = 0 for j in range(n): if a[i][j] == k: ...
229
638_D. Three-dimensional Turtle Super Computer
A super computer has been built in the Turtle Academy of Sciences. The computer consists of n·m·k CPUs. The architecture was the paralellepiped of size n × m × k, split into 1 × 1 × 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer nu...
def main(): s = input().split() n, m, k = int(s[0]), int(s[1]), int(s[2]) processor = [] for x in range(n): for y in range(m): s = input() for z in s: processor.append(int(z) == 1) if x < n - 1: emptyLine = input() counter = 0 m...
230
690_A1. Collective Mindsets (easy)
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage. ...
n = int(input()) print(n // 2 + n % 2)
231
712_D. Memory and Scores
Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score a and Lexa starts with score b. In a single turn, both Memory and Lexa get some integer in the range [ - k;k] (i.e. one integer among - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k) and add...
mod=10**9+7 f=[0]*500000 def POW(a,b): if(b==0): return 1 if(b&1): return POW(a,b//2)**2*a%mod else: return POW(a,b//2)**2 def C(n,m): if(m>n): return 0 t=f[n]*POW(f[m],mod-2)%mod*POW(f[n-m],mod-2)%mod return t f[0]=1 for i in range(1,500000): f[i]=f[i-1]*i%mod a,b,k,t=map(int,input().split(' ')) an...
232
733_C. Epidemic in Monstropolis
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city. Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monste...
def main(): n = int(input()) a = list(map(int, input().split())) m = int(input()) b = list(map(int, input().split())) sum1, sum2 = 0, 0 for i in a: sum1 += i for i in b: sum2 += i # validar que podemos obtener solucion if sum1 != sum2: print('NO') ret...
233
779_A. Pupils Redistribution
In Berland each high school student is characterized by academic performance — integer value between 1 and 5. In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known — integer value between 1 and 5. Th...
n = int(input()) linea = list(map(int, input().split())) lineb = list(map(int, input().split())) lines = linea + lineb c1 = lines.count(1) c2 = lines.count(2) c3 = lines.count(3) c4 = lines.count(4) c5 = lines.count(5) cc1 = linea.count(1) cc2 = linea.count(2) cc3 = linea.count(3) cc4 = linea.count(4) cc5 = linea.count...
234
825_E. Minimal Labels
You are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: * Labels form a valid permutation of length n — an integer sequence such that each integ...
#!/usr/local/bin/python3 from collections import defaultdict import heapq num_nodes, num_edges = map(int, input().split()) ins = defaultdict(set) out = defaultdict(int) for _ in range(num_edges): node_out, node_in = map(int, input().split()) ins[node_in].add(node_out) out[node_out] += 1 zeros = [-node ...
235
870_A. Search for Pretty Integers
You are given two lists of non-zero digits. Let's call an integer pretty if its (base 10) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer? Input The first line contains two integers n and m (1 ≤ n, m ≤ 9) — the length...
a,b=map(int,input().split()) s=input().split() x=list(map(int,s)) s=input().split() y=list(map(int,s)) o=10 for i in range(a): for j in range(b): if x[i]==y[j]: if x[i]<o: o=x[i] x1=min(x) y1=min(y) if o<10: print(o) else: print(min(y1,x1)*10+max(x1,y1))
236
918_A. Eleven
Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. <image> Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested th...
n=int(input()) a,b,r=1,2,'' for i in range(1,n+1): if i==a: r+='O';a,b=b,a+b else: r+='o' print(r)
237
940_A. Points on the line
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2. Diame...
n,d = map(int,input().split()) a=list(map(int,input().split())) a.sort(); i=0 cnt=0 cnt1=0 if n==1: print("0") else: for i in range(n): cnt=0 for j in range(i+1,n): d1=a[j]-a[i] if d1>d: break; cnt+=1 if(cnt1<cnt): cnt1=cnt...
238
993_D. Compute Power
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume. You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task ca...
# Codeforces Round #488 by NEAR (Div. 2) import collections from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import math import sys def getIntList(): return list(map(int, input().split())) import bisect def makePair(z): return [(z[i], z[i+1]) for i in range(0,le...
239
1008_D. Pave the Parallelepiped
You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C. Find the number of different groups of three integers (a, b, c) such that 1≤ a≤ b≤ c and parallelepiped A× B× C can be paved with parallelepipeds a× b× c. Note, that all small parallelepipeds have to be rotated in the same d...
from sys import stdin from math import gcd def main(): input() l = stdin.read().splitlines() d = [3., 1., 2., 2., 2., 1.] * 16667 for i in range(4, 100001): for j in range(i, 100001, i): d[j] += 1. for i, s in enumerate(l): a, b, c = map(int, s.split()) k = gcd(...
240
1031_B. Curiosity Has No Limits
When Masha came to math classes today, she saw two integer sequences of length n - 1 on the blackboard. Let's denote the elements of the first sequence as a_i (0 ≤ a_i ≤ 3), and the elements of the second sequence as b_i (0 ≤ b_i ≤ 3). Masha became interested if or not there is an integer sequence of length n, which e...
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict import threading BUFSIZE = 8192 clas...
241
1054_B. Appending Mex
Initially Ildar has an empty array. He performs n steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset [0...
n = int(input()) data = input().split() max = 0 for i in range(n): back = max if max<int(data[i]): max=int(data[i]) if i==0 and data[i]!="0": print(1) exit() elif int(data[i])>back+1: print(i+1) exit() if int(data[i])<=back+1: print(-1)
242
1076_B. Divisor Subtraction
You are given an integer number n. The following algorithm is applied to it: 1. if n = 0, then end algorithm; 2. find the smallest prime divisor d of n; 3. subtract d from n and go to step 1. Determine the number of subtrations the algorithm will make. Input The only line contains a single integer n (2 ≤...
from collections import deque as de import math class My_stack(): def __init__(self): self.data = [] def my_push(self, x): return (self.data.append(x)) def my_pop(self): return (self.data.pop()) def my_peak(self): return (self.data[-1]) def my_contains(self, x): ...
243
1097_B. Petr and a Combination Lock
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: <image> Petr called his car dealer, who in...
n = int(input()) a = [0] for _ in range(n): curr = int(input()) mods = [] for o in a: mods.extend([o + curr, o - curr]) a = mods[:] #print(a) print("YES" if any(x%360 == 0 for x in a) else "NO")
244
1144_F. Graph Without Long Directed Paths
You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the numb...
# lista doble enlazada o(1) en operaciones en los bordes from collections import deque def solve(): global n, m n, m = map(lambda x: int(x), input().split()) global maxValue maxValue = n**2 graph = [[] for _ in range(0, n)] edges = [] for _ in range(0, m): u, v = map(lambda x: int(...
245
1184_D1. Parallel Universes (Easy)
The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250. Heidi recently got her hands on a multiverse observation to...
n,k,m,t=map(int,input().split()) for i in range(t): a,b=map(int,input().split()) if a==1: if b<=k: k+=1 n+=1 print(n,k) else : if k>b: n=n-b k=k-b else : n=b print(n,k)
246
1203_A. Circle of Students
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
t=int(input()) while t: n=int(input()) a=list(map(int,input().split())) b=[0]*n for i in range(n): b[a[i]-1]=i+1 k=0 flag=0 # print(b) if n==1: print("YES") elif abs(b[0]-b[1])==1 or abs(b[0]-b[1])==n-1: if abs(b[0]-b[1])==1: k=b[0]-b[1] else: k=b[1]-b[2] for j in range(1,n): if j==n-1: ...
247
121_C. Lucky Permutation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how ...
def lucky(x): s=str(x) return s.count('4')+s.count('7')==len(s) def Gen_lucky(n): if(len(n)==1): if(n<"4"): return 0 if(n<"7"): return 1 return 2 s=str(n) if(s[0]<'4'): return 0 if(s[0]=='4'): return Gen_lucky(s[1:]) if(s[0]<'7...
248
1244_G. Running in Pairs
Demonstrative competitions will be held in the run-up to the 20NN Berlatov Olympic Games. Today is the day for the running competition! Berlatov team consists of 2n runners which are placed on two running tracks; n runners are placed on each track. The runners are numbered from 1 to n on each track. The runner with nu...
n, t = [int(i) for i in input().split()] import os def tr(qq): return (qq*(qq+1))//2 if t < tr(n): print(-1) exit() upp = 2 * (tr(n) - tr(n//2)) if n % 2 == 1: upp -= (n+1)//2 if t >= upp: # print(upp) # exit() os.write(1, (str(upp) + '\n').encode()) ans = list(range(1, n+1)) # p...
249
1286_A. Garland
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
def ip(): n=int(input()) a=list(map(int,input().split())) rem=set([i for i in range(1,n+1)])-set(a) if n==1: return 0 o=e=0 for i in rem: if i%2==0: e+=1 else: o+=1 ct=0 i=0 while i<len(a) and a[i]==0: i+=1 if i==len(a): ...
250
1305_B. Kuroni and Simple Strings
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence! ...
s = input() to_ans = [False for _ in range(len(s))] def solve(s, left, right): #right inclusive if left >= right: return while left <= right and s[left] == ")": left += 1 while right >= left and s[right] == "(": right -= 1 if left >= right: return else: to_ans[left] = True to_ans[right] = True solve...
251
1349_D. Slime and Biscuits
Slime and his n friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the i-th player has a_i biscuits. At each second, Slime will choose a biscuit randomly uniformly among all a_1 + a_2 + … + a_n biscuits, and the owner of this biscuit will give it to a random unifor...
import os import sys input = sys.stdin.buffer.readline #sys.setrecursionlimit(int(2e5)) from collections import deque import math # list(map(int, input().split())) ##################################################################################### class CF(object): def __init__(self): self.mod = 998244...
252
136_B. Ternary Logic
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it...
def untor(a, c): res = '' while a or c: a, ma = divmod(a, 3) c, mc = divmod(c, 3) x = 0 while (ma + x)%3 != mc: x += 1 res = str(x) + res try: return int(res, 3) except Exception as e: return 0 a, c = map(int, input().split()) print(un...
253
1392_B. Omkar and Infinity Clock
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem: You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope...
t=int(input()) for i in range(t): n,k=map(int,input().split()) ar=list(map(int,input().split())) m=max(ar) new=[] for i in range(n): new.append(m-ar[i]) if k%2==0: mx=max(new) for j in range(n): new[j]=mx-new[j] print(*new)
254
1433_C. Dominant Piranha
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the...
for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) if len(set(l))==1: print(-1) else: m=max(l) for i in range(n): if i>0: if i<n-1: if l[i]==m and (l[i-1]<m or l[i+1]<m): print(i+1) break else: if l[i]==m and l[i-1]<m: print(i+1) break ...
255
1481_B. New Colony
After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you). <image> You are given an array h_1, h_2, ..., ...
import collections import string import math import copy import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in fil...
256
1508_C. Complete the MST
As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all...
def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f ...
257
181_B. Number of Triplets
You are given n points on a plane. All points are different. Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC. The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are consi...
n = int(input()) points_array = [] cords = [] for i in range(2001): cords.append([False] * 2001) for i in range(n): x, y = [a for a in input().split()] points_array.append([int(x), int(y)]) cords[int(x)+1000][int(y)+1000] = True count = 0 for i in range(n): for j in range(i+1, n): x1, y1...
258
204_D. Little Elephant and Retro Strings
The Little Elephant has found a ragged old black-and-white string s on the attic. The characters of string s are numbered from the left to the right from 1 to |s|, where |s| is the length of the string. Let's denote the i-th character of string s as si. As the string is black-and-white, each character of the string is...
Mod=1000000007 n,k=map(int,input().split(' ')) s=' '+input() f,fs,g,gs,w=[0]*1000005,[0]*1000005,[0]*1000005,[0]*1000005,[0]*1000005 qx,qw,qb=[0]*1000005,[0]*1000005,[0]*1000005 q=0 f[0]=fs[0]=1 for i in range(1,n+1): lg=(i-k if i-k>=q else q) if s[i]!='B': f[i]=fs[i-1]-fs[lg-1]+Mod f[i]-=(Mod if f[i]>=Mod else 0...
259
278_B. New Problem
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your...
from itertools import * alphabet="abcdefghijklmnopqrstuvwxyz"; def isValid(s, names): for name in names: if name.find(s)!=-1: return False return True def newProblem(names): for i in range(1,3): for s in product(alphabet, repeat=i): st="" for c in s: ...
260
372_A. Counting Kangaroos is Fun
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is ...
# Made By Mostafa_Khaled bot = True import math,sys n=int(input());k=n a=sorted([int(x) for x in sys.stdin.read().strip().split('\n')]) p1=math.floor((n-1)/2);p2=n-1 while p1>=0: if 2*a[p1]<=a[p2]: k-=1;a[p2]=0;p2-=1 p1-=1 k=max(math.ceil(n/2),k) sys.stdout.write(str(k)) # Made By Mostafa_Kh...
261
393_C. Blocked Points
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if: * the Euclidean distance between A and B is one unit and neither A nor B is blocked; * or there is some inte...
from math import sqrt n = int(input()) if n == 0: print(1) else: print(4 * int(n * sqrt(2)))
262
416_D. Population Size
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions. Polycarpus believes that if...
n = int(input()) a = list(map(int, input().split())) i = 0 ans = 0 while i < n: ans += 1 i1 = i while i1 < n and a[i1] == -1: i1 += 1 if i1 == n: break i2 = i1 + 1 while i2 < n and a[i2] == -1: i2 += 1 if i2 == n: break dist = i2 - i1 step = (a[i2] - a...
263
443_B. Kolya and Tandem Repeat
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be? See notes for definition of a tandem repeat. I...
s=input() k=int(input()) n=len(s) if k>=n: print(int(2*((n+k)//2))) raise SystemExit ll=0 for i in range(k+1): for l in range((n+i)//2,i-1,-1): if s[n-(l-i):n]==s[n+i-2*l:n-l]: if l>ll: ll=l break j=ll while 2*j<=n: j=j+1 for i in range(n-2*j): if s[i:i+j]==s[...
264
465_C. No to Palindromes!
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more. Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable st...
import sys def main(): # fin = open("input.txt", "r") fin = sys.stdin fout = sys.stdout L = list("abcdefghijklmnopqrstuvwxyz") n, p = map(int, fin.readline().split()) A = list(fin.readline()) for i in range(n - 1, 1, -1): pr = ord(A[i - 1]) - ord("a") pp = ord(A[i - 2]) -...
265
489_B. BerSU Ball
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
n = int(input()) b = list(map(int, input().split())) m = int(input()) g = list(map(int, input().split())) b.sort() g.sort() res = 0 i = 0 j = 0 while i < n and j < m: if abs(b[i]-g[j]) <= 1: res += 1 i += 1 j += 1 elif b[i] > g[j]: j += 1 else: i += 1 print(res)...
266
513_A. Game
Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls f...
n1 , n2 , k1 , k2 = map(int , (input().split(" "))) if n1 <= n2: print('Second') else: print('First')
267
538_B. Quasi Binary
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not. You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers. Input The first line contains a single...
import math a = input() d = int(max(a)) print(d) dec = math.ceil(math.log10(int(a))) c = [0]*d if int(a) != 10**dec: for i in a: for j in range(int(i)): c[j] = c[j]+10**(dec-1) dec = dec - 1 d='' for i in c: d += str(i)+' ' if int(a) == 10**dec: print(a) else: print(d.strip()...
268
630_E. A rectangle
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem. A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will...
x1,y1,x2,y2 = input().split( ) x1=int(x1) y1=int(y1) x2=int(x2) y2=int(y2) x =int(x2 - x1) y =int(y2 - y1) if x % 2 == 0: if y % 2 == 1: n= int(int( x + 1 ) * int(y + 1) / 2) else: t0=int(x*y)+int(x)+int(y) t1=int(t0)//2 n=int(t1)+1 else: n = int((x + 1) / 2 * ( y + 1 )) print(n)
269
658_B. Bear and Displayed Friends
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti. Spring is starting and the Winter sleep is ...
str1 = input().split() n = int(str1[0]) k = int(str1[1]) q = int(str1[2]) friends = list(map(lambda x: int(x), input().split())) online = set() for i in range(q): str1 = input().split() if str1[0] == '2': if int(str1[1]) in online: print("YES") else: print("NO") els...
270
680_D. Bear and Tower of Cubes
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length. A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3....
#!/usr/bin/env python3 import sys # 1 8 27 64 125 216 343 512 729 1000 # 1-7: blocks of size 1 # 8-15: 1 block of size 2, blocks of size 1 # 16-23: 2 blocks of size 2, blocks of size 1 # 24-26: 3 blocks of size 2, blocks of size 1 # 27-34: 1 block of size 3, blocks of size 1 # Maximum will always be when you have th...
271
747_C. Servers
There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n. It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to ...
n, q = map(int, input().split()) servers = [i for i in range(1, n+1)] res, used = [], {} for i in range(q): t, s, d = map(int, input().split()) finish = t + d for i in list(used.keys()): if t >= i: servers += used[i] servers.sort() del used[i] if s > len(serv...
272
794_C. Naming Company
Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company. To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor ea...
from sys import * f = lambda: sorted(stdin.readline()[:-1]) a, b = f(), f() n = len(a) u = v = '' i, j = 0, -1 x, y = n - 1 >> 1, n - 2 >> 1 while x != -1: if a[i] < b[j]: u += a[i] i += 1 else: v += a[i + x] x -= 1 if y == -1: break elif a[i] < b[j]: u += b[j] j -= 1...
273
815_B. Karen and Test
Karen has just arrived at school, and she has a math test today! <image> The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. Th...
from sys import exit, stdin, stdout n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] if n == 1: print(a[0]) exit(0) mod = 1000000007 f = [0] * (n + 1) f[0] = 1 for i in range(1, n + 1): f[i] = (f[i-1] * i) % mod def f_pow(a, k): if k == 0: return 1 if k % 2 == 1: ...
274
887_B. Cubes for Masha
Absent-minded Masha got set of n cubes for her birthday. At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x. To make a number Masha can rotate her cubes and put them in a row. Aft...
n = int(input()) lst = [] for i in range(n): a = list(map(int,input().split())) lst.append(a) cnt = 0 ans = 0 if n == 1: i = 1 while 1: if i == 10: break if i in lst[0]: i += 1 else: print(i - 1) break elif n == 2: i = 1 f = 0 whil...
275
90_B. African Crossword
An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded. To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a lette...
n, m = [int(x) for x in input().split()] lr = [] lc = [] lst = [] for i in range(n): l = list(input()) lr.append(l) for i in range(m): l = [] for j in range(n): s = lr[j][i] l.append(s) lc.append(l) for i in range(n): for j in range(m): s = lr[i][j] if lr[i].count...
276
985_E. Pencils and Boxes
Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to ...
n, k, d = list(map(int, input().split())) a = sorted(list(map(int, input().split()))) b = [0] * n i = j = 0 for i in range(n): while a[i] - a[j] > d: j += 1 b[i] = j c = [0] * n for i in range(k - 1, n): c[i] = c[i - 1] + int(i - b[i] + 1 >= k and (b[i] == 0 or c[i - k] > c[b[i] - 2] or (b[i] == 1 a...
277
1000_C. Covered Points Count
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every k ∈ [1..n], calculate the number of points with integer ...
n=int(input()) a=[] for i in range(n): l,r=map(int,input().split()) a.append([l,1]) a.append([r+1,-1]) a.sort() # print(a) ans=[0]*(n+1) idx=0 for i in range(len(a)-1): idx+=a[i][1] ans[idx]+=a[i+1][0]-a[i][0] for i in range(1,n+1): print(ans[i],end=" ") print()
278
1025_D. Recovering BST
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees! Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and s...
from math import gcd import random,time,sys input=sys.stdin.buffer.readline def main(): n=int(input()) a=list(map(int,input().split())) #a=[2*random.randint(1,10**9) for i in range(n)] start=time.time() a+=[0] dp=[[False for j in range(n)] for i in range(n)] GCD=[0 for i in range(n+1)] ...
279
110_B. Lucky String
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i...
n=int(input()) x='a'+'bcda'*25002 print(x[:n])
280
1139_E. Maximize Mex
There are n students and m clubs in a college. The clubs are numbered from 1 to m. Each student has a potential p_i and is a member of the club with index c_i. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next d days. There is a coding competit...
import sys input = sys.stdin.readline n, m = map(int, input().split()) p = list(map(int, input().split())) c = list(map(int, input().split())) d = int(input()) disable = [False] * n base = 5001 ds = [int(input())-1 for _ in range(d)] for ele in ds: disable[ele] = True # Create Graph childs = [[] for i in range(...
281
1157_E. Minimum Array
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1. You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% ...
class SegmentTree: @classmethod def all_identity(cls, operator, equality, identity, size): return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length())) @classmethod def from_initial_data(cls, operator, equality, identity, data): size = 1 << (len(data)-1).bit_lengt...
282
117_B. Very Interesting Game
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representi...
a, b, m = map(int, input().split()) k = s = 10 ** 9 % m i = 0 while k and i < a: i += 1 if k < m - b: exit(print(1, str(i).zfill(9))) k += s if k >= m: k -= m print(2)
283
1198_C. Matching vs Independent Set
You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line...
import sys input = sys.stdin.readline T = int(input()) for _ in range(T): N, M = map(int, input().split()) X = [[] for i in range(3*N)] for i in range(M): x, y = map(int, input().split()) x, y = min(x,y), max(x,y) X[x-1].append((y-1, i+1)) MAT = [] IND = [] DONE = [...
284
1215_B. The Number of Products
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative; 2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a...
input() a=list(map(int,input().split())) q,w,e,t,y=0,0,1,0,0 for i in a: if e>0: q+=1 if i>0: e=1 else: e=-1 else: w+=1 if i>0: e=-1 else: e=1 if e>0: t+=q y+=w else: t+=w y+=q...
285
127_E. E-reader Display
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-read...
n=int(input()) T=[] for i in range(n): T.append(input()[::-1]) Val=['0','1'] S=0 L1=[0]*n C1=[0]*n for diag in range(n-1): for i in range(diag+1): l,c=L1[i],C1[diag-i] if T[i][diag-i]!=Val[(l+c)%2]: S+=1 L1[i]=1-l C1[diag-i]=1-c L2=[0]*n C2=[0]...
286
1342_E. Placing Rooks
Calculate the number of ways to place n rooks on n × n chessboard so that both following conditions are met: * each empty cell is under attack; * exactly k pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two...
import io,os input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys def solve(n,k): mod=998244353 if k==0: ans=1 for i in range(1,n+1): ans*=i ans%=mod return ans if k>=n: return 0 inv=lambda x: pow(x,mod-2,mod) Fact=[1] #階乗 ...
287
155_C. Hometask
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about ...
s = input() + "#" k = int(input()) arr = [input() for _ in range(k)] res = 0 for t in arr: a, b = 0, 0 for i in range(len(s)): if s[i] == t[0]: a += 1 elif s[i] == t[1]: b += 1 else: if a and b: res += min(a, b) a, b = 0, 0 ...
288
177_D1. Encrypting Messages
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...
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 = ' ')
289
245_F. Log Stream Analysis
You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the ...
import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisect from datetime import datetime def main(): ...
290
270_D. Greenhouse Effect
Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant o...
n, m = [int(x) for x in input().split()] d = [0 for i in range(m)] for i in range(n): c, x = [x for x in input().split()] c = int(c) d[c-1] = max(d[:c])+1 print(n-max(d))
291
294_A. Shaass and Oskols
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ...
n = int(input()) l = list(map(int,input().split())) n1 = int(input()) for i in range(n1): x,y = map(int,input().split()) if len(l)==1: l[0]=0 elif x==1: l[x]+=l[x-1]-y l[x-1]=0 elif x==len(l): l[x-2]+=y-1 l[x-1]=0 else: l[x-2]+=y-1 l[x]+=l[x-1]-y l[x-1]=0 for i in l: print(i)
292
317_D. Game with Powers
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact). Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive in...
from sys import stdin, stdout import math, collections mod = 10**9+7 def isPower(n): if (n <= 1): return True for x in range(2, (int)(math.sqrt(n)) + 1): p = x while (p <= n): p = p * x if (p == n): return True return False n = int(input()) a...
293
365_A. Good Number
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th ...
import sys x=input().split() n=int(x[0]) k=int(x[1]) list=[] for i in range(0,n): y=input() list.append(y) l=0 for j in list: flag=1 for z in range(0,k+1): if str(z) not in j: flag=0 break if flag==1: l=l+1 print(l)
294
409_C. Magnum Opus
Salve, mi amice. Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus. Rp: I Aqua Fortis I Aqua Regia II Amalgama VII Minium IV Vitriol Misce in vitro et æstus, et nil admirari. Festina lente, et nulla tenaci invia est via. Fac...
b =[1,1,2,7,4] a =list(map(int,input().split())) ans = 100 for i in range(5): ans = min(a[i]//b[i],ans) print(ans)
295
459_E. Pashmak and Graph
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 (perh...
from sys import * f = list(map(int, stdin.read().split())) n, m = f[0], f[1] d = [[] for i in range(100001)] for j in range(2, len(f), 3): x, y, w = f[j:j + 3] d[w].append((y, x)) s = [0] * (n + 1) for q in d: for y, k in [(y, s[x]) for y, x in q]: s[y] = max(s[y], k + 1) print(max(s))
296
505_D. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, tha...
def main(): n, m = map(int, input().split()) n += 1 cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)] def root(x): if x != cluster[x]: cluster[x] = x = root(cluster[x]) return x for _ in range(m): a, b = map(int, input().split()) ab[a]....
297
554_E. Love Triangles
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (the...
class DSU(object): def __init__(self, n): self.father = list(range(n)) self.size = n def union(self, x, s): x = self.find(x) s = self.find(s) if x == s: return self.father[s] = x self.size -= 1 def find(self, x): xf = self.father[...
298
580_D. Kefa and Dishes
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfact...
import os import sys from io import BytesIO,IOBase def main(): n,m,k = map(int,input().split()) a = list(map(float,input().split())) tree = [[0]*n for _ in range(n)] for i in range(k): x,y,z = map(int,input().split()) tree[x-1][y-1] = float(z) po = [1] while len(po) != n: ...
299
602_C. The Two Routes
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
n, m = map(int, input().split()) dist = [0] * (n + 1) for row in range(n + 1): dist[row] = [1] * (n + 1) for i in range(m): a, b = map(int, input().split()) dist[a][b] = dist[b][a] = 2 x, v, i = 3 - dist[1][n], [0] * (n + 1), 1 d = [n + 1] * (n + 1) res = d[1] = 0 while i != n: v[i] = 1 for j i...