name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p01885 Escape from the Hell
Example Input 3 9 6 3 5 2 3 1 2 2 2 Output 2
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, L = map(int, readline().split()) P = [list(map(int, readline().split())) for i in range(N)] C = [int(readline()) for i in range(N)] P.sort(key = lambda x: (x[0] - x[1]), reverse=1) INF = 10**18 S = [0]...
p02022 Mercy
H: Mercy Santa Claus found a group doing programming even though it was Christmas. Santa Claus felt sorry for them, so he decided to give them a cake. There are $ N $ types of cream, and the taste is $ A_1, A_2, A_3, \ dots, A_N $. There are $ M $ types of sponges, and the taste is $ B_1, B_2, B_3, \ dots, B_M $. ...
```python n, m = map(int, input().split()) a = sum(list(map(int, input().split()))) b = sum(list(map(int, input().split()))) print(a*b) ```
p02164 Satake likes straight
Problem Satake doesn't like being bent. For example, I don't like pencils, chopsticks, and bent-shaped houses, and I don't like taking actions such as turning right or left. By the way, Satake who lives on the XY plane is $ N $ shops $ (X_ {1}, Y_ {1}), (X_ {2}, Y_ {2}), \ ldots, (X_ {N} , Y_ {N}) I was asked to shop...
```python #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline(...
p02305 Intersection
For given two circles $c1$ and $c2$, print 4 if they do not cross (there are 4 common tangent lines), 3 if they are circumscribed (there are 3 common tangent lines), 2 if they intersect (there are 2 common tangent lines), 1 if a circle is inscribed in another (there are 1 common tangent line), 0 if ...
```python import math c1x,c1y,c1r = [int(i) for i in input().split()] c2x,c2y,c2r = [int(i) for i in input().split()] d = math.sqrt(pow(c1x-c2x, 2) + pow(c1y-c2y, 2)) s = c1r + c2r if d > s: print(4) elif d == s: print(3) else: if c1r > c2r: if d + c2r > c1r: print(2) elif d...
p02452 Includes
For given two sequneces $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$, determine whether all elements of $B$ are included in $A$. Note that, elements of $A$ and $B$ are sorted by ascending order respectively. Constraints * $1 \leq n, m \leq 200,000$ * $-1,000,000,000 \leq a_0 < a_1 < ... <...
```python n = int(input()) a = set(map(int, input().split())) m = int(input()) print(+a.issuperset(set(map(int, input().split())))) ```
1032_C. Playing Piano
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence a_1, a_2, …, a_n of key numbers: the more a number is, the closer it is to the right end of the piano keyboard. Paul is very clever and knows that the essential thing is...
```python n = int(input()) u = list(map(int, input().split())) d = [] for i in range(5): d.append([0] * n) for i in range(5): d[i][0] = 1 for i in range(1, n): if u[i] == u[i - 1]: s1 = 0 for j in range(5): if d[j][i - 1] == 1: s1 += 1 if s1 > 1: ...
1055_A. Metro
Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home. In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice ...
```python n, s = input().split() n = int(n) s = int(s) a = input().split() b = input().split() for j in range(n): a[j] = int(a[j]) b[j] = int(b[j]) if a[0]==1: if a[s-1]==1: print("YES") elif b[s-1]==1: for i in range(s,n): if a[i]==1 and b[i]==1: print("YES") break else: print("NO") el...
1077_B. Disturbed People
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise. Vova thinks that people in the i-th flats are distur...
```python n = int(input()) A = [int(i) for i in input().split()] V = [] for i in range(n-2): if (A[i]==1 and A[i+1]==0 and A[i+2]==1): V.append(i+1) V.append(1000) k = 0 l = 0 n = len(V) for i in range(n): if (V[i]-V[l] != 2): d = i-l k += (d+1)//2 l = i print(k) ```
1098_A. Sum in the tree
Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vert...
```python # alpha = "abcdefghijklmnopqrstuvwxyz" prime = 998244353 # INF = 100000000000 # from heapq import heappush from collections import defaultdict, deque t = 1#int(input()) from math import sqrt for test in range(t): n = int(input()) p = [0, 0] p.extend(list(map(int, input().split()))) s = [0] ...
1119_B. Alyona and a Narrow Fridge
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but ...
```python n,h=input().split() n=int(n) h=int(h) l=list(map(int,input().split())) k=[] r=0 for i in range(n): k.append(l[i]) k.sort(reverse=True) ans=0 for j in range(0,len(k),2): ans=ans+k[j] if(ans<=h): r=i+1 else: break print(r) ```
1145_F. Neat Words
Input The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive. Output Output "YES" or "NO". Examples Input NEAT Output YES Input WORD Output NO Input CODER Output NO Input APRILFOOL Output NO Input AI O...
```python lin = set(list('WETYIAFHKLZXVNM')) s = input() print('YES' if len(set(list(s)).intersection(lin)) in [len(set(list(s))), 0] else 'NO') ```
1166_E. The LCMs Must be Large
Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia? There are n stores numbered from 1 to n in Nlogonia. The i-th of these stores offers a positive integer a_i. Each day among the last m days Dora bought a single integer from s...
```python m, n = map(int, input().split()) s = [0] * m for w in range(m): for i in list(map(int, input().split()))[1:]: s[w] |= 1 << i for i in s: for j in s: if not (i & j): print('impossible') exit(0) print('possible') ```
1185_C1. Exam in BerSU (easy version)
The only difference between easy and hard versions is constraints. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: *...
```python n, m = map(int, input().split()) a = list(map(int, input().split())) cnt = [0] * 101 curr = 0 for i in range(n): tm = m - a[i] ans = 0 for j in range(1, 101): tmp = int(tm / j) if tmp >= cnt[j]: tm -= cnt[j] * j ans += cnt[j] else: tm -= ...
1203_F2. Complete the Projects (hard version)
The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete ...
```python # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! # TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!! from sys import stdin, stdout import math import copy #T = int(input()) #N = int(input()) #print(N) N,r = [int(x) for x in stdin.readline().split()] #arr = [int(x) for x in stdin.readline().s...
1220_E. Tourism
Alex decided to go on a touristic trip over the country. For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score w_i which is as high as interesting city seems to A...
```python from collections import defaultdict def get_neighbors(edges): neighbors = defaultdict(set, {}) for v1, v2 in edges: neighbors[v1].add(v2) neighbors[v2].add(v1) return dict(neighbors) def get_component(neighbors_map, root): if root not in neighbors_map: return {root}...
1246_A. p-binary
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer. For example,...
```python n,p=map(int,input().split()) #print("{0:b}".format(n).count('1')) t=0 while (("{0:b}".format(n).count('1'))>t or n<t) and n>=0: t+=1 n-=p if n<0: print(-1) else: print(t) ```
1265_E. Beautiful Mirrors
Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there ...
```python N = int(input()) P = list(map(int, input().split())) mod = 998244353 p = 0 q = 1 for i in range(N): p, q = (100 * (p+q)) % mod, (P[i] * q) % mod print((p * pow(q, mod-2, mod))%mod) ```
1287_A. Angry Students
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
```python n=int(input()) for i in range(n): m=int(input()) l=list(input()) p=[] c=0 r=len(l) for i in range(r): if l[i]=="P": c+=1 if i==r-1: p.append(c) if l[i]=="A": p.append(c) c=0 if len(p)!=1: if p[0]==0: print(max(p)) else: p.pop(0) print(max(p)) else: print(0) ```
1307_A. Cow and Haybales
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a...
```python t = int (input ()) ans = [] for i in range (t): day = 0 p = list (map (int, input ().split ())) n, d = p # flag = False num = list (map (int, input ().split ())) for k in range (1, n) : while (num[k] > 0 and day + k <= d) : num[0] += 1 num[k]...
1330_A. Dreamoon and Ranking Collection
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
```python cycles = int(input()) def find_v(x, places): places = set(places) v = 0 i = 1 while True: if i in places: v = i elif x > 0: v = i x -= 1 else: break i += 1 return v results = [] for cycle in range(cycles):...
1350_A. Orac and Factors
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b. For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
```python t = int(input()) for _ in range(t): n, k = map(int, input().split()) ans = n for i in range(2, n + 1): if n % i == 0: ans += i break ans += 2 * (k - 1) print(ans) ```
1370_D. Odd-Even Subsequence
Ashish has an array a of size n. A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements. Consider a subsequence s of a. He defines the cost of s as the minimum between: * The maximum among all elements...
```python import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() n,k = MI() a = LI() def check(mid,isEven): ans = 0 for i in range(n): ...
1417_E. XOR Inverse
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)). An inversion i...
```python import os from sys import stdin, stdout class Input: def __init__(self): self.lines = stdin.readlines() self.idx = 0 def line(self): try: return self.lines[self.idx].strip() finally: self.idx += 1 def array(self, sep = ' ', cast = ...
1434_C. Solo mid Oracle
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the ...
```python import sys input = sys.stdin.readline def solve_case(): a, b, c, d = [int(x) for x in input().split()] if a > b * c: print(-1) else: k = a // (b * d) print(a * (k + 1) - k * (k + 1) // 2 * b * d) def main(): for _ in range(int(input())): solve_case() main...
145_A. Lucky Conversion
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 two strings a and b of the same length n. The strings consist only of lucky digits. Pety...
```python a,b=input(),input();c,d=0,0 for i in range(len(a)): if a[i]!=b[i]: if a[i]=='4': c+=1 else: d+=1 print(max(c,d)) ```
1485_C. Floor and Mod
A pair of positive integers (a,b) is called special if ⌊ a/b ⌋ = a mod b. Here, ⌊ a/b ⌋ is the result of the integer division between a and b, while a mod b is its remainder. You are given two integers x and y. Find the number of special pairs (a,b) such that 1≤ a ≤ x and 1 ≤ b ≤ y. Input The first line contains a s...
```python import sys input = sys.stdin.readline import math t = int(input()) for f in range(t): x,y = map(int,input().split()) ok = 1 ng = y+1 while ng-ok > 1: c = (ng+ok)//2 if c*c-1 <= x: ok = c else: ng = c ans = 0 ans += (ok*(ok-1))//2 if...
150_A. Win or Freeze
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circl...
```python n = int(input()) p = n arr = [] while p%2==0: arr.append(2) p = p//2 x = int(p**0.5)+1 for i in range(3,x,2): while p%i==0: arr.append(i) p = p//i if p>2: arr.append(p) if n==1 or len(arr)==1: print(1) print(0) elif len(arr)==2: print(2) else: x = arr[0]*arr[1] ...
1535_E. Gold Transfer
You are given a rooted tree. Each vertex contains a_i tons of gold, which costs c_i per one ton. Initially, the tree consists only a root numbered 0 with a_0 tons of gold and price c_0 per ton. There are q queries. Each query has one of two types: 1. Add vertex i (where i is an index of query) as a son to some ver...
```python import os import sys input = sys.stdin.buffer.readline def main(): (Q, A0, C0) = [int(x) for x in input().split()] N = Q + 2 A = [0] * N C = [0] * N P = [0] * N pref = [0] * N # pref[u] is sum of A from root to u (inclusive, immutable) anc = [None for i in range(N)] # anc[u]...
182_D. Common Divisors
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with. String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string ...
```python s1=input() s2=input() n=len(s1) m=len(s2) cnt=0 from math import gcd g=gcd(n,m) for i in range(g): #curr=s1[:i+1] if n%(i+1)==0 and m%(i+1)==0: if s1[:i+1]*(n//(i+1))==s1 and s1[:i+1]*(m//(i+1))==s2: cnt+=1 print(cnt) ```
22_E. Scheme
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third mem...
```python import sys n = int(input()) g = [int(i) - 1 for i in sys.stdin.readline().split()] def solve(n, g): vertex_id = [-1]*n current_id = 0 cycle_starts = [] cycle_starts_by_vertex = [-1]*n cycle_vertex_sample = [] start_on_cycle = [] cycle_index_by_ID = [] for v in range(n): ...
255_D. Mr. Bender and Square
Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy. We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right f...
```python import sys ii = lambda: sys.stdin.readline().strip() idata = lambda: [int(x) for x in ii().split()] sdata = lambda: list(ii()) def solve(): n, x, y, c = idata() r = n ** 2 l = -1 while l + 1 < r: middle = (l + r) // 2 ans = 1 + 2 * (middle + 1) * middle ans -= pow(midd...
279_D. The Minimum Number of Variables
You've got a positive integer sequence a1, a2, ..., an. All numbers in the sequence are distinct. Let's fix the set of variables b1, b2, ..., bm. Initially each variable bi (1 ≤ i ≤ m) contains the value of zero. Consider the following sequence, consisting of n operations. The first operation is assigning the value of...
```python def Solve(x,B): if((X,x,B) in Mem): return Mem[(X,x,B)] if(len(B)>X): return False if(x==len(L)): return True if(Form(L[x],B)): A=list(B) for e in range(len(B)): r=A[e] A[e]=L[x] if(Solve(x+1,tuple(sorted(A)))): ...
301_C. Yaroslav and Algorithm
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. 1. The algorithm receives a string as the input. We denote this input string as a. 2. The algorithm consists of some number of command. Сommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strin...
```python print ( """0??<>1 1??<>2 2??<>3 3??<>4 4??<>5 5??<>6 6??<>7 7??<>8 8??<>9 9??>>??0 ??<>1 ?0>>0? ?1>>1? ?2>>2? ?3>>3? ?4>>4? ?5>>5? ?6>>6? ?7>>7? ?8>>8? ?9>>9? ?>>?? >>?""" ) ```
328_A. IQ Test
Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions. Arithmetic progression is a sequence a1, a1 + d, a1 + 2d, ..., a1 + (n - 1)d, where a1 and d are any numbers. Ge...
```python import sys fin = sys.stdin a = list(map(int, fin.readline().split())) d = a[1] - a[0] if a[2] - a[1] == a[3] - a[2] == d: print(a[3] + d) else: d = a[1] / a[0] if a[2] / a[1] == a[3] / a[2] == d and d * a[3] == int(d * a[3]): print(int(d * a[3])) else: print(42) ```
34_B. Sale
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ...
```python n, m = map(int, input().split()) a = list(map(int, input().split())) a.sort() ans = 0 for i in range(len(a)): if a[i] < 0: ans += a[i] m -= 1 if m == 0: break print(-1 * ans) ```
373_C. Counting Kangaroos is Fun
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is ...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt'...
418_A. Football
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once. The appointed Judge was the most experienced member — Pavel. But since he was the wi...
```python n,k=map(int,input().split()) a=n*(n-1)//2 if(n*k>a): print(-1) else: print(n*k) for i in range(1,n+1): for j in range(k): print(i,(i+j)%n+1) ```
466_E. Information Graph
There are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place: * either employee y became the boss of employee x (at that, employee x didn't have a bos...
```python import sys input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ n, m = map(int, input().split()) ev = [tuple(map(int, input().split())) for _ in range(m)] g = [[] for _ in range(n + 1)] qry = [[] for _ in range(m + 1)] roots = set(range(1, n + 1)) qcnt = 0 for e in ev: if e[0] == 1: g[e[2...
48_C. The Race
Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer. So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α li...
```python eps=10**(-9) mn=10 mx=100000000 n=int(input()) arr=list(map(int,input().split())) for i in range(n): mn = max(mn,(arr[i]*10)/(i+1)) mx = min(mx,((arr[i]+1)*10)/(i+1)) ans1=((n+1)*mn)//10 ans2=((n+1)*(mx-eps))//10 if ans2>ans1: print('not unique') else: print('unique') print(int(ans1)) ...
53_A. Autocomplete
Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list co...
```python s = input() l = len(s) n = int(input()) u = [] for i in range(n): a = input() #print('Taken input', a,len(a),l) if a[:l] == s: if len(u) == 0: u.append(a if len(a) == l else a[l:]) elif len(a) == l: u = [a] + u else: j = 0 k = 0 while True: if u[k] == s: if k < len(u) - 1: ...
567_C. Geometric Progression
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers. He wants to know how many subsequences of length three can be selected from a, so that they form a geometric p...
```python import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]...
610_B. Vika and Squares
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i. Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will ...
```python import itertools import math n = int(input()) a = [int(x) for x in input().split()] amin = min(a) b = list(filter(lambda x: x[1] == amin, enumerate(a))) l = len(b) k = max((b[(i+1) % l][0] - b[i][0] - 1)%n for i in range(l)) print(amin*n + k) ```
630_L. Cracking the Code
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives. A young hacker Vasya disassembled the program and foun...
```python #Nearly Lucky ''' a=list(map(str,input())) l=0 for i in range(len(a)): if(a[i]=='4' or a[i]=='7'): l+=1 if(l==4 or l==7 or l==44 or l==47 or l==74 or l==77): print("YES") else: print("NO")''' #IQ Test ''' a=int(input()) b=list(map(int,input().strip().split())) e,o=[],[] for i in range(len(...
659_D. Bicycle Race
Maria participates in a bicycle race. The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west. Let's introduce a system of coordinates, directing the Ox axis from west to east, and th...
```python read = lambda: map(int, input().split()) vect = lambda a, b: a[0] * b[1] - a[1] * b[0] vector = lambda A, B: (B[0] - A[0], B[1] - A[1]) n = int(input()) p = [tuple(read()) for i in range(n)] cnt = 0 for i in range(2, n): v1 = vector(p[i], p[i - 1]) v2 = vector(p[i - 1], p[i - 2]) if vect(v1, v2...
682_A. Alyona and Numbers
After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers — the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column ...
```python from math import ceil,floor n,m = map(int, input().split()) res = 0 for i in range(1,n+1): req = 5 - i%5 res += ((m-req) // 5) +1 print(res) ```
748_D. Santa Claus and a Palindrome
Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative — that means that Santa doesn't find this s...
```python import sys import math def solve(): k, n = map(int, input().split()) D = {} for line in sys.stdin: s, a = line.split() if s in D: D[s].append(int(a)) else: D[s] = [int(a)] res = 0 center = 0 for s in D: revs = s[::-1] if...
771_C. Bear and Tree Jumps
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them. Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n. Limak recently learned how to jump. He can jump from a vertex to any verte...
```python """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlin...
796_C. Bank Hacking
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. <image> There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the ...
```python import sys input = sys.stdin.readline from collections import Counter n = int(input()) arr = list(int(i) for i in input().split()) + [-int(1e9+3)] c = Counter(arr) top, sec = sorted(set(arr))[-1:-3:-1] top_cnt = [int(i == top) for i in arr] sec_cnt = [int(i == sec) for i in arr] edges = list(list(map(int, i...
816_D. Karen and Test
Karen has just arrived at school, and she has a math test today! <image> The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. Th...
```python n = int(input()) p = list(map(int,input().split())) MOD = 10**9+7 mode = 0 if n%4 == 3: n-= 1 new = [] for i in range(n): if mode == 0: new.append(p[i]+p[i+1]) else: new.append(p[i]-p[i+1]) mode = 1-mode p = new def calc0(p): res = 0 ncr = 1 n = len(p)//2-...
841_D. Leha and another game about graph
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say...
```python import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys import heapq INF=10**9 def Dijkstra(graph, start,m): dist=[INF]*len(graph) parent=[INF]*len(graph) queue=[(0, start)] while queue: path_len, v=heapq.heappop(queue) if dist[v]==INF: dist[v]=path_len fo...
862_E. Mahmoud and Ehab and the function
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, <image>. Dr. Evil wants Ma...
```python from bisect import * f = lambda: list(map(int, input().split())) n, m, q = f() k = m - n + 1 a = f() s = sum(a[0:n:2]) - sum(a[1:n:2]) b = [0] + f() for i in range(2, m + 1, 2): b[i] = -b[i] for i in range(m): b[i + 1] += b[i] u = [b[j] - b[j + n] for j in range(1, k, 2)] v = [b[j + n] - b[j] for j in ran...
888_C. K-Dominant Character
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c. You have to find minimum k such that there exists at least one k-dominant character. Input The first line contains string s consisting of lowercas...
```python word = input() n = len(word) d,e = {},{} for i in range(n): if word[i] in d: d[word[i]].append(i+1) else: e[word[i]] = 0 d[word[i]] = [i+1] # print(d,e) for i in d: temp = d[i] if len(temp)==1: cnt = temp[0] cnt = max(n-temp[0]+1,cnt) e[i] = cnt ...
911_A. Nearest Minimums
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. Input The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ...
```python from sys import maxsize n = int(input()) arr = list(map(int,input().split())) m = maxsize res= maxsize ind = [] for i in range(len(arr)): if arr[i] < m: m = arr[i] ind = [i] res=maxsize elif arr[i] == m: ind.append(i) if ind[-1]-ind[-2] < res and len(ind) > 1: ...
95_A. Hockey
Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin ...
```python n = int(input()) a = [] for i in range(n): a.append(input().rstrip()) w = list(input().rstrip()) c = input().rstrip() m = len(w) z = [] i = 0 while i < m: for j in range(n): if w[i].lower() == a[j][0].lower(): if i + len(a[j]) <= m: f = 1 for k in ra...
p02585 AtCoder Beginner Contest 175 - Moving Piece
Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N. Now, he will choose one square and place the piece on that square. Then, he will make the following move some n...
```python n,k=map(int,input().split()) p=list(map(int,input().split())) c=list(map(int,input().split())) for i in range(n): p[i]-=1 ans=max(c) for i in range(n): f=i r=0 l=[] while True: f=p[f] l.append(c[f]) r+=c[f] if f==i: break t=0 for j in ran...
p02716 AtCoder Beginner Contest 162 - Select Half
Given is an integer sequence A_1, ..., A_N of length N. We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen. Find the maximum possible sum of the chosen elements. Here \lfloor x \rfloor denotes the greatest integer not greater than x. ...
```python N=int(input()) A=list(map(int, input().split())) dp = [[0 for i in range(2)] for j in range(N+1)] if N in [2, 3]: print(max(A)) else: dp[2][0] = A[1] dp[2][1] = A[0] dp[3][0] = A[2] dp[3][1] = max(A[1], A[0]) for i in range(4, N+1): if i % 2 == 0: dp[i][0] = max(max(dp[i-2][0], dp[i-2...
p02845 Sumitomo Mitsui Trust Bank Programming Contest 2019 - Colorful Hats 2
N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green. The person numbered i says: * "In front of me, exactly A_i people are wearing hats with the same color as mine." Assuming that all these statements are correct, find the number of p...
```python N = int(input()) A = list(map(int,input().split())) MOD = 1000000007 C = [3] + [0 for i in range(N)] ans = 1 for a in A: ans *= C[a] ans %= MOD C[a] -= 1 C[a+1] += 1 print(ans) ```
p02982 AtCoder Beginner Contest 133 - Good Distance
There are N points in a D-dimensional space. The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}). The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}. How many pairs (i, j) (i < j) are there such ...
```python n,d=map(int,input().split()) A=[list(map(int,input().split())) for i in range(n)] ans=0 for i in range(n): for j in range(i): dis=sum([(A[i][k]-A[j][k])**2 for k in range(d)]) if dis**(1/2)==int(dis**(1/2)): ans+=1 print(ans) ```
p03265 AtCoder Beginner Contest 108 - Ruined Square
There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order. (Assume that the positive x-axis points right, and the positive y-axis points up.) Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4). ...
```python a,b,c,d=map(int,input().split()) print(c+b-d,d-a+c,a+b-d,b-a+c) ```
p03424 AtCoder Beginner Contest 089 - Hina Arare
In Japan, people make offerings called hina arare, colorful crackers, on March 3. We have a bag that contains N hina arare. (From here, we call them arare.) It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow. We have ...
```python input() print(['Three', 'Four']['Y' in input()]) ```
p03738 AtCoder Beginner Contest 059 - Comparison
You are given two positive integers A and B. Compare the magnitudes of these numbers. Constraints * 1 ≤ A, B ≤ 10^{100} * Neither A nor B begins with a `0`. Input Input is given from Standard Input in the following format: A B Output Print `GREATER` if A>B, `LESS` if A<B and `EQUAL` if A=B. Examples Input 3...
```python a = int(input()) b = int(input()) print("LESS" if a<b else "EQUAL" if a == b else "GREATER") ```
p00006 Reverse Sequence
Write a program which reverses a given string str. Input str (the size of str ≤ 20) is given in a line. Output Print the reversed str in a line. Example Input w32nimda Output admin23w
```python st = input() print(st[::-1]) ```
p00138 Track and Field Competition
The athletics competition 200M semi-final three races were held. Eight players (24 players in total) will participate in each group. A total of eight players, including the top two players in each group and the top two players from all the players in each group who are third or lower, will advance to the final. Create...
```python import heapq from collections import namedtuple Data = namedtuple("Data", "time number") all_player = [] for _ in range(3): player = [input().split(" ") for lp in range(8)] player = [Data(float(time), number) for number, time in player] heapq.heapify(player) data = heapq.heappop(player) ...
p00271 Temperature Difference
Welcome to PC Koshien, players. Physical condition management is important to participate in the event. It is said that at the turn of the season when the temperature fluctuates greatly, it puts a strain on the body and it is easy to catch a cold. The day you should be careful about is the day when the difference betwe...
```python c = 0 while c <= 6: a, b = map(int,input().split()) c = c + 1 print(a - b) ```
p00925 Miscalculation
Example Input 1+2*3+4 11 Output M
```python s,ans=input(),int(input()) x=int(s[0]) for i in range(1,len(s),2): y=int(s[i+1]) x=x*y if s[i]=='*' else x+y print("IMLU"[int(eval(s)==ans)+(int(x==ans)<<1)]) ```
p01943 Multiplication Is Interesting
F: Multiplication is fun --Multiplication Is Interesting - story Namba, a high school boy, is thinking of giving her a few lines on her birthday. She is a girl who loves multiplication, so Namba wants to give her a sequence that will allow her to enjoy multiplication as much as possible. However, when the calculation...
```python from decimal import * import sys import copy def main(): getcontext().prec = 1000 input = sys.stdin.readline n, k = input().split() n = int(n) k = Decimal(k) a = [Decimal(input()) for i in range(n)] if Decimal(0) in a: print(n) sys.exit() if k == Decimal(0): ...
p02376 Maximum Flow
A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Constraints * $2 \leq |V...
```python # Acceptance of input import sys file_input = sys.stdin V, E = map(int, file_input.readline().split()) adj_mat = [[0] * V for i in range(V)] for line in file_input: u, v, c = map(int, line.split()) adj_mat[u][v] = c # Ford???Fulkerson algorithm import collections # BFS for residual capacity ne...
1005_D. Polycarp and Div 3
Polycarp likes numbers that are divisible by 3. He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Poly...
```python n = input() buf = 0 c = 0 m = 0 for i in range(len(n)): buf += int(n[i]) m += 1 if int(n[i]) % 3 == 0 or buf % 3 == 0 or m >= 3: buf = 0 c += 1 m = 0 print(c) ```
1029_B. Creating the Contest
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order. You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as...
```python n=int(input()) a=list(map(int,input().split())) b=[] for _ in range(n-1): if a[_+1]<=a[_]*2: b.append(1) else: b.append(0) b.append(1); s=0; c=[] for i in range(n): if b[i]==1: s+=1 c.append(s) else: s=0 if c[len(c)-1]==max(c) and c.count(max(c))==1: ...
104_A. Blackjack
One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one! Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to...
```python n=int(input()) if n<11 or n>21: print(0) elif n==20: print(15) else: print(4) ```
1071_B. Minimum path
You are given a matrix of size n × n filled with lowercase English letters. You can change no more than k letters in this matrix. Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is f...
```python def solve(m, matrix, good, n): c = 'z' for x in range(n): y = m - x if y < 0 or y >= n: continue if not good[x][y]: continue if x < n - 1: c = min(c, matrix[x + 1][y]) if y < n - 1: c = min(c, matrix[x][y + 1]) for x in range(n): y = m - x if...
1093_D. Beautiful Graph
You are given an undirected unweighted graph consisting of n vertices and m edges. You have to write a number on each vertex of the graph. Each number should be 1, 2 or 3. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd. Calculate the number of possible ways t...
```python from collections import deque from sys import stdin, stdout input = stdin.readline saida = [] t = int(input()) modulo = 998244353 for _ in range(t): ans = 1 part = 0 factor = 0 fila = deque([]) n, m = map(int, input().split()) if m > (n // 2) * ( n // 2 + 1): saida.append(...
1113_D. Sasha and One More Name
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in t...
```python s=input() if len(set(s[:len(s)//2]))<=1: print("Impossible");exit() for i in range(1,len(s)): n=s[i:]+s[:i] if(n==n[::-1])and(n!=s): print(1);exit() print(2) ```
1141_F2. Same Sum Blocks (Hard)
This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a...
```python n=int(input()) a=list(map(int,input().split())) dic={} for i in range(n): sm=0 for j in range(i,n): sm+=a[j] if sm in dic: dic[sm].append((i,j)) else: dic[sm]=[(i,j)] ans=0 anskey=-1 for key in dic: cnt=0 last=-1 for a,b in sorted(dic[key]): ...
1162_A. Zoning Restrictions Again
You are planning to build housing on a street. There are n spots available on the street on which you can build a house. The spots are labeled from 1 to n from left to right. In each spot, you can build a house with an integer height between 0 and h. In each spot, if a house has height a, you will gain a^2 dollars fro...
```python n, h, m = map(int, input().split()) houses = [h] * n for i in range(m): tmp = list(map(int, input().split())) for j in range(tmp[0]-1, tmp[1]): if tmp[2] <= houses[j]: houses[j] = tmp[2] total = 0 for i in houses: total += i*i print(total) ```
1200_A. Hotelier
Amugae has a hotel consisting of 10 rooms. The rooms are numbered from 0 to 9 from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similar...
```python input() l = [0]*10 s = input() for i in range(len(s)): e = s[i] if e == 'L': l[l.index(0)] = 1 elif e == 'R': l[len(l) - l[::-1].index(0) - 1] = 1 else: l[int(e)] = 0 print(*l, sep = '') ```
1240_F. Football
There are n football teams in the world. The Main Football Organization (MFO) wants to host at most m games. MFO wants the i-th game to be played between the teams a_i and b_i in one of the k stadiums. Let s_{ij} be the numbers of games the i-th team played in the j-th stadium. MFO does not want a team to have much...
```python import random import math def set_color(game, color): color_count[game[0]][game[2]] -= 1 color_count[game[1]][game[2]] -= 1 game[2] = color color_count[game[0]][game[2]] += 1 color_count[game[1]][game[2]] += 1 def fix(node): minimum = math.inf maximum = 0 for i in range(k): ...
1261_A. Messy
You are fed up with your messy room, so you decided to clean it up. Your room is a bracket sequence s=s_{1}s_{2}... s_{n} of length n. Each character of this string is either an opening bracket '(' or a closing bracket ')'. In one operation you can choose any consecutive substring of s and reverse it. In other words,...
```python import os, sys, math def solve(seq, k): seq = [ 1 if a == '(' else -1 for a in seq ] size = len(seq) result = [] def rotate(fr, to): assert fr <= to result.append((fr + 1, to + 1)) while fr < to: seq[fr], seq[to] = seq[to], seq[fr] fr += 1 to -= 1 # print(''.join('(' if q > 0 else ')' f...
1283_B. Candies Division
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
```python n = int(input()) k = [] d = [] r = [] m = [] dk = [] h = 0 z = [] for i in range(n): a = list(map(int,input().split())) k.append(a[0]) d.append(a[1]) r.append(a[0] // a[1]) h += r[i] * a[1] m.append(a[0]-((a[0] // a[1])*a[1])) if (a[1]//2 == m[i]): h += m[i] elif (a[1]/...
1367_F1. Flying Sort (Easy Version)
This is an easy version of the problem. In this version, all numbers in the given array are distinct and the constraints on n are less than in the hard version of the problem. You are given an array a of n integers (there are no equals elements in the array). You can perform the following operations on array elements:...
```python t=int(input()) for you in range(t): n=int(input()) l=input().split() li=[int(i) for i in l] z=list(li) z.sort() hashi=dict() for i in range(n): hashi[z[i]]=i+1 for i in range(n): li[i]=hashi[li[i]] hashi=dict() dp=[0 for i in range(n)] for i in range...
1389_A. LCM Problem
Let LCM(x, y) be the minimum positive integer that is divisible by both x and y. For example, LCM(13, 37) = 481, LCM(9, 6) = 18. You are given two integers l and r. Find two integers x and y such that l ≤ x < y ≤ r and l ≤ LCM(x, y) ≤ r. Input The first line contains one integer t (1 ≤ t ≤ 10000) — the number of tes...
```python T=int(input()) for _ in range(T): l,r=map(int,input().split()) if abs(l-r)==1 and l!=1: print(-1,-1) elif 2*l>r : print(-1,-1) else: print(l,2*l) ```
1409_D. Decrease the Sum of Digits
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
```python for _ in range(int(input())): n,k=[int(x) for x in input().split()] if n%k==0:print(0) else:print(k-(n%k)) ```
1430_B. Barrels
You have n barrels lined up in a row, numbered from left to right from one. Initially, the i-th barrel contains a_i liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels x and y (the x-th barrel shouldn't be empty) and pour any possible amount of wa...
```python def solve(): n,k=map(int,input().split()) if n==1: print(0) return ls=list(map(int,input().split())) ls.sort() res=ls.pop() for i in range(k): if ls: res+=ls.pop() print(res) return for _ in range(int(input())): solve() ```
1453_D. Checkpoints
Gildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage. There is at most one checkpoint on each stage, and there is always a checkp...
```python t=int(input()) for _ in range(t): n=int(input()) if n%2==1: print(-1) continue ans=[] tmp=0 for i in range(2,62): if 1<<i&n: ans.append('1') for j in range(i-2): ans.append('0') tmp+=1 for i in range(tmp): ans.append('1') if 2&n: ans.append('1') pr...
1477_B. Nezzar and Binary String
Nezzar has a binary string s of length n that he wants to share with his best friend, Nanako. Nanako will spend q days inspecting the binary string. At the same time, Nezzar wants to change the string s into string f during these q days, because it looks better. It is known that Nanako loves consistency so much. On th...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): def __init__(self, file): self.newlines = 0 self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write ...
1527_D. MEX Tree
You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u ≠ v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k. The MEX of a sequence of integers is the smallest non-n...
```python import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations ...
159_C. String Manipulation 1.0
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo th...
```python # cook your dish here n=int(input()) s=list(input())*n d={} for i in range(len(s)): if s[i] not in d: d[s[i]]=[i] else: d[s[i]].append(i) m=int(input()) for i in range(m): o,c=input().split() s[d[c].pop(int(o)-1)]='' print(''.join(s)) ```
201_A. Clear Symmetry
Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j. L...
```python x=int(input()) n=1 while n*n+1<2*x: n+=2 if x==3: n=5 print(n) ```
225_E. Unsolvable
Consider the following equation: <image> where sign [a] represents the integer part of number a. Let's find all integer z (z > 0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x, y > 0), for which the ...
```python print([0,1,3,15,63,4095,65535,262143,73741816,536396503,140130950,487761805,319908070,106681874,373391776,317758023,191994803,416292236,110940209,599412198,383601260,910358878,532737550,348927936,923450985,470083777,642578561,428308066,485739298,419990027,287292016,202484167,389339971,848994100,273206869,8530...
24_C. Sequence of points
You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center o...
```python n, k = map(int, input().split()) ax = [] ay = [] mx, my = map(int, input().split()) for i in range(n): x, y = map(int, input().split()) ax.append(x) ay.append(y) k %= 2*n for i in range(k): mx = 2*ax[i % n] - mx my = 2*ay[i % n] - my print(mx, " ", my) ```
298_A. Snow Footprints
There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint ...
```python arg = int(input()) s2=input() start = -1 ending = -1 flag9 = 0 if "R" in s2: for n in range(0, arg): if s2[n]=="R" and flag9 == 0: start = n + 1 flag9 = 1 if s2[n]== "R" and s2[n+1] == "L": ending = n + 1 elif s2[n] == "R": ending = n + 2 else: for n in range(0, arg): if s2[n]=="L"...
320_D. Psychos in a Line
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangeme...
```python n = int(input()) aa = list(map(int,input().split())) live = [] ans=0 for i in range(n-1,-1,-1): c = 0 while len(live)!=0 and live[-1][0]<aa[i]: c = max(c+1,live[-1][1]) live.pop() if c>ans: ans =c live.append((aa[i],c)) print(ans) ```
369_A. Valera and Plates
Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat d...
```python class CodeforcesTask369ASolution: def __init__(self): self.result = '' self.n_m_k = [] self.plan = [] def read_input(self): self.n_m_k = [int(x) for x in input().split(" ")] self.plan = [int(x) for x in input().split(" ")] def process_task(self): c...
391_B. Word Folding
You will receive 5 points for solving this problem. Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using t...
```python t = {} for i, c in enumerate(input()): if c not in t: t[c] = (i, 1) elif (t[c][0] - i) & 1: t[c] = (i, t[c][1] + 1) print(max(b for a, b in t.values())) ```
413_A. Data Recovery
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors. The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in...
```python n, m, mmin, mmax = map(int, input().split()) s = list(map(int, input().split())) s = sorted(s) if s[0] < mmin or s[m - 1] > mmax: print("Incorrect") elif s[0] == mmin and s[m - 1] == mmax: print("Correct") elif s[0] != mmin and s[m - 1] != mmax: if n - m < 2: print("Incorrect") else: ...
43_C. Lucky Tickets
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid a...
```python n=int(input()) inp = list(map(int,input().split())) l=[0,0,0] for item in inp: l[item%3]+=1 a=l[0] b=l[1] c=l[2] print (min(b,c)+a//2) ```
509_D. Restoring Numbers
Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula: <image> Vasya wrote down matrix v on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a p...
```python """ Codeforces Contest 289 Div 2 Problem D Author : chaotic_iak Language: Python 3.4.2 """ ################################################### SOLUTION def main(): n,m = read() matrix = [read() for _ in range(n)] mod = 10**11 for i in range(n-1): poss = set() for j in range...
584_C. Marina and Vasya
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string. More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and ...
```python fs = frozenset(list("abc")) def calc(s1, s2): return len(list(filter(lambda x: x[0] == x[1], zip(s1, s2)))) if __name__ == '__main__': n, t = map(int, input().split()) s1 = input() s2 = input() q = n - t c = calc(s1, s2) need = q - c w = 0 ss = ['x'] * len(s1) if n...
606_C. Sorting Railway Cars
An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it...
```python def LIS(s): n = len(s) L = [0]*n appear = [False]*n L[0] = 1 find = [-1]*n appear[s[0]] = True find[s[0]] = 0 for i in range(1,len(s)): if s[i]>0 and appear[s[i]-1]: L[i] = L[find[s[i]-1]] + 1 else: L[i] = 1 appear[s[i]] = True ...
628_C. Bear and String Distance
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only. The distance between two letters is defined as the difference between their positions in the alphabet. For example, <image>, and <image>. Also, the distance between two nice strings is defined as t...
```python #import sys #sys.stdin = open('in', 'r') #n = int(input()) #a = [int(x) for x in input().split()] alph = 'abcdefghijklmnopqrstuvwxyz' n,k = map(int, input().split()) s = input() res = '' for c in s: if k > 0: r = ord('z') - ord(c) l = ord(c) - ord('a') if r >= l: if k >...