name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1084_E. The Fair Nut and Strings
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time. Then, he lost his sheet with strings. He remembers that all written strings were lexicog...
```python def solve(n, k, start, end): tot = 0 lvl = 1 for i in range(n): lvl += lvl - int(start[i] == 'b') - int(end[i] == 'a') if lvl >= k: tot += k * (n-i) break else: tot += lvl return tot n, k = map(int, input().split()) start = input...
1104_B. Game with string
Two people are playing a game with a string s, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A p...
```python s = input() stack = [] l = "" t = 0 for x in s: if x == l: t += 1 stack.pop(-1) if len(stack) > 0: l = stack[-1] else: l = "" else: stack.append(x) l = x if t % 2 == 0: print("No") else: print("Yes") ```
1152_C. Neko does Maths
Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher. Neko has two integers a and b. His goal is to find a non-negative integer k such that the least common multiple of a+k and b+k is the smallest possible. If there are multiple optimal integers k, he needs ...
```python a, b = map(int, input().split()) q = abs(a-b) if q == 0: print(0) else: dq = [] dq2 = [] for i in range(1, int(q**0.5)+1): if not q%i: dq.append(i) if i != q//i: dq2 = [q//i] + dq2 dq = dq + dq2 dq = dq[::-1] if a < b: a, b = ...
1174_A. Ehab Fails to Be Thanos
You're given an array a of length 2n. Is it possible to reorder it in such way so that the sum of the first n elements isn't equal to the sum of the last n elements? Input The first line contains an integer n (1 ≤ n ≤ 1000), where 2n is the number of elements in the array a. The second line contains 2n space-separat...
```python n = int(input()) a = list(map(int, input().split())) a.sort() if sum(a[:n]) < sum(a[n:]): print(*a) else: print(-1) ```
1191_F. Tokitsukaze and Strange Rectangle
There are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area. The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be ...
```python from sys import stdin, stdout from collections import defaultdict n = int(input()) pts = [] for i in range(n): x, y = map(int, stdin.readline().split()) pts.append((x, y)) pts.sort() cts = [0]*(n+1) x_map = {} ctr = 0 for p in pts: if p[0] not in x_map: ctr += 1 x_map[p[0]] = ctr...
1230_C. Anadi and Domino
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi ha...
```python n, m = map(int, input().split()) edges = [[int(x) - 1 for x in input().split()] for _ in range(m)] p = [6 ** i for i in range(n)] res = 0 for mask in range(6 ** n): colors = [0] + [(mask // p[i]) % 6 for i in range(n)] used = set(tuple(sorted([colors[u], colors[v]])) for u, v in edges) res = max(r...
1271_E. Common Number
At first, let's define function f(x) as follows: $$$ \begin{matrix} f(x) & = & \left\{ \begin{matrix} x/2 & \mbox{if } x is even \\\ x - 1 & \mbox{otherwise } \end{matrix} \right. \end{matrix} $$$ We can see that if we choose some value v and will apply function f to it, then apply f to f(v), and so on, we'll eventua...
```python n, k = map(int,input().split()) p = 1 w = 0 while p * 2 <= k: p *= 2 w += 1 kk = k - p #2**w * tr <= n - kk odd = (n-kk)//2**w if odd % 2 == 0: odd -= 1 p = 1 w = 0 while 2 * (2*p - 1) < k: p *= 2 w += 1 poz = k - 2*(p-1) if poz == 0: #2**(w-1) * strzal + (2**w-1) <= n even = (n-(2**w-1))//2**(w-1) ...
1294_F. Three Paths on a Tree
You are given an unweighted tree with n vertices. Recall that a tree is a connected undirected graph without cycles. Your task is to choose three distinct vertices a, b, c on this tree such that the number of edges which belong to at least one of the simple paths between a and b, b and c, or a and c is the maximum pos...
```python import sys input = sys.stdin.readline n=int(input()) E=[[] for i in range(n+1)] for i in range(n-1): x,y=map(int,input().split()) E[x].append(y) E[y].append(x) def dfs(t): L=[-1]*(n+1) L[t]=0 Q=[t] while Q: x=Q.pop() for to in E[x]: if L[to]==-1: ...
1337_B. Kana and Dragon Quest game
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. <image> The dragon has a hit p...
```python import math t=int(input()) for i in range(t): x,n,m=map(int,input().split()) if(x-m*10<=0): print("YES") else: s=x for i in range(n): j=math.floor(s/2)+10 # print(x," ",j) if(j>s): break else: s=j if(s-(m*10)<=0): print("YES") else: print("NO") ```
137_A. Postcards and photos
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
```python import math l = list(map(str, input())) t = 0 while len(l) != 0: c = 0 b = l[0] x = 1 while True: if x == len(l): t += math.ceil(x / 5) l = [] break elif b == l[x]: x += 1 else: t += math.ceil(x/5) ...
13_A. Numbers
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1. Note that all computa...
```python import math def sumInBase(num, base): ans = 0 while num != 0: ans += num % base num //= base return ans A = int(input()) sumofAll = 0 for i in range(2, A): sumofAll += sumInBase(A, i) temp = math.gcd(sumofAll, A - 2) print('{}/{}'.format(sumofAll // temp, (A - 2) // temp)) ...
1423_J. Bubble Cup hypothesis
The Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem: Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,...
```python T = input() mod = int(1e9 + 7) a = map(int, input().split()) c = [] for n in a: b = (n // 2 + 2) b = b * b b //= 4 c.append(str(b % mod)) print(' '.join(c)) ```
1443_C. The Delivery Dilemma
Petya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants. Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his ord...
```python from itertools import accumulate for _ in range(int(input())): n, delivery, pickup = int(input()), [*map(int, input().split())], [*map(int, input().split())] dp = sorted(zip(delivery, pickup)) new_delivery = [i[0] for i in dp] new_pickup = [i[1] for i in dp] new_pickup_acc = [*accumulate(n...
1468_L. Prime Divisors Selection
Suppose you have a sequence of k integers A = [a_1, a_2, ... , a_k] where each a_i ≥ 2. A sequence of prime integers P = [p_1, p_2, ..., p_k] is called suitable for the sequence A if a_1 is divisible by p_1, a_2 is divisible by p_2 and so on. A sequence of prime integers P is called friendly if there are no unique in...
```python from math import gcd def t_prime(n): if n == 1: return False for p in [2,3,5,7,11,13,17,19,23]: if p < n and pow(p,n-1,n) != 1: return False return True primes = [i for i in range(2,10**5) if t_prime(i)];pset = set(primes);n, k = map(int, input().split());l = list(map(int...
1493_F. Enchanted Matrix
This is an interactive problem. There exists a matrix a of size n × m (n rows and m columns), you know only numbers n and m. The rows of the matrix are numbered from 1 to n from top to bottom, and columns of the matrix are numbered from 1 to m from left to right. The cell on the intersection of the x-th row and the y-...
```python import sys input = sys.stdin.readline flush = sys.stdout.flush from collections import Counter from math import sqrt def query(h, w, i1, j1, i2, j2): print("? {} {} {} {} {} {}".format(h, w, i1, j1, i2, j2)) flush() return int(input()) def fac(x): cnt = Counter() if not x % 2: wh...
1516_C. Baby Ehab Partitions Again
Baby Ehab was toying around with arrays. He has an array a of length n. He defines an array to be good if there's no way to partition it into 2 subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in a so tha...
```python import collections import itertools from functools import reduce mod = (10 ** 9) + 7 def permutationbysum(): for _ in range(int(input())): num, l, r, achieve = map(int, input().split()) k = r - l + 1 if (k * (k + 1)) // 2 <= achieve <= (k * (num * 2 + 1 - k)) // 2: o...
1543_D1. RPD and Rap Sheet (Easy Version)
This is the easy version of the problem. The only difference is that here k=2. You can make hacks only if both the versions of the problem are solved. This is an interactive problem. Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwise XOR ...
```python try: import sys def solve(): n,k = map(int,input().split()) print(0) sys.stdout.flush() glad = int(input()) if(glad == 1): return for i in range(1 , n): print(i^(i-1)) sys.stdout.flush() glad = int...
171_E. MYSTERIOUS LANGUAGE
You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language. Input This program has only one test, and it's empty (it doesn't give your program anything to rea...
```python n=input() print("INTERCAL") ```
191_C. Fools and Roads
They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each ...
```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...
215_C. Crosses
There is a board with a grid consisting of n rows and m columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number i and column number j as (i, j). A group of six numbers (a, b, c, d, x0, y0), where 0 ≤ a...
```python from sys import stdin def read(): return map(int, stdin.readline().split()) def ways(h,w,area): if area == h*w: return 2 * ( (h+1)//2 * (w+1)//2 ) - 1 if area > h*w: return 0 if area < h+w-1: return 0 area = h*w - area if area % 4 != 0: return 0 area //= 4 ans = 0 h //= 2 w //=...
239_C. Not Wool Sequences
A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 ≤ l ≤ r ≤ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0. The expression <image> means applying the o...
```python n, m = map(int, input().split()) MOD = 10 ** 9 + 9 ans = pow(2, m, MOD) - 1 step = pow(2, m, MOD) - 2 for i in range(n - 1): ans = (ans * step) % MOD step -= 1 while ans < 0: ans += MOD while ans >= MOD: ans -= MOD print(ans) ```
264_A. Escape from Stones
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order. The stones always fall to the center of Liss's inter...
```python z,zz=input,lambda:list(map(int,z().split())) fast=lambda:stdin.readline().strip() zzz=lambda:[int(i) for i in fast().split()] szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz()) from string import * from re import * from collections import * from queue import * from sys import * from collec...
288_A. Polo the Penguin and Strings
Little penguin Polo adores strings. But most of all he adores strings of length n. One day he wanted to find a string that meets the following conditions: 1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. 2. No two neighbouring...
```python a,b=[int(i) for i in input().split()] if b>a: print(-1) else: if b==1: if a>1: print(-1) else:print('a') else: b-=2 for i in range(0,a-b): if i%2==0:print('a',end='') else:print('b',end='') for i in range(b): p...
313_A. Ilya and Bank Account
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
```python n=int(input()) if n>=0: print(n) else: r=n+(2*n) n=str(n) k=len(n) ones=int(n[k-1]) huns=int(n[k-2]) if ones>=huns: print(int(n[:k-1])) else: f=n[:k-2]+n[k-1] print(int(f)) ```
358_D. Dima and Hares
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with c...
```python from collections import defaultdict from itertools import accumulate import sys input = sys.stdin.readline ''' for CASES in range(int(input())): n, m = map(int, input().split()) n = int(input()) A = list(map(int, input().split())) S = input().strip() sys.stdout.write(" ".join(map(str,ANS))+"\n") ''' inf = 10...
381_C. Sereja and Prefixes
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current seq...
```python MAX_LEN = int(1e5) n = int(input()) a = [list(map(int, input().split())) for i in range(n)] m = int(input()) b = list(map(lambda x:int(x)-1, input().split())) curr, k, c, res = 0, 0, [], [] for i in range(n): t = a[i] last = curr if t[0] == 1: curr += 1 if len(c) < MAX_LEN: ...
402_B. Trees in a Row
The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen...
```python n, k = map(int, input().split()) a = list(map(int, input().split())) tmp = {} for i in range(n): x = a[i] - i * k if x > 0: tmp[x] = tmp.get(x, 0) + 1 x = max(tmp, key = lambda x: tmp[x]) print(n - tmp[x]) if tmp[x] == n: exit(0) for i in range(n): if x + i * k > a[i]: print('+...
42_C. Safe cracking
Right now you are to solve a very, very simple problem — to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both...
```python ring = list(map(int, input().split())) n = len(ring) record = [] def halve(pos): a, b = pos % n, (pos + 1) % n ring[a] //= 2 ring[b] //= 2 record.append('/%d' % (a + 1)) def increment(pos): a, b = pos % n, (pos + 1) % n ring[a] += 1 ring[b] += 1 record.append('+%d' % (a + 1)) while True: ...
452_A. Eevee
You are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Syl...
```python n = int(input()) s = input() evol = ['vaporeon', 'jolteon', 'flareon', 'espeon', 'umbreon', 'leafeon', 'glaceon', 'sylveon'] for e in evol : if len(e) != n : continue for i in range(n): if s[i] != e[i] and s[i] != '.': break if i == n-1 : print(e) break...
521_E. Cycling City
You are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to bot...
```python from typing import List import sys n, m = [int(a) for a in input().split(' ')] adj: List[List[int]] = [[]] + [[] for _ in range(n)] visited: List[bool] = [False] * (n + 1) parent: List[int] = [0] * (n + 1) depth: List[int] = [0] * (n + 1) low: List[int] = [0] * (n + 1) cx: List[int] = [0] * (n + 1) cy: ...
549_B. Looksery Party
The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time ...
```python n=int(input().strip()) nums=['']+[' '+input().strip() for _ in range(n)] a=[0]+list(map(int,input().split())) def send(x): for i in range(1,n+1): if nums[x][i]=='1': a[i]-=1 vis=[0]*(n+1) while True: for i in range(1,n+1): if not vis[i] and not a[i]: vis[i]=...
575_D. Tablecity
There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves. Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Eac...
```python print(2001) for i in range(1 , 1001): print(f"{i} 1 {i} 2") print(f"1 1 1 2") for i in range(1 , 1001): print(f"{i} 1 {i} 2") ```
597_B. Restaurant
A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time li and the finish time ri (li ≤ ri). Restaurant management can accept and reject orders. What is the maximal number of orders the ...
```python n=int(input()) a=[] for i in range(n): a.append(tuple(map(int,input().split()))) a.sort(key=lambda x:x[1]) cnt=0;cur=-10 i=0 while i<n: if cur<a[i][0]: cur=a[i][1] cnt+=1 i+=1 print(cnt) ```
618_D. Hamiltonian Spanning Tree
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are <image> roads in total. It takes exactly y seconds to traverse any single road. A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any t...
```python from collections import defaultdict from collections import deque from functools import reduce n, x, y = [int(x) for x in input().split()] E = defaultdict(set) for i in range(n-1): u, v = [int(x) for x in input().split()] E[u].add(v) E[v].add(u) if x > y: for v in E: if len(E[v]) == n...
639_B. Bear and Forgotten Tree 3
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n. Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only th...
```python n, d, h = list(map(int, input().split())) if h < (d + 1) // 2 or (h == d == 1 and n > 2): print(-1) exit() i = 1 while i <= h: print(i, i + 1) i += 1 if i <= d: print(1, h + 2) i = h + 2 while i <= d: print(i, i + 1) i += 1 i += 1 while i <= n: if h == d: print(2, ...
690_A3. Collective Mindsets (hard)
Heidi got one brain, thumbs up! But the evening isn't over yet and one more challenge awaits our dauntless agent: after dinner, at precisely midnight, the N attendees love to play a very risky game... Every zombie gets a number ni (1 ≤ ni ≤ N) written on his forehead. Although no zombie can see his own number, he can ...
```python t = int(input()) for _ in range(t): n, r = map(int, input().split()) s = sum(map(int, input().split())) x = 1 while (s + x + r) % n != 0: x += 1 print(x) ```
713_A. Sonya and Queries
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: 1. + ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occur...
```python #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict from itertools import permutations BUFSIZE = 8192 class FastIO(IOBase): newli...
733_E. Sleep in Class
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs. The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest ste...
```python n=int(input()) string = input() q1,q2,B,C=[],[],[],[] A=0 for i in range(n): if string[i] == "D": q1.append(i) else: q2.append(n-1-i) for i in range(len(q1)): A+=(q1[i]-i)*2+1 B.append(A) A=0 temp = [] for i in range(len(q2)): A+=(q2[len(q2)-1-i]-i)*2+1 C.append(A) C....
779_C. Dishonest Sellers
Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi. Not all of sellers are honest, so now some products could be more expensive than after a week of discou...
```python n,k=map(int,input().split()) l=list(map(int,input().split())) m=list(map(int,input().split())) c=0 s=0 for i in range(n): if(l[i]<=m[i]): s+=l[i] c+=1 if(c>=k): for i in range(n): if(l[i]>m[i]): s+=m[i] print(s) else: r=k-c p=[] for i in range(n):...
848_E. Days of Floral Colours
The Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days. On the rim of the Floral Clock are 2n flowers, numbered from 1 to 2n clockwise, each of which has a colour among all n possible ones. For each colour, the...
```python #https://codeforces.com/problemset/problem/848/E f = [0, 4, 8, -1, 16, -10, 4, -12, -48, 26, -44, 15, -16, -4, -4, -1] jly = 998244353 t = 0 x = [0, 0, 0, 24, 4, 240, 204, 1316, 2988, 6720, 26200, 50248, 174280, 436904, 1140888, 3436404] n = int(input()) for i in range(16, n + 1): t = 0 for j in range...
870_C. Maximum splitting
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prime, i.e. if...
```python solve = lambda n: -1 if n in {1, 2, 3, 5, 7, 11} else n // 4 - n % 2 print(*[solve(int(input())) for i in range(int(input()))]) ```
897_B. Chtholly's request
— Thanks a lot for today. — I experienced so many great things. — You gave me memories like dreams... But I have to leave now... — One last request, can you... — Help me solve a Codeforces problem? — ...... — What? Chtholly has been thinking about a problem for days: If a number is palindrome and length of its ...
```python import itertools as it k, p = [int(elem) for elem in input().split()] def build_palindroms(digits): global k global val n = digits // 2 values = [10 ** (digits - 1 - i) + 10 ** i for i in range(n)] for comb in it.product(range(1, 10), *[range(0, 10) for i in range(n - 1)]): if not...
918_C. The Monster
As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. <image> Thus, he came up with a puz...
```python s = input() res, n = 0, len(s) for i in range(n-1): j, c, q = i , 0, 0 while j < n and c + q >= 0: if(s[j] == '('): c += 1 elif(s[j] == ')'): c -= 1 else: q += 1 if(c < q): c, q = q, c res += (c == q) j += 1 print(res) ```
940_C. Phone Numbers
And where the are the phone numbers? You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t. It's guaranteed that the answ...
```python n,k=map(int,input().split()) s=input() l=sorted(list(set(list(s)))) if k<=n: for i in range(k-1,-1,-1): z=[] for j in l: if s[i]<j: z.append(j) if len(z)>0: z.sort() t=s[:i]+z[0]+l[0]*(k-i-1) break else: t=s+(k-n)*l[0] print(t) ```
p02632 AtCoder Beginner Contest 171 - Strivore
How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"? The answer can be enormous, so print it modulo (10^9+7). Constraints * K is an integer between 1 and 10^6 (inclusive). * S is a string of length between 1...
```python import sys,queue,math,copy,itertools,bisect,collections,heapq def main(): MOD = 10**9 + 7 NI = lambda : int(sys.stdin.readline()) SI = lambda : sys.stdin.readline().rstrip() K = NI() S = SI() LS = len(S) f = [1] * (K+LS) r = [1] * (K+LS) c = 1 for i in range(1, K + L...
p02763 AtCoder Beginner Contest 157 - Simple String Queries
You are given a string S of length N consisting of lowercase English letters. Process Q queries of the following two types: * Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) * Type 2: answer the number of different characters occurring in the substring of S betwee...
```python def main(): import sys b=sys.stdin.buffer input=b.readline n=int(input()) d=[0]*n+[1<<c-97for c in input()[:n]] for i in range(n-1,0,-1):d[i]=d[i+i]|d[i-~i] r=[] add=r.append input() for q,a,b in zip(*[iter(b.read().split())]*3): i,s=int(a)+n-1,0 if q<b'2': d[i]=1<<b[0]-97 ...
p02898 AtCoder Beginner Contest 142 - Roller Coaster
N friends of Takahashi has come to a theme park. To ride the most popular roller coaster in the park, you must be at least K centimeters tall. The i-th friend is h_i centimeters tall. How many of the Takahashi's friends can ride the roller coaster? Constraints * 1 \le N \le 10^5 * 1 \le K \le 500 * 1 \le h_i \le 5...
```python n, k = map(int, input().split()) h = list(map(int, input().split())) print(sum(x >= k for x in h)) ```
p03033 AtCoder Beginner Contest 128 - Roadwork
There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 ...
```python from collections import deque, defaultdict from heapq import heappush, heappop import sys input = sys.stdin.readline N, Q = map(int, input().split()) events = [None] * (2*N) for i in range(N): S, T, X = map(int, input().split()) events[2*i] = (S-X, X) events[2*i+1] = (T-X, -X) events.sort(key=lam...
p03174 Educational DP Contest - Matching
There are N men and N women, both numbered 1, 2, \ldots, N. For each i, j (1 \leq i, j \leq N), the compatibility of Man i and Woman j is given as an integer a_{i, j}. If a_{i, j} = 1, Man i and Woman j are compatible; if a_{i, j} = 0, they are not. Taro is trying to make N pairs, each consisting of a man and a woman...
```python def popcount(i): assert 0 <= i < 0x100000000 i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 N = int(input()) A = [list(map(int, input().split())) for _ in range(N)] mod = 10**9+7 dp = [0]*(2*...
p03322 AtCoder Regular Contest 099 - Eating Symbols Hard
In Takahashi's mind, there is always an integer sequence of length 2 \times 10^9 + 1: A = (A_{-10^9}, A_{-10^9 + 1}, ..., A_{10^9 - 1}, A_{10^9}) and an integer P. Initially, all the elements in the sequence A in Takahashi's mind are 0, and the value of the integer P is 0. When Takahashi eats symbols `+`, `-`, `>` an...
```python import random from collections import defaultdict def solve(n, s, xs, m): ans = [10 ** 9] * (n + 1) for x in xs: p = 0 h = 0 y = 1 r = pow(x, m - 2, m) pos = [0] * (n + 1) hashes = [0] * (n + 1) for i, c in enumerate(s, start=1): if...
p03476 AtCoder Beginner Contest 084 - 2017-like Number
We say that a odd number N is similar to 2017 when both N and (N+1)/2 are prime. You are given Q queries. In the i-th query, given two odd numbers l_i and r_i, find the number of odd numbers x similar to 2017 such that l_i ≤ x ≤ r_i. Constraints * 1≤Q≤10^5 * 1≤l_i≤r_i≤10^5 * l_i and r_i are odd. * All input values ...
```python from itertools import accumulate q=int(input()) lr=[list(map(int,input().split())) for i in range(q)] p=[2] pc=[0]*100001 pc[2]=1 ans=[0]*100001 for i in range(3,100001): for j in p: if(i%j==0): break if(j*j>i): p.append(i) pc[i]=1 if(pc[i//2+1]==1): ans[i]=1 br...
p03641 AtCoder Regular Contest 080 - Young Maids
Let N be a positive even number. We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below. First, let q be an empty sequence. Then, perform the following operation until p becomes empty: * Select two adjacent elem...
```python inf = 10**10 def sg_func(a,b): res = [0,0,0] if(a[2]==0): res[0] = min(a[0],b[0]) res[1] = min(a[1],b[1]) else: res[0] = min(a[0],b[1]) res[1] = min(a[1],b[0]) res[2] = (a[2]+b[2])%2 return res class Seg_cus(): def __init__(self,x): #####単位元#...
p03798 AtCoder Beginner Contest 055 - Menagerie
Snuke, who loves animals, built a zoo. There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered...
```python N = int(input()) s = input() for t in ["SS","SW","WS","WW"]: for i in range(1,N-1): if (s[i] =="o" and t[i]=="S") or (s[i]=="x" and t[i]=="W"): t += t[i-1] else: if t[i-1] =="S": t += "W" else: t +="S" if (t[N-2]==t[0] and...
p03965 AtCoder Beginner Contest 046 - AtCoDeer and Rock-Paper
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition: (※) After each turn, (the number of times the player has played Paper)≦(the number of times the ...
```python s = input() n = len(s) print(s[(n+1)//2:].count("g")-s[:(n+1)//2].count("p")) ```
p00056 Goldbach's Conjecture
It is known that even numbers greater than or equal to 4 can be represented by the sum of two prime numbers. This is called the Goldbach's conjecture, and computer calculations have confirmed that it is correct up to a fairly large number. For example, 10 can be represented by the sum of two prime numbers, 7 + 3 and 5 ...
```python import bisect,sys from itertools import * n=range(50001);a=list(n);a[1]=0 for i in range(2,224):a[i*2::i]=[0]*len(a[i*2::i]) for x in map(int,sys.stdin): if x:print(sum(1 for d in compress(n[:x//2+1],a[:x//2+1])if a[x-d])) ```
p00187 Stoning Fortune
With the motto "Creating your own path," a shrine created a fortune-telling fortune with its own hands. Ask the person who draws the lottery to throw six stones first, then the line segment connecting the first and second of the thrown stones, the line segment connecting the third and fourth, the fifth and six The fort...
```python # Aizu Problem 0187: Stoning Fortune # import sys, math, os, bisect # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input.txt", "rt") def on_segment(p, q, r): # Given three colinear points p, q, r, the function checks if # point q lies on line segment 'pr...
p00342 Maximization of Rational Expression
N different natural numbers are given. If you select four different ones and set them as $ A $, $ B $, $ C $, $ D $, the following formula $ \ Frac {A + B} {C --D} $ I want to find the maximum value of. Given N different natural numbers, choose 4 different from them and create a program to find the maximum valu...
```python n = int(input()) a = sorted(map(int,input().split())) b = [(a[i + 1] - a[i], i) for i in range(n -1)] b.sort(key = lambda x:x[0]) if b[0][1] < n - 2:print((a[-1] + a[-2]) / b[0][0]) elif b[0][1] == n - 3: if b[1][1] == n - 2:print(max((a[-1] + a[-2]) / b[2][0], (a[-1] + a[-4]) / b[0][0], (a[-3] + a[-4]) /...
p00538 Cake 2
Carving the cake 2 (Cake 2) JOI-kun and IOI-chan are twin brothers and sisters. JOI has been enthusiastic about making sweets lately, and JOI tried to bake a cake and eat it today, but when it was baked, IOI who smelled it came, so we decided to divide the cake. became. The cake is round. We made radial cuts from a p...
```python import sys sys.setrecursionlimit(100000) N, *A = map(int, open(0).read().split()) memo = [[-1]*N for i in range(N)] for i in range(N): memo[i][i] = A[i] if N % 2 else 0 def dfs(p, q, t): if memo[p][q] != -1: return memo[p][q] if t: memo[p][q] = r = max(A[p] + dfs((p+1)%N, q, 0), A[...
p00700 Exploring Caves
There are many caves deep in mountains found in the countryside. In legend, each cave has a treasure hidden within the farthest room from the cave's entrance. The Shogun has ordered his Samurais to explore these caves with Karakuri dolls (robots) and to find all treasures. These robots move in the caves and log relativ...
```python for _ in range(int(input())): m=dx=dy=0 while 1: x,y=map(int,input().split()) if x==y==0:break dx+=x dy+=y l=dx*dx+dy*dy if (m==l and mx<dx) or m<l:m,mx,my=l,dx,dy print(mx,my) ```
p00841 Atomic Car Race
In the year 2020, a race of atomically energized cars will be held. Unlike today’s car races, fueling is not a concern of racing teams. Cars can run throughout the course without any refueling. Instead, the critical factor is tire (tyre). Teams should carefully plan where to change tires of their cars. The race is a r...
```python def solve(): from bisect import bisect from itertools import accumulate from sys import stdin f_i = stdin while True: n = int(f_i.readline()) if n == 0: break a = list(map(int, f_i.readline().split())) b = float(f_i.readline()) ...
p00973 Fair Chocolate-Cutting
Fair Chocolate-Cutting You are given a flat piece of chocolate of convex polygon shape. You are to cut it into two pieces of precisely the same amount with a straight knife. Write a program that computes, for a given convex polygon, the maximum and minimum lengths of the line segments that divide the polygon into two...
```python #!/usr/bin/python3 from decimal import Decimal from fractions import Fraction import math import os import sys def main(): N = read_int() A = [Vec(*read_ints()) for _ in range(N)] print(*solve(N, A), sep='\n') def solve(N, Points): if DEBUG: dprint('polygon({!r}, fill=False)'.form...
p01105 Boolean Expression Compressor
Boolean Expression Compressor You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning. The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule: > <E>...
```python a=65280; b=61680; c=52428; d=43690; e=65535 from heapq import heappush, heappop base = [a, b, c, d, e, 0] Q = [(1, el) for el in base] L = {el: 1 for el in base} H = [] get = L.get push = H.append while Q: l, p = heappop(Q) if L[p] < l: continue if l+1 < get(p ^ e, 17): L[p ^ e] = l+1 ...
p01558 Substring
Given a string of length n s = s1, s2,…, sn and m queries. Each query qk (1 ≤ k ≤ m) is one of four types, "L ++", "L-", "R ++", "R-", and l [for the kth query qk. k] and r [k] are defined below. * L ++: l [k] = l [k-1] + 1, r [k] = r [k-1] * L-: l [k] = l [k-1] -1, r [k] = r [k-1] * R ++: l [k] = l [k-1], r [k] = r...
```python def main(): n, m = map(int, input().split()) s = input() mem = set() base = ord("a") - 1 mod1 = 1000000007 mod2 = 2147483647 h1 = [0] h2 = [0] for c in s: h1.append((h1[-1] * 27 + ord(c) - base) % mod1) h2.append((h2[-1] * 27 + ord(c) - base) % mod2) pow_mem1 = {0:1} pow_mem2 = {...
p01720 Minus One
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of...
```python from collections import deque, defaultdict n, m, s, t = map(int, input().split()) s -= 1 t -= 1 edges = [[] for _ in range(n)] for _ in range(m): x, y = map(int, input().split()) x -= 1 y -= 1 edges[x].append(y) edges[y].append(x) def dist_from(s): INF = 10 ** 20 dist = [INF] * n dist[s] = 0 ...
p01858 Sendame
A: Isono, let's do that! --Sendame - story Nakajima "Isono ~, let's do that!" Isono "What is that, Nakajima" Nakajima "Look, that's that. It's hard to explain because I have to express it in letters for some reason." Isono "No, it seems that you can put in figures and photos, right?" <image> Nakajima "It's true!...
```python K = int(input()) Is = [input() for i in range(K)] Ns = [input() for i in range(K)] atk_I = 0 atk_N = 0 #"mamoru", "tameru", "kougekida" #"Isono-kun", "Nakajima-kun", "Hikiwake-kun" for i, n in zip(Is, Ns): i_n = [i, n] if (i_n.count("mamoru") == 2): pass elif (i_n.count("mamoru") == 1): if (i_n.count("...
p02280 Binary Trees
A rooted binary tree is a tree with a root node in which every node has at most two children. Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T: * node ID of u * parent of u * sibling of u * the number of children of u * depth of u * height of...
```python class Node: def __init__(self, parent, left, right): self.parent = parent self.left = left self.right = right d = {} def get_all_depth(t, u, p): d[u] = p if t[u].right is not None: get_all_depth(t, t[u].right, p+1) if t[u].left is not None: get_all_dept...
p02427 Enumeration of Subsets I
Print all subsets of a set $S$, which contains $0, 1, ... n-1$ as elements. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elements. Constraints * $1 \leq n \leq 18$ In...
```python n = int(input()) print("0:") for b in range(1,2**n): a = bin(b)[2:] a = a[::-1] ans = [] for i in range(len(a)): if a[i] == "1": ans.append(i) ans.sort() print(str(b)+":",*ans) ```
1055_C. Lucky Days
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days [l_a; r_a] are lucky, then there are some unlucky days: [r_a + 1...
```python def gcd(a, b): return b if a == 0 else gcd(b % a, a) l1, r1, t1 = map(int, input().split()) l2, r2, t2 = map(int, input().split()) g = gcd(t1, t2) d = l2 - l1 s = d % g #print(g, d, s) ans1 = min(r1 - l1 - s, r2 - l2) + 1 s = (g - s) % g #print(s) ans2 = min(r1 - l1, r2 - l2 - s) + 1 print(max(ans1, an...
1077_D. Cutting Out
You are given an array s consisting of n integers. You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s. Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find s...
```python def check(d,h): temp=0 for i in d.values(): temp+=i//mid if temp>=k: return True return False n,k=map(int,input().split()) arr=list(map(int,input().split())) d={} for i in arr: if i in d:d[i]+=1 else:d[i]=1 l=1 r=n ans=0 while l<=r: mid=(l+r)//2 if check(d,mid): ans=max...
1098_C. Construct a tree
Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree! Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the s...
```python def clc(mid): sm , i , cp = 0 , 1 , n cur = 1 while(cp + 1 > cur): sm = sm + i * cur i+= 1 cp -= cur cur = cur * mid return sm + i * cp n , s = map(int,input().split()) sm = n * (n + 1) // 2 dp = [0] * 100005 x = [0] * 100005 y = [0] * 100005 x[0] = 1 if s + 1...
1119_D. Frets On Fire
Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day. In return, the fleas made a bigger ukulele for her: it has n strings, and each string has (10^{18} + 1) frets numerated from 0 to 10^{18}. The fleas use the array s_1, s_2, …...
```python import sys import math def lower(num,arr): ans=-1 low,high=0,len(arr)-1 while (low<=high): mid=(low+high)//2 if arr[mid]<=num: ans=max(ans,mid) low=mid+1 else: high=mid-1 return ans n=int(sys.stdin.readline()) arr=list(map(int,sys.std...
1146_A. Love "A"
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not. Alice can erase some characters from her string s. She would like to know wh...
```python lita=input() a=lita.count('a') b=len(lita) if a>(b/2): print(b) else: print(2*a-1) ```
1167_A. Telephone Number
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
```python def check(n ,s): if n < 11: print("NO") return k = n-11 t = "8" if t in s[:k+1]: print("YES") return else: print("NO") return for i in range(int(input())): n = int(input()) s = input() check(n,s) ```
1185_D. Extra Element
A sequence a_1, a_2, ..., a_k is called an arithmetic progression if for each i from 1 to k elements satisfy the condition a_i = a_1 + c ⋅ (i - 1) for some fixed c. For example, these five sequences are arithmetic progressions: [5, 7, 9, 11], [101], [101, 100, 99], [13, 97] and [5, 5, 5, 5, 5]. And these four sequence...
```python n=int(input()) a=list(map(int,input().split())) res=-1 a=list(map(lambda x: (x[1],x[0]),enumerate(a))) a.sort() cnt=0 if n==2: res=1 else: #keep 1 and 2 diff=a[1][0]-a[0][0] cnt=0 prev=a[0][0] ind=0 for i in range(1,len(a)): if a[i][0]-prev==diff: prev=a[i][0] else: cnt+=1 ...
1204_B. Mislove Has Lost an Array
Mislove had an array a_1, a_2, ⋅⋅⋅, a_n of n positive integers, but he has lost it. He only remembers the following facts about it: * The number of different numbers in the array is not less than l and is not greater than r; * For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(...
```python from sys import stdin def count(N, l, r): resultmin, resultmax = 0, 0 fmax, smax = 1, 1 for n in range(N): if l: resultmin += fmax fmax *= 2 l -= 1 else: resultmin += 1 if r: resultmax += smax smax *= ...
1220_G. Geolocation
You are working for the Gryzzl company, headquartered in Pawnee, Indiana. The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be n antennas located somewhere in the park....
```python import sys import math n = int(input()) x = [0]*n y = [0]*n for i in range(n): x[i], y[i] = map(int, input().split()) sx = sum(x) sy = sum(y) for i in range(n): x[i] = n * x[i] - sx y[i] = n * y[i] - sy m = int(input()) d = [0]*n e = [0]*n HD = 0 def check(a, b): global HD HE ...
1266_A. Competitive Programmer
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red. "Oh, I just spent x_i hours solving problems", said the i-th of them. Bob wants to train his math skills...
```python T = int(input()) for t in range(T): a = [int(x) for x in list(input())] if sum(a)%3==0 and a.count(0)>0 and (a.count(0)+a.count(2)+a.count(4)+a.count(6)+a.count(8)>1): print("red") else: print("cyan") ```
1287_C. Garland
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland....
```python import sys n = int(input()) if n == 1: print(0) sys.exit() arr = list(map(int, input().split())) arr = [i % 2 if i != 0 else -1 for i in arr] skipped = sum([i == -1 for i in arr]) if skipped == n: print(1) sys.exit() ans = 0 for i in range(n - 1): if (arr[i] == 0) and (arr[i + 1] ==...
1307_C. Cow and Message
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside. The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic pr...
```python import os import sys def main(): s=input() dp=[[0]*(27) for i in range(27)] d=[0]*27 for i in range(len(s)): k=ord(s[i])-97 for j in range(27): dp[k][j]+=d[j] d[k]+=1 ans=0 for i in range(27): for j in range(27): ans=max(ans, dp[i][j]) for i in d: ans=max(ans , i) print(ans) if __name_...
1330_C. Dreamoon Likes Coloring
Dreamoon likes coloring cells very much. There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n. You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n) Dreamoon will perform m operations. In i-th operation, Dreamoon will choose a number ...
```python import sys input = sys.stdin.readline n, m = map(int, input().split()) l = list(map(int, input().split())) sum_l = sum(l) if sum_l < n: print(-1) exit() diff = sum_l - n prev = 1 ans = [0] for i in range(m): ans.append(max(prev + ans[-1] - diff, ans[-1] + 1)) diff -= prev - (ans[-1] - ...
1350_C. Orac and LCM
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integ...
```python #x,y = map(int,input().split()) #arr = [int(i) for i in input().split()] #x,y = map(int,input().split()) from collections import Counter import math mod = 10**9+7 n = int(input()) arr = [int(i) for i in input().split()] suffix = [arr[-1]] for i in range(n-1): x = suffix[0] y = math.gcd(x,arr[n-i-2]) suff...
1393_B. Applejack and Storages
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well). A...
```python import sys input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) u = [0]*int(1e5+1) for i in a: u[i] += 1 can1 = 0 can2 = 0 for i in u: can1 += i//4 can2 += i%4//2 q = int(input()) for i in range(q): p, x = map(str,input().split()) x = int(x) if p == "+": ...
1418_A. Buying Torches
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: * exchange 1 stick for x sticks (you lose 1 stick and gain x sticks...
```python """ - math - from math import factorial from math import gcd from math import pi large_p = 10**9 + 7 from itertools import accumulate # 累積和 from operator import mul - other - from collections import Counter from itertools import combinations from itertools import combinations_with_replacement from itertools i...
145_C. Lucky Subsequence
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has sequence a consisting of n integers. The subsequence of the sequence a is such subseque...
```python import sys input = sys.stdin.readline def solve(): n, k = map(int, input().split()) a = [4,7] d = dict() idx = 0 for p in range(1,10): for m in range(1<<p): v = 0 for i in range(p): v = v*10+a[(m >> i)&1] d[v] = idx idx += 1 #print(d) c = [0]*idx b = 0 for v in map(int, input().sp...
1485_E. Move and Swap
You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root v...
```python from collections import deque T = int(input()) def solve(E, W): nodes = {idx: (w, []) for idx, w in weights.items()} for u, v in E: nodes[u][1].append(v) nodes[v][1].append(u) layers = [] visited = set([1]) parents = {idx: None for idx in weights.keys()} Q = deque([1...
1536_A. Omkar and Bad Story
Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array a = [a_1, a_2, …, a_n] of n distinct integers. An array b = [b_1, b_2, …, b_k] is called nice if for any two distinct elements b_i, b_j of b, |b_i-b_j| appears ...
```python from sys import stdin input = stdin.readline def solve(): n = int(input()) a = [int(x) for x in input().split()] for i in a: if i < 0: print("NO") return ans = list(range(0, 101)) print("YES") print(len(ans)) print(*ans) t = int(input()) for _ in r...
183_A. Headquarters
Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters e...
```python n = int(input()) r = 1; c = 1 for i in range(n): s = input() if (len(s) == 4): r += 1; c += 1 elif(s == "UL" or s == "DR"): r += 1 else: c += 1 print(r * c) ```
230_B. T-primes
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. Input The f...
```python N=1000000 a=[1]*N a[0]=a[1]=0 s=set() for i,x in enumerate(a): if x: s.add(i*i) for j in range(i+i,N,i): a[j] = 0 n= int(input()) lis = list(map(int,input().split())) for i in lis: print("YES" if i in s else "NO") ```
256_A. Almost Arithmetical Progression
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: * a1 = p, where p is some integer; * ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is som...
```python R = lambda: map(int, input().split()) n = int(input()) arr = list(R()) dp = [[0] * (n + 1) for i in range(n + 1)] for i in range(n): p = -1 for j in range(i): dp[i][j] = max(dp[i][j], dp[j][p] + 1) p = j if arr[j] == arr[i] else p print(max(max(dp[i]) for i in range(n)) + 1) ```
27_A. Next Test
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ...
```python def main(): MAX = 3005 n = int(input()) nums = list(map(int, input().split(' '))) a = [False] * MAX for i in nums: a[i] = True for i in range(1, MAX): if not a[i]: return i return -1 print(main()) ```
329_A. 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 a = [] n = int(input()) for i in range(0, n): a.append(input()) l = [0 for i in range(0, n)] c = [0 for i in range(0, n)] for i in range(0, n): for j in range(0, n): if a[i][j] == 'E': l[i] += 1 c[j] += 1 if n in l and n in c: print('-1') exit() if n in l: ...
34_D. Road Map
There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept ...
```python import sys sys.setrecursionlimit(100000) n, r1, r2 = map(int, input().split()) a = list(map(int, input().split())) g = {} num = 0 for k, v in enumerate(a): num += 1 if num == r1: num += 1 # print(k, num, v) if num not in g: g[num] = [] g[num].append(v) if v not in g:...
396_B. 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() ) 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: if j >= a: return ...
418_C. Square Table
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column...
```python """ Codeforces Round 241 Div 1 Problem E Author : chaotic_iak Language: Python 3.3.4 """ class InputHandlerObject(object): inputs = [] def getInput(self, n = 0): res = "" inputs = self.inputs if not inputs: inputs.extend(input().split(" ")) if n == 0: re...
445_A. DZY Loves Chessboard
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa...
```python n,m = map(int,input().split()) for i in range(n): s = list(input()) for j in range(m): if s[j]==".": if (i+j)%2==0: s[j]="W" else:s[j]="B" k="".join(s) print(k) ```
467_B. Fedor and New Game
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3». The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ...
```python def dif(a, b): cont = 0 for i in range(0, len(a)): if a[i]!=b[i]: cont+=1 return cont n, m, k = [int(x) for x in input().split()] lista = [] string = '' for i in range (0, m+1): string = bin(int(input()))[2:] string = ('0'*(n-len(string)))+string if i<m: ...
53_C. Little Frog
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that ...
```python from itertools import zip_longest n = int(input()) z = (n+1)//2 for p,q in zip_longest(range(1,z+1),range(n,z,-1)): if q: print(p, q, end=' ') else: print(p) ```
567_E. President and Roads
Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes alo...
```python from heapq import * import sys MOD = 1000000181 def addM(a,b): return (a+b)%MOD def mulM(a,b): return (a*b)%MOD def dijk(adj,n,s): dist = [10**18]*n ways = [0]*n frontier = [] dist[s] = 0 ways[s] = 1 heappush(frontier,(0,s)) while (len(frontier)>0): x = heappop(f...
610_D. Vika and Segments
Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbo...
```python from sys import stdin from itertools import repeat from collections import defaultdict def main(): n = int(stdin.readline()) h = defaultdict(list) w = defaultdict(list) for i in range(n): a, b, c, d = map(int, input().split()) if a > c: a, c = c, a if b > d:...
630_N. Forecast
The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic developmen...
```python a,b,c=map(float,input().split()) q=((b*b-4*a*c)**0.5) x=((-b+q)/(2*a)) y=((-b-q)/(2*a)) print(max(x,y)) print(min(x,y)) ```