name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p00605 Vampirish Night
There is a vampire family of N members. Vampires are also known as extreme gourmets. Of course vampires' foods are human blood. However, not all kinds of blood is acceptable for them. Vampires drink blood that K blood types of ones are mixed, and each vampire has his/her favorite amount for each blood type. You, cook ...
```python while True: n, k = map(int, input().split()) if n == 0: break s_list = list(map(int, input().split())) for _ in range(n): b_list = list(map(int, input().split())) for i in range(k): s_list[i] -= b_list[i] for s in s_list: if s < 0: print("No") break else: pri...
p00881 Twenty Questions
Consider a closed world and a set of features that are defined for all the objects in the world. Each feature can be answered with "yes" or "no". Using those features, we can identify any object from the rest of the objects in the world. In other words, each object can be represented as a fixed-length sequence of boole...
```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 ...
p01012 Planarian Regeneration
Notes For this problem, it is recommended to use floating point numbers, which are more accurate than double. Input m n x k l y For input, six integers m, n, x, k, l, y are given in the above input format. These six integers correspond to those in the problem statement, repeating the horizontal m: n cut x times...
```python m,n,x=[int(i) for i in input().split()] k,l,y=[int(i) for i in input().split()] res=0.5*(1.0+((m**2+n**2)**x)/((m+n)**(2*x))) res*=0.5*(1.0+((k**2+l**2)**y)/((k+l)**(2*y))) print(res) ```
p01144 Princess's Marriage
Princess'Marriage Marriage of a princess English text is not available in this practice contest. A brave princess in a poor country, knowing that gambling payouts are determined by the parimutuel method, felt more familiar with gambling and was convinced of her victory in gambling. As a result, he spent more money t...
```python while True: N,M = map(int,input().strip().split(" ")) if [N,M] == [0,0]: break L = [] S = 0 for i in range(N): l = list(map(int,input().strip().split(" "))) l.reverse() L.append(l) S = S + l[0]*l[1] L.sort() for j in range(0,N): t = N...
p01283 Strange String Manipulation
A linear congruential generator produces a series R(⋅) of pseudo-random numbers by the following for- mulas: <image> where S, A, C, and M are all parameters. In this problem, 0 ≤ S, A, C ≤ 15 and M = 256. Now suppose we have some input string I(⋅), where each character in the string is an integer between 0 and (M - ...
```python import math M = 256 def entropy_if_smallest(ctr,bound): ret = 0 for v in ctr: if v == 0: continue ret -= (v / N) * math.log2(v / N) if ret >= bound: return None return ret def solve(src): ans_h = float('inf') ans = None for s in range(16): ...
p01453 Spring Tiles
One morning when you woke up, it was in a springy labyrinth. I don't know why I'm in such a strange place. You have the option of waiting for help here, but you know from experience that if you stay in a labyrinth like this for a long time, a gust of wind will surely blow you away. It was. However, the time until the ...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): W, H = map(int, readline().split()) S = [readline().strip() for i in range(H)] R = [[0]*W for i in range(H)] P = [] cnt = 0 for i in range(H): Si = S[i] for j in...
p01899 Yamanote-line Game
B: Yamanote-line Game-Yamanote-line Game- Bean (?) Knowledge The Yamanote line is convenient. The reason is that you can ride as many laps as time allows just by paying 130 yen. However, if you board with a ticket, you must be careful about the valid time of the ticket. It seems safe with an IC card. Taking advantage...
```python n, d = map(int, input().split()) lst = list(map(int, input().split())) ans = sum([x - d for x in lst if x - d >= 0]) print(ans if ans else "kusoge") ```
p02322 Knapsack Problem with Limitations II
You have $N$ items that you want to put them into a knapsack. Item $i$ has value $v_i$, weight $w_i$ and limitation $m_i$. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most $W$, that is capacity of the knapsack. * You ...
```python import sys from collections import deque readline = sys.stdin.readline write = sys.stdout.write def solve(): N, W = map(int, readline().split()) vs = [0]*N; ws = [0]*N; ms = [0]*N for i in range(N): vs[i], ws[i], ms[i] = map(int, readline().split()) V0 = max(vs) V = sum(v * min(V...
p02467 Prime Factorize
Factorize a given integer n. Constraints * 2 ≤ n ≤ 109 Input n An integer n is given in a line. Output Print the given integer n and :. Then, print prime factors in ascending order. If n is divisible by a prime factor several times, the prime factor should be printed according to the number of times. Print a s...
```python import math n=int(input()) factors=[] n1=n p=2 while p<=math.sqrt(n): if n%p==0: n//=p factors.append(str(p)) else: p+=1 if n!=1: factors.append(str(n)) print(str(n1)+": "+" ".join(factors)) ```
1020_D. The hat
This is an interactive problem. Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered ...
```python from sys import stdout n = int(input()) if n % 4 == 2: print("! -1") exit(0) print("?", 1) stdout.flush() a = int(input()) print("?", 1 + n // 2) stdout.flush() b = int(input()) if a == b: print("!", 1) exit(0) l = 1 r = 1 + n // 2 while(l != r): mid = ( l + r ) // 2 print("?", mid) ...
1066_E. Binary Numbers AND Sum
You are given two huge binary integer numbers a and b of lengths n and m respectively. You will repeat the following process: if b > 0, then add to the answer the value a~ \&~ b and divide b by 2 rounding down (i.e. remove the last digit of b), and repeat the process again, otherwise stop the process. The value a~ \&~...
```python MOD = 998244353 n, m = map(int, input().split()) a = input()[::-1] b = input()[::-1] c = [0] * n for i in range(n): if a[i] == '1': c[i] = pow(2, i, MOD) for i in range(n - 1): c[i + 1] += c[i] ans = 0 for i in range(m): if b[i] == '1': if i >= n: ans += c[-1] e...
1108_C. Nice Garland
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan...
```python from sys import stdin,stdout from math import gcd,sqrt from collections import deque input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') L=lambda:list(R()) P=lambda x:stdout.write(x) hg=lambda x,y:((y+x-1)//x)*x pw=lambda x:1 if x==1 else 1+pw(x//2) chk=l...
1156_A. Inscribed Figures
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier. Future students will be asked just a single question. They are given a sequen...
```python n = int(input()) sh = list(map(int, input().split())) sh += [0] ans = "" el = 0 for i in range(n - 1): if len(sh) >= 3: if sh[i] == 3 and sh[i + 1] == 1 and sh[i + 2] == 2: el -= 1 if sh[i] == 2 and sh[i + 1] == 3 or sh[i] == 3 and sh[i + 1] == 2: ans = "Infinite" break elif sh[i] == 1 and sh[i + ...
1178_D. Prime Graph
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to...
```python def SieveOfEratosthenes(n): prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 pp=[] for p in range(2, n + 1): if prime[p]: pp.append(p) return pp def f(n): Primes=SieveOfEratosthenes(10000) de...
1196_D1. RGB Substring (easy version)
The only difference between easy and hard versions is the size of the input. You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'. You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ...
```python t=int(input()) while t: n,m=map(int,input().split()) s=input() s1="RGB"*(m//3)+"".join(["R","G","B"][:m%3]) s2="GBR"*(m//3)+"".join(["G","B","R"][:m%3]) s3="BRG"*(m//3)+"".join(["B","R","G"][:m%3]) mi=10**9 #print(s1) for i in range(0,n-m+1): c1,c2,c3=0,0,0 for ...
1213_E. Two Small Strings
You are given two strings s and t both of length 2 and both consisting only of characters 'a', 'b' and 'c'. Possible examples of strings s and t: "ab", "ca", "bb". You have to find a string res consisting of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and...
```python from itertools import product def main(): n, s, t = int(input()), input(), input() print('YES') abc = ('abc', 'acb', 'bac', 'bca', 'cab', 'cba') if s[0] != s[1] and t[0] != t[1]: for p in abc: if s not in p and t not in p: print(p[0] * n, p[1] * n, p[2] * ...
1237_A. Balanced Rating Changes
Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced — their sum is equal to 0. Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means...
```python import math as ma x= int(input()) a = [] o = [] e = [] t = [] for i in range (x): p = int(input()) a.append(p) if p%2 ==0: e.append(p) else: o.append(p) t.append(p//2) r = int(abs(sum(e)/2 + sum(t))) for i in a: if i % 2 ==0: print(int(i/2)) else: if(r!=0): print(ma.ceil(i/2)) r-=1 els...
1278_E. Tests for problem D
We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem. Given an undirected labeled tree consisting of n vertices, find a set of segments such that: 1. both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n ...
```python def main(): import sys input = sys.stdin.buffer.readline N = int(input()) adj = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) st = [1] seen = [0] * (N+1) seen[1] = 1 LL = [0] * (2 * ...
1299_B. Aerodynamic
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of t...
```python n = int(input()) if n % 2 == 0: a = [0]*n x1, y1 = list(map(int, input().split())) x11, y11 = x1, y1 for i in range(n-1): x2, y2 = list(map(int, input().split())) a[i] = [x2-x1, y2-y1] x1, y1 = x2, y2 a[n-1] = [x11-x2, y11-y2] fl = True for i in range(int(n/...
1362_E. Johnny and Grandmaster
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. ...
```python import io import os from collections import Counter MOD = 10 ** 9 + 7 def solve(N, P, K): if P == 1: return len(K) % 2 K.sort(reverse=True) left = Counter() right = Counter() for k in K: if not left: # Left represents highest unmatched power left...
1383_A. String Transformation 1
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently. Koa the Koala has two...
```python def count(a, b, length, result): for i in range(len(a)): if a[i] > b[i]: return -1 if a[i] == b[i]: a[i] = b[i] = 1000 if a == b: return result k = min(b) j = b.index(k) save = a[j] for i in range(len(a)): if a[i] == save: ...
1404_A. Balanced Bitstring
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each). You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w...
```python import sys input = sys.stdin.readline for f in range(int(input())): n,k=map(int,input().split()) s=input() poss=True sol=[2]*n ones=0 zeros=0 for i in range(n): if i<k: if s[i]=="1": sol[i]=1 ones+=1 if s[i]=="0": ...
1447_D. Catching Cheaters
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the ...
```python from collections import defaultdict import sys n,m=map(int,input().split()) s=input() t=input() dp=[[0 for i in range(m+1)] for j in range(n+1)] for i in range(n): for j in range(m): if s[i]==t[j]: dp[i+1][j+1]=dp[i][j]+2 else: dp[i+1][j+1]=max(0,max(dp[i+1]...
1472_D. Even-Odd Game
During their New Year holidays, Alice and Bob play the following game using an array a of n integers: * Players take turns, Alice moves first. * Each turn a player chooses any element and removes it from the array. * If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice...
```python #: Author - Soumya Saurav import sys,io,os,time from collections import defaultdict from collections import Counter from collections import deque from itertools import combinations from itertools import permutations import bisect,math,heapq alphabet = "abcdefghijklmnopqrstuvwxyz" input = sys.stdin.readline ...
1498_E. Two Houses
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m...
```python from sys import stdin, stdout input = stdin.readline def MyIter(n): for k in range(n-1, 0, -1): i = 0 while i + k < n: yield i, i + k i += 1 def solve(n, a): dct = [[] for i in range(n)] for i, el in enumerate(a): dct[el].append(i + 1) for i,...
1520_D. Same Differences
You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≤ t ≤ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5). The second line of each test ca...
```python import sys def get_ints(): return list(map(int, sys.stdin.readline().strip().split())) testcases = int(input()) for testcase in range(testcases): n = int(input()) arr = get_ints() dicts = {} for i in range(n): newelem = arr[i] - i if newelem not in dicts: dicts[...
154_B. Colliders
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery:...
```python from sys import stdin import math n, k = map(int, stdin.readline().rstrip().split(" ")) a = [[] for i in range(n+1)] act = {} active = [0]*(n+1) for i in range(2,n+1): if not a[i]: act[i]=0 for j in range(i,n+1,i): a[j].append(i) storing = {} for _ in range(k): s, v = ...
21_B. Intersection
You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numb...
```python a1, b1, c1 = [int(i) for i in input().split()] a2, b2, c2 = [int(i) for i in input().split()] if c1 != c2 and (a1 == 0 and b1 == 0) and (a2 == 0 and b2 == 0) : print(0) elif (a1 == 0 and b1 == 0 and c1 == 0) or (a2 == 0 and b2 == 0 and c2 == 0) : print(-1) elif (a1 == 0 and b1 == 0 and c1 != 0) or (a...
269_B. Greenhouse Effect
Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant o...
```python n=int(input().split()[0]) a=[] for _ in range(n): a.append(int(input().split()[0])) dp=[0]*n for i in range(n): dp[i]= 1 for j in range(i): if a[j]<= a[i] and dp[j]>= dp[i]: dp[i]=dp[j]+1 print(n-max(dp)) ```
291_D. Parallel Programming
Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n. Polycarpus needs to come up with a parallel program model. For each memory cell number i this ...
```python n, k = map(int, input().split()) a = [1 for i in range(n + 1)] a[n] = 0 for iter in range(k): for i in range(1, n - 1): target = n - i if a[i + 1] > target - a[i]: # find right number target -= a[i] print(n - target, end=' ') a[i] += a[n - ta...
316_E1. Summer Homework
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi....
```python n,m = map(int,input().split()) a = list(map(int,input().split())) f = [1,1] for i in range(2,n+1): f.append(f[i-1] + f[i-2]) f[i] %= 10 ** 9 for q in range(m): z,l,r = map(int,input().split()) if z == 1: a[l-1] = r else: s = 0 for j in range(l-1,r): ...
33_B. String Problem
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary ch...
```python import sys, string import itertools s, t = input().strip(), input().strip() if len(s) != len(t): print(-1) sys.exit() vertices = string.ascii_lowercase g = { c: { c: 0 } for c in vertices } n = int(input()) for i in range(n): u, v, cost = input().split() cost = int(cost) if v not in g[u] or g[u][...
386_B. Fly, freebies, fly!
Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n ...
```python n = int(input()) lst = sorted(list(map(int, input().split()))) t = int(input()) ans = 1 for i in range(len(lst) - 1): temp = 1 k = i + 1 while k < len(lst) and lst[k] - lst[i] <= t: temp += 1 k += 1 if temp > ans: ans = temp print(ans) ```
407_A. Triangle
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the app...
```python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
456_D. A Lot of Games
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the re...
```python input = __import__('sys').stdin.readline class Node: def __init__(self): self.end = False self.nxt = {} self.w = None self.l = None def __setitem__(self, i, x): self.nxt[i] = x def __getitem__(self, i): return self.nxt[i] def makeTrie(strs): root = Node() ...
479_B. Towers
As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest a...
```python n,k=map(int,input().split()) a=list(map(int,input().split())) s="" c=0 best=[max(a)-min(a),c,""] if n>1: for pog in range(k): m=0 i=0 mp=100000000000000000 ip=0 m=max(a) i=a.index(m) mp=min(a) ip=a.index(mp) if m!=mp: a[i]...
501_B. Misha and Changing Handles
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the re...
```python n = input() lista_nuevos = [] lista_viejos = [] for i in range(int(n)): elem = input().split(' ') if (elem[0] not in lista_viejos) and (elem[0] not in lista_nuevos): lista_viejos.append(elem[0]) lista_nuevos.append(elem[1]) elif elem[0] in lista_nuevos: indice = lista_nuev...
552_C. Vanya and Scales
Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally spea...
```python from sys import exit w, m = map(int, input().split()) if w in (2, 3): print('YES') exit() while True: if m in (0, 1): print('YES') exit() prev = 1 cur = w while cur < m: prev = cur cur *= w if cur == m: print('YES') exit() sum1k ...
579_C. A Problem about Polyline
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positiv...
```python a,b=(int(i) for i in input().split()) if (a<b): print('-1') elif (a==b): print(a) else: i1=(a+b)//(2*b); i2=(a-b)//(2*b) if i2 is not 0: p=(a+b)/2 q=(a-b)/2 print(min(p/i1,q/i2)) else: print((a+b)/(2*i1)) ```
600_B. Queries about less or equal elements
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj. Input The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — ...
```python # upsolve from bisect import bisect_right x = input() a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] a = sorted(a) for i in b: print(bisect_right(a,i), end = " ") print() ```
622_E. Ants in Leaves
Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. N...
```python import sys def read_input(): n = int(sys.stdin.buffer.readline().decode('utf-8')) graph = [[] for _ in range(n)] tree = [0] * n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): graph[u-1].append(v-1) graph[v-1].append(u-1) tree[u-1] +=...
644_A. Parliament of Berland
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans. New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two ch...
```python #Codeforces : Parliament of Bearland n,a,b=[int(x) for x in input().split()] p=list() pos=a for i in range(b): pos=a if(i+1<=n): q=[i+1] else: q=[0] pos=0 for j in range(1,a): if(b%2==0): if(i%2==0): if(j%2==0): ...
671_A. Recycling Bottles
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin. We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can c...
```python def main(): from math import hypot from sys import stdin ax, ay, bx, by, tx, ty = map(float, input().split()) s, tot = input(), 0. m0 = m1 = m2 = m3 = -9e9 j = k = 0 for i, s in enumerate(stdin.read().splitlines()): x, y = map(float, s.split()) r = hypot(tx - x, ty ...
739_A. Alyona and mex
Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri,...
```python n,m=map(int,input().split()) min_val=9999999 for _ in range(m): y,x=map(int,input().split()) if min_val>x-y: x1=x y1=y min_val=x-y print(min_val+1) L=[0]*n tp=0 listNum=[] for i in range(n): listNum.append(tp) tp+=1 if tp>min_val: tp=0 for i in listNum[:-1]:...
785_A. Anton and Polyhedrons
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: * Tetrahedron. Tetrahedron has 4 triangular faces. * Cube. Cube has 6 square faces. * Octahedron. Octahedron has 8 triangular faces. * Dodecahedron. Dodecahedron has 12 pentagonal faces. *...
```python a = int(input()) sum = 0 for i in range(1,a+1): b = input() if b == 'Tetrahedron': sum += 4 elif b == 'Cube': sum += 6 elif b == 'Octahedron': sum += 8 elif b == 'Dodecahedron': sum += 12 else: sum += 20 print(sum) ```
807_A. Is it rated?
Is it rated? Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it. Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before ...
```python #####--------------Template Begin-------------------#### import math import sys import string #input = sys.stdin.readline def ri(): #Regular input return input() def ii(): #integer input return int(input()) def li(): #list input return input().split() def mi(): #map input return list(map(int, input().spli...
831_B. Keyboard Layouts
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet. You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i...
```python a=list(input()) b=list(input()) d=[] for i in range(26): a.append(chr(ord(a[i])-32)) b.append(chr(ord(b[i])-32)) c=list(input()) for i in c: try: d.append(b[a.index(i)]) except: d.append(i) print(''.join(d)) ```
852_C. Property
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property. Bill’s property can be observed as a convex...
```python n = int(input()) a = input().split() for i in range(n): a[i] = int(a[i]) b = [] for i in range(0, n-1): b.append((a[i]-(n-a[i+1]), i)) b.append((a[n-1]-(n-a[0]), n-1)) b = sorted(b) ans = n*[0] for i in range(n): # the line segment at index b[i][1] ans[b[i][1]] = i for i in range(n): print...
876_D. Sorting the Coins
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then...
```python import sys input = sys.stdin.readline n = int(input()) p = list(map(int, input().split())) flag = [1]*n r = n-1 cnt = 0 print(1, end=' ') for i in range(n-1): flag[p[i]-1] = 0 while flag[r]==0: r -= 1 cnt += 1 print(i+2-cnt, end=' ') print(1) ```
8_D. Two Friends
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wa...
```python def a(): t1, t2 = map(int, input().split()) cinema = complex(*map(int, input().split())) house = complex(*map(int, input().split())) shop = complex(*map(int, input().split())) cinema_to_house = abs(house - cinema) cinema_to_shop = abs(shop - cinema) shop_to_house = abs(house - shop...
922_C. Cave Painting
Imp is watching a documentary about cave painting. <image> Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp. Imp ...
```python n,k = list(map(int,input().split())) # n = int(input()) # k = int(input()) d = {} pos = False for i in range(1,k+1): r = n%i try: d[r] += 1 if(d[r] > 1): print("No") # print(i) pos = True break except: d[r] = i # if(i > int(1e7)): # print("No") # break if(not pos): print("Yes") ...
94_D. End of Exams
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w, m = map(int, input().split()) w = float(w) eps = 1e-9 req = n * w / m cup = [req] * m ans = [[] for _ in range(m)] j = 0 for i in range(n): milk = w cnt = 0 while j < m a...
978_B. File Name
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
```python n=int(input()) s=input() c=0 k=0 for i in s: if i=='x': c=c+1 else: c=0 if c>=3: k=k+1 print(k) ```
998_A. Balloons
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside. T...
```python def solution(n, b): if n <= 2 and b == [b[0]] * n: return -1 return f'1 {b.index(min(b)) + 1}' def main(): packs = int(input()) balloons = input().split() print(solution(packs, balloons)) if __name__ == '__main__': main() ```
p02658 AtCoder Beginner Contest 169 - Multiplication 2
Given N integers A_1, ..., A_N, compute A_1 \times ... \times A_N. However, if the result exceeds 10^{18}, print `-1` instead. Constraints * 2 \leq N \leq 10^5 * 0 \leq A_i \leq 10^{18} * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 ... A_N Output P...
```python n=int(input()) l=list(map(int,input().split())) l.sort() ans=1 for i in range(n): ans*=l[i] if ans>10**18: ans=-1 break print(ans) ```
p02787 AtCoder Beginner Contest 153 - Crested Ibis vs Monster
Ibis is fighting with a monster. The health of the monster is H. Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points. The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health. Ibis wins wh...
```python H,N=map(int,input().split()) ab=[list(map(int,input().split())) for _ in range(N)] x=max(a for a,b in ab) dp=[0]*(H+x) for i in range (1,H+x): dp[i]=min(dp[i-a]+b for a,b in ab) print(dp[H]) ```
p02923 AtCoder Beginner Contest 139 - Lower
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i. You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square. Find the maximum numb...
```python le=int(input()) l=list(map(int,input().split())) ans=0 e=0 for i in range(le)[:-1]: if l[i]<l[i+1]: ans=max(ans,i-e) e=i+1 ans=max(ans,le-e-1) print(ans) ```
p03202 AtCoder Grand Contest 029 - Lexicographic constraints
There are N strings arranged in a row. It is known that, for any two adjacent strings, the string to the left is lexicographically smaller than the string to the right. That is, S_1<S_2<...<S_N holds lexicographically, where S_i is the i-th string from the left. At least how many different characters are contained in ...
```python N=int(input()) A=[int(i) for i in input().split()] def Check(K): stack=[] n=A[0] for i in range(1,N): if A[i-1]<A[i]: n=A[i] else: if K==1: return False n=A[i] while True: l=0 if stack: l=stack[-1][0] if l>n: stack.pop()...
p03509 Code Festival Team Relay (Parallel) - White and Blue
Ringo Kingdom Congress is voting on a bill. N members are present, and the i-th member (1 ≤ i ≤ N) has w_i white ballots and b_i blue ballots. Each member i will put all the w_i white ballots into the box if he/she is in favor of the bill, and put all the b_i blue ballots into the box if he/she is not in favor of the ...
```python n, p = map(int, input().split()) w, b = [], [] for _ in range(n): ww, bb = map(int, input().split()) w.append(ww) b.append(bb) s = [] for ww, bb in zip(w, b): s.append((100 - p) * ww + p * bb) s.sort(reverse=True) score = -sum(b) * p cnt = 0 while score < 0: score += s[cnt] cnt += 1...
p03992 CODE FESTIVAL 2016 qual A - CODEFESTIVAL 2016
This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it `CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`. So he has decided to make a program that puts the single space he omitted. You are given a string s with 12 letters. Output the string putting a single space between the fi...
```python s = list(input()) f= ''.join(s[:4]) b=''.join(s[4:]) print(f,b,sep=' ') ```
p00080 Third Root
The solution of $ x ^ 3 = q $ is to calculate the recurrence formula $ x_ {n + 1} = x_n-\ frac {x_ {n} ^ 3 --q} {3x_ {n} ^ 2} $ It can be calculated approximately with. Put a positive number $ \ frac {q} {2} $ in $ x_1 $ $ x_2 = x_1-\ frac {x_ {1} ^ 3 --q} {3x_ {1} ^ 2} $, $ x_3 = x_2-\ frac {x_ {2} ^ 3 --q} {3x_ {2}...
```python while True : q = int(input()) if q == -1 : break else : x = q / 2 while abs(x ** 3 - q) >= 0.00001 * q : x -= ((x ** 3 - q) / (3 * x ** 2)) print(f"{x:.6f}") ```
p00212 Highway Express Bus
Mr. A is planning to travel alone on a highway bus (hereinafter referred to as "bus") during his high school holidays. First, Mr. A chose the town he wanted to visit the most and made it his destination. Next, you have to decide the route to transfer the bus from the departure point to the destination. When connecting,...
```python from heapq import heappush, heappop INF = 10 ** 20 while True: c, n, m, s, d = map(int, input().split()) s -= 1 d -= 1 if c == 0: break edges = [[] for _ in range(n * (c + 1))] for _ in range(m): a, b, f = map(int, input().split()) a -= 1 b -= 1 for i in range(c + 1): ed...
p00589 Extraordinary Girl II
She loves e-mail so much! She sends e-mails by her cellular phone to her friends when she has breakfast, she talks with other friends, and even when she works in the library! Her cellular phone has somewhat simple layout (Figure 1). Pushing button 1 once displays a character (’), pushing <image> it twice in series di...
```python # AOJ 1003: Extraordinary Girl II # Python3 2018.7.4 bal4u tbl = ["", "',.!?", "abcABC", "defDEF", "ghiGHI", "jklJKL", \ "mnoMNO", "pqrsPQRS", "tuvTUV", "wxyzWXYZ"] while True: try: s = input().strip() except: break ans, i = '', 0 while i < len(s): c = s[i] w, d, i = 0, int(c), i+1 while i ...
p00726 The Genome Database of All Space Life
In 2300, the Life Science Division of Federal Republic of Space starts a very ambitious project to complete the genome sequencing of all living creatures in the entire universe and develop the genomic database of all space life. Thanks to scientific research over many years, it has been known that the genome of any spe...
```python def main(): def pearser(s, n): if s == "": return "" i = 0 while 1: if not s[i].isdigit():break i += 1 if i == 0: r = pearser(s[i + 1:], n - 1) return s[0] + r if s[i] == "(": r = Parentp(s[i:],...
p00866 Stopped Watches
In the middle of Tyrrhenian Sea, there is a small volcanic island called Chronus. The island is now uninhabited but it used to be a civilized island. Some historical records imply that the island was annihilated by an eruption of a volcano about 800 years ago and that most of the people in the island were killed by pyr...
```python from itertools import permutations BASE = 12*3600 def convert(v): return "%02d:%02d:%02d" % (v // 3600, (v // 60) % 60, v % 60) while 1: N = int(input()) if N == 0: break R = set() L = [] for i in range(N): ts = set() *E, = map(int, input().split()) for ...
p01268 Matsuzaki Number
Professor Matsuzaki is a scientist studying the truth of the universe. Life, the universe, all the answers are said to be 42, but Professor Matsuzaki thinks that this alone is not enough to elucidate the truth of the universe. Professor Matsuzaki believes that the truth of the universe is represented by a function cons...
```python def eratosthenes(n): prime_table = [False,False,True]+[False if i%2!=0 else True for i in range(n-2)] i=3 pn=[2] while i*i<=n: if prime_table[i]: j=i*i pn.append(i) while j<=n: prime_table[j]=False j+=i i+=2 ...
p01438 Butterfly
Claire is a man-eater. She's a real man-eater. She's going around with dozens of guys. She's dating all the time. And one day she found some conflicts in her date schedule. D'oh! So she needs to pick some dates and give the others up. The dates are set by hours like 13:00 to 15:00. She may have more than one date with...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x i...
p01744 Dense Amidakuji
There is an Amidakuji that consists of w vertical bars and has a height (the number of steps to which horizontal bars can be added) of h. w is an even number. Of the candidates for the place to add the horizontal bar of this Amidakuji, the ath from the top and the bth from the left are called (a, b). (When a horizontal...
```python from collections import defaultdict import sys def solve(): readline = sys.stdin.readline write = sys.stdout.write H, W, N = map(int, readline().split()) A = [0]*W B = [0]*W C = [0]*W for i in range(W//2): A[i] = i * 2 + 1 A[-i-1] = i * 2 B[i*2] = C[i*2 - 1...
p01884 Similarity of Subtrees
Example Input 5 1 2 1 3 1 4 1 5 Output 6
```python from collections import deque, defaultdict import sys def main(): readline = sys.stdin.readline write = sys.stdout.write N = int(readline()) G = [[] for i in range(N)] for i in range(N-1): a, b = map(int, readline().split()); a -= 1; b -= 1 G[a].append(b) G[b].appen...
p02021 Working
G: Working Kou decided to do the same number of jobs every day for the next $ N $. $ A_i $ jobs are added on the $ i $ day of the $ N $ day. Mr. Kou has no work to do now, and he doesn't have to finish all the work by the $ N $ day. How many jobs can you do in a day? However, Mr. Kou is excellent, so he can do as ...
```python from itertools import accumulate n=int(input()) a=list(accumulate(map(int,input().split()))) for i in range(100,0,-1): for j in range(n): if i*(j+1)>a[j]:break else: print(i) break ```
p02163 How old are you
Problem It seems that a magician with a smoky smell will show off his magic. "Now, think of one favorite integer." You decide to think of your counting years in your head. The magician has thrown the query $ N $ times. Each query is one of the following: 1. "Multiply the number you have in mind by $ x $." 2. "Add ...
```python n = int(input()) queries = [list(map(int, input().split())) for i in range(n)] s, t = 1, 0 for q in queries: if q[0] == 1: s *= q[1] t *= q[1] elif q[0] == 2: t += q[1] else: t -= q[1] print(-t, s) ```
p02304 Segment Intersections: Manhattan Geometry
For given $n$ segments which are parallel to X-axis or Y-axis, find the number of intersections of them. Constraints * $1 \leq n \leq 100,000$ * $ -1,000,000,000 \leq x_1, y_1, x_2, y_2 \leq 1,000,000,000$ * Two parallel segments never overlap or touch. * The number of intersections $\leq 1,000,000$ Input In the fi...
```python # Acceptance of input import sys file_input = sys.stdin n = file_input.readline() EP = [] l = -1000000001 u = 1000000001 vs_x = set() for line in file_input: x1, y1, x2, y2 = (map(int, line.split())) if x1 == x2: if y1 < y2: EP.append((y1, l, x1)) EP.append((y2, u, ...
p02451 Binary Search
For a given sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, find a specific value $k$ given as a query. Constraints * $1 \leq n \leq 100,000$ * $1 \leq q \leq 200,000$ * $0 \leq a_0 \leq a_1 \leq ... \leq a_{n-1} \leq 1,000,000,000$ * $0 \leq k_i \leq 1,000,000,000$ Input The input i...
```python # AOJ ITP2_6_A: Binary Search # Python3 2018.6.24 bal4u from bisect import bisect_left n = int(input()) a = list(map(int, input().split())) a.append(1000000001) # > 1,000,000,000 q = int(input()) for i in range(q): k = int(input()) p = bisect_left(a, k) print(1 if a[p] == k else 0) ```
1017_C. The Phone Number
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number! The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband. The sequence of n integers is called a...
```python n = int(input()) b = int(n ** 0.5) ans = [] for i in range(0, n, b): ans = [j for j in range(i + 1, min(i + 1 + b, n + 1))] + ans print(*ans) ```
1085_D. Minimum Diameter Tree
You are given a tree (an undirected connected graph without cycles) and an integer s. Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible. Let's define the diameter of...
```python # Since the weight of an edge can be 0, the solution # boils down to counting the leaf nodes from sys import stdin node,sWeight= map(int,input().split()) tree = [0]*node for l in stdin.readlines(): a,b = map(int,l.split()) tree[a-1] += 1; tree[b-1] +=1 print(2*sWeight/tree.count(1)) ```
1105_B. Zuhair and Strings
Given a string s of length n and integer k (1 ≤ k ≤ n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s: * x non-intersecting (non-overlapping) substrings of length k, * all characters of these x substrings are the same (i.e. each substring contains only one ...
```python import bisect def level(xs, k): level = 0 index = 0 while index < len(xs): level += 1 index = bisect.bisect_left(xs, xs[index] + k, index) return level """ assert level([], 2) == 0 assert level([0,1], 2) == 1 assert level([0,1,2], 2) == 2 assert level([10,12,14], 2) == 3 asse...
1132_E. Knapsack
You have a set of items, each having some integer weight not greater than 8. You denote that a subset of items is good if total weight of items in the subset does not exceed W. You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set...
```python import os import sys from functools import lru_cache, reduce from io import BytesIO sys.setrecursionlimit(30000) input = BytesIO(os.read(0, os.fstat(0).st_size)).readline print = lambda x: os.write(1, str(x).encode()) def main(): init_w = int(input()) cnt = [int(i) for i in input().split()] d...
1153_A. Serval and Bus
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, th...
```python import math def main(): n,t=map(int,input().split()) num=n mini=120000000 route=0 while(n>0): s,d=map(int,input().split()) if(s>=t): wa=s-t if(wa<mini): mini=wa route=num-n+1 elif(s<t): ti=(int)(mat...
1231_B. Ania and Minimizing
Ania has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with? Input The first...
```python n,k=map(int,input().split()) l=list(input()) if k==0: print(*l,sep='') elif n==1: print(0) else: if l[0]!='1': #print("HI") l[0]='1' k-=1 for i in range(1,n): #print(k) if k>0 and int(l[i])>0: if l[i]!='0': l[i]='0' ...
1272_D. Remove One Element
You are given an array a consisting of n integers. You can remove at most one element from this array. Thus, the final length of the array is n-1 or n. Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array. Recall that the contiguous subarray a wi...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in...
1295_E. Permutation Separation
You are given a permutation p_1, p_2, ... , p_n (an array where each integer from 1 to n appears exactly once). The weight of the i-th element of this permutation is a_i. At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p_1, p_2, ... , ...
```python def main(): import sys input = sys.stdin.buffer.readline N = int(input()) P = list(map(int, input().split())) A = list(map(float, input().split())) class LazySegTree: # Range add query def __init__(self, A, initialize=True, segfunc=min, ident=2000000000): ...
1316_E. Team Building
Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of p players playing in p different positions. She also recognizes the importance of audience support, so she wants to select k people as part of the audience. There are n people in Byteland. Alice needs ...
```python import io import os # PSA: # The key optimization that made this pass was to avoid python big ints by using floats (which have integral precision <= 2^52) # None of the other optimizations really mattered in comparison. # Credit for this trick goes to pajenegod: https://codeforces.com/blog/entry/77309?#comm...
1338_A. Powered Addition
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second: * Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{...
```python import math from sys import stdin, stdout t = int(stdin.readline().strip()) def solve(): n = int(stdin.readline().strip()) arr = list(map(int, (stdin.readline().strip().split()))) ans = 0 now = arr[0] for i in range(1, len(arr)): if arr[i] < now: ans = max(ans, len(b...
1380_A. Three Indices
You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Find three indices i, j and k such that: * 1 ≤ i < j < k ≤ n; * p_i < p_j and p_j > p_k. Or say that there are no such indices. Input The first lin...
```python def solve(arr): for i in range(1, len(arr)-1): if arr[i] > arr[i-1] and arr[i] > arr[i+1]: print("YES") print(i, i+1, i+2) return print("NO") for _ in range(int(input())): input() arr = [int(e) for e in input().split()] solve(arr) ```
1400_A. String Similarity
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
```python t = int(input()) for _ in range(t): n = int(input()) s = input() print(s[0::2]) ```
1444_B. Divide and Sum
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q). Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r...
```python n=int(input()) a=list(map(int,input().split())) mod=998244353 def ncr(n, r, p): # initialize numerator # and denominator num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den, p - 2, p)) % p a.sort()...
1469_C. Building a Fence
You want to build a fence that will consist of n equal sections. All sections have a width equal to 1 and height equal to k. You will place all sections in one line side by side. Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the i-th section is equal...
```python for _ in range(int(input())): bool = True n, h = map(int, input().split()) list = [int(x) for x in input().split()] maxi, mini = list[0], list[0] for i in range(1, n): maxi = max(maxi - h + 1, list[i]) mini = min(mini + h - 1, list[i] + h - 1) if maxi > mini: ...
1494_E. A-Z Graph
You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty. You should process m queries with it. Each query is one of three types: * "+ u v c" — add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in...
```python import sys input=sys.stdin.readline n,m=map(int,input().split()) graph=[] for i in range(n): graph.append({}) numcyc=0 numgoodcyc=0 for i in range(m): s=list(map(str,input().split())) if s[0]=='+': x=int(s[1])-1 y=int(s[2])-1 c=s[3] graph[x][y]=c if x in graph[y] and graph[y][x]!=0: ...
1517_D. Explorer Space
You are wandering in the explorer space of the 2050 Conference. The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1. At each step, y...
```python n, m, k = map(int, input().split()) h = [] for i in range(n): h.append(list(map(int, input().split()))) v = [] for i in range(n - 1): v.append(list(map(int, input().split()))) if k % 2 == 0: d = [[0] * m for i in range(n)] for t in range(k // 2): dt = [[0] * m for i in range(n)] for i in ra...
172_B. Pseudorandom Sequence Period
Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i ≥ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this val...
```python import sys a, b, m, x = tuple(map(int, input().split())) z=[0]*(m+1) cnt=1 z[x]=cnt while True: cnt += 1 x = (x*a+b)%m if z[x] > 0: print(str(cnt-z[x])) sys.exit(0) z[x] = cnt ```
192_C. Dynasty Puzzles
The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the...
```python import sys import math from heapq import *; input = sys.stdin.readline from functools import cmp_to_key; def pi(): return(int(input())) def pl(): return(int(input(), 16)) def ti(): return(list(map(int,input().split()))) def ts(): s = input() return(list(s[:len(s) - 1])) def invr(): re...
216_C. Hiring Staff
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff. The store will work seven days a week, but not around the clock. Every day at least k people must work in the store. Berland has a law that determines the order of working days and non-working...
```python n, m, k = map(int, input().split()) res, x = [], 1 if k == 1: while x <= n + m: res += [str(x)] x += n - 1 else: res = ['1'] while x <= n + m: res += [str(x)]*(k-1) x += n if x <= n + m + 1: res.append(str(x-1)) print(len(res)) print(' '.join(res...
23_C. Oranges and Apples
In 2N - 1 boxes there are apples and oranges. Your task is to choose N boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges. Input The first input line contains one number T — amount of tests. The description of each test starts with a natural number N — amou...
```python import sys input = sys.stdin.readline t = int(input()) for cs in range(t): n = int(input()) arr = [] for i in range(2 * n - 1): a, b = map(int, input().split()) arr.append((a, b, i)) arr.sort() res = [] for i in range(0, len(arr), 2): if i + 1 < len(arr): if arr[i][1] > arr[i + 1...
265_A. Colorful Stones (Simplified Edition)
There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively. Initially S...
```python stones = list(input()) instructions = list(input()) position = 0 i=0 for j in range(len(instructions)): if instructions[j] == stones[i]: i+=1 print(i+1) ```
289_A. Polo the Penguin and Segments
Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the ...
```python a,b = map(int, input().split()) c = 0 for i in range(a): d,e = map(int, input().split()) c += (e-d+1) if not(c%b): print(0) else: print((b-(c%b))%b) ```
314_A. Sereja and Contest
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the...
```python from sys import stdin,stdout nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) def fn(a): print('a',a) n=len(a) pos1=[0] for i in range(1,n): pos1+=[pos1[-1]+a[i]*i] print('pos1',pos1) neg=[] for i in range(n): neg+=[i*(n-i-1...
336_C. Vasily the Bear and Sequence
Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b...
```python from sys import stdin,stdout nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) for _ in range(1):#nmbr()): n=nmbr() a=lst() bits=[[0 for _ in range(34)] for _ in range(n)] for i in range(n): for j in range(34): bits[i][33-j]=(a[i]>>j...
359_D. Pair of Numbers
Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: 1. there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; 2. value r - l takes the maximum...
```python import math #import math #------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() s...
382_C. Arithmetic Progression
Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1. For example, sequences [1, 5], [10], [5...
```python n=int(input()) p=input().rstrip().split(' ') p.sort(key=int) if len(p)==1: print(-1) elif len(set(p))==1: print(1) print(p[0]) elif len(p)==2: if int(p[0])+2==int(p[1]): print(3) print(int(p[0])-2,int(p[0])+1,int(p[len(p)-1])+2) elif (int(p[0])+int(p[1]))%2==0: prin...
430_C. Xor-tree
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which ...
```python N = int(1e5+3) n = int(input()) adj = list([] for i in range(N)) for _ in range(n-1): u, v = map(int, input().split()) adj[u].append(v) adj[v].append(u) a = [0] + list(map(int, input().split())) b = [0] + list(map(int, input().split())) def dfs(u, p, c_lvl, p_lvl, d): stk = [(u, p, c_lvl, p_l...