name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1186_D. Vus the Cossack and Numbers
Vus the Cossack has n real numbers a_i. It is known that the sum of all numbers is equal to 0. He wants to choose a sequence b the size of which is n such that the sum of all numbers is 0 and each b_i is either ⌊ a_i ⌋ or ⌈ a_i ⌉. In other words, b_i equals a_i rounded up or down. It is not necessary to round to the ne...
```python import heapq import math n=int(input()) a=[None]*n h=[] mh=[] s=0 d=[0]*n for i in range(n): a[i]=float(input()) if a[i]!=int(a[i]): if a[i]<0: heapq.heappush(h,[math.floor(a[i])-math.ceil(a[i]),i]) else: heapq.heappush(mh,[math.ceil(a[i])-math.floor(a[i]),i]) ...
1205_C. Palindromic Paths
This is an interactive problem You are given a grid n× n, where n is odd. Rows are enumerated from 1 to n from up to down, columns are enumerated from 1 to n from left to right. Cell, standing on the intersection of row x and column y, is denoted by (x, y). Every cell contains 0 or 1. It is known that the top-left ce...
```python n = int(input()) a=[] for i in range(0,n+1): temp= [0]*(n+1) a.append(temp) a[1][1]=1 def ask(x1,y1,x2,y2): print("?",x1,y1,x2,y2) a= int(input()) if a: return True else: False for i in range(3,n+1,1): a[1][i] = a[1][i-2]^(not(ask(1,i-2,1,i))) for i in range(2...
1248_D1. The World Is Just a Programming Task (Easy Version)
This is an easier version of the problem. In this version, n ≤ 500. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believe...
```python import sys input = sys.stdin.readline def matcher(correcti): open_=0 close_=0 count=0 excess=0 for i in range(len(correcti)): if correcti[i]=='(': open_+=1 if correcti[i]==')': close_+=1 if close_>open_ and open_==0: excess+=1 ...
1288_C. Two Arrays
You are given two integers n and m. Calculate the number of pairs of arrays (a, b) such that: * the length of both arrays is equal to m; * each element of each array is an integer between 1 and n (inclusive); * a_i ≤ b_i for any index i from 1 to m; * array a is sorted in non-descending order; * array b ...
```python '''input 10 1 ''' # A coding delight from sys import stdin, stdout import gc gc.disable() input = stdin.readline import math # main starts n, m = list(map(int, input().split())) mod = 10 ** 9 + 7 dp1 = [[1 for x in range(m + 1)] for y in range(n + 1)] dp2 = [[1 for y in range(m + 1)] for y in range(n + 1)] ...
1331_F. Elementary!
Input The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive. Output Output "YES" or "NO". Examples Input GENIUS Output YES Input DOCTOR Output NO Input IRENE Output YES Input MARY Output NO Input SMARTP...
```python z="QWERTYUIOPASDFGHJKLZXCVBNM" t="01101101001001010111101011" s = input() cur = '-' for i in s: for j in range(26): if z[j] == i: if cur == '-': cur = t[j] elif t[j] != cur: print('NO') exit(0) print('YES') ```
1352_A. Sum of Round Numbers
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
```python import sys num_lines = int(input()) for i in range(num_lines): cont = 0 resp = '' whole_number = sys.stdin.readline().strip('\n') length = len(whole_number) - 1 for idx, k in enumerate(whole_number): if k != '0': cont += 1 num = int(k) * 10 **...
1371_E2. Asterism (Hard Version)
This is the hard version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x ...
```python import sys import math from math import factorial, inf, gcd, sqrt from heapq import * from functools import * from itertools import * from collections import * from typing import * from bisect import * import random sys.setrecursionlimit(10**5) def rarray(): return [int(i) for i in input().split()] t ...
1419_A. Digit Game
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
```python for _ in range(int(input())): a = int(input()) number = input() raze = [0,0] #odd,even breach = [0,0] #odd,even count = 0 while count<len(number): if count%2==0: if int(number[count])%2==0: raze[1]+=1 else: r...
1437_A. Marketing Scheme
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy str...
```python for _ in range(int(input())): a,b = map(int,input().split()) aa = a%(b+1);bb = b%(b+1) if(aa>=(b+1)/2 and bb>=(b+1)/2): print("YES") else: print("NO") ```
1461_E. Water Level
In recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras. <image>...
```python k, l, r, t, x, y = map(int, input().split()) k -= l r -= l l = 0 if k < x - y or (k > r - y and k < x): print("No") exit() if x > y: if k + y > r: k -= x t -= 1 print("Yes" if t <= k // (x - y) else "No") else: if l + x + y - r <= 1: print("Yes") exit() ...
1538_B. Friends and Candies
Polycarp has n friends, the i-th of his friends has a_i candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all a_i to be the same. To solve this, Polycarp performs the following set of actions exactly once: * Polycarp chooses k (0 ≤ k ≤ n) arbitrary friends...
```python import sys,os,io from sys import stdin,stdout from math import log, gcd, ceil from collections import defaultdict, deque, Counter from heapq import heappush, heappop from bisect import bisect_left , bisect_right import bisect import math input = stdin.readline alphabets = list('abcdefghijklmnopqrstuvwxyz') ...
207_D1. The Beaver's Problem - 3
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
```python print('1') ```
231_D. Magic Box
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1...
```python x,y,z=map(int,input().split()) a,b,c=map(int,input().split()) a1,a2,a3,a4,a5,a6=map(int,input().split()) sum=0 if x>a: sum+=a6 if x<0: sum+=a5 if y>b: sum+=a2 if y<0: sum+=a1 if z>c: sum+=a4 if z<0: sum+=a3 print(sum) ```
257_C. View Angle
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this a...
```python import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br...
280_C. Game on Tree
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree. The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtre...
```python # https://codeforces.com/problemset/problem/280/C from collections import defaultdict, deque import sys nodes = int(sys.stdin.readline()) edges = defaultdict(list) for line in sys.stdin: a, b = line.split() a = int(a) b = int(b) edges[a].append(b) edges[b].append(a) bfs = deque([(1, 1)]) ...
303_B. Rectangle Puzzle II
You are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers (x, y) (0 ≤ x ≤ n, 0 ≤ y ≤ m). Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (...
```python from fractions import gcd n, m, x, y, a, b = map(int, input().split()) r = gcd(a, b) a, b = a // r, b // r r = min(n // a, m // b) a, b = a * r, b * r cx, cy = (a + 1) // 2, (b + 1) // 2 dx, dy = min(n - a, max(cx, x) - cx), min(m - b, max(cy, y) - cy) print(dx, dy, a + dx, b + dy) # Made By Most...
32_C. Flea
It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to s centimeters. A flea has found herself at the center of some cell of the checked board of the size n × m centimeters (each cell is 1 × 1 centimeters). She can jump as she wishes for an arbitrary n...
```python n,m,s=map(int,input().split()) r = (-(-n//s)) * (s if n%s==0 else n%s) c = (-(-m//s)) * (s if m%s==0 else m%s) print(r*c) ```
351_A. Jeff and Rounding
Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: * choose indexes i and j (i ≠ j) that haven't been chosen yet; * round elemen...
```python n, k, s = int(input()), 0, 0 for i in input().split(): j = int(i[-3: ]) if j == 0: k += 1 else: s += j c = s // 1000 + int(s % 1000 > 500) a, b = max(0, n - k), min(2 * n - k, n) if a <= c <= b: s = abs(c * 1000 - s) else: s = min(abs(a * 1000 - s), abs(b * 1000 - s)) print(str(s // 1000) + '.' + ...
375_B. Maximum Submatrix 2
You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations? Let's assume that the rows of matrix a are numbered from 1 to n ...
```python ''' from bisect import bisect,bisect_left from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import *''' #------------------------------------------------------------------------ ...
397_D. On Sum of Fractions
Let's assume that * v(n) is the largest prime number, that does not exceed n; * u(n) is the smallest prime number strictly greater than n. Find <image>. Input The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases. Each of the following t lines of the input contains integer n (2 ≤ n ≤ ...
```python T = int( input() ) #for every prime x #(b-a)/ab #1/a-1/b MAX = 33000 bePrime = [0] * MAX; primNum = [] for j in range(2, MAX): if bePrime[j] == 0: primNum.append( j ) i = j while i < MAX: bePrime[i] = 1 i = i + j def isPrime( a ): for j in primNum:...
41_E. 3-cycles
During a recent research Berland scientists found out that there were n cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three...
```python p = int(input()) print( ( p // 2 ) ** 2 + ( p // 2) * ( p % 2 ) ) for i in range(p//2): for j in range(p//2, p): print(i+1, j+1) ```
490_D. Chocolate
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a1 × b1 segments large and the second one is a2 × b2 segments large. Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself...
```python def decomp(a): cnt2 = 0 while a%2==0: a = a//2 cnt2 += 1 cnt3 = 0 while a%3==0: a = a//3 cnt3 += 1 return a,cnt2,cnt3 def cut(a,b,d,p): while d>0: if a%p==0: a = (p-1)*a//p d = d-1 elif b%p==0: b = (p-...
514_D. R2D2 and Droid Army
An army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(1...
540_E. Infinite Inversions
There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting seq...
```python import sys from collections import defaultdict class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _get_sum(self, r): ''' sum on interval [0, r) ''' result = 0 while r > 0: result += self.tree[r-1] ...
569_A. Music
Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk. Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite ...
```python T, S, q = map(int, input().split()) count = 0 while True: count += 1 ds = S * (q - 1) S += ds if S >= T: break print(count) ```
58_D. Calendar
BerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one sep...
```python # t = int(input()) # while t>0: n = int(input()) // 2 a = sorted([input() for i in range(n * 2)], reverse=1) d = input() L = sum(len(i) for i in a) // n ans = [] for i in range(n): x = a.pop() for y in a[::-1]: if len(x) + len(y) == L: ans.append(min(x + d + y, y + d + x)) ...
631_C. Report
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands o...
```python def compress(ops): cops = [] for r, dir in ops: while cops and cops[-1][0] <= r: cops.pop() if not cops or cops[-1][1] != dir: cops.append((r, dir)) return cops def transform(lst, ops): mr, mdir = ops[0] sections = [range(mr, len(lst))] ost =...
660_A. Co-prime Array
You are given an array of n elements, you must make it a co-prime array in as few moves as possible. In each move you can insert any positive integral number you want not greater than 109 in any place in the array. An array is co-prime if any two adjacent numbers of it are co-prime. In the number theory, two integer...
```python def gcd(x, y): if y == 0: return x return gcd(y, x % y) n = int(input()) a = list(map(int, input().split())) last = 1 ans = [] for i in range(n): if gcd(a[i], last) != 1: ans.append(1) ans.append(a[i]) last = a[i] print(len(ans) - n) for i in range(len(a...
706_D. Vasiliy's Multiset
Author has gone out of the stories about Vasiliy, so here is just a formal task description. You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: 1. "+ x" — add integer x to multiset A. 2. "- x" — erase one occurrence of integer x from multiset A. It's g...
```python # ------------------- fast io -------------------- 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...
74_B. Train
A stowaway and a controller play the following game. The train is represented by n wagons which are numbered with positive integers from 1 to n from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or idle...
```python n, rider, cop = map(int, input().split()) rider, cop = rider - 1, cop - 1 if input().strip() == 'to head': cop_dir = -1 else: cop_dir = 1 for pos, ch in enumerate(input().strip()): #print(pos, ch, rider, cop, cop_dir) if ch == '1': rider = -1 else: if cop_dir == -1 and ride...
773_A. Success Rate
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y. Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the s...
```python import math as mt import sys,string,bisect input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) d=defaultdict(int) def extended_gcd(a,b): if(a...
818_B. Permutation Game
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it. The game consists of m steps. On each step the current leader with index i counts out ai...
```python n, m = map(int, input().split()) l = list(map(int, input().split())) a = [-1] * n s = set(range(1, n + 1)) d = set() for i in range(m - 1): for j in range(1, n + 1): if (l[i] + j - l[i + 1]) % n == 0: if j in d and a[l[i] - 1] != j: print(-1) exit() ...
864_A. Fair Game
Petya and Vasya decided to play a game. They have n cards (n is an even number). A single integer is written on each card. Before the game Petya will choose an integer and after that Vasya will choose another integer (different from the number that Petya chose). During the game each player takes all the cards with num...
```python #python3 #utf-8 from collections import Counter cards_nr = int(input()) number_counter = Counter() for _ in range(cards_nr): curr_number = int(input()) number_counter[curr_number] += 1 if len(number_counter) != 2: print('NO') else: num1, num2 = list(number_counter) if number_counter[num...
934_C. A Twisty Movement
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon. A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, th...
```python n = int(input()) A = list(map(int, input().split())) one = [0] two = [0] for i in A: one.append(one[-1]) two.append(two[-1]) if i == 1: one[-1] += 1 else: two[-1] += 1 rdp1 = [[1] * n for _ in range(n)] rdp2 = [[1] * n for _ in range(n)] for l in range(n): for r in range(l ...
988_B. Substrings Sort
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
```python # We are the all singing all dancing crap of the world n = int(input()) khela = [] for i in range(n): s = input() khela.append([len(s),s]) khela = sorted(khela) if (n==1): print('YES') print(khela[0][1]) else: lent = len(khela) for i in range(lent-1): c = ...
p02594 AtCoder Beginner Contest 174 - Air Conditioner
You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above. The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner? Constraints * -40 \leq X \leq 40 * X is an integer. Input Input is given from Standard Input in the follo...
```python d = int(input()) if d >= 30: print("Yes") else: print("No") ```
p02725 AtCoder Beginner Contest 160 - Traveling Salesman around Lake
There is a circular pond with a perimeter of K meters, and N houses around them. The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond. When traveling between these houses, you can only go around the pond. Find the minimum distance that needs to ...
```python k,n=map(int,input().split()) l=list(map(int, input().split())) m=k-(l[n-1]-l[0]) for i in range(1,n): m=max(m,l[i]-l[i-1]) print(k-m) ```
p02856 DISCO Presents Discovery Channel Code Contest 2020 Qual - Digit Sum Replace
N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals. The preliminary stage consists of several rounds, which will take place as follows: * All the N contestants will participate in the first round. * W...
```python n=int(input()) DC=[list(map(int,input().split())) for _ in range(n)] D,S=0,0 for d,c in DC: D +=c S +=d*c print(D-1+(S-1)//9) ```
p02992 AtCoder Beginner Contest 132 - Small Products
Find the number of sequences of length K consisting of positive integers such that the product of any two adjacent elements is at most N, modulo 10^9+7. Constraints * 1\leq N\leq 10^9 * ~~1~~ 2\leq K\leq 100 (fixed at 21:33 JST) * N and K are integers. Input Input is given from Standard Input in the following forma...
```python import sys def solve(): N, K = map(int, input().split()) MOD = 10**9 + 7 U = []; V = [] for x in range(1, int(N**.5)+1): U.append(x) if x < N//x: V.append(N//x) V.reverse(); U.extend(V) L = len(U) prv = 0 R = [] for x in U: R.append(x-p...
p03133 Yahoo Programming Contest 2019 - Odd Subrectangles
There is a square grid with N rows and M columns. Each square contains an integer: 0 or 1. The square at the i-th row from the top and the j-th column from the left contains a_{ij}. Among the 2^{N+M} possible pairs of a subset A of the rows and a subset B of the columns, find the number of the pairs that satisfy the f...
```python def rankmod2(A): global N, M ret = 0 i = 0 j = 0 while i < N and j < M: if A[i][j]: ret += 1 else: for ii in range(i+1, N): if A[ii][j]: A[i], A[ii] = A[ii], A[i] ret += 1 br...
p03278 AtCoder Regular Contest 101 - Ribbons on Tree
Let N be an even number. There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i. Snuke would like to decorate the tree with ribbons, as follows. First, he will divide the N vertices into N / 2 pairs. Here, each vertex must ...
```python mod = 10**9+7 #出力の制限 N = 2*10**5 g1 = [1, 1] # 元テーブル g2 = [1, 1] #逆元テーブル inverse = [0, 1] #逆元テーブル計算用テーブル for i in range( 2, N + 1 ): g1.append( ( g1[-1] * i ) % mod ) inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod ) g2.append( (g2[-1] * inverse[-1]) % mod ) import sys sys.setrecursionli...
p03433 AtCoder Beginner Contest 088 - Infinite Coins
E869120 has A 1-yen coins and infinitely many 500-yen coins. Determine if he can pay exactly N yen using only these coins. Constraints * N is an integer between 1 and 10000 (inclusive). * A is an integer between 0 and 1000 (inclusive). Input Input is given from Standard Input in the following format: N A Output...
```python a = int(input()) b = int(input()) print("Yes" if (a % 500 <= b) else "No") ```
p03592 CODE FESTIVAL 2017 qual A - fLIP
We have a grid with N rows and M columns of squares. Initially, all the squares are white. There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attach...
```python N,M,K = map(int, input().split()) for i in range(N+1): for j in range(M+1): if j*(N-i)+i*(M-j) == K: print('Yes') exit() print('No') ```
p03749 AtCoder Grand Contest 013 - Placing Squares
Joisino has a bar of length N, which has M marks on it. The distance from the left end of the bar to the i-th mark is X_i. She will place several squares on this bar. Here, the following conditions must be met: * Only squares with integral length sides can be placed. * Each square must be placed so that its bottom si...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N,M,*X = map(int,read().split()) MOD = 10 ** 9 + 7 def mult(a,b,c,d,e,f): # (a+bx+cx^2)(d+ex+fx^2) modulo 1-4x+2x^2-x^3 a,b,c,d,e = a*d,a*e+b*d,a*f+b*e+c*d,b*f+c*e,c*f b += e; c -...
p03913 CODE FESTIVAL 2016 Final - Cookies
Rng is baking cookies. Initially, he can bake one cookie per second. He can also eat the cookies baked by himself. When there are x cookies not yet eaten, he can choose to eat all those cookies. After he finishes eating those cookies, the number of cookies he can bake per second becomes x. Note that a cookie always n...
```python N,A=map(int,input().split()) ans=N for i in range(-10,10): x=int(N**.5)+i if x>0: test=x+A+(N-1)//x+1 ans=min(ans,test) for n in range(2,41): for i in range(2*n,int(N**(1/n))+1000): test=i+n*A q=i//n r=i%n prod=pow(q,n-r)*pow(q+1,r) test+=...
p00015 National Budget
A country has a budget of more than 81 trillion yen. We want to process such data, but conventional integer type which uses signed 32 bit can represent up to 2,147,483,647. Your task is to write a program which reads two integers (more than or equal to zero), and prints a sum of these integers. If given integers or t...
```python p = int(input()) for j in range(p): a, b = int(input()), int(input()) x = str(a+b) print("overflow" if len(x)>80 else a+b) ```
p00147 Fukushimaken
"Fukusekiken" is a popular ramen shop where you can line up. But recently, I've heard some customers say, "I can't afford to have vacant seats when I enter the store, even though I have a long waiting time." I'd like to find out why such dissatisfaction occurs, but I'm too busy to check the actual procession while the ...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0147 """ import sys from sys import stdin from heapq import heappop, heappush from collections import deque input = stdin.readline class Seat(): def __init__(self, n): self.seat = '_' * n def get(self, num...
p00298 Mighty Man
There was a powerful school where powerful people gathered. At the athletic meet of the powerful school, powerful people march in a formation. While the powerhouses always want to show off their power, most of them don't want to walk on their own. So I thought that some of them would be at the bottom, and a lot of peo...
```python import sys f = sys.stdin n = int(f.readline()) s = [list(map(int, line.split())) for line in f] p = [[i==j for j in range(n + 1)] for i in range(n + 1)] c = [0] + [c for c,w in s] sum_w = [0] + [w for c,w in s] for i in range(1, len(sum_w)): sum_w[i] += sum_w[i - 1] for length in range(n): for ...
p00468 Party
problem You decide to invite your friends of the school and your friends of a friend to the Christmas party. The number of students in your school is n, and each student is assigned a number from 1 to n. Your number is 1. You have a list of who and who are your friends. Based on this list, create a program that asks f...
```python while True: n=int(input()) m=int(input()) if n==0: break a=[None for _ in range(m)] b=[None for _ in range(m)] friend = set() friend1=set() friend2=set() for i in range(m): a[i],b[i] = list(map(int, input().split())) if a[i] ==1: friend.a...
p00660 High and Low Cube
I came to the summer festival with the elementary school students in my neighborhood. To put it bluntly, it plays the role of a guardian, but the smell of yakisoba and takoyaki in the store, and the sound of fireworks that can be heard from time to time, are still exciting even at this age. But today I have to keep an ...
```python class Surface: def __init__(self, mp): self.mp = mp def mirror(self): for y in range(5): self.mp[y] = self.mp[y][::-1] def mirror_ud(self): for y in range(2): self.mp[y], self.mp[4 - y] = self.mp[4 - y], self.mp[y] def spin90(self): ne...
p00803 Starship Hakodate-maru
The surveyor starship Hakodate-maru is famous for her two fuel containers with unbounded capacities. They hold the same type of atomic fuel balls. There, however, is an inconvenience. The shapes of the fuel containers #1 and #2 are always cubic and regular tetrahedral respectively. Both of the fuel containers should b...
```python ans = [] # 答え while True: N = int(input()) if not N: break now_cube = int(N ** (1 / 3 + 0.000001)) now_pyramid = 0 tmp_ans = now_cube ** 3 # 立方体の一辺を小さくしていく、立方体の辺ごとに四角錐の一辺の長さを求め、容量を求める for i in range(now_cube, -1, -1): while True: # もし次の値が最大容量を超...
p01337 The Number of the Real Roots of a Cubic Equation
Description Since the cubic equation: ax ^ 3 + bx ^ 2 + cx + d = 0 is given, please check the number of positive real roots and the number of negative real roots, respectively. The number of roots shall be counted including the multiple roots. Input The input consists of multiple test cases, and the number is rec...
```python n=int(input()) def f(a,b,c,d): return lambda x:a*x**3+b*x**2+c*x+d for i in range(n): a,b,c,d=map(int,input().split()) fx=f(a,b,c,d) D=b**2-3*a*c if D<=0 : if d==0: pl=mi=0 elif (a>0 and d<0) or (a<0 and d>0): pl,mi=1,0 elif (a<0 and d<0) or ...
p01504 AYBABTU
There is a tree that has n nodes and n-1 edges. There are military bases on t out of the n nodes. We want to disconnect the bases as much as possible by destroying k edges. The tree will be split into k+1 regions when we destroy k edges. Given the purpose to disconnect the bases, we only consider to split in a way that...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(t): N, T, K = map(int, readline().split()) if N == T == K == 0: return False G = [[] for i in range(N)] E = [] res = 0 for i in range(N-1): a, b, c = map(int, readline().split()) res += ...
p01819 Where is the Boundary
Example Input 2 1 WE Output 1 2
```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**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x i...
p02101 Let's Go To School
Problem Gaccho loses motivation as the final exam approaches and often misses school. There are N days left until the final exam. Gaccho's motivation on day i is Xi, and the motivation needed to go to school on day i is Yi. Gaccho goes to school only on days when Xi ≥ Yi. Haji, who was worried about Gaccho, decided to...
```python N,P=map(int,input().split()) xs=[] ys=[] dp=[[[1e9 for i in range(N+1)] for j in range(N+1)] for k in range(N+1)] memo=[[0 for i in range(N+1)] for j in range(N+1)] for i in range(N): x,y=map(int,input().split()) xs.append(x) ys.append(y) for start in range(N): preuse=0 for now in range(s...
p02239 Breadth First Search
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$. Constraints * $1 \leq n \leq 100$ Input In the first line, an integer $n$ denoting the number of vertic...
```python import sys input = lambda: sys.stdin.readline().rstrip() from collections import deque def resolve(): n = int(input()) ukv = [list(map(int, input().split())) for _ in range(n)] dist = [-1]*n que = deque() que.append(0) dist[0] = 0 while len(que)>0: v = que.popleft() ...
p02385 Dice III
Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical. Co...
```python roll_dict = dict(E = (3, 1, 0, 5, 4, 2), W = (2, 1, 5, 0, 4, 3), S = (4, 0, 2, 3, 5, 1), N = (1, 5, 2, 3, 0, 4)) dice1 = list(map(int, input().split())) dice2 = list(map(int, input().split())) dices = [] dices.append(dice1) judge = False for i in "EWSN": dice = dices[0] new_dice = [] for j in range(6...
1000_B. Light It Up
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, ...
```python n,M=map(int,input().split()) s=[int(x) for x in input().split()] ss=[s[0]] so=[] se=[] for i in range(n-1): ss.append(s[i+1]-s[i]) ss.append(M-s[n-1]) if (n+1)%2==1: for i in range(int(n/2)): so.append(ss[2*i]) se.append(ss[2*i+1]) so.append(ss[n]) sss=sum(so) a=0 b=...
1025_C. Plasticine zebra
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras. Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now ...
```python import sys s = input() n = len(s) if n == 1: print(1) sys.exit(0) for i in range(n-1): if s[i] == s[i+1] and (s[n-1] != s[0]): x = s[:i+1] y = s[i+1:n] s = x[::-1] + y[::-1] ans = 1 mx = 1 for i in range(1, n): if s[i] != s[i-1]: mx += 1 else: ans = max(mx, ans) mx = 1 print(max(mx, ans)...
1068_E. Multihedgehog
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as fol...
```python from collections import deque n, k = list(map(int, input().split())) G = [set() for _ in range(n + 1)] q, nq = deque(), deque() for _ in range(n - 1): u, v = list(map(int, input().split())) G[u].add(v) G[v].add(u) for u in range(1, n + 1): if len(G[u]) == 1: q.append(u) step = 0 ...
1090_D. Similar Arrays
Vasya had an array of n integers, each element of the array was from 1 to n. He chose m pairs of different positions and wrote them down to a sheet of paper. Then Vasya compared the elements at these positions, and wrote down the results of the comparisons to another sheet of paper. For each pair he wrote either "great...
```python # SHRi GANESHA author: Kunal Verma # import os import sys from bisect import bisect_left, bisect_right from collections import Counter, defaultdict from functools import reduce from io import BytesIO, IOBase from itertools import combinations from math import gcd, inf, sqrt, ceil, floor #sys.setrecursi...
110_A. Nearly Lucky Number
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
```python # your code goes here n=int(input()) n=str(n) k=0 for i in range(len(n)): if int(n[i]) == 4 or int(n[i]) == 7: k=k+1 if k==4 or k==7: print('YES') else: print('NO') ```
1139_D. Steps to One
Vivek initially has an empty array a and some integer constant m. He performs the following algorithm: 1. Select a random integer x uniformly in range from 1 to m and append it to the end of a. 2. Compute the greatest common divisor of integers in a. 3. In case it equals to 1, break 4. Otherwise, return to...
```python import sys factors = [] dp = [] mod = (int)(1e9+7) inv_m = 0 def sub(a, b): a -= b a %= mod if a < 0: a += mod return a def add(a, b): return (a + b) % mod def mul(a, b): return (a * b) % mod def pow(a, b): if b == 0: return 1 if b & 1: return mul(a, pow(a, b - 1)) else: aux = pow(a, b >> 1)...
1157_D. N Problems During K Days
Polycarp has to solve exactly n problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in k days. It means that Polycarp has exactly k days for training! Polycarp doesn't want to procrastinate, so he wants to sol...
```python """ b[i] = a[i] - i - 1 b[i] <= b[i+1] < 2b[i] + i - 1 sum(b) == r """ def solve(n, k): r = n - k*(k+1)//2 if r < 0: return None b0 = r//k r -= b0*k seq = [None]*k seq[0] = b0 b = b0 for i in range(1,k): bn = b*2 + i - 1 h = r//(k-i) i...
117_A. Elevator
And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator...
```python n, m = map(int, input().split()) k = 2 * (m - 1) for i in range(n): s, f, t = map(int, input().split()) d = t % k if s < f: print(k * (s <= d) + f - 1 + t - d) elif f < s: print(k * (d + s > k + 1) + k + 1 - f + t - d) else: print(t) ```
1198_B. Welfare State
There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the governm...
```python n = int(input()) a = list(map(int,input().split())) mark=[1 for i in range(n)] query = [] q = int(input()) m = -1 for i in range(q): next = list(map(int,input().split())) if next[0]==2: m = max(m,next[1]) query.append(next) mx = 0 for i in range(n): if a[i]<m: a[i]=m for i in r...
1215_A. Yellow Cards
The final match of the Berland Football Cup has been held recently. The referee has shown n yellow cards throughout the match. At the beginning of the match there were a_1 players in the first team and a_2 players in the second team. The rules of sending players off the game are a bit different in Berland football. If...
```python a1=int(input()) a2=int(input()) k1=int(input()) k2=int(input()) n=int(input()) m1=n - (k1-1)*a1 - (k2-1)*a2 if m1<0: m1=0 m2=0 if a1*k1 + a2*k2 <=n: m2=a1+a2 elif k1<=k2: if n//k1 <= a1: m2=n//k1 else: m2=m2+a1 n=n-a1*k1 m2=m2 + min(a2, n//k2) elif k2 < k1...
1238_C. Standard Free2play
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height h, and there is a moving platform on each height x from 1 to h. Each platform is either hidden inside the cliff or moved out. At first, there are n moved out platforms...
```python n= int(input()) for z in range(n): h, am = map(int, input().split()) arr = list(map(int, input().split())) ch = h i = 1 ac = 0 while i < am: if ch - arr[i] >= 2: ch = arr[i] + 1 elif i < am - 1 and arr[i + 1] == ch - 2 or ch == 2: ch -= 2 ...
1256_D. Binary String Minimizing
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1'). In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do ...
```python '''q=int(input()) for i in range(q): n,k=map(int,input().split()) a=input() b=[] indices=[] for j in range(n): if(a[j]=='0'): indices.append(j) b.append(a[j]) e=0 t=0 while(k>0 and e<=len(indices)): if(indices[e]<=k): b[indices[e]],b[t]=b[t],b[indices[e]] k=k-indices[e] t=t+1 el...
127_D. Password
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t...
```python from sys import stdin def findpass(s): arr = suff_array(s) n = len(s) maxidx = arr[n - 1] valid = False for i in range(n - 1): if arr[i] == maxidx: valid = True break if not valid: maxidx = arr[maxidx - 1] if maxidx == 0: return ...
12_C. Fruits
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ash...
```python n, m = input().split(" ") n = int(n) m = int(m) priceList = [] res = [] least = 0 most = 0 fruitCount = 0 seq = input().split(" ") for i in seq: priceList.append(int(i)) item = [] count = [] for i in range(m): inp = input() if inp in item: count[item.index(inp)] += 1 else: ...
1323_E. Instant Noodles
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task. You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left ha...
```python from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline M = mod = 10**9 + 7 def factors(n):return sorted(set(redu...
1342_D. Multiple Testcases
So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem! Initially, each test in that problem is just an array. The maximum size of an array...
```python import sys from collections import defaultdict from bisect import bisect_left input = sys.stdin.readline ''' n, m = map(int, input().split()) n = int(input()) A = list(map(int, input().split())) S = input().strip() for CASES in range(int(input())): ''' inf = 100000000000000000 # 1e17 mod = 998244353 ''' # e...
1364_D. Ehab's Last Corollary
Given a connected undirected graph with n vertices and an integer k, you have to either: * either find an independent set that has exactly ⌈k/2⌉ vertices. * or find a simple cycle of length at most k. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a...
```python import io import os from collections import Counter, defaultdict, deque import sys sys.setrecursionlimit(10 ** 5 + 1) from types import GeneratorType # https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): ...
1406_B. Maximum Product
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ...
```python import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, ...
1427_C. The Hard Work of Paparazzi
You are a paparazzi working in Manhattan. Manhattan has r south-to-north streets, denoted by numbers 1, 2,…, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,…,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the interse...
```python #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque impo...
1450_C1. Errich-Tac-Toe (Easy Version)
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version. Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces. In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell ...
```python def disti(b,ind): a=[] for i in b: h=[] for j in i: h.append(j) a.append(h) ans=0 id=0 for i in range(n): start = ind[id%3] id+=1 for j in range(start ,n,3): left='' right='' up='' down='' mid1='' mid2='' if(j-2 >= 0): left = a[i][j-2] + a[i][j-1] + a[i][j] if(j+...
1474_A. Puzzle From the Future
In the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way: * he creates an integer c as a result of bitwise summing of a and b without transfe...
```python for tc in range(int(input())): n = int(input()) b = input() a = ['' for i in range(n)] d = ['0' for i in range(n)] if b[0] == '0':d[0] = '1' else:d[0] = '2' for i in range(1,n): if b[i] == '0': if d[i-1] != '1': d[i] = '1' else:d[i] =...
149_C. Division into Teams
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the ...
```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...
1523_C. Compression and Expansion
<image> William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands. A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just...
```python import sys T = int(sys.stdin.readline().strip()) for t in range (0, T): n = int(sys.stdin.readline().strip()) x = int(sys.stdin.readline().strip()) ans = [[x]] for i in range (0, n - 1): x = int(sys.stdin.readline().strip()) ans.append(ans[-1][:]) if x == 1: ...
155_B. Combination
Ilya plays a card game by the following rules. A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom co...
```python n=int(input()) arr=[] for i in range(n): a,b=map(int,input().split()) arr.append((b,a)) arr.sort(reverse=True) counter=1 ans=0 i=0 while(counter and i<n): counter-=1 counter+=arr[i][0] ans+=arr[i][1] i+=1 print(ans) ```
177_C2. Party
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friends...
```python from collections import defaultdict def Root(child): while(Parent[child]!=child): child = Parent[child] return child def Union(a,b): root_a = Root(a) root_b = Root(b) if(root_a!=root_b): if(Size[root_a]<Size[root_b]): Parent[root_a] = root_b ...
221_D. Little Elephant and Array
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query ...
```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.wri...
245_E. Mishap in Club
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen. On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, ...
```python #Problem Set N: Collaborated with no one n = input() in_visit = 0 out_visit = 0 for i in range(len(n)): if n[i] == '+': in_visit += 1 if out_visit: out_visit -= 1 elif n[i] == '-': out_visit += 1 if in_visit: in_visit -= 1 pr...
270_C. Magical Boxes
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a...
```python from math import* n = int(input()) v=0 for i in range(n): a = [int(x)for x in input().split(' ')] k = ceil(fabs(log(a[1],4))) if k==0: k=1 if k+a[0]>v: v = k+a[0] print(v) ```
317_C. Balance
A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tub...
```python read = lambda: map(int, input().split()) n, v, e = read() adj = [[] for _ in range(n + 1)] As = [0] + list(read()) Bs = [0] + list(read()) ans = [] for _ in range(e): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) def flow(a, b, d): As[a] -= d As[b] += d ans.appe...
341_C. Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the resea...
```python #lahub and Permutations import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 mod = 10**9+7 def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗) res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod ...
388_D. Fox and Perfect Sets
Fox Ciel studies number theory. She thinks a non-empty set S contains non-negative integers is perfect if and only if for any <image> (a can be equal to b), <image>. Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or). Please calculate the number of perfect sets consisting of ...
```python from math import factorial MOD = 10**9+7 k = int(input()) bink = list(map(int, bin(k)[2:])) N = len(bink) # dp[i][j][k] = first i bits, j bases, # k = 1 if maxor matches k, 0 else dp = [[[0,0] for j in range(i+2)] for i in range(N+1)] dp[0][0][1] = 1 for i in range(1, N+1): for j in range(i+1): ...
409_B. Mysterious Language
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language. Input This program has only one test (your program doesn't have to read anything). Output ...
```python """==================================================================================== ==================================================================================== ___ _______ ___ _______ ___ ___ | /\ | | \ | | / | | | | |\ /| ...
436_C. Dungeons and Candies
During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell ...
```python def put(): return map(int, input().split()) def diff(x,y): ans = 0 for i in range(n*m): if s[x][i]!= s[y][i]: ans+=1 return ans def find(i): if i==p[i]: return i p[i] = find(p[i]) return p[i] def union(i,j): if rank[i]>rank[j]: i,j = j,i ...
459_D. Pashmak and Parmida's problem
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak. There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indic...
```python # 459D import sys from collections import Counter class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _getSum(self, r): ''' sum on interval [0, r] ''' result = 0 while ...
480_C. Riding in a Lift
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. Howe...
```python def solve(n, st, k): MOD = int(1e9 + 7) dp = [0] * (n + 1) prefix_sum = [0] * (n + 1) dp[st] = 1 for times in range(k): prefix_sum[0] = 0 for i in range(1, n + 1): prefix_sum[i] = prefix_sum[i - 1] + dp[i] if prefix_sum[i] >= MOD: prefix_sum[i] -= MO...
529_B. Group Photo 2 (online mirror version)
Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo. Simply speaking, the process of photographing can be describ...
```python from operator import neg n = int(input()) a = [tuple(map(int, input().split())) for i in range(n)] def check(max_h): k = n // 2 b = [] for w, h in a: if h > max_h: if k <= 0 or w > max_h: return 1 << 60 b.append((h, w)) k -= 1 el...
554_D. Kyoya and Permutation
Let's define the permutation of length n as an array p = [p1, p2, ..., pn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on. Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a...
```python def F(n): a,b = 1,0 for i in range(n): a,b = b,a+b return b def ans(n,k): if n == 0: return [] elif n == 1: return [1] elif k > F(n): return [2,1] + [i+2 for i in ans(n-2,k-F(n))] else: return [1] + [i+1 for i in ans(n-1,k)] n,k = map(int,i...
580_C. Kefa and Park
Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the ver...
```python M=lambda:map(int,input().split()) n,m=M() *c,=M() t=[[]for i in range(n)] v=[0]*n for i in range(n-1): x,y=M() t[x-1].append(y-1) t[y-1].append(x-1) a=i=0 q=[(0,0)] while i<len(q): x,N=q[i] v[x]=1 if c[x]+N<=m: L=1 for y in t[x]: if not v[y]: ...
602_B. Approximating a Constant Range
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver...
```python n = int(input()) arr = list(map(int,input().split())) d = {} mx = 0 for c in arr: nd = {} nd[c-0.5] = d.get(c-0.5,0)+1 nd[c+0.5] = d.get(c+0.5,0)+1 mx = max(mx,nd[c-0.5],nd[c+0.5]) d = nd print(mx) ```
673_B. Problems for Round
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: * Problemset of ...
```python n, m = map(int, input().split()) s1 = set() s2 = set() for _ in range(m): a, b = map(int, input().split()) a, b = min(a, b), max(a, b) if a in s2 or b in s1: print(0) exit(0) s1.add(a) s2.add(b) if not s2: s2.add(n) s1.add(1) print(max(0, min(s2) - max(s1))) ```
719_C. Efim and Strange Grade
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after th...
```python n, t = map(int, input().split()) tmp = input() s = [] for i in range(n): s.append(tmp[i]) ind = n perenos = 0 for i in range(n): if (s[i] == '.'): nach = i + 1 for i in range(nach, n): if (int(s[i]) > 4): ind = i break if (ind == n): print(*s, sep="") exit() while (...
740_A. Alyona and copybooks
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t...
```python n, a, b, c = map(int, input().split()) h=n%4 if h==0: d=0 else: if h==1: d=min(a*3,a+b,c) if h==2: d=min(a*2,b,c*2) if h==3: d=min(a,b+c,c*3) print(d) ```
787_B. Not Afraid
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one...
```python def test(l): l1=[] l2=[] for i in range(len(l)): if l[i]<0 and l[i] not in l2: l2.append(l[i]) elif l[i]>0 and l[i] not in l1: l1.append(l[i]) if len(l1)==0 or len(l2)==0: return False for x in l1: if (x*(-1)) in l2: retur...