name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p03312 AtCoder Regular Contest 100 - Equal Cut
Snuke has an integer sequence A of length N. He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen. Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the ma...
```python N=int(input()) A=list(map(int,input().split())) from itertools import accumulate C=[0]+list(accumulate(A)) l,r=1,3 x=10**16 for m in range(2,N-1): a,b,c,d=C[l],C[m]-C[l],C[r]-C[m],C[N]-C[r] while l<m-1 and abs(C[m]-C[l+1]*2)<abs(a-b): l+=1 a,b=C[l],C[m]-C[l] while r<N-1 and abs(C[N...
p03469 AtCoder Beginner Contest 085 - Already 2018
On some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in `yyyy/mm/dd` format. For example, January 23, 2018 should be written as `2018/01/23`. After finishing the document, she noticed that she had mistakenly wrote `2017` at the beginning of the date col...
```python s=input() print("2018/"+s[5:]) ```
p03631 AtCoder Beginner Contest 070 - Palindromic Number
You are given a three-digit positive integer N. Determine whether N is a palindromic number. Here, a palindromic number is an integer that reads the same backward as forward in decimal notation. Constraints * 100≤N≤999 * N is an integer. Input Input is given from Standard Input in the following format: N Output...
```python N = input() print('Yes' if N == N[-1::-1] else 'No') ```
p03789 AtCoder Grand Contest 011 - Increasing Numbers
We will call a non-negative integer increasing if, for any two adjacent digits in its decimal representation, the digit to the right is greater than or equal to the digit to the left. For example, 1558, 11, 3 and 0 are all increasing; 10 and 20170312 are not. Snuke has an integer N. Find the minimum number of increasi...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines """ ・1,11,111,...に分解して9個ずつまとめる ・9倍して考える。9N+x の digit sum <= x となる最小のxが知りたい ・xが満たせばx+1も満たすので、二分探索できる """ N = [x - ord('0') for x in map(int,read().rstrip())][::-1] # とりあえず 9 倍 N = [9 * x for x...
p03957 CODE FESTIVAL 2016 qual C - CF
This contest is `CODEFESTIVAL`, which can be shortened to the string `CF` by deleting some characters. Mr. Takahashi, full of curiosity, wondered if he could obtain `CF` from other strings in the same way. You are given a string s consisting of uppercase English letters. Determine whether the string `CF` can be obtai...
```python import re print("YNeos"[re.match(".*C.*F.*",input())==None::2]) ```
p00049 Blood Groups
Create a program that reads the attendance numbers of students in a class and the data that stores the ABO blood group and outputs the number of people for each blood type. There are four types of ABO blood types: A, B, AB, and O. Input A comma-separated pair of attendance numbers and blood types is given over mult...
```python from collections import Counter import sys d=Counter([i.split(",")[1].strip() for i in sys.stdin]) [print(d[i]) for i in ["A","B","AB","O"]] ```
p00179 Mysterious Worm
Dr. A of the Aizu Institute of Biological Research discovered a mysterious insect on a certain southern island. The shape is elongated like a hornworm, but since one segment is shaped like a ball, it looks like a beaded ball connected by a thread. What was strange was that there were many variations in body color, and ...
```python from collections import deque def new_color(s, i, rgb): for color in rgb: if color != s[i] and color != s[i + 1]: break return s[:i] + color * 2 + s[i + 2:] def solve(s): length = len(s) monos = ["r" * length, "g" * length, "b" * length] if s in monos: print(0) return dic = {s:...
p00335 Pancake
At the pancake shop you work for, pancake dough is lined up in a row on an elongated iron plate and baked. Pancakes can be completed by turning them over with a spatula several times. How many times you turn it over to complete it depends on the pancake. Since the spatula is large, two adjacent pancakes will be turned...
```python n = int(input()) pancake = list(map(int, input().split())) ans = 10**9 for i in range(4): cnt = [0] * n cnt[0] += i for j in range(n-1): diff = pancake[j] - cnt[j] if diff > 0: cnt[j] += diff cnt[j+1] += diff diff = pancake[n-1] - cnt[n-1] if diff >...
p00526 Illumination
Illumination Illuminations are displayed in the corridors every year at the JOI High School Cultural Festival. The illuminations consist of N light bulbs, which are lined up in a row from the west side to the east side of the corridor. Each light bulb is either on or off. A machine that operates a light bulb is sleep...
```python N = int(input()) *A, = map(int, input().split()) for i in range(N): A[i] ^= i&1 B = [] prev = A[0]; cnt = 0 for i in range(N): if prev != A[i]: B.append(cnt) cnt = 1 else: cnt += 1 prev = A[i] B.append(cnt) if len(B) == 1: print(B[0]) elif len(B) == 2: print(B[0] + ...
p00693 Cyber Guardian
In the good old days, the Internet was free from fears and terrorism. People did not have to worry about any cyber criminals or mad computer scientists. Today, however, you are facing atrocious crackers wherever you are, unless being disconnected. You have to protect yourselves against their attacks. Counting upon you...
```python # AOJ 1111: Cyber Guardian # Python3 2018.7.15 bal4u import re while True: n, m = map(int, input().split()) if (n|m) == 0: break rule, ans = [], [] for i in range(n): g, s, d = input().split() rule.append((g[0] == 'p', re.compile((s+d).replace("?", "\d")))) for i in range(m): s, d, m = input().sp...
p00834 Inherit the Spheres
In the year 2xxx, an expedition team landing on a planet found strange objects made by an ancient species living on that planet. They are transparent boxes containing opaque solid spheres (Figure 1). There are also many lithographs which seem to contain positions and radiuses of spheres. <image> Figure 1: A strange o...
```python from collections import defaultdict, deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False C0 = [list(map(int, readline().split())) for i in range(N)] U = [1]*N D = defaultdict(list) for i in range(N): ...
p00966 String Puzzle
Problem J String Puzzle Amazing Coding Magazine is popular among young programmers for its puzzle solving contests offering catchy digital gadgets as the prizes. The magazine for programmers naturally encourages the readers to solve the puzzles by writing programs. Let's give it a try! The puzzle in the latest issue ...
```python from bisect import bisect n, a, b, q = map(int, input().split()) W = [input().split() for i in range(a)] X = [int(x) for x, c in W] C = [c for x, c in W] P = [list(map(int, input().split())) for i in range(b)] Y = [y for y, h in P] + [n+1] D = [0]*b for i in range(b): y0, h = P[i]; y1 = Y[i+1] l = ...
p01368 Merry Christmas
International Christmas Present Company (ICPC) is a company to employ Santa and deliver presents on Christmas. Many parents request ICPC to deliver presents to their children at specified time of December 24. Although same Santa can deliver two or more presents, because it takes time to move between houses, two or more...
```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 ...
p01550 Card
Now I have a card with n numbers on it. Consider arranging some or all of these appropriately to make numbers. Find the number obtained by adding all the numbers created at this time. For example, if you have 1 and 2, you will get 4 numbers 1, 2, 12, 21 so the total number is 36. Even if the same numbers are produced ...
```python import sys read = sys.stdin.read write = sys.stdout.write def solve(): MOD = 10**9 + 7 N, *A = map(int, read().split()) L = 10**5 fact = [1]*(L+1) rfact = [1]*(L+1) r = 1 for i in range(1, L+1): fact[i] = r = r * i % MOD rfact[L] = r = pow(fact[L], MOD-2, MOD) for...
p01706 Reverse a Road II
Problem Statement JAG Kingdom is a strange kingdom such that its $N$ cities are connected only by one-way roads. The $N$ cities are numbered $1$ through $N$. ICPC (International Characteristic Product Corporation) transports its products from the factory at the city $S$ to the storehouse at the city $T$ in JAG Kingdom...
```python import sys readline = sys.stdin.readline write = sys.stdout.write from collections import deque class Dinic: def __init__(self, N): self.N = N self.G = [[] for i in range(N)] self.D = {} def add_edge(self, fr, to, cap): forward = [to, cap, None] forward[2] = b...
p02273 Koch Curve
Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n. The Koch curve is well known as a kind of fractals. You can draw a Koch curve in the following algorithm: * Divide a given segment (p1, p2) into three equal segments. * Replace the middle segment by the two sides of...
```python import math def koch(d,x1,y1,x2,y2): if d == 0: return xs = (2*x1+x2)/3 ys = (2*y1+y2)/3 xt = (x1+2*x2)/3 yt = (y1+2*y2)/3 xu = (xt-xs)*math.cos(math.pi/3) - (yt-ys)*math.sin(math.pi/3) + xs yu = (xt-xs)*math.sin(math.pi/3) + (yt-ys)*math.cos(math.pi/3) + ys koch(d...
p02420 Shuffle
Your task is to shuffle a deck of n cards, each of which is marked by a alphabetical letter. A single shuffle action takes out h cards from the bottom of the deck and moves them to the top of the deck. The deck of cards is represented by a string as follows. abcdeefab The first character and the last character co...
```python while 1: s = input() if s == "-": break for _ in range(int(input())): h = int(input()) s = s[h:] + s[:h] print(s) ```
1010_C. Border
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are...
```python from math import gcd n, k = map(int, input().split()) A = list(map(int, input().split())) g = 0 for ai in A: g = gcd(g, ai) s = set() x = 0 while True: d = (g*x) % k if d not in s: s.add(d) else: break x += 1 print(len(s)) print(*sorted(s)) ```
109_C. Lucky Tree
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. One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of...
```python import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mo...
1120_C. Compress String
Suppose you are given a string s of length n consisting of lowercase English letters. You need to compress it using the smallest possible number of coins. To compress the string, you have to represent s as a concatenation of several non-empty strings: s = t_{1} t_{2} … t_{k}. The i-th of these strings should be encode...
```python def f(x): z=[0 for i in range(len(x))] l=0 r=0 for i in range(1,len(x)): if i<=r: z[i]=min(z[i-l],r-i+1) while i+z[i]<len(x) and x[z[i]]==x[i+z[i]]: z[i]+=1 if i+z[i]-1>r: l,r=i,i+z[i]-1 return z a=list(map(int,input('').split()))...
1169_A. Circle Metro
The circle line of the Roflanpolis subway has n stations. There are two parallel routes in the subway. The first one visits stations in order 1 → 2 → … → n → 1 → 2 → … (so the next stop after station x is equal to (x+1) if x < n and 1 otherwise). The second route visits stations in order n → (n-1) → … → 1 → n → (n-1) ...
```python n,a,x,b,y=map(int,input().split(" ")) flag =1 while a!=x and b!=y: a = a+ 1 b = b-1 if(a==n+1): a = 1 if(b==0): b=n if(a==b): flag =0 print('YES') break; if flag==1: print ('NO') ```
1187_C. Vasya And Array
Vasya has an array a_1, a_2, ..., a_n. You don't know this array, but he told you m facts about this array. The i-th fact is a triple of numbers t_i, l_i and r_i (0 ≤ t_i ≤ 1, 1 ≤ l_i < r_i ≤ n) and it means: * if t_i=1 then subbarray a_{l_i}, a_{l_i + 1}, ..., a_{r_i} is sorted in non-decreasing order; * if t_i...
```python """609C""" # import math # import sys def main(): n,m = map(int,input().split()) l = [] s = [] r = [] d = [0]*n for _ in range(m): a,b,c = map(int,input().split()) s.append(a) b-=1 l.append(b) c-=1 r.append(c) if a==1: d[b]+=1 d[c]-=1 dx = [-1]*(n-1) add = 0 for i in range(n): ...
1206_B. Make Product Equal One
You are given n numbers a_1, a_2, ..., a_n. With a cost of one coin you can perform the following operation: Choose one of these numbers and add or subtract 1 from it. In particular, we can apply this operation to the same number several times. We want to make the product of all these numbers equal to 1, in other wo...
```python def func(lst): prod = 1 for item in lst: if item!=0: prod = prod*item return prod w = int(input()) a=list(map(int,input().split())) count=0 count1=0 for i,item in enumerate(a): if item<0 and item !=-1: count+=abs(item+1) a[i]=-1 if ...
1249_B1. Books Exchange (easy version)
The only difference between easy and hard versions is constraints. There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers ...
```python import sys import math import heapq import bisect from collections import Counter from collections import defaultdict from io import BytesIO, IOBase import string class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() ...
128_B. String
One day in the IT lesson Anna and Maria learned about the lexicographic order. String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The le...
```python from heapq import * l=input() k=int(input()) n=len(l) if k>n*(n+1)/2: print("No such line.") quit() ss=[(l[i],i) for i in range(n)] heapify(ss) while k: k-=1 t=heappop(ss) if k==0: print(t[0]) else: if t[1]<n-1: heappush(ss,(t[0]+l[t[1]+1],t[...
1332_C. K-Complete Word
Word s of length n is called k-complete if * s is a palindrome, i.e. s_i=s_{n+1-i} for all 1 ≤ i ≤ n; * s has a period of k, i.e. s_i=s_{k+i} for all 1 ≤ i ≤ n-k. For example, "abaaba" is a 3-complete word, while "abccba" is not. Bob is given a word s of length n consisting of only lowercase Latin letters a...
```python import sys input=sys.stdin.readline t=int(input()) def find(no): global par if par[no]==no: return no par[no]=find(par[no]) return par[no] for _ in range(t): n,k=map(int,input().split()) s=[ord(i)-97 for i in input()] par=[i for i in range(n)] vis=[0 for i in range...
1352_F. Binary String Reconstruction
For some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated. You are given three numbers: * n_0 — th...
```python for testcase in range(int(input())): n0, n1, n2 = map(int, input().split()) if n1 == 0: if n0: ans = "0" * (n0 + 1) else: ans = "1" * (n2 + 1) else: ans = ["0" * (n0 + 1), "1" * (n2 + 1)] for i in range(n1 - 1): ans.append(str(i &...
1372_D. Omkar and Circle
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem! You are given n nonnegative integers a_1, a_2, ..., a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 ≤ i ≤ n, the elements a_{i - 1} and a_...
```python n = int(input()) a = [int(x) for x in input().split()] if n == 1: print(a[0]) exit() evens = [a[0]] odds = [a[1]] for i in range(2,n): if i % 2 == 0: evens.append(evens[-1]+a[i]) else: odds.append(odds[-1] + a[i]) # print(evens) # print(odds) maxi = 0 for i in range(len(evens)): score = evens[i] if ...
1395_C. Boboniu and Bit Operations
Boboniu likes bit operations. He wants to play a game with you. Boboniu gives you two sequences of non-negative integers a_1,a_2,…,a_n and b_1,b_2,…,b_m. For each i (1≤ i≤ n), you're asked to choose a j (1≤ j≤ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise...
```python from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) z=[] ma=0 for i in a: x=float("infinity") for j in b: x=min(i&j,x) ma=max(x,m...
1419_E. Decryption
An agent called Cypher is decrypting a message, that contains a [composite number](https://en.wikipedia.org/wiki/Composite_number) n. All divisors of n, which are greater than 1, are placed in a circle. Cypher can choose the initial order of numbers in the circle. In one move Cypher can choose two adjacent numbers in ...
```python from sys import stdin, stdout # 6 # 2 3 6 # 30 # 2,3,5 # 2 30 6 3 15 5 10 # 2 - (30) - 6 - 3 - 15 - 5 - 10 # P1 - (x*P1) - P1P2 - P2 - (x*P2) - P2P3 - P3 - (x*P3) - P1P3 def decryption(n): r1 = [] r2 = 0 factor_a = getfactor(n) prime_a = getprime(n) hs = set() prime_dic = {} ...
1437_F. Emotional Fishermen
n fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i. Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of sh...
```python from collections import defaultdict import sys input = sys.stdin.readline n = int(input()) a = map(int, input().split()) mod = 998244353 d = defaultdict(int) for x in a: d[x] += 1 d[0] = 0 b = list(d.items()) b.sort() m = len(b) ba = [0] * m cn = [0] * (m + 1) k = h = 0 for i, x in enumerate(b): while...
1462_D. Add to Neighbour and Remove
Polycarp was given an array of a[1 ... n] of n integers. He can perform the following operation with the array a no more than n times: * Polycarp selects the index i and adds the value a_i to one of his choice of its neighbors. More formally, Polycarp adds the value of a_i to a_{i-1} or to a_{i+1} (if such a neighbo...
```python def check(sm): cur = 0 for i in range(n): cur += lis[i] if cur == sm: cur = 0 elif cur > sm: return False return cur == 0 t = int(input()) s = "" for i in range(t): n = int(input()) lis = [*map(int, input().split())] sm = sum(lis) ans = -1 for j in ran...
1487_E. Cheap Dinner
Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert. There are n_1 different types of first courses Ivan can buy (the i-th of them costs a_i coins), n_2 different types of second courses (the i-th of them costs b_i coins), n_3 different types of dri...
```python MAX_VAL = 2 ** 31 def prepare_values(vals): zipped_vals = list(zip(vals, range(1, len(vals) + 1))) zipped_vals.sort() pairs = [(old_i, i) for i, (val, old_i) in enumerate(zipped_vals, 1)] return zipped_vals, dict(pairs) def renumber_ids(dic, l): return [dic[x] for x in l] def get_fir...
1511_B. GCD Length
You are given three integers a, b and c. Find two positive integers x and y (x > 0, y > 0) such that: * the decimal representation of x without leading zeroes consists of a digits; * the decimal representation of y without leading zeroes consists of b digits; * the decimal representation of gcd(x, y) without...
```python for _ in range(int(input())): a,b,c=map(int,input().split()) x=(10**(a-c)+1)*(10**(c-1)) y=10**(b-1) print(x,y) ```
1538_G. Gift Set
Polycarp has x of red and y of blue candies. Using them, he wants to make gift sets. Each gift set contains either a red candies and b blue candies, or a blue candies and b red candies. Any candy can belong to at most one gift set. Help Polycarp to find the largest number of gift sets he can create. For example, if x...
```python import sys,io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline read = lambda: map(int,input().split()) O = [] for _ in range(int(input())): x,y,a,b = read() if a==b: O.append(str(min(x,y)//a)) continue if a<b: a,b = b,a d = a-b L = [0,(x+y)//(a+b)+1] whil...
165_B. Burning Midnight Oil
One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <...
```python """ Solution to the 706B problem on CodeForces. """ import sys import math def binary_search(k, target): beg, end = 1, target while beg + 1 < end: number = (beg + end) // 2 if (lambda_function(target, k, number)): end = number else: beg = number if ...
186_C. Plant
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
```python N = int(input()) result = (pow(2, N, int(1e9 + 7)) * (pow(2, N, int(1e9 + 7)) + 1)) % int(1e9+7) result = (result * pow(2, int(1e9+5), int(1e9+7))) % int(1e9+7) print(result) ```
207_D5. 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('2') ```
281_C. Rectangle Puzzle
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side tha...
```python import os import sys from io import BytesIO, IOBase import math def main(): pass 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 ...
304_B. Calendar
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year...
```python import sys import datetime y1, m1, d1 = map(int, input().split(':')) y2, m2, d2 = map(int, input().split(':')) print(abs((datetime.date(y1, m1, d1) - datetime.date(y2, m2, d2)).days)) ```
330_C. Purification
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the ro...
```python n = int(input()) grid = [input() for line in range(n)] total = sum([ln.count('.') for ln in grid]) rowsWSpcN = len([True for ln in grid if '.' in ln]) colsWSpcN = len([True for col in range(n) if '.' in [ln[col] for ln in grid]]) rowsWSpc = [ln.count('.') for ln in grid] colsWSpc = [[ln[col] for ln in grid].c...
352_A. Jeff and Digits
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number ...
```python import collections n = int(input()) l = list(map(int,input().split())) s = "" if 0 in l: c1 = collections.Counter(l) s+=('0'*c1[0]) x = (c1[5]//9)*9 s = ('5'*x) + s print(int(s)) else: print(-1) ```
376_B. I.O.U.
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The...
```python n,m = map(int, input().split()) debt=[0]*(n+1) for i in range(m): a,b,c = map(int, input().split()) debt[a]-=c debt[b]+=c ans=0 for i in debt: if i>0: ans+=i print(ans) ```
447_C. DZY Loves Sequences
DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one numb...
```python """ pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppp...
469_D. Two Sets
Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Hel...
```python class DisjointSet: def __init__(self, n): self._fa = list(range(n)) def union(self, x, y): x = self.get_father(x) y = self.get_father(y) self._fa[x] = y return y def get_father(self, x): y = self._fa[x] if self._fa[y] == y: return...
542_E. Playing on Graph
Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a res...
```python def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) ...
56_A. Bar
According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check ...
```python a=['ABSINTH','BEER','BRANDY','CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] l=0 for i in range(int(input())): x=input() try: if(int(x)<18): l+=1 except: if(x in a): l+=1 print(l) ```
612_C. Replace To Make Regular Bracket Sequence
You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a...
```python s = input() stack = [] res = 0 for c in s: if c in '(<[{': stack.append(c) else: if not stack: print('Impossible') break last = stack.pop() if last + c not in ('[]', '()', '<>', '{}'): res += 1 else: if stack: print('Impo...
632_C. The Smallest String Concatenation
You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n — the number of strings (...
```python from functools import cmp_to_key def comparator(a,b): return -1 if a+b <= b+a else 1 def smallest_string(str_list): return "".join(sorted(str_list, key=cmp_to_key(comparator))) if __name__ == '__main__': n = int(input()) str_list = [] for _ in range(n): s = input() str_l...
750_B. New Year and North Pole
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the N...
```python n = int(input()) x = 0 y = 0 fl = True for i in range(n): ar = input().split() d = int(ar[0]) if fl: if x == 0 and ar[1] != 'South': fl = False if x == 20000 and ar[1] != 'North': fl = False if ar[1][0] == 'S': if x + d > 20000: ...
818_G. Four Melodies
Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This t...
```python import sys n = int(sys.stdin.readline()) a = [0] + [int(i) for i in sys.stdin.readline().split()] dp = [[0]*(n + 1) for i in range(n + 1)] ans = 0 maxnum = [0] * (10**5 + 2) maxmod = [0] * 7 for y in range(n + 1): maxmod = [0] * 7 for ai in a: maxnum[ai] = 0 for i in range(y): ...
844_C. Sorting by Subsequences
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is...
```python n = int(input()) a = list(map(int, input().split())) a = sorted(range(n), key=lambda i: a[i]) s = [] for i in range(n): if a[i] + 1: l = [] s.append(l) while a[i] + 1: l.append(i + 1) a[i], i = -1, a[i] print(len(s)) for l in s: print(len(l)...
913_C. Party Lemonade
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity. Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci r...
```python n = input().split() l = int(n[1]) n = int(n[0]) c = input().split() cperl = [] for i in range(n): c[i] = int(c[i]) cperl.append([(c[i])/2**i, 2**i, i]) cperl.sort() f = False nl = [0] nc = [0] i = 0 while not f: p = nl[i] nl[i] += cperl[i][1] * ((l-p)//cperl[i][1]) nc[i] += c[cperl[i][2]] ...
935_C. Fifa and Fafa
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by...
```python import math i,x1,y1,x2,y2=input().split() R=int(i) x=int(x1) y=int(y1) xx=int(x2) yy=int(y2) a=(x-xx)*(x-xx) b=(y-yy)*(y-yy) d=math.sqrt(a+b) flag=0 if a+b >= R*R: print(x,end=" ") print(y,end=" ") print(R) flag=1 elif flag!=1 and d!=0: r=(d+R)/2 t=xx + r*(x-xx)/d u=yy + r*(y-yy)/d...
961_B. Lecture Sleep
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute. Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th m...
```python from collections import Counter def main(): n, k = list(map(int, input().split())) a = list(map(int, input().split())) t = list(map(int, input().split())) print(solve(n, k, a, t)) def solve(n, k, a, t): minsum = sum(ai for ai, ti in zip(a,t) if ti == 1) inc = sum(ai for ai, ti in zip...
989_A. A Blend of Springtime
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead. "What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone." "But these blends are at their best, aren't they?" ...
```python s=input() f=False for i in range(len(s)-2): t=s[i:i+3] if 'A' in t and 'B' in t and 'C' in t: f=True if f: print('YES') else: print('NO') ```
p02599 AtCoder Beginner Contest 174 - Range Set Query
We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i. You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have? Constraints * 1\leq N,Q \leq 5 \times 10^5 * 1\leq c_i \leq N * 1\leq ...
```python import sys input=sys.stdin.readline n,q=map(int,input().split()) c=list(map(int,input().split())) l=[list(map(int,input().split())) for i in range(q)] for i in range(q): l[i].append(i) l.sort(key=lambda x:x[1]) L=[-1]*(5*10**5+1) class Bit: def __init__(self,n): self.size=n self.tree=[0]*(n + 1)...
p02730 AtCoder Beginner Contest 159 - String Palindrome
A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied: * S is a palindrome. * Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome. * The string consisting of the (N+3)/2-st through N-th charact...
```python s=input() n=len(s) s1=s[:n//2] s2=s[n//2+1:] if s1==s2 and s1==s1[::-1]: print("Yes") else: print("No") ```
p02863 AtCoder Beginner Contest 145 - All-you-can-eat
Takahashi is at an all-you-can-eat restaurant. The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i. The restaurant has the following rules: * You can only order one dish at a time. The dish ordered will be immediately served and ready to eat. * You cannot or...
```python n, t = map(int, input().split()) items = [tuple(map(int, input().split())) for _ in range(n)] items.sort() ma = items[-1][0] dp = [0] * (t+ma) for a, b in items: for i in range(t+ma-1, a-1, -1): if i-a < t: dp[i] = max(dp[i], dp[i-a] + b) print(max(dp)) ```
p02998 AtCoder Beginner Contest 131 - Must Be Rectangular!
There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i). We will repeat the following operation as long as possible: * Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at...
```python import sys input = sys.stdin.readline M = 10**5 n = int(input()) G = [[] for _ in range(2*M+1)] for _ in range(n): x, y = map(int, input().split()) G[x].append(y+M) G[y+M].append(x) seen = [False]*(2*M+1) def dfs(v): stack = [v] seen[v] = True cnt_x, cnt_y = 0, 0 while stack: v = stack.pop(...
p03139 NIKKEI Programming Contest 2019 - Subscribers
We conducted a survey on newspaper subscriptions. More specifically, we asked each of the N respondents the following two questions: * Question 1: Are you subscribing to Newspaper X? * Question 2: Are you subscribing to Newspaper Y? As the result, A respondents answered "yes" to Question 1, and B respondents answer...
```python n,a,b=map(int,input().split()) and_=min(a,b) or_=max(0, a+b-n) print(and_, or_) ```
p03283 AtCoder Beginner Contest 106 - AtCoder Express 2
In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters: * The ...
```python n,m,q=map(int,input().split()) a=[[0 for _ in range(n)] for _ in range(n)] for i in range(m): x,y=map(int,input().split()) a[x-1][y-1]+=1 for j in range(n): for k in range(1,n): a[j][k]=a[j][k]+a[j][k-1] for l in range(q): ans=0 L,R=map(int,input().split()) for g in range(L-1,R): ...
p03438 AtCoder Petrozavodsk Contest 001 - Two Arrays
You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N. Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal. Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two ac...
```python n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) x=sum(b)-sum(a) y=0 for i in range(n): if a[i]<b[i]: y+=-((a[i]-b[i])//2) print("No" if x<y else "Yes") ```
p03597 AtCoder Beginner Contest 074 - Bichrome Cells
We have an N \times N square grid. We will paint each square in the grid either black or white. If we paint exactly A squares white, how many squares will be painted black? Constraints * 1 \leq N \leq 100 * 0 \leq A \leq N^2 Inputs Input is given from Standard Input in the following format: N A Outputs Print...
```python N = int(input()) ** 2 A = int(input()) print(str(N - A)) ```
p00021 Parallelism
There are four points: $A(x_1, y_1)$, $B(x_2, y_2)$, $C(x_3, y_3)$, and $D(x_4, y_4)$. Write a program which determines whether the line $AB$ and the line $CD$ are parallel. If those two lines are parallel, your program should prints "YES" and if not prints "NO". Input Input consists of several datasets. In the fir...
```python num=int(input()) for i in range (num): info=list(map(float,input().split())) info=list(map(lambda x:int(x*10**6),info)) if info[2]==info[0]: if info[6]==info[4]: print("YES") else: print("NO") elif info[6]==info[4]: if info[2]==info[0]: ...
p00152 Bowling
I decided to do bowling as a recreation of the class. Create a program that inputs the pitching information for each participant and outputs the grade information in descending order of score. If there is a tie, output in ascending order of student ID number. However, it is assumed that the number of participants is 3 ...
```python while 1: m = int(input()) if m == 0: break result = [] for _ in range(m): datas = list(map(int, input().split())) student = datas.pop(0) score = 0 frame = 1 while 1: if frame == 10: while datas != []: ...
p00473 Dividing Snacks
problem There is one bar-shaped candy with a length of N mm (where N is an even number). Two JOI officials decided to cut this candy into multiple pieces and divide them into a total of N / 2 mm. did. For unknown reasons, this candy has different ease of cutting depending on the location. The two examined the candy e...
```python n = int(input()) dp = [float('inf')]*(n+1) dp[0] = 0 cost = [int(input()) for _ in range(n-1)] for i in range(1,n): for j in range(i): if dp[i-j]+cost[i-1] < dp[j]: dp[j] = dp[i-j]+cost[i-1]# = min(dp[j],dp[i-j]+cost[i-1]) if dp[j]+cost[i-1] < dp[i-j]: dp[i-j] = dp[j]+cost[i-1]# = min(dp[...
p00665 Everything Starts With Your Vote
There is the word heuristics. It's a relatively simple approach that usually works, although there is no guarantee that it will work. The world is full of heuristics because it is simple and powerful. Some examples of heuristics include: In an anime program, the popularity of a character is proportional to the total a...
```python import sys input = sys.stdin.readline while True: n, m, k, l = map(int, input().split()) if n == 0: break ranking = [] for _ in range(n): name, x = input().split() x = int(x) ranking.append([x, name]) ranking.sort(key=lambda x:(-x[0], x[1])) favs = {input().strip() for _ in rang...
p00939 Bringing Order to Disorder
Example Input 20 Output 4
```python def solve(): D = input() N = len(D) *DI, = map(int, D) su = sum(DI) pd = 1 for d in D: pd *= int(d) + 1 memo = [{} for i in range(N)] def dfs0(i, s, p): key = (s, p) if i == N: return s > 0 or (s == 0 and p < pd) if key in memo[i]: ...
p01072 Plants
Problem Gaccho owns a field separated by W horizontal x H vertical squares. The cell in the x-th column and the y-th row is called the cell (x, y). Only one plant with a height of 0 cm is planted on the land of some trout, and nothing is planted on the land of other trout. Gaccho sprinkles fertilizer on the field at ...
```python #!/usr/bin/env python3 import itertools import math def main(): w, h, t = map(int, input().split()) p = int(input()) fert = [] for _ in range(p): x, y, _ = map(int, input().split()) fert.append((y, x)) stage = [list(map(int, input().split())) for _ in range(h)] for r...
p01680 Everlasting -One-
Problem Statement "Everlasting -One-" is an award-winning online game launched this year. This game has rapidly become famous for its large number of characters you can play. In this game, a character is characterized by attributes. There are $N$ attributes in this game, numbered $1$ through $N$. Each attribute takes...
```python from collections import deque MOD = 10**9 + 7 while 1: N, M = map(int, input().split()) if N == M == 0: break G = [[] for i in range(N)] for i in range(M): a, b = map(int, input().split()) G[a-1].append(b-1) G[b-1].append(a-1) que = deque() used = [0]*N ...
p01824 Surface Area of Cubes
Example Input 2 2 2 1 0 0 0 Output 24
```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 = 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 ...
p02246 15 Puzzle
The goal of the 15 puzzle problem is to complete pieces on $4 \times 4$ cells where one of the cells is empty space. In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 15 as shown below. 1 2 3 4 6 7 8 0 5 10 11 12 9 13 14 15 You can move a piece toward the empty space a...
```python import heapq distance = ( (0,1,2,3,1,2,3,4,2,3,4,5,3,4,5,6), (1,0,1,2,2,1,2,3,3,2,3,4,4,3,4,5), (2,1,0,1,3,2,1,2,4,3,2,3,5,4,3,4), (3,2,1,0,4,3,2,1,5,4,3,2,6,5,4,3), (1,2,3,4,0,1,2,3,1,2,3,4,2,3,4,5), (2,1,2,3,1,0,1,2,2,1,2,3,3,2,3,4), ...
p02392 Range
Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No". Constraints * 0 ≤ a, b, c ≤ 100 Input Three integers a, b and c separated by a single space are given in a line. Output Print "Yes" or "No" in a line. Examples Input 1 3 8 Output Yes Input 3 8 1 Output...
```python a,b,c = map(int,(input().split())) if(a < b and b < c): print("Yes") else: print("No") ```
1015_F. Bracket Substring
You are given a bracket sequence s (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of...
```python def add(a,b): if a+b>=mod: return (a+b)%mod return a+b n=int(input())*2 s=input() d=[[0,0] for i in range(len(s)+1)] aux='' for i in range(len(s)): if s[i]=='(': d[i][1]=i+1 x=aux+')' for j in range(1,i+2): if x[j::] ==s[0:len(x)-j]: d[i]...
1062_A. A Prank
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 ≤ a_1 < a_2 < … < a_n ≤ 10^3, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he...
```python n = int(input()) l = [*map(int, input().split())] res = i = 0 while i < n: j = i + 1 while j < n and l[j] - l[j - 1] == 1: j += 1 res = max(res, j - i - 2 + int(l[i] == 1) + int(l[j - 1] == 1000)) # print(res, i, j) i = j print(min(res, n - 1)) ```
1103_B. Game with modulo
This is an interactive problem. Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: * "x", if (x mod a) ≥ (y mod a). ...
```python import sys def ask(x, y): print("?", x, y) return input() == "y" while input() == "start": if not ask(0, 1): print("! 1") continue d = 1 while ask(d, d * 2): d *= 2 r = d l = d // 2 while l + 1 < r: m = (l + r) // 2 if ask(m, m * 2): ...
1131_B. Draw!
You still have partial information about the score during the historic football match. You are given a set of pairs (a_i, b_i), indicating that at some point during the match the score was "a_i: b_i". It is known that if the current score is «x:y», then after the goal it will change to "x+1:y" or "x:y+1". What is the l...
```python n=int(input()) arr= [] arr.append((0,0)) ans = 1 for _ in range(n): a,b=map(int,input().split()) arr.append((a,b)) for i in range(1,n+1): preva = arr[i-1][0] prevb = arr[i-1][1] cura = arr[i][0] curb = arr[i][1] if preva == cura and prevb==curb: pass elif preva==prevb: ...
1151_D. Stas and the Queue at the Buffet
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of n high school students numbered from 1 to n. Initially, each student i is on position i. Each student i is characterized by two numbers — a_i and b_i. Dissatisfaction of the person i equals the product of a_i b...
```python # Why do we fall ? So we can learn to pick ourselves up. t = int(input()) ss = [] for _ in range(0,t): a,b = map(int,input().split()) ss.append([b-a,a,b]) ss = sorted(ss) s = 0 for i in range(1,t+1): s += ss[i-1][1]*(i-1)+ss[i-1][2]*(t-i) print(s) ```
1173_C. Nauuo and Cards
Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n...
```python n=int(input()) arr1=list(map(int,input().split())) arr2=list(map(int,input().split())) arr3=[0] mini=n+1 for i in range(0,len(arr2)): if arr2[i]<mini and arr2[i]!=0: mini=arr2[i] if mini==n+1: print(len(arr1)) exit() q=n+1 a=0 b=0 m=0 for i in range(0,len(arr2)): if mini==arr2[i]: ...
122_C. Lucky Sum
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what i...
```python li=set() def addi(n): if n>10**10+1: return li.add(n) addi(n*10+4) addi(n*10+7) addi(4) addi(7) li=list(set(li)) li.sort() #print(len(li)) l,r=map(int,input().split()) ans=0 for x in li: #print(x) if x>=r: #print("l",l) ans+=x*(r-l+1) #print("ans",ans) ...
1251_B. Binary Palindromes
A palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i ∈ [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes. You have n binary strings s_1, s_2, ..., s_n (each s_i consists of zeroes and/or ones). You ca...
```python Q = int(input()) for q in range(Q): n = int(input()) arr = [input() for i in range(n)] lens = [len(i) % 2 for i in arr] counts = [i.count('1') for i in arr] if sum(counts) % 2 == 0: print(n) else: if 1 in lens: print(n) else: print(n - 1...
1294_A. Collecting Coins
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that ...
```python import sys T = int(sys.stdin.readline()) for _ in range(T): a, b, c, n = map(int , sys.stdin.readline().split()) if not (a+b+c+n)%3 and max(a, b, c)<=(a+b+c+n)//3: print('YES') else: print('NO') ```
1315_A. Dead Pixel
Screen resolution of Polycarp's monitor is a × b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x, y) (0 ≤ x < a, 0 ≤ y < b). You can consider columns of pixels to be numbered from 0 to a-1, and rows — from 0 to b-1. Polycarp wants to open a rectangular window of maximal size, which ...
```python t=int(input()) for _ in range(t): a,b,x,y=map(int,input().split()) print(max(max(a-1-x,x)*b,max(b-1-y,y)*a)) ```
1359_A. Berland Poker
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he...
```python def main_function(): from sys import stdin from sys import stdout from math import ceil input = stdin.readline print = stdout.write for _ in range(int(input())): n, m, k = map(int, input().split()) if m <= n//k: print(f'{m}\n') else: pri...
1379_C. Choosing flowers
Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly n flowers. Vladimir went to a flower shop, and he was amazed to see that there are m types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers ...
```python from sys import stdin import math from bisect import bisect_right input = stdin.readline for _ in range(int(input())): n, m = map(int, input().split(" ")) a = [] xs = [] ans = 0 for i in range(m): x, y = map(int, input().split(" ")) a.append((y, x)) xs.append(x) ...
139_A. Petr and Book
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
```python n=int(input()) l=list(map(int,input().split())) i=0 while(n>0): if i==7: i=0 n -= l[i] if n>0: i+=1 print(i+1) ```
1468_F. Full Turn
There are n persons located on a plane. The i-th person is located at the point (x_i, y_i) and initially looks at the point (u_i, v_i). At the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full 360-degree turn. It is said...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): def __init__(self, file): self.newlines = 0 self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write ...
1492_E. Almost Fault-Tolerant Database
You are storing an integer array of length m in a database. To maintain internal integrity and protect data, the database stores n copies of this array. Unfortunately, the recent incident may have altered the stored information in every copy in the database. It's believed, that the incident altered at most two elemen...
```python def solvetestcase(): n,m = [int(e) for e in input().split(" ")] db = [] for _ in range(n): db.append([int(e) for e in input().split(" ")]) return solve_helper(n,m,db) def solve_helper(n,m,db, start=True): found_candidate = -1 max_diffs = 0 for i in range(1,n): dif...
1515_F. Phoenix and Earthquake
Phoenix's homeland, the Fire Nation had n cities that were connected by m roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair n-1 of these roads so that all the cities are connected again. The i-th city has a_i tons of asphalt. x tons of asphalt are used up when repairing a road...
```python from collections import deque class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, a): acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy] ...
1542_E1. Abnormal Permutation Pairs (easy version)
This is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on n. You can only make hacks if both versions are solved. A permutation of 1, 2, …, n is a sequence of n integers, where each integer from 1 to n appears exactly once. For example, [2,3,1,4] i...
```python def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0...
16_E. Fish
n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The ...
```python # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase # sys.setrecursionlimit(10**4) def main(): n=int(input()) prob=[] for _ in range(n): prob.append(list(map(float,input().split()))) dp=[-1 for ...
190_C. STL
Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer. We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integer...
```python ###pyrival template for fast IO import os import sys from io import BytesIO, IOBase # 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....
214_C. Game
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies....
```python n = int(input()) h = [int(q) - 1 for q in input().split()] u = [set([int(q) - 1 for q in input().split()][1:]) for i in range(n)] t = 1e9 def g(): for i in p: if h[i] == k and not v[i]: return i for k in range(3): p = list(range(n)) d = -1 v = [q.copy() for q in u] w...
263_A. Beautiful Matrix
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
```python mat = [] for x in range(0, 5): a = list(map(int, input().split())) mat.append(a) for i in a: if i == 1: row = a.index(1) col = mat.index(a) print(abs(row - 2) + abs(col - 2)) ```
287_A. IQ Test
In the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the p...
```python # Description of the problem can be found at http://codeforces.com/problemset/problem/287/A l_l = list([input() for _ in range(4)]) dx = [ 0, 0, 1, 1] dy = [ 0, -1, -1, 0] for i in range(3): for j in range(3): t = 0 for z in range(4): t += (-1 if l_l[i + dy[z]][j + dx[z]...
312_A. Whose sentence is it?
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of ...
```python import re n = int(input()) for i in range(n): s = input() rainbow = re.search(r"\Amiao\.", s) freda = re.search(r"lala\.\Z", s) if rainbow and not freda: print("Rainbow's") elif freda and not rainbow: print("Freda's") else: print("OMG>.< I don't know!") ```
334_D. Chips
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output....
380_C. Sereja and Brackets
Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")". Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of...
```python import sys input = sys.stdin.readline s = input() M = int(input()) def next_pow_2(n): p = 1 while p < n: p <<= 1 return p def represented_range(node, size): l = node r = node while l < size: l = 2*l r = 2*r + 1 return l-size, r-size class SegTree: ...
401_B. Sereja and Contests
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot...
```python import math x,k=map(int,input().split(" ")) given=[0 for x in range(x-1)] for _ in range(k): a=list(map(int,input().split(" "))) if a[0]==2: given[a[1]-1]=1 else: given[a[2]-1]=1 given[a[1]-1]=1 cmax=0 for y in range(x-1): if given[y]==0: cmax=cmax+1 pp=0 t=0 ss...