name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1194_D. 1-2-K Game
Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one). Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the ch...
```python from sys import stdin, stdout from collections import Counter def rsingle_int(): return int(stdin.readline().rstrip()) def rmult_int(): return [ int(x) for x in stdin.readline().rstrip().split() ] def rmult_str(): return stdin.readline().rstrip().split() def r_str(): return stdin.readli...
1276_C. Beautiful Rectangle
You are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen. A rectangle (rectangular matrix)...
```python n = int(input()) arr = list(map(int, input().split())) d = {} for i in arr: d[i] = d.get(i, 0) + 1 d2 = {} for k, v in d.items(): d2.setdefault(v, []).append(k) s = n prev = 0 ansp = ansq = anss = 0 for p in range(n, 0, -1): q = s // p if p <= q and q * p > anss: anss = q * p ...
1296_D. Fight with Monsters
There are n monsters standing in a row numbered from 1 to n. The i-th monster has h_i health points (hp). You have your attack power equal to a hp and your opponent has his attack power equal to b hp. You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it...
```python n,a,b,k= map(int,input().split()) l=[int(x) for x in input().split()] power=[] for x in l: rem=x%(a+b) if rem==0: if b%a!=0: power.append((b//a)+1) else: power.append((b//a)) else: if rem<=a: power.append(0) else: if (rem-a)%a==0: power.append(((rem-a)//a)) else: power....
131_D. Subway
A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to mo...
```python import sys from collections import deque sys.setrecursionlimit(30000) sz = 3333 cyclic = 0 begin = 0 end = 0 cycle = [] graph = [] used = [] parent = [] dist = [] def dfs(current,prev): global graph,begin,end,used,parent used[current] = 1 for nxt in graph[current]: if used[nxt] != 2 and n...
1339_A. Filling Diamonds
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
```python n = int(input()) for _ in range(n): a = input() print(a) ```
1360_E. Polygon
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2...
```python def solve(): n = int(input()) polygon = [None for i in range(n)] for i in range(n): polygon[i] = list(map(int, input())) for i in range(n - 2, -1, -1): for j in range(i, -1, -1): if polygon[i][j] == 1: if polygon[i][j + 1] == 0 and polygon[i + 1][...
1380_F. Strange Addition
Let a and b be some non-negative integers. Let's define strange addition of a and b as following: 1. write down the numbers one under another and align them by their least significant digit; 2. add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite n...
```python from sys import stdin import sys class LazySegTree: def __init__(self,N,first): self.LV = (N-1).bit_length() self.NO = 2**self.LV self.First = first self.data = [first] * (2*self.NO) self.lazy = [None] * (2*self.NO) def calc(self,l,r): retur...
1424_F. Coins
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them: All of them take a sit at their round table, some of them with the golde...
```python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
1445_B. Elimination
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests. A result of the elimination stage is the tota...
```python for k in range(int(input())): a, b, c, d = input().split() a, b, c, d = int(a), int(b), int(c), int(d) if a+b >= c+d: print(a+b) else: print(c + d) ```
146_B. Lucky Mask
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of...
```python s=input() a,b=(s.split()[0]),(s.split()[1]) dif=len(a)-len(b) mask='' tmp=int(a) tmp+=1 t=str(tmp) while(1): for i in t: if(i in ['4','7']): mask+=i if(mask==b): break else: tmp+=1 t=str(tmp) mask='' print(tmp) ```
1495_D. BFS Trees
We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are ...
```python import sys, os from collections import defaultdict, deque if os.environ['USERNAME']=='kissz': inp=open('in2.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def solve(): n,m=map(...
1519_A. Red and Blue Beans
You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: * has at least one red bean (or the number of red beans r_i ≥ 1); * has at least one blue bean (or the number of blue beans b_i ≥ 1); * the number of red and blue beans should diff...
```python def solve(): r, b, d = map(int, input().split(' ')) packets = min(r, b) ma = max(r, b) if d == 0: if r == b: return "YES" return "NO" needed = -1 if ma % packets == 0: needed = ma // packets else: needed = ma // packets + 1 if (n...
1546_A. AquaMoon and Two Arrays
AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays a and b, both consist of n non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero): * She chooses two indices i and j (1 ≤ i, j ≤ n), then decreases the i-th element ...
```python cases=int(input()) for idx in range(cases): n=int(input()) a=list(map(int, input().split())) b=list(map(int, input().split())) if sum(a)!=sum(b): print(-1) elif a==b: print(0) else: tuples=[] count=0 for i in range(n): if a[i]==b[i]: continue ...
173_B. Chamber of Secrets
"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anyb...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write i...
193_C. Hamming Distance
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have ...
```python def get_input(): a, b, d = map(int, input().split()) c, e = map(int, input().split()) f = int(input()) return [a, b, c, d, e, f] def check_condition(a, b, c, d, e, f): condition1 = (a + b + c) % 2 == 0 condition2 = (d + e + a) % 2 == 0 condition3 = (e + f + c) % 2 == 0 ...
266_A. Stones on the Table
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
```python n=int(input()) word=input() count=0 for i in range(0,n-1): if word[i]==word[i+1]: count+=1 print(count) ```
28_A. Bender Problem
Robot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate ...
```python from collections import defaultdict def main(): n, m = map(int, input().split()) tmp = list(tuple(map(int, input().split())) for _ in range(n)) nails = [abs(a - c) + abs(b - d) for (a, b), (c, d) in zip(tmp, tmp[2:] + tmp[:2])] segments = defaultdict(list) for i, s in enumerate(map(int, ...
315_A. Sereja and Bottles
Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle ...
```python n = int(input()) a = [] b = [] for i in range(n): ap, bp = map(int, input().split()) a.append(ap) b.append(bp) ok = [False] * n for i in range(n): for j in range(n): if b[i] == a[j] and i != j: ok[j] = True print(ok.count(False)) ```
337_C. Quiz
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,...
```python import os import sys from io import BytesIO, IOBase import math def main(): pass # region fastio 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 ...
383_C. Propagating tree
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1. This tree has a special property: when a value val is added to a value of node i, the value -val is ...
```python class BIT(): """区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する add: 区間[begin, end)にvalを加える get_val: i番目(0-indexed)の値を求める """ def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def get_val(self, i): i = i + 1 s = 0 while i <= self.n: ...
404_B. Marathon
Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes. As the length of t...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def main(): a, d =map(float, input().split(' ')) ans = [] for i in range(1, int(input()) + 1): cur_round_pos = d * i % (a * 4) if cur_round_pos <= a: y = 0 x = cur_round_pos elif cur_round...
431_C. k-Tree
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree. A k-tree is an infinite rooted tree where: * each vertex has exactly k children; * each edge has some weight; * if we look at the edges that goes ...
```python n,k,d = input().split() n,k,d = int(n),int(k),int(d) ans1 = [0 for _ in range(101)] ans1[0] = 1 ans = [0 for _ in range(101)] for i in range(d): ans[i] = 0 for i in range(0,n + 1): j = 1 while j <= k and i - j >= 0: ans1[i] += ans1[i - j] j += 1 for i in range(d,n + 1)...
476_C. Dreamoon and Sums
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of...
```python a, b = (input()).split(' ') a = int(a) b=int(b) result = a*b*(b-1)*(a*b+b+2)//4 #result = int(result) result = result % ( 10**9 +7) print((result)) ```
49_D. Game
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can...
```python n=int(input()) def hamming(a,b): global n ret=0 for i in range(n): ret+=int(a[i]!=b[i]) return ret s=input() a=['0' if q%2==0 else '1' for q in range(n)] b=['0' if q%2==1 else '1' for q in range(n)] print(min(hamming(s,a),hamming(s,b))) ```
524_D. Social Network
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarp...
```python def main(): mode="filee" if mode=="file":f=open("test.txt","r") get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()] gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")] [n,m,t]=get() [a,b]=[[0]*20002,[0]*20002] ...
599_C. Day at the Beach
One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles. At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the heig...
```python n = int(input()) hs = list(map(int, input().split())) max_h = 0 rs = [] max_hs = [0] * n for i, h in enumerate(hs): rs.append((h, i)) max_h = max(max_h, h) max_hs[i] = max_h rs.sort() p, r = 0, -1 ans = 0 while r < n - 1: nh, nr = rs[p] if r >= nr: p += 1 else: r = nr ...
620_B. Grandfather Dovlet’s calculator
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (<https://en.wikipedia.org/wiki/Seven-segment_display>). <image> Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find t...
```python #!/usr/bin/env python3 if __name__ == '__main__': a, b = map(int, input().split()) act = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6] r = 0 for i in range(a, b+1): r += sum(act[ord(c)-ord('0')] for c in str(i)) print(r) ```
641_A. Little Artem and Grasshopper
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him. The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grassh...
```python n = int(input()) s = input() arr = list(map(int, input().split())) seen = set() current_index = 0 while True: command = s[current_index] step = arr[current_index] if command == ">": current_index += step else: current_index -= step # print(current_index) if current_...
690_E1. Photographs (I)
The Human-Cow Confederation (HC2), led by Heidi, has built a base where people and cows can hide, guarded from zombie attacks. The entrance to the base is protected by an automated gate which performs a kind of a Turing test: it shows the entering creature a photograph and asks them whether the top and bottom halves of...
```python a = '''YES NO NO YES NO NO NO NO NO YES YES YES YES YES NO YES NO YES NO YES NO NO YES NO NO YES NO NO YES YES NO YES NO YES NO YES YES YES NO YES YES NO YES YES NO YES YES YES NO YES NO NO NO YES YES YES YES NO NO NO YES NO NO NO NO NO NO NO YES NO YES NO YES NO NO NO YES YES NO YES YES NO NO NO NO NO NO YES...
715_A. Plus and Square Root
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : 1. Pr...
```python import sys from math import * from fractions import gcd readints=lambda:map(int, input().strip('\n').split()) n=int(input()) prev=2 for i in range(1,n+1): nxt = (i*(i+1))**2 cur = (nxt-prev)//i print(cur) prev=int(sqrt(nxt)) ```
735_C. Tennis Championship
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately. Organizers are stil...
```python f = [0, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 113490...
75_C. Modified GCD
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers. A common divisor for two positive numbers is a number which both numbers are divisible by. But your teacher wants to give you a harder task, in this task...
```python import math from sys import * from bisect import bisect_right input=stdin.readline print=stdout.write a,b=map(int,input().split()) n=int(input()) gcd=math.gcd(a,b) ##print(gcd) factors=[] i=1 while(i*i<=gcd): if gcd%i==0: factors.append(gcd//i) if (i*i)!=gcd: factors.append...
780_B. The Meeting Place Cannot Be Changed
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction. At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi ...
```python def solve(t,x,v): l=[x[i]-v[i]*t for i in range(len(x))] r=[x[i]+v[i]*t for i in range(len(x))] return 1 if max(l)<=min(r) else 0 n=int(input()) x=list(map(int,input().split())) v=list(map(int,input().split())) l=0 h=10**9 cnt=0 while l<h and cnt<100: mid=l+(h-l)/2 cnt+=1 if solve(mid...
803_F. Coprime Subsequences
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1. Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7. Note th...
```python # 803F import math import collections def do(): n = int(input()) nums = map(int, input().split(" ")) count = collections.defaultdict(int) for num in nums: for i in range(1, int(math.sqrt(num))+1): cp = num // i if num % i == 0: count[i] += 1 ...
828_D. High Load
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be ...
```python import sys def main(): n,k = map(int,sys.stdin.readline().split()) a = n-k if a ==1: print(2) for i in range(k): print(1,i+2) elif a > k+1 : l = ((a-1)//k +1)*2 if (a-1)%k>1: print(l+2) elif (a-1)%k==1: print(l+1) ...
84_E. Track
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle n × m in size divi...
```python import sys from array import array # noqa: F401 from itertools import combinations from collections import deque def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) chars = ( ['}' * (m + 2)] + ['}' + ''.join('{' if c == 'S' else '|' if c == 'T' ...
873_B. Balanced Substring
You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring. You have to determine the length of the longest balanc...
```python inp=lambda:map(int,input().split()) n=int(input()) s=input() a0=[0]*(10**5+1) a1=[0]*(10**5+1) if(s[0]=='0'): a0[0]=1 else: a1[0]=1 for i in range(1,n): if(s[i]=='0'): a0[i]=a0[i-1]+1 a1[i]=a1[i-1] else: a0[i]=a0[i-1] a1[i]=a1[i-1]+1 lab=[-2]*(2*10**5+1) m=[...
899_A. Splitting in Teams
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams...
```python n = int(input()) a = list(map(int,input().split())) one = a.count(1) two = a.count(2) def func(a,b): if(a>b): count = b a = a-b count = count + a//3 elif(b>a): count = a a = a-count elif(a==b): count = a return count if(one==0): pri...
91_B. Queue
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus stan...
```python n = int(input()) A = [int(i) for i in input().split()] suf = [[10**10, -1] for i in range(n)] from bisect import bisect_left suf[-1][0] = A[-1] suf[-1][1] = n-1 for i in range(n-2, -1, -1): if suf[i+1][0] > A[i]: suf[i][0] = A[i] suf[i][1] = i else: suf[i][0] = suf[i+1][0] ...
975_E. Hag's Khashba
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering. Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and othe...
```python from sys import stdin from math import * rl = lambda l: tuple(map(int, l.split())) rd = lambda: rl(input()) class Point(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, pt): return Point(self.x + pt.x, self.y + pt.y) def __iadd__(self, pt): retur...
995_D. Game
Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n → R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a mo...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time (n, r) = (int(i) for i in input().split()) c = [int(i) for i in input().split()] start = time.time() s = sum(c) n2 = 2**n ans = [s/n2] for i in range(r): (k, new) = (int(i) for i in input().split()) s += new - c[k] c[k] ...
p02644 AtCoder Beginner Contest 170 - Pond Skater
Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west. Some of the squares have a lotus leaf on it and cannot be entered. The square (i,j) has a lotus leaf on i...
```python from collections import deque dxdy = ((-1,0), (1,0), (0,-1), (0,1)) # タプルやリストで持っておくと便利 H, W, K = map(int,input().split()) x1, y1, x2, y2 = map(int,input().split()) mp = [input() for _ in range(H)] INF = 10**10 dist = [[INF]*W for _ in range(H)] dist[x1-1][y1-1] = 0 q = deque() q.append((x1-1,y1-1)) # スタート地点を...
p02773 AtCoder Beginner Contest 155 - Poll
We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it. Print all strings that are written on the most number of votes, in lexicographical order. Constraints * 1 \leq N \leq 2 \times 10^5 * S_i (1 \leq i \leq N) are strings consisting of lowercase English letters. * The length of S...
```python from collections import Counter n=int(input()) a=[input() for _ in range(n)] c=Counter(a) max_cnt=max(c.values()) names=[name for name,v in c.items() if v==max_cnt] names.sort() print(*names,sep='\n') ```
p03043 AtCoder Beginner Contest 126 - Dice and Coin
Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them: 1. Throw the die. The current score is the result of the die. 2. As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each t...
```python import math n,k=map(int,input().split()) ans=0 for i in range(1,n+1): ans+=(1/2)**math.ceil(max(math.log2(k/i),0)) print(ans/n) ```
p03185 Educational DP Contest - Frog 3
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i. Here, h_1 < h_2 < \cdots < h_N holds. There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N: * If the frog is currently on Stone i, jump to one of ...
```python def fi(i, x): a, b = lines[i] return a*x+b def find(x): def f(i): return fi(i+1,x) > fi(i,x) mn, mx = -1, len(lines)-1 idx = (mn+mx)//2 while mx-mn>1: if f(idx): mx, idx = idx, (mn + idx)//2 continue mn, idx = idx, (mx + idx)//2 retu...
p03332 AtCoder Grand Contest 025 - RGB Coloring
Takahashi has a tower which is divided into N layers. Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower. He defines the beauty of the tower as follows: * The beauty of the tower is the sum of the scores of the N layers, where the sco...
```python N, A, B, K = map(int, input().split()) mod = 998244353 # 階乗 & 逆元計算 factorial = [1] inverse = [1] for i in range(1, N+2): factorial.append(factorial[-1] * i % mod) inverse.append(pow(factorial[-1], mod-2, mod)) # 組み合わせ計算 def nCr(n, r): if n < r or r < 0: return 0 elif r == 0: ...
p03491 AtCoder Regular Contest 087 - Prefix-free Game
For strings s and t, we will say that s and t are prefix-free when neither is a prefix of the other. Let L be a positive integer. A set of strings S is a good string set when the following conditions hold true: * Each string in S has a length between 1 and L (inclusive) and consists of the characters `0` and `1`. * A...
```python """ Writer: SPD_9X2 https://atcoder.jp/contests/arc087/tasks/arc087_c 初期状態で出ている数字を木としてあらわす 数字でふさがっている所はもう追加できない まだおけるのは、空いている部分だけ Lがでかいので、深さを考えていては死ぬ そのままふさぐと、置ける場所は1減る 伸ばしておけば、Lまで増やして置ける 置ける場所の偶奇か? 置ける場所が0で来たら負け→初手が奇数なら先手勝ち・そうでないなら後手勝ち? 伸ばせる奴は偶奇反転に使える 部分で考えてみるか→ Grundy数計算 深さ1の部分木のGrundy → 1 深さ2の部分木のGr...
p03653 AtCoder Grand Contest 018 - Coins
There are X+Y+Z people, conveniently numbered 1 through X+Y+Z. Person i has A_i gold coins, B_i silver coins and C_i bronze coins. Snuke is thinking of getting gold coins from X of those people, silver coins from Y of the people and bronze coins from Z of the people. It is not possible to get two or more different col...
```python from heapq import heappushpop import sys X, Y, Z = map(int, sys.stdin.readline().split()) N = X+Y+Z ABC = [list(map(int, sys.stdin.readline().split())) for _ in range(N)] ABC.sort(key = lambda x: x[0] - x[1], reverse = True) GB = [None]*N Q = [a - c for a, _, c in ABC[:X]] Q.sort() gs = sum(a for a, _, _ in ...
p03809 AtCoder Grand Contest 010 - Cleaning
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation: * Select a pair of different...
```python import sys sys.setrecursionlimit(10 ** 6) def dfs(v, p, aaa): if len(links[v]) == 1: return aaa[v] children = [] for u in links[v]: if u == p: continue result = dfs(u, v, aaa) if result == -1: return -1 children.append(result) ...
p03977 Kyoto University Programming Contest 2016 - Cookie Breeding Machine
A professor invented Cookie Breeding Machine for his students who like cookies very much. When one cookie with the taste of x is put into the machine and a non-negative integer y less than or equal to 127 is input on the machine, it consumes the cookie and generates two cookies with the taste of y and (x XOR y). Here...
```python N,T=0,0 for i in range(int(input())): N,T=map(int,input().split()) if N&1==0: T^=127 print(T+(N-1)*127) ```
p00066 Tic Tac Toe
Tic-tac-toe is a game in which you win when you put ○ and × alternately in the 3 × 3 squares and line up ○ or × in one of the vertical, horizontal, and diagonal lines (Fig.). 1 to Fig. 3) <image> | <image> | <image> --- | --- | --- Figure 1: ○ wins | Figure 2: × wins | Figure 3: Draw In tic-tac-toe, ○ and × alterna...
```python ok = [[0,4,8], [2,4,6], [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8]] while True: try: s = input() except EOFError: break flag = False for i in ok: if s[i[0]] == s[i[1]] == s[i[2]] and s[i[0]] != 's': print(s[i[0]]) flag = True ...
p00198 Trouble in Shinagawa's Artifacts
Artist Shinagawa was asked to exhibit n works. Therefore, I decided to exhibit the six sides of the cube colored with paint as a work. The work uses all six colors, Red, Yellow, Blue, Magenta, Green, and Cyan, and each side is filled with one color. Shinagawa changed the arrangement of colors even for cubic works with ...
```python D = [ (1, 5, 2, 3, 0, 4), # 'U' (3, 1, 0, 5, 4, 2), # 'R' (4, 0, 2, 3, 5, 1), # 'D' (2, 1, 5, 0, 4, 3), # 'L' ] p_dice = (0, 0, 0, 1, 1, 2, 2, 3)*3 def rotate_dice(L0): L = L0[:] for k in p_dice: yield L L[:] = (L[e] for e in D[k]) while 1: N = int(input()) if...
p00352 Handsel
Alice and Brown are brothers in a family and each receives pocket money in celebration of the coming year. They are very close and share the total amount of the money fifty-fifty. The pocket money each receives is a multiple of 1,000 yen. Write a program to calculate each one’s share given the amount of money Alice an...
```python a, b = map(int, input().split()) cash = (a+b)//2 print(cash) ```
p00559 Foehn Phenomena
In the Kingdom of IOI, the wind always blows from sea to land. There are $N + 1$ spots numbered from $0$ to $N$. The wind from Spot $0$ to Spot $N$ in order. Mr. JOI has a house at Spot $N$. The altitude of Spot $0$ is $A_0 = 0$, and the altitude of Spot $i$ ($1 \leq i \leq N$) is $A_i$. The wind blows on the surface ...
```python n, q, s, t = map(int, input().split()) a_lst = [int(input()) for _ in range(n + 1)] diff = [a_lst[i + 1] - a_lst[i] for i in range(n)] temp = sum([-d * s if d > 0 else -d * t for d in diff]) def score(d): if d > 0: return -s * d else: return -t * d for _ in range(q): l, r, x = map(int, input().s...
p00712 Unit Fraction Partition
A fraction whose numerator is 1 and whose denominator is a positive integer is called a unit fraction. A representation of a positive rational number p/q as the sum of finitely many unit fractions is called a partition of p/q into unit fractions. For example, 1/2 + 1/6 is a partition of 2/3 into unit fractions. The dif...
```python from fractions import gcd def solve(p, q, a, n, l=1): ans = 1 if p==1 and q<=a and q>=l else 0 denom = max(l, q//p) p_denom = denom*p while n*q >= p_denom and denom <= a: #n/denom >= p/q: p_, q_ = p_denom-q, q*denom if p_ <= 0: denom += 1 p_denom += p ...
p00983 Reordering the Documents
Reordering the Documents Susan is good at arranging her dining table for convenience, but not her office desk. Susan has just finished the paperwork on a set of documents, which are still piled on her desk. They have serial numbers and were stacked in order when her boss brought them in. The ordering, however, is not...
```python def main(): mod = 10 ** 9 + 7 n, m = map(int, input().split()) a = [int(x) for x in input().split()] if not m: print(0) return mx = [0] * (n + 1) mn = [mod] * (n + 1) for i in range(n): if mx[i] > a[i]: mx[i + 1] = mx[i] else: ...
p01115 Expression Mining
Expression Mining Consider an arithmetic expression built by combining single-digit positive integers with addition symbols `+`, multiplication symbols `*`, and parentheses `(` `)`, defined by the following grammar rules with the start symbol `E`. E ::= T | E '+' T T ::= F | T '*' F F ::= '1' | '2' | '3' | '4' | '5'...
```python import sys readline = sys.stdin.readline write = sys.stdout.write sys.setrecursionlimit(10**5) def solve(): N = int(readline()) if N == 0: return False S = readline().strip() + "$" L = len(S) pt = [0]*L st = [] for i in range(L): if S[i] == '(': st.appen...
p01414 Rectangular Stamps
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to increase creativity by drawing pictures. Let's draw a pattern well using a square stamp. I want to use stamps of various sizes to complete the picture of the red, ...
```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 ...
p01568 Repairing
In the International City of Pipe Construction, it is planned to repair the water pipe at a certain point in the water pipe network. The network consists of water pipe segments, stop valves and source point. A water pipe is represented by a segment on a 2D-plane and intersected pair of water pipe segments are connected...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def dot3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy) def cross3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (by - oy) - (bx ...
p02005 Colorful Drink
In the Jambo Amusement Garden (JAG), you sell colorful drinks consisting of multiple color layers. This colorful drink can be made by pouring multiple colored liquids of different density from the bottom in order. You have already prepared several colored liquids with various colors and densities. You will receive a d...
```python import sys liquids={} O=[] N = int(input()) for i in range(N): C,D=(input().split()) if C in liquids.keys(): liquids[C].append(int(D)) else: liquids[C]=[] liquids[C].append(int(D)) for i in liquids.keys(): liquids[i]=list(set(liquids[i])) liquids[i].sort() M = int...
p02149 Lunch
Problem One day, Kawabayashi is about to have lunch at the school cafeteria. There are three types of daily lunch menus for school cafeterias: A lunch, B lunch, and C lunch. Kawabayashi is a glutton, so I would like to eat all three types of daily lunch menus one by one. However, Kawabayashi decided to put up with one...
```python a, b, c = map(int, input().split()) if a > b and a > c: print ('A') elif b > a and b > c: print ('B') else: print('C') ```
p02290 Projection
For given three points p1, p2, p, find the projection point x of p onto p1p2. <image> Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xi, yi ≤ 10000 * p1 and p2 are not identical. Input xp1 yp1 xp2 yp2 q xp0 yp0 xp1 yp1 ... xpq−1 ypq−1 In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 0 0 3 4 1 2 5 output: 3.1200000000 4.1600000000 """ import sys class Segment(object): __slots__ = ('source', 'target') def __init__(self, source, target): self.source = complex(source) self.target = complex(target) def do...
p02437 Priority Queue
Priority queue is a container of elements which the element with the highest priority should be extracted first. For $n$ priority queues $Q_i$ ($i = 0, 1, ..., n-1$) of integers, perform a sequence of the following operations. * insert($t$, $x$): Insert $x$ to $Q_t$. * getMax($t$): Report the maximum value in $Q_t$. ...
```python import sys from collections import defaultdict from heapq import heappop, heappush n = int(sys.stdin.readline().split()[0]) A = defaultdict(list) ans = [] for query in sys.stdin: if query[0] == '0': t, x = query[2:].split() heappush(A[t], -int(x)) elif query[0] == '1': if A[que...
1020_B. Badge
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick. Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ...
```python n = int(input()) p = list(map(int, input().split())) for i in range(len(p)): p[i] = p[i] - 1 ans = [0] * len(p) for i in range(len(p)): visit = [0] * len(p) visit[i] = 1 p0 = i while True: pp = p[p0] if (visit[pp] == 1): ans[i] = pp break else: visit[pp] = 1 p0...
1043_E. Train Hard, Win Easy
Zibi is a competitive programming coach. There are n competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems. Rules of scoring also are...
```python import sys n,m = [int(x) for x in sys.stdin.buffer.readline().split()] inp = [int(x) for x in sys.stdin.buffer.read().split()] order = sorted(range(n),key=lambda i:inp[2*i]-inp[2*i+1]) score = [0]*n val = sum(inp[1:2*n:2]) for ind in range(n): i = order[ind] # Do second problem together with orde...
1066_C. Books Queries
You have got a shelf and want to put some books on it. You are given q queries of three types: 1. L id — put a book having index id on the shelf to the left from the leftmost existing book; 2. R id — put a book having index id on the shelf to the right from the rightmost existing book; 3. ? id — calculate the...
```python from sys import * n = int(stdin.readline()) A = {} i ,j = 1,0 # print(i,j) for l in range(n): x, y = stdin.readline().split("\n") x, k = map(str,x.split()) k = int(k) if(x=='?'): stdout.write(str(min(A[k]-i , j-A[k]))+'\n') elif(x=='R'): j += 1 A[k] = j else: i -= 1 A[k] = i ```
1089_F. Fractions
You are given a positive integer n. Find a sequence of fractions (a_i)/(b_i), i = 1 … k (where a_i and b_i are positive integers) for some k such that: $$$ \begin{cases} $b_i$ divides $n$, $1 < b_i < n$ for $i = 1 … k$ \\\ $1 ≤ a_i < b_i$ for $i = 1 … k$ \\\ \text{$∑_{i=1}^k (a_i)/(b_i) = 1 - 1/n$} \end{cases} $$$ I...
```python from math import sqrt from itertools import count, islice from fractions import Fraction def isPrime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n) - 1))) def factors(n: int): _factors = [] for i in range(2, int(sqrt(n)) + 1): times = 0 while n % i == 0: ...
1108_A. Two distinct points
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. <image> The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an...
```python qry=int(input()) for _ in range(qry): lrs=list(map(int,input().split())) if lrs[0]==lrs[2]: print(lrs[0],lrs[3]) else: print(lrs[0],lrs[2]) ```
1178_B. WOW Factor
Recall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", ...
```python s = input() n = len(s) count_o = [] count_w = 0 count = 0 for i in range(1, n): if s[i] == 'v' and s[i-1] == 'v': count_w += 1 elif s[i] == 'o': count_o.append(count_w) for c in count_o: count += c * (count_w-c) print(count) ```
1196_B. Odd Sum Segments
You are given an array a consisting of n integers a_1, a_2, ..., a_n. You want to split it into exactly k non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the e...
```python import math import sys for _ in range(int(input())): n,k=map(int,sys.stdin.readline().split()) l=list(map(int,sys.stdin.readline().split())) c=0 for i in l: if i%2!=0: c+=1 if c%2!=k%2 or c<k: print("NO") else: print("YES") cnt=1 for ...
1213_D1. Equalizing by Division (easy version)
The only difference between easy and hard versions is the number of elements in the array. You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋). You can perform such an operation any (possibl...
```python import collections import functools import math import sys import bisect def In(): return map(int, sys.stdin.readline().split()) input = sys.stdin.readline def eqdiv(): n,k = In() cost = [0]*int(1e5*2+10) count = cost[:] l = list(In()) l.sort() for i in l: i = int(i) ...
1236_E. Alice and the Unfair Game
Alice is playing a game with her good friend, Marisa. There are n boxes arranged in a line, numbered with integers from 1 to n from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have m chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, ...
```python import sys input = sys.stdin.readline n,m=map(int,input().split()) A=list(map(int,input().split())) if n==1: print(0) sys.exit() from collections import Counter R=Counter() L=Counter() for i in range(n): R[i+1]=1 L[i+1]=1 for i,a in enumerate(A): x=R[a-(i+1)] del R[a-(i+1)] R[...
1278_C. Berry Jam
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were 2n jars of strawberry and blueberry jam. All the 2n jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exa...
```python import os, sys, atexit from io import BytesIO, StringIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline _OUTPUT_BUFFER = StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) t = int(input()) while t: n = int(input()) l...
1321_D. Navigation System
The map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along...
```python import sys from collections import deque def bfs(g,src,d,found): q=deque() q.append(src) d[src]=0 while q: rmv=q.popleft() for child in g[rmv]: if d[child]==-1: d[child]=d[rmv]+1 q.append(child) found[child]=1 ...
1340_C. Nastya and Unexpected Guest
If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya. On the way from Denis's house to the girl's house is a road of n lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place s...
```python import collections n,m=map(int,input().split()) arr=list(map(int,input().split())) arr=sorted(arr) g,r=map(int,input().split()) q=collections.deque() q.append((0,0,0)) checked=[[-1]*(g) for _ in range(m)] checked[0][0]=0 while len(q)!=0: v,t,cnt=q.popleft() if v!=m-1: cost1=arr[v+1]-arr[v] if t+c...
1362_C. Johnny and Another Rating Drop
The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills. The boy is now looking at the ratings of consecutive participan...
```python class Solution(): def __init__(self): for t in range(int(input())): n = int(input()) self.solve(n) def solve(self, n): b = format(n, "b") res = 0 while b: res += int(b, 2) b = b[:-1] print(res) Solution() ``...
1382_D. Unmerge
Let a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array merge(a,b) of length n+m recursively as follows: * If one of the arrays is empty, the result is the other array. That is, merge(∅,b)=b and merge(a,∅)=a. In particular, merge(∅,∅)=∅. * If both arrays a...
```python def isSubsetSum(set, n, sum): # The value of subset[i][j] will be # true if there is a # subset of set[0..j-1] with sum equal to i subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) # If sum is 0, then answer is true for i in range(n +...
1425_D. Danger of Mad Snakes
Mr. Chanek The Ninja is one day tasked with a mission to handle mad snakes that are attacking a site. Now, Mr. Chanek already arrived at the hills where the destination is right below these hills. The mission area can be divided into a grid of size 1000 × 1000 squares. There are N mad snakes on the site, the i'th mad s...
```python # from __future__ import print_function,division # range = xrange import sys input = sys.stdin.readline sys.setrecursionlimit(10**4) from sys import stdin, stdout from collections import defaultdict, Counter from functools import lru_cache M = 10**9+7 fact = [1]*(2001) def fac(n): if(n==0 or n==1): ...
1447_B. Numbers Box
You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it. You can perform the following operation any number of times (possibly zero): * Choose any two adjacent cells and multiply the values in them b...
```python N = int(input()) for _ in range(N): n,m = map(int,input().split()) a = list() for i in range(n): a += list(map(int,input().split())) a.sort() minAbs = 101 countNegative = 0 for i in range(len(a)): if a[i] <= 0: countNegative += 1 a[i]...
1472_A. Cards for Friends
For the New Year, Polycarp decided to send postcards to all his n friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size w × h, which can be cut into pieces. Polycarp can cut any sheet of paper w × h that he has in only two cases: * If w is even, then he can cut t...
```python import sys def cardsForFriends(): for _ in range(int(input())): w, h, n = map(int, input().split()) ans, tmp = 1, 1 while not w & 1: w //= 2 ans += tmp tmp *= 2 while not h & 1: h //= 2 ans += tmp tmp *= 2 if ans >= n: print('YES') else: print('NO') def main(): cardsFor...
1498_C. Planar Reflections
Gaurang has grown up in a mystical universe. He is faced by n consecutive 2D planes. He shoots a particle of decay age k at the planes. A particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age k-1. If a particle has d...
```python import sys import collections import math import bisect import heapq inf = sys.maxsize def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() mod = 1000000007 for _ in ...
1520_B. Ordinary Numbers
Let's call a positive integer n ordinary if in the decimal notation all its digits are the same. For example, 1, 2 and 99 are ordinary numbers, but 719 and 2021 are not ordinary numbers. For a given number n, find the number of ordinary numbers among the numbers from 1 to n. Input The first line contains one integer...
```python """ Don't see the standings during the contest!!! you will lose motivation. """ # ---------------------------------------------------Import Libraries--------------------------------------------------- import sys import time import os from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, co...
1547_G. How Many Paths?
You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of ...
```python import sys input = sys.stdin.buffer.readline sys.setrecursionlimit(10**7) def scc_dfs1(s, links, status, postorder): stack = [s] status[s] = 0 while stack: v = stack[-1] limit = len(links[v]) while status[v] < limit: u = links[v][status[v]] status[v...
291_B. Command Line Arguments
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document. In the Pindows operating system a strings ...
```python import sys # f = sys.stdin # f = open("input.txt", "r") a = input() i = 0 while i < len(a): if a[i] == '"': end = a.index('"', i+1) print("<", a[i+1:end], ">", sep="") i = end+1 elif a[i] != " " != '"' and (a[i-1] == " " or i-1 < 0): try: end = a.index(" ", ...
362_B. Petya and Staircases
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. No...
```python import sys n, m = map(int, input().split()) if m != 0: data = [int(el) for el in input().split()] data.sort() if data[0] == 1 or data[-1] == n: print('NO') sys.exit() for e in range(m - 2): if data[e] + data[e + 1] + data[e + 2] == data[e] * 3 + 3: print('...
385_E. Bear in the Field
Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains grow...
```python #Simple non-optimized class of matrices. Used with small dense matrices. import functools import itertools import math class NotAMatrixError(Exception): pass class MatrixSizeError(Exception): def __init__(self, s1, s2): print('sizes do not match : ', s1, ', ', s2) class NotSquareError(Excep...
456_B. Fedya and Maths
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression: (1n + 2n + 3n + 4n) mod 5 for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language). Input The si...
```python n=int(input()) if n==0: answer=4 else: a=1 if n%4==0: a+=6+1 elif n%4==1: a+=2+3 elif n%4==2: a+=4+9 else: a+=8+7 if n%2==0: a+=6 else: a+=4 answer=a%5 print(answer) ```
552_A. Vanya and Table
Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur mult...
```python n = int(input()) matrix = [[0] * 100 for i in range(100)] for t in range(n): x1, y1, x2, y2 = map(int, input().split()) for i in range(y1 - 1, y2): for j in range(x1 - 1, x2): matrix[i][j] += 1 answer = 0 for row in matrix: answer += sum(row) print(answer) ```
579_A. Raising Bacteria
You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimu...
```python xStr = input() x = int(xStr) put = 0 while x>0: if x%2 == 0: x = x//2 continue else: put = put+1 x = x//2 print(put) ```
5_E. Bindian Signalizing
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night. In case of any danger the watchman could make a fire on the hill. One watchman coul...
```python n = int(input()) hill = tuple(map(int, input().split())) pairs = 0 highest, at = max((h, k) for k, h in enumerate(hill)) last = highest count = 0 p = list() push = p.append pop = p.pop for at in range(at - 1, at - n, -1): current = hill[at] while current > last: pairs += count last, co...
622_C. Not Equal on a Segment
You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi. For the i-th query find any position pi (li ≤ pi ≤ ri) so that api ≠ xi. Input The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the number of elements in a and the number of queries. The second...
```python import sys n, m = map(int, sys.stdin.readline().split()) a = list(map(int, sys.stdin.readline().split())) assert(len(a) == n) prev = [-1] * n l = r = 0 while l < n: while r < n and a[l] == a[r]: r += 1 # [l, r) --> a[l] for i in range(l, r): prev[i] = l - 1 l = r for i in r...
670_E. Correct Bracket Sequence Editor
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, ...
```python n, m, p = [int(x) for x in input().split()] A = input().rstrip() B = input().rstrip() pair = [0] * n stack = [] for (i, c) in enumerate(A): if c == '(': stack.append(i) else: j = stack.pop() pair[i] = j pair[j] = i start = 0 pointer = p - 1 left = list(range(-1, n-1))...
696_B. Puzzles
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city h...
```python n = int(input()) if n ==1: print(1) exit(0) l = list(map(int,input().split())) w = [[]for i in range(n)] sz = [1]*n for i in range(n-1): w[l[i]-1].append(i+1) for i in range(n-1,-1,-1): for j in range(len(w[i])): sz[i]+=sz[w[i][j]] ans = [0]*n for i in range(n): for j in range(len(...
717_C. Potions Homework
Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe ...
```python fuck = int(input()) a = sorted(int(input()) for _ in range(fuck)) print(sum(a[i]*a[-i-1] for i in range(fuck))%10007) # Surprise motherfucker ```
761_D. Dasha and Very Difficult Problem
Dasha logged into the system and began to solve problems. One of them is as follows: Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai. About sequences a and b we know that their elements are in the range from l to...
```python read = lambda: map(int, input().split()) n, l, r = read() a = list(read()) p = list(read()) d = [i for i in range(n)] d.sort(key = lambda x: p[x]) cur = l - a[d[0]] b = [0] * n for ind in d: b[ind] = a[ind] + cur if b[ind] < l: cur = l - a[ind] b[ind] = l cur += 1 if max(b) > r: ...
784_F. Crunching Numbers Just for You
You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done... You are given an array of integers. Sort it in non-descending order. Input The input consists of a single line...
```python a = input()[2:] n = [0 for i in range(1000000)] g = 123 for i in range(130000): g *= 3 a = list(map(int, a.split())) x = [0 for _ in range(len(a))] for i in range(len(x)): x[i] = min(a) a.remove(x[i]) for o in x: print(o, end=' ') ```
876_B. Divisiblity of Differences
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible. Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in mu...
```python n, k , m = map(int, input().split()) a = list(map(int, input().split())) ai =[[]*100000 for i in range(100000)] h = 0 z = 0 v = 0 for i in range(n): h =a[i]%m ai[h].append(a[i]) if len(ai[h])==k: print('Yes') print(*ai[h]) v +=1 break if v == 0: print('No') ```
8_B. Obsession with Robots
The whole world got obsessed with robots,and to keep pace with the progress, great Berland's programmer Draude decided to build his own robot. He was working hard at the robot. He taught it to walk the shortest path from one point to another, to record all its movements, but like in many Draude's programs, there was a ...
```python __author__ = "runekri3" def cells_touching(cell_1, cell_2): abs_x = abs(cell_1[0] - cell_2[0]) if abs_x > 1: return False abs_y = abs(cell_1[1] - cell_2[1]) if abs_y > 1: return False if not (abs_x == 1 and abs_y == 1): return True movements = input() total_move...
922_A. Cloning Toys
Imp likes his plush toy a lot. <image> Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies. Initially, Imp has only on...
```python # Imports ############################################## # Input (x, y) = tuple(map(lambda x:int(x), input().split())) ############################################## # Main code yes = 'Yes' no = 'No' res = yes if y == 0: res = no elif y == 1 and x != 0: res = no elif x < y-1: res = no elif (...
94_B. Friends
One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something. The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people" Igor just c...
```python e = [[False] * 5 for i in range(5)] for i in range(int(input())): a, b = map(int, input().split()) e[a - 1][b - 1] = e[b - 1][a - 1] = True for a in range(3): for b in range(a + 1, 4): for c in range(b + 1, 5): if len({e[a][b], e[a][c], e[b][c]}) == 1: print('WI...