Dataset Viewer
Auto-converted to Parquet Duplicate
name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1037_E. Trips
There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: * ...
```python from collections import deque def solve(adj, m, k, uv): n = len(adj) nn = [len(a) for a in adj] q = deque() for i in range(n): if nn[i] < k: q.append(i) while q: v = q.popleft() for u in adj[v]: nn[u] -= 1 if nn[u] == k-1: ...
1060_A. Phone Numbers
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit. For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not. You have n cards with digits, and you want to use them to make as many phone n...
```python n = int(input()) s = input() k = s.count("8") l = n - k if k <= l//10: print(k) else: while k > l//10: k -= 1 l += 1 print(min(k, l//10)) ```
1101_A. Minimum Integer
You are given q queries in the following form: Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i]. Can you answer all the queries? Recall that a number x belongs to segment [l, r] if l ≤ x ≤ r. Input The first l...
```python n = int(input()) A = [] for i in range(n): A = A+[input().split()] for a in A: if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]): print(a[2]) else: print(int(a[2])*(int(a[1])//int(a[2])+1)) ```
1189_D1. Add on a Tree
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al...
```python m = int(input()) l = [0 for _ in range(m + 1)] for _ in range(m - 1): a,b = map(int, input().split()) l[a] += 1 l[b] += 1 if 2 in l: print("NO") else: print("YES") ```
1208_D. Restore Permutation
An array of integers p_{1},p_{2}, …,p_{n} is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4]. There is a hidden permutation of length n. ...
```python from sys import stdin,stdout class Tree(object): def __init__(self,n): self.tree=[0]*(4*n+10) self.b=[0]*(n+10) self.a=list(map(int,stdin.readline().split())) self.n=n def update(self,L,C,l,r,rt): if l==r: self.tree[rt]+=C return ...
1227_D1. Optimal Subsequences (Easy Version)
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily...
```python # class SegmentTree(): # adapted from https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ # def __init__(self,arr,func,initialRes=0): # self.f=func # self.N=len(arr) # self.tree=[0 for _ in range(2*self.N)] # self.initialRes=initialRes # for i in r...
1269_E. K Integers
You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. ...
```python n = int(input()) a = [0] + list(map(int, input().split())) pos, pb, ps = [[0] * (n + 1) for x in range(3)] def add(bit, i, val): while i <= n: bit[i] += val i += i & -i def sum(bit, i): res = 0 while i > 0: res += bit[i] i -= i & -i return res def find(bi...
1291_E. Prefix Enlightenment
There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you ...
```python from sys import stdin input = stdin.readline n , k = [int(i) for i in input().split()] pairs = [i + k for i in range(k)] + [i for i in range(k)] initial_condition = list(map(lambda x: x == '1',input().strip())) data = [i for i in range(2*k)] constrain = [-1] * (2*k) h = [0] * (2*k) L = [1] * k + [0] * k dp1...
1311_F. Moving Points
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ...
```python import bisect def getsum(tree , i): s = 0 i += 1 while i>0: s += tree[i] i -= i & (-i) return s def updatebit(tree , n , i , v): i+= 1 while i <= n: tree[i] += v i += i & (-i) n = int(input()) x = list(map(int , input().split())) v = list(map(int , in...
1334_D. Minimum Euler Cycle
You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of...
```python # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2020/7/1 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(n, l, r): # 1, 2, 1, 3, ..., 1, n # 2, 3, 2, 4, ..., 2, n # ... # n-1, n # 1 lo, hi = 1, n...
1354_F. Summoning Minions
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions c...
```python from sys import stdin, gettrace from heapq import nlargest if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() INF = int(10E10) def main(): def solve(): n, k = map(int, input().split()) mm = [] for i in range(1...
1374_E1. Reading Books (easy version)
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ...
```python import sys input=sys.stdin.readline f=lambda :list(map(int, input().strip('\n').split())) n, k=f() _11=[] _01=[] _10=[] for _ in range(n): t, a, b=f() if a and b: _11.append(t) elif a: _10.append(t) elif b: _01.append(t) _01.sort(); _10.sort(); _11.sort() for i in range(1, len(_01)): _01[i]+=_01[i...
1398_A. Bad Triangle
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
```python t=int(input()) for z in range(t): n=int(input()) arr=list(map(int,input().split())) min= arr[0] + arr[1] pos=True for i in range(2,n): if(arr[i]>=min): pos=False posf=i break if(pos): print("-1") else: print("1 2", posf+1)...
1421_B. Putting Bricks in the Wall
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid f...
```python l=[] for _ in range(int(input())): n=int(input()) a=[] for i in range(n): a.append(list(input())) if a[0][1]==a[1][0]: if a[n-1][n-2]==a[n-2][n-1]: if a[n-1][n-2]==a[0][1]: l.append("2") l.append("1 2") l.append("2 1")...
143_A. Help Vasilisa the Wise 2
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha...
```python inn = list(map(int, input().split(" "))) r1 = inn[0] r2 = inn[1] inn = list(map(int, input().split(" "))) c1 = inn[0] c2 = inn[1] inn = list(map(int, input().split(" "))) d1 = inn[0] d2 = inn[1] x = int((d1+c1-r2)/2) y = int(((2*r1)-d1-c1+r2)/2) a = int(((2*c1)-d1-c1+r2)/2) b = int((r2-(2*c1)+d1+c1)/2) if x ...
1466_F. Euclid's nightmare
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words h...
```python import sys input = sys.stdin.buffer.readline def _find(s, u): p = [] while s[u] != u: p.append(u) u = s[u] for v in p: s[v] = u return u def _union(s, u, v): su, sv = _find(s, u), _find(s, v) if su != sv: s[su] = sv return su != sv n, m = map(int, input().split()...
1490_G. Old Floppy Drive
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it. Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm: * the drive takes one positive number x...
```python def findIndexGE(prefixSumsMax,startSum,query): n=len(prefixSumsMax) b=n i=-1 while b>0: while i+b<n and startSum+prefixSumsMax[i+b]<query: i+=b b//=2 i+=1 return i def main(): t=int(input()) allans=[] for _ in range(t): n,m=readInt...
1513_C. Add One
You are given an integer n. You have to apply m operations to it. In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once. You have to find the length of n after applying m operations. Since...
```python from os import path import sys,time from math import ceil, floor,gcd,log,log2 ,factorial from collections import defaultdict ,Counter , OrderedDict , deque from heapq import heapify , heappush , heappop from bisect import * # from functools import reduce from operator import mul from itertools import permutat...
1540_C1. Converging Array (Easy Version)
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved. There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each operat...
```python def putin(): return map(int, input().split()) def sol(): n = int(input()) C = list(putin()) B = list(putin()) q = int(input()) x = int(input()) min_arr = [x] min_part_sums = [x] part_sums = [C[0]] for i in range(1, n): part_sums.append(part_sums[-1] + C[i]) ...
168_A. Wizards and Demonstration
Some country is populated by wizards. They want to organize a demonstration. There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr...
```python num,wiz,per = map(int,input().split()) k = 0 while (k+wiz)/num*100 < per: k += 1 print(k) ```
20_B. Equation
You are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order. Input The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0. Output In case of infinite root cou...
```python a, b, c = map(float, input().split()) D = b ** 2 - (4 * a * c) if D < 0: print(0) elif a == 0 and b == 0 and c != 0: print(0) elif a == 0 and b == 0 and c == 0: print(-1) elif a == 0: x0 = c / -(b) print(1) print(x0) elif b == 0: print(1) print(0) elif D == 0 and (a > 0 or a < ...
260_B. Ancient Prophesy
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha...
```python s=input() n=len(s) l=list("0987654321") cnt={} for i in range(n-9): t=s[i:i+10] if t[0] in l and t[1] in l and t[2]=="-" and t[3] in l and t[4] in l and t[5]=="-" and t[6] in l and t[7] in l and t[8] in l and t[9] in l: if 2013<=int(t[6:11])<=2015 and 1<=int(t[3:5])<=12: if int(t[3:5]) in [1,3,...
284_B. Cows and Poker Game
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any bett...
```python #!/bin/python # -*- coding: utf-8 -*- n = int(input()) s = input() print(int(s.count('I') == 1) if 'I' in s else s.count('A')) ```
379_A. New Year Candles
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
```python a, b = map(int, input().split()) c, s = a, 0 while a >= b: s += a // b a = (a // b) + (a % b) print(s + c) ```
39_H. Multiplication Table
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn...
```python k=int(input()) for i in range(1,k): z,a=i,[] for j in range(k-1): p,s=z,"" while p: s=str(p%k)+s p//=k z+=i a.append(s) print(*a) ```
44_B. Cola
To celebrate the opening of the Winter Computer School the organizers decided to buy in n liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly a bottles 0.5 in volume, b one-liter bottles and c of two...
```python def nik(rudy,x,y,z,cot): for i in range(z+1): for j in range(y+1): t = rudy - i*2 -j if t>=0 and x*0.5 >= t: cot+=1 return cot rudy, x, y, z = list(map(int,input().split())) cot = 0 print(nik(rudy,x,y,z,cot)) ```
519_B. A and B and Compilation Errors
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s...
```python n = int(input()) a_sum = sum(map(int, input().split())) b_sum = sum(map(int, input().split())) c_sum = sum(map(int, input().split())) print(a_sum - b_sum) print(b_sum - c_sum) ```
545_C. Woodcutters
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
```python ll=lambda:map(int,input().split()) t=lambda:int(input()) ss=lambda:input() #from math import log10 ,log2,ceil,factorial as f,gcd #from itertools import combinations_with_replacement as cs #from functools import reduce #from bisect import bisect_right as br #from collections import Counter n=t() x,h=[],[] fo...
593_C. Beautiful Function
Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the i...
```python def f(x): if x == n: return "0" if x == 0: return "(" + str(X[0]) + "+" + f(1) + ")" ss = "(abs((t-" + str(x-1) + "))-abs((t-" + str(x) + ")))" tmp = (X[x] - X[x - 1]) // 2 re = (X[x] - X[x - 1]) - 2 * tmp X[x] -= re ...
615_A. Bulbs
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
```python import math nm = input().split() n = int(nm[0]) m = int(nm[1]) lis = [ 0 for i in range(m+1)] for _ in range(n) : inp = list(map(int, input().split())) inp.pop(0) for i in inp: lis[i]=1 prev = i if sum(lis)==m: print("YES") else: print("NO") ```
634_C. Factory Repairs
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but ...
```python from functools import reduce class SegmentTree(): def __init__(self, L, function = lambda x,y: x+y, initilizer = None): self.function = function self.initilizer = initilizer N = self.size = len(L) M = 1 << N.bit_length() self.margin = 2*M - N self.L = [None ...
663_A. Rebus
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds. Input The only line of the input contains a re...
```python s = input().split() plus = 1 minus = 0 for ch in s: if (ch == '+') : plus += 1 if (ch == '-') : minus += 1 n = int(s[len(s) - 1]) maxx = plus * n - 1 * minus minn = plus - n * minus now = n - (plus - minus) if (n>maxx or n<minn): print("Impossible") else: pre = '+' print("Possible") for ...
730_J. Bottles
Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda ai and bottle volume bi (ai ≤ bi). Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda...
```python f = lambda: list(map(int, input().split())) n = int(input()) a, b = f(), f() d = [[None] * 10001 for i in range(n)] def g(i, s): if s <= 0: return (0, s) if i == n: return (1e7, 0) if not d[i][s]: x, y = g(i + 1, s - b[i]) d[i][s] = min(g(i + 1, s), (x + 1, y + b[i] - a[i])) ...
776_A. A Serial Killer
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
```python def main(): l = input().split() print(*l) for _ in range(int(input())): a, b = input().split() l[a == l[1]] = b print(*l) if __name__ == '__main__': main() ```
7_B. Memory Manager
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: ...
```python t, m = map(int, input().split()) disk = [False] * m req = 0 for i in range(t): inp = input().split() if inp[0][0] == "a": c = 0 inp[1] = int(inp[1]) for j in range(m): if disk[j]: c = 0 else: c += 1 if c == inp...
820_D. Mister B and PR Shifts
Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation whi...
```python from sys import stdin def main(): n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) inf = [0] * (n + 1) curr = 0 d = 0 for i in range(n): curr += abs(i + 1 - a[i]) if a[i] > i + 1: d += 1 inf[a[i] - i - 1] += 1 elif a...
846_E. Chemistry in Berland
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment. Fortunately, chemical laws allow material transformations (yes, chemistry i...
```python import sys # @profile def main(): f = sys.stdin # f = open('input.txt', 'r') # fo = open('log.txt', 'w') n = int(f.readline()) # b = [] # for i in range(n): # b.append() b = list(map(int, f.readline().strip().split(' '))) a = list(map(int, f.readline().strip().split(' '...
868_A. Bark to Unlock
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p...
```python one=input() num=int(input()) twos=[] for i in range(num): twos.append(input()) if (one in twos) or (one[::-1] in twos): print("YES") else: flag1,flag2=False,False for i in range(num): if twos[i][0]==one[1]: flag1=True if twos[i][1]==one[0]: flag2=True if(flag1 and flag2): p...
893_D. Credit Card
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card. She starts with 0 money on her account. In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, ...
```python #Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue, bisect #sys.stdin = open("input.txt", "r") MOD = 10**9+7 sys.setrecursionlimit(1000000) n, d = map(int, input().split()) a = list(map(int, input().split())) p = [0 for i in range(n)] for i in range(n): p[i] = p[i-1]+a[i] mx = [-1 f...
915_A. Garden
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
```python def is_prime(a): return all(a % i for i in range(2, a)) n, k = map(int, input().split()) l = [int(x) for x in input().split()] if is_prime(k): if k in l: print(1) else: print(k) else: ll = [] for i in range(len(l)): if k % l[i] == 0: ll.append(l[i]) ...
938_B. Run For Your Prize
You and your friend are participating in a TV show "Run For Your Prize". At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positi...
```python input() a=list(map(int,input().split())) ans=0 for x in a: z=min(x-1,1000000-x) ans=max(z,ans) print(ans) ```
963_B. Destruction of a Tree
You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or...
```python from collections import defaultdict,deque import sys import bisect import math input=sys.stdin.readline mod=1000000007 def bfs(root,count): q=deque([root]) vis.add(root) while q: vertex=q.popleft() for child in graph[vertex]: if ans[child]==0: ans[child...
990_E. Post Lamps
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked an...
```python import sys from array import array n, m, k = map(int, input().split()) block = list(map(int, input().split())) a = [0] + list(map(int, input().split())) if block and block[0] == 0: print(-1) exit() prev = array('i', list(range(n))) for x in block: prev[x] = -1 for i in range(1, n): if prev...
p02613 AtCoder Beginner Contest 173 - Judge Status Summary
Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A. The problem has N test cases. For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is `AC`,...
```python n=int(input()) S = [] for i in range(n): S.append(input()) for t in ["AC","WA","TLE","RE"]: print(f"{t} x {S.count(t)}") ```
p02744 Panasonic Programming Contest 2020 - String Equivalence
In this problem, we only consider strings consisting of lowercase English letters. Strings s and t are said to be isomorphic when the following conditions are satisfied: * |s| = |t| holds. * For every pair i, j, one of the following holds: * s_i = s_j and t_i = t_j. * s_i \neq s_j and t_i \neq t_j. For example, `a...
```python a='a' exec('a=[s+chr(c)for s in a for c in range(97,ord(max(s))+2)];'*~-int(input())) print(*a) ```
p02879 AtCoder Beginner Contest 144 - 9x9
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation. Given are two integers A and B. If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead. Constraints * 1 \leq A \leq 20 * 1 \leq B ...
```python a,b = map(int,input().split()) print(a*b) if(a<=9 and b<=9) else print(-1) ```
p03013 AtCoder Beginner Contest 129 - Typical Stairs
There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time. However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps. How many are there to climb ...
```python n,m = map(int,input().split()) a_list = [int(input()) for _ in range(m)] dp = [1]*(n+1) for a in a_list: dp[a] = 0 for i in range(2,n+1): if dp[i] != 0: dp[i] = dp[i-1] + dp[i-2] print(dp[n]%(10**9+7)) ```
p03153 KEYENCE Programming Contest 2019 - Connecting Cities
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads. Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from heapq import heappush, heappop, heapify from collections import defaultdict """ ・最小値のある場所を調べる。左右にまたがる辺は結ばない。 ・最小値の両隣は必ず最小値と結ぶ。 ・結んだあと1点に縮約していく。 """ N,D,*A = map(int,read().split()) A = ...
p03297 AtCoder Grand Contest 026 - rng_10s
Ringo Mart, a convenience store, sells apple juice. On the opening day of Ringo Mart, there were A cans of juice in stock in the morning. Snuke buys B cans of juice here every day in the daytime. Then, the manager checks the number of cans of juice remaining in stock every night. If there are C or less cans, D new can...
```python def main(): import math def gcd(a, b): while b: a, b = b, a % b return a N = int(input()) ABCD = [list(map(int, input().split())) for i in range(N)] for A,B,C,D in ABCD: # 在庫が買う本数以下 or 在庫追加が買う本数以下 if A < B or D < B: print("No") ...
p03455 AtCoder Beginner Contest 086 - Product
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. Constraints * 1 ≤ a,b ≤ 10000 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the product is odd, print `Odd`; if it is even, print `Even`. E...
```python print("Odd" if sum([int(i) % 2 for i in input().split()])==2 else "Even") ```
p03616 AtCoder Regular Contest 082 - Sandglass
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb. The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per...
```python X=int(input()) K=int(input()) r=list(map(int,input().split())) Q=int(input()) p=[tuple(map(int,input().split())) for i in range(Q)] N=Q L=0 R=Q-1 start=0 sign="-" # N: 処理する区間の長さ N0 = 2**(N-1).bit_length() data = [0]*(2*N0) INF = 0 # 区間[l, r+1)の値をvに書き換える # vは(t, value)という値にする (新しい値ほどtは大きくなる) def update(l, r...
p03774 AtCoder Beginner Contest 057 - Checkpoints
There are N students and M checkpoints on the xy-plane. The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j). When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance. T...
```python n,m=map(int,input().split()) p=[list(map(int, input().split())) for _ in range(n)] c=[list(map(int, input().split())) for _ in range(m)] for i in p: d=[abs(i[0]-c[j][0])+abs(i[1]-c[j][1]) for j in range(len(c))] print(d.index(min(d))+1) ```
p03943 AtCoder Beginner Contest 047 - Fighting over Candies
Two students of AtCoder Kindergarten are fighting over candy packs. There are three candy packs, each of which contains a, b, and c candies, respectively. Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible. Not...
```python l=sorted(list(map(int,input().split()))) print("Yes" if l[0]+l[1]==l[2] else "No") ```
p00035 Is it Convex?
4 different points on the plane Read the coordinates of $ A (x_a, y_a) $, $ B (x_b, y_b) $, $ C (x_c, y_c) $, $ D (x_d, y_d) $ and read those 4 points Create a program that outputs YES if there is no dent in the quadrangle $ ABCD $ with the coordinates as the vertices, and NO if there is a dent. A quadrangle with a de...
```python def gai(a,b,c,d): S = a*d - b*c return(S) while True: try: x1,y1,x2,y2,x3,y3,xp,yp = map(float,input().split(",")) A1,A2,B1,B2,C1,C2,D1,D2 = x1,y1,x2,y2,x3,y3,xp,yp if gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) < 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) < 0 and gai(x3...
p00167 Bubble Sort
Sorting algorithms for sorting data are basic algorithms indispensable in computer science. For example, as shown in the figure below, the operation of "sorting the elements of an array of integer values ​​in ascending order" is alignment. <image> Many alignment algorithms have been devised, but one of the basic alg...
```python def bubble_sort(n): arr = [int(input()) for _ in range(n)] cnt = 0 for i in range(n): for j in range(n-1, i, -1): if arr[j] < arr[j-1]: arr[j], arr[j-1] = arr[j-1], arr[j] cnt += 1 return cnt while True: n = int(input()) if n == 0: b...
p00323 Metal Recycling
PCK, which recycles Aizu's precious metal, Aizunium, has a network all over the country and collects Aizunium with many collection vehicles. This company standardizes the unit of weight and number of lumps for efficient processing. A unit called "bokko" is used for the weight of the lump. x Bocco's Aidunium weighs 2 x...
```python n = int(input()) size = 200100 total = [0 for _ in range(size)] for _ in range(n): s = sum(map(int, input().split())) total[s] += 1 for i in range(size - 1): if total[i] % 2: print(i, 0) total[i + 1] += total[i] // 2 ```
p00822 Weather Forecast
You are the God of Wind. By moving a big cloud around, you can decide the weather: it invariably rains under the cloud, and the sun shines everywhere else. But you are a benign God: your goal is to give enough rain to every field in the countryside, and sun to markets and festivals. Small humans, in their poor vocabu...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01086 Short Phrase
Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections ...
```python tanku = [5, 7, 5, 7, 7] while True: n = int(input()) if n==0: break w = [len(input()) for i in range(n)] ans = 0 for i in range(n): sum = 0 k = 0 for j in range(i, n): sum += w[j] if sum == tanku[k]: sum = 0 k += 1 if k==5: ans = i+1 ...
p01356 Nearest Station
I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station. Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up ...
```python def solve(): n,m,a,b,p,q = map(int,input().split()) if a==1 and b==1: if (p+q)*n <= m: return m - (p+q)*n else: k = m//(p+q) return min(m-k*(p+q),(k+1)*(p+q)-m) else: ans = m for i in range(min(n-1,40),-1,-1): f = p*(a...
p01538 Kakezan
Taro is an elementary school student who has just learned multiplication. Somehow, he likes multiplication, so when he sees numbers, he wants to multiply. He seems to like to do the following for integers greater than or equal to 0. (Processing flow) * Procedure 1. If a certain integer n greater than or equal to 0 is ...
```python "かけざん" "最大のものを取得して、一桁になるまでに操作を行う回数を答える" def kakezan(n): ret = 0 str_n = str(n) digit_amount = len(str_n) for i in range(digit_amount-1): # print(str_n[:i+1]) # print(str_n[i+1:]) # print("") ret = max(ret, int(str_n[:i+1])*int(str_n[i+1:])) return ret Q...
p01694 Step Aerobics
Step up and down Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and...
```python while True: N = int(input()) if N == 0: break a = input() b = a.split() x = 0 for i in range(N//2): if b[2 * i] == 'lu' and b[(2 * i)+1] == 'ru': x += 1 if b[2 * i] == 'ru' and b[(2 * i)+1] == 'lu': x += 1 if b[2 * i] == 'ld' a...
p01974 Pigeonhole principle
problem Given $ N $ different natural numbers $ a_i $. I decided to make a pair by choosing a different natural number from the given natural numbers. Output one pair that can be created with a value difference that is a multiple of $ N -1 $. It should be noted that such a pair always exists. Example Input 5 1...
```python N = int(input()) a = [int(x) for x in input().split()] x, y = -1, -1 for i in range(N) : for j in range(N) : if i != j and abs(a[i] - a[j]) % (N - 1) == 0 : x, y = i, j print(a[x], a[y]) ```
p02260 Selection Sort
Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: SelectionSort(A) 1 for i = 0 to A.length-1 2 mini = i 3 for j = i to A.length-1 4 if A[j] < A[mini] 5 mini = j 6 swap A[i] and A[mini]...
```python n = int(input()) s = list(map(int, input().split())) indexMin = 0 count = 0 for start in range(n): indexMin = s[start:].index(min(s[start:])) + start s[start], s[indexMin] = s[indexMin], s[start] if start != indexMin: count+=1 print(*s) print(count) ```
p02408 Finding Missing Cards
Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers). The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond. Note 解説 Input In the first line, the number of cards n (n ≤ 52) is given. In the following n line...
```python n=int(input()) cs = [ (s,k) for s in ['S','H','C','D'] for k in range(1,14) ] for _ in range(n): s,k=input().split() cs.remove((s,int(k))) for (s, k) in cs: print(s, k) ```
101_C. Vectors
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А: * Turn the vector by 90 degrees clockwise. * Add to the vector a certain vector C. Operations could be performed in any order any number of times. ...
```python import math def ok(xa, ya): x, y = xb - xa, yb - ya d = math.gcd(abs(xc), abs(yc)) if xc == 0 and yc == 0: return x == 0 and y == 0 if xc == 0: return x % yc == 0 and y % yc == 0 if yc == 0: return x % xc == 0 and y % xc == 0 if (x % d != 0) or (y % d != 0): ...
1043_A. Elections
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t...
```python import math n = int(input()) l= list(map(int,input().split())) s = 2*sum(l) z= s/n p = max(l) an = int(z+1) print(max(p,an)) ```
1107_D. Compression
You are given a binary matrix A of size n × n. Let's denote an x-compression of the given matrix as a matrix B of size n/x × n/x such that for every i ∈ [1, n], j ∈ [1, n] the condition A[i][j] = B[⌈ i/x ⌉][⌈ j/x ⌉] is met. Obviously, x-compression is possible only if x divides n, but this condition is not enough. For...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup------------------------...
1136_D. Nastya Is Buying Lunch
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to de...
```python import sys import math import bisect from math import sqrt def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) mod = int(1e9)+...
End of preview. Expand in Data Studio

This dataset is based on the "code_contests" dataset by DeepMind, licensed under CC BY 4.0. Original dataset available at: https://huggingface.co/datasets/deepmind/code_contests

このデータセットは、deepmind/code_contestsからAtCoderのデータのみを抽出し、Pythonで正解として提出された最初のコードを取得して格納したものです。これにより、教師あり学習に適した形に整えられています。

This dataset is created by extracting only the data from AtCoder within deepmind/code_contests and retrieving the first Python code submission marked as correct. As a result, it has been formatted to be suitable for supervised learning.

Dataset({
    features: ['name', 'description', 'solutions'],
    num_rows: 8139
})

First element example

description

There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.

We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: 

  * Either this person does not go on the trip, 
  * Or at least k of his friends also go on the trip. 



Note that the friendship is not transitive. That is, if a and b are friends and b and c are friends, it does not necessarily imply that a and c are friends.

For each day, find the maximum number of people that can go on the trip on that day.

Input

The first line contains three integers n, m, and k (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5, 1 ≤ k < n) — the number of people, the number of days and the number of friends each person on the trip should have in the group.

The i-th (1 ≤ i ≤ m) of the next m lines contains two integers x and y (1≤ x, y≤ n, x≠ y), meaning that persons x and y become friends on the morning of day i. It is guaranteed that x and y were not friends before.

Output

Print exactly m lines, where the i-th of them (1≤ i≤ m) contains the maximum number of people that can go on the trip on the evening of the day i.

Examples

Input

4 4 2
2 3
1 2
1 3
1 4


Output

0
0
3
3


Input

5 8 2
2 1
4 2
5 4
5 2
4 3
5 1
4 1
3 2


Output

0
0
0
3
3
4
4
5


Input

5 7 2
1 5
3 2
2 5
3 4
1 2
5 3
1 3


Output

0
0
0
0
3
4
4

Note

In the first example, 

  * 1,2,3 can go on day 3 and 4. 



In the second example, 

  * 2,4,5 can go on day 4 and 5. 
  * 1,2,4,5 can go on day 6 and 7. 
  * 1,2,3,4,5 can go on day 8. 



In the third example, 

  * 1,2,5 can go on day 5. 
  * 1,2,3,5 can go on day 6 and 7.

solutions

```python
from collections import deque

def solve(adj, m, k, uv):
    n = len(adj)
    nn = [len(a) for a in adj]
    q = deque()
    for i in range(n):
        if nn[i] < k:
            q.append(i)
    while q:
        v = q.popleft()
        for u in adj[v]:
            nn[u] -= 1
            if nn[u] == k-1:
                q.append(u)
    res = [0]*m
    nk = len([1 for i in nn if i >= k])
    res[-1] = nk
    for i in range(m-1, 0, -1):
        u1, v1 = uv[i]

        if nn[u1] < k or nn[v1] < k:
            res[i - 1] = nk
            continue
        if nn[u1] == k:
            q.append(u1)
            nn[u1] -= 1
        if not q and nn[v1] == k:
            q.append(v1)
            nn[v1] -= 1

        if not q:
            nn[u1] -= 1
            nn[v1] -= 1
            adj[u1].remove(v1)
            adj[v1].remove(u1)

        while q:
            v = q.popleft()
            nk -= 1
            for u in adj[v]:
                nn[u] -= 1
                if nn[u] == k - 1:
                    q.append(u)
        res[i - 1] = nk
    return res

n, m, k = map(int, input().split())
a = [set() for i in range(n)]
uv = []
for i in range(m):
    u, v = map(int, input().split())
    a[u - 1].add(v - 1)
    a[v - 1].add(u - 1)
    uv.append((u-1, v-1))

res = solve(a, m, k, uv)
print(str(res)[1:-1].replace(' ', '').replace(',', '\n'))
```                  
Downloads last month
19