name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p03291 AtCoder Beginner Contest 104 - We Love ABC
The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions: * 1 ≤ i < j < k ≤ |T| (|T| is the length of T.) * T_i = `A` (T_i is the i-th character of T from the beginning.) * T_j = `B` * T_k = `C` For example, when T = `ABCBC`, there are three triples of...
```python s=input() n=len(s) dp=[4*[0]for i in range(n+1)] dp[0][0]=1 for i in range(1,n+1): for j in range(4): dp[i][j]+=dp[i-1][j]*((s[i-1]=="?")*2+1) if s[i-1] in "A?":dp[i][1]+=dp[i-1][0] if s[i-1] in "B?":dp[i][2]+=dp[i-1][1] if s[i-1] in "C?":dp[i][3]+=dp[i-1][2] for j in range(4):dp[i][j]%=10**9+7 ...
p03447 AtCoder Beginner Contest 087 - Buying Sweets
You went shopping to buy cakes and donuts with X yen (the currency of Japan). First, you bought one cake for A yen at a cake shop. Then, you bought as many donuts as possible for B yen each, at a donut shop. How much do you have left after shopping? Constraints * 1 \leq A, B \leq 1 000 * A + B \leq X \leq 10 000 * ...
```python print(eval(input()+"-"+input())%int(input())) ```
p03607 AtCoder Beginner Contest 073 - Write and Erase
You are playing the following game with Joisino. * Initially, you have a blank sheet of paper. * Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times. * Then, you are asked a question: How many numbe...
```python n=int(input()) s=set() for i in range(n): x=input() if x in s: s.discard(x) else: s.add(x) print(len(s)) ```
p03768 AtCoder Grand Contest 012 - Splatter Painting
Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on th...
```python import sys input = sys.stdin.readline INF = 10**14 N, M = map(int, input().split()) graph = [[] for _ in range(N)] for _ in range(M): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) maxd = 0 Q = int(input()) Query = [] Color = [] for _ in range(Q): v, d, c = m...
p03937 AtCoder Grand Contest 007 - Shik and Stone
We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including t...
```python H,W=map(int,input().split());print(["Imp","P"][H+W-1==sum(input().count("#")for _ in range(H))]+"ossible") ```
p00029 English Sentence
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters. The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separate...
```python word_list = input().split(' ') word_dict = {} longest_word_len = 0 longest_word = '' high_freq_word_num = 0 for word in word_list: if longest_word_len < len(word): longest_word_len = len(word) longest_word = word if word not in word_dict: word_dict[word] = 1 else : ...
p00160 Delivery Fee
The courier charges for a courier company are set according to size and weight as shown in the table below. A size | B size | C size | D size | E size | F size --- | --- | --- | --- | --- | --- | --- Size | 60 cm or less | 80 cm or less | 100 cm or less | 120 cm or less | 140 cm or less | 160 cm or less Weight | 2kg o...
```python S = [60, 80, 100, 120, 140, 160] W = [2, 5, 10, 15, 20, 25] P = [600, 800, 1000, 1200, 1400, 1600] while 1: n = int(input()) if n == 0: break r = 0 for i in range(n): x, y, h, w = map(int, input().split()) s = x + y + h for j in range(6): if s <= S[...
p00487 Bug Party
Do you know Just Odd Inventions? The business of this company is to "just odd inventions". Here, it is abbreviated as JOI. JOI is conducting research to confine many microorganisms in one petri dish alive. There are N microorganisms to be investigated, and they are numbered 1, 2, ..., N. When each microorganism is tra...
```python # AOJ 0564: Bug Party # Python3 2018.6.30 bal4u import heapq tbl = [] N = int(input()) for i in range(N): a, b = map(int, input().split()) tbl.append((a, b)) tbl.sort() Q = [] ans = s = sz = 0 for t in tbl: s += t[0] heapq.heappush(Q, (t[1], t[0])) sz += 1 while sz and sz*Q[0][0] < s: s -= Q[0][1] ...
p00816 Shredding Company
You have just been put in charge of developing a new shredder for the Shredding Company. Although a ``normal'' shredder would just shred sheets of paper into little pieces so that the contents would become unreadable, this new shredder needs to have the following unusual basic characteristics. * The shredder takes as ...
```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...
p00947 Quality of Check Digits
Example Input 0 3 1 7 5 9 8 6 4 2 7 0 9 2 1 5 4 8 6 3 4 2 0 6 8 7 1 3 5 9 1 7 5 0 9 8 3 4 2 6 6 1 2 3 0 4 5 9 7 8 3 6 7 4 2 0 9 5 8 1 5 8 6 9 7 2 0 1 3 4 8 9 4 5 3 6 2 0 1 7 9 4 3 8 6 1 7 2 0 5 2 5 8 1 4 3 6 7 9 0 Output 0
```python from itertools import product T = [list(map(int, input().split())) for i in range(10)] def calc(v): val = 0 for e in v: val = T[val][e] return val ans = 0 for code in product(range(10), repeat=4): e = calc(code) ok = 1 code = list(code) + [e] for i in range(5): d ...
p01080 Traffic Tree
Problem A graph is given in which N vertices, each numbered from 1 to N, are connected by N-1 undirected edges. For each vertex, output the shortest number of steps to start from that vertex and visit all vertices. However, one step is to follow one side from one vertex and move to another vertex. Constraints * 2 ≤...
```python def main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 9) from collections import deque N = int(input()) #隣接リストの作成 G = [[] for _ in range(N)] for _ in range(N - 1): u, v = map(int, input().split()) u -= 1 v -= 1 G[u]...
p01350 Carrot Tour
I'm traveling to a country with a rabbit. There are n cities in this country numbered from 1 to n, and the rabbit is now in city 1. City i is a point on the coordinate plane (xi, yi) ). Rabbits travel to meet the following conditions. * The travel path is a polygonal line, each part of which must be a line segment co...
```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 ...
p01832 Shifting a Matrix
Example Input 3 2 R1 Output 3 1 2 4 5 6 7 8 9
```python from string import digits import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, L = map(int, readline().split()) S = readline().strip() *I, = range(N*N) LRUD = "LRUD" FS = [[], [], [], []] for i in range(N): base = N*i F = I[:] for j ...
p01967 Many Kinds of Apples
A: Many Kinds of Apples Problem Statement Apple Farmer Mon has two kinds of tasks: "harvest apples" and "ship apples". There are N different species of apples, and N distinguishable boxes. Apples are labeled by the species, and boxes are also labeled, from 1 to N. The i-th species of apples are stored in the i-th bo...
```python n = int(input()) C = list(map(int, input().split())) q = int(input()) data = [] for _ in range(q): t, x, d = map(int, input().split()) data.append([t, x, d]) apple = [0] * n for D in data: t, x, d = D if t == 1: apple[x-1] += d if apple[x-1] > C[x-1]: print(x) ...
p02114 Fissure Puzzle Easy
Problem There is a grid of $ N \ times N $ cells. Initially all cells are white. Follow the steps below to increase the number of black squares. Select one white cell from the cells that are even-numbered from the top and even-numbered from the left. The selected square turns black. Further, the adjacent white square...
```python from collections import deque n = int(input()) A = [input() for i in range(n)] cnt = 0 dd = [[-1, 0], [0, -1], [1, 0], [0, 1]] used = {} for i in range(n): for j in range(n): if A[i][j] == 'x' or (i, j) in used: continue deq = deque([(j, i)]) used[i, j] = 1 cnt...
p02254 Huffman Coding
We want to encode a given string $S$ to a binary string. Each alphabet character in $S$ should be mapped to a different variable-length code and the code must not be a prefix of others. Huffman coding is known as one of ways to obtain a code table for such encoding. For example, we consider that appearance frequencyc...
```python from heapq import heappop, heappush from collections import Counter class Node: def __init__(self, weight): self.weight = weight def set_parent(self,parent): self.parent = parent def get_length(self): try: tmp = 1 + self.parent.get_length() ...
p02402 Min
Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence. Constraints * $0 < n \leq 10000$ * $-1000000 \leq a_i \leq 1000000$ Input In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in...
```python input() l=list([int(i) for i in input().split()]) print(min(l), max(l), sum(l)) ```
1004_A. Sonya and Hotels
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate ...
```python n, d = map(int,input().split()) a = list(map(int,input().split())) count = 0 for i in range(n-1): if a[i + 1] - a[i] == 2 * d: count +=1 elif a[i + 1] - a[i] > 2 * d: count += 2 print(count + 2) ```
1028_A. Find Square
Consider a table of size n × m, initially fully white. Rows are numbered 1 through n from top to bottom, columns 1 through m from left to right. Some square inside the table with odd side length was painted black. Find the center of this square. Input The first line contains two integers n and m (1 ≤ n, m ≤ 115) — th...
```python import os import sys import math def main(): n,m = [int(i) for i in input().split()] centeri, centerj = -1,-1 starti, startj = -1,-1 for i in range(n): s = input() if not 'B' in s: continue if starti == -1: starti = i a = [int(pos) f...
1046_G. Space Isaac
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a num...
```python import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) a = list(map(int, input().split())) + [0]*500000 ans_S = 0 a[n] = a[0] + m s = [0]*600600 for i in range(n): s[i] = a[i + 1] - a[i] s[n] = -1 for i in range(n): s[2*n - i] = s[i]...
1070_F. Debate
Elections in Berland are coming. There are only two candidates — Alice and Bob. The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views: ...
```python arr = [[],[],[]] ans = 0 temp=0 for _ in range(int(input())): s,c = input().split() if s=='11': ans+=int(c) temp+=1 elif s=='00': arr[0].append(int(c)) elif s=='01': arr[1].append(int(c)) else: arr[2].append(int(c)) temp1 = min(len(arr[1]),len(arr[2]...
1092_B. Teams Forming
There are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i. The coach wants to form n/2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equa...
```python n1=int(input()) s1=list(map(int,input().split())) s1.sort() sa1=0 se2=0 for i in range(0,n1,2): sa1=sa1+s1[i] for i in range(1,n1,2): se2=se2+s1[i] print(se2-sa1) ```
1140_E. Palindrome-less Arrays
Let's denote that some array b is bad if it contains a subarray b_l, b_{l+1}, ..., b_{r} of odd length more than 1 (l < r and r - l + 1 is odd) such that ∀ i ∈ \{0, 1, ..., r - l\} b_{l + i} = b_{r - i}. If an array is not bad, it is good. Now you are given an array a_1, a_2, ..., a_n. Some elements are replaced by -...
```python class PalArray(): P = 998244353 def __init__(self, n, k, a): self.n, self.k, self.a = n, k, a self.dp = None def fast_pow(self, a, b): r = 1 while b > 0: if b%2 == 1: r = (r*a)%self.P a = (a*a)%self.P b = int(b/2)...
1159_C. The Party and Sweets
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i an...
```python n, m = list(map(int, input().split())) b = list(map(int, input().split())) g = list(map(int, input().split())) b.sort() g.sort() if b[-1] > g[0]: print(-1) elif b[-1] == g[0]: print(sum(g) + m * (sum(b) - b[-1])) elif n == 1: print(-1) else : print(sum(g) + b[-1] + b[-2] * (m - 1) + m * (sum(b...
1181_C. Flag
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in n ⋅ m colored pieces that form a rectangle with n rows and m columns. The colored pieces attracted Innokenty's attention so he immediately came up with the ...
```python import os from io import BytesIO, StringIO #input = BytesIO(os.read(0, os.fstat(0).st_size)).readline DEBUG = True debug_print = print if DEBUG else lambda *x,**y: None def input_as_list(): return list(map(int, input().split())) def array_of(f, *dim): return [array_of(f, *dim[1:]) for _ in range(di...
119_B. Before Exam
Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be... To prepare for the exam, one has to study proofs of n theorems...
```python n,k = map(int, input().split()) a = list(map(int, input().split())) ansMin, ansMax = 10**10, -10**10 were = [0]*n sz = n//k for i in range(int(input())): cur = 0.0 t = map(int, input().split()) for x in t: were[x-1]=1 cur+=a[x-1] cur/=sz ansMin = min(ansMin, cur) ansM...
1216_F. Wi-Fi
You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms a...
```python mod=10**9+7 from sys import stdin, stdout import bisect from bisect import bisect_left as bl #c++ lowerbound bl(array,element) from bisect import bisect_right as br #c++ upperbound import itertools import collections import math import heapq from random import randint as rn def modinv...
123_B. Squares
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is cons...
```python a, b, x_1, y_1, x_2, y_2 = map(int, input().split()) a_b, a_e = (x_2 + y_2), (x_1 + y_1) b_b, b_e = (x_2 - y_2), (x_1 - y_1) if a_b > a_e: a_b, a_e = a_e, a_b if b_b > b_e: b_b, b_e = b_e, b_b if a_b % (2 * a) != 0: a_b = (a_b // (2 * a) + 1) * (2 * a) a_result, b_result = 0, 0 if a_b <= a...
125_C. Hobbits' Party
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensu...
```python n = int(input()) d = int(0.5 + (1 + 8*n)**0.5 / 2) curr = 1 res = [[] for _ in range(d)] for i in range(d): j = i + 1 while len(res[i]) < d - 1: res[i].append(str(curr)) res[j].append(str(curr)) curr += 1 j += 1 print(d) for l in res: print(' '.join(l)) ```
1281_E. Jeremy Bearimy
Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign ea...
```python import sys def input(): return sys.stdin.readline().strip() def solve(): k = int(input()) n = 2*k e = [[] for i in range(n)] p = [None]*(n) for i in range(n-1): a, b, t = map(int, input().split()) a -= 1 b -= 1 e[a].append((b,t)) e[b].append((a,t)) q = [0] qi = 0 while qi < len(q): x = ...
1301_E. Nanosoft
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored w...
```python def main(): import sys input = sys.stdin.buffer.readline # max def STfunc(a, b): if a > b: return a else: return b # クエリは0-indexedで[(r1, c1), (r2, c2)) class SparseTable(): def __init__(self, grid): # A: 処理したい2D配列 ...
1325_E. Ehab's REAL Number Theory Problem
You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion o...
```python from collections import deque import sys input=sys.stdin.readline def make_mf(): res=[-1]*(mxa+5) ptoi=[0]*(mxa+5) pn=1 for i in range(2,mxa+5): if res[i]==-1: res[i]=i ptoi[i]=pn pn+=1 for j in range(i**2,mxa+5,i): if re...
1344_D. Résumé Review
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you ha...
```python import os import sys #sys.setrecursionlimit(int(2e5)) from collections import deque import math readline = sys.stdin.readline ##################################################################################### class CF(object): def __init__(self): self.eps = 1e-7 self.n, self.k = list(...
1366_D. Two Divisors
You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the size of the ar...
```python import sys from collections import deque, Counter from itertools import product from functools import reduce input = sys.stdin.buffer.readline n = int(input()) ls = list(map(int, input().split())) mx = max(ls) pr = [i for i in range(mx+1)] for u in range(2, mx+1): if u*u > mx: break if pr[u] == u: ...
1387_A. Graph
You are given an undirected graph where each edge has one of two colors: black or red. Your task is to assign a real number to each node so that: * for each black edge the sum of values at its endpoints is 1; * for each red edge the sum of values at its endpoints is 2; * the sum of the absolute values of all...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self....
1408_D. Searchlights
There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should ...
```python n, m = map(int, input().split()) robbers = [] lights = [] for i in range(n): a, b = map(int, input().split()) robbers.append((a, b)) for i in range(m): c, d = map(int, input().split()) lights.append((c, d)) C = [0] * 1000002 for a, b in robbers: for c, d in lights: if a <= c: ...
1452_B. Toy Blocks
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in ...
```python from __future__ import division, print_function import bisect import math import heapq import itertools import sys from collections import deque from atexit import register from collections import Counter from functools import reduce if sys.version_info[0] < 3: from io import BytesIO as stream else: f...
1475_G. Strange Beauty
Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i ≠ j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For exam...
```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 ...
1526_A. Mean Inequality
You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i ≠ \frac{b_{i-1}+b_{i+1}}...
```python for x in range(int(input())): n = int(input()) m=list(map(int,input().split())) m.sort(reverse=True) a=[0]*2*n for i in range(n): a[2*i]=m[i] for i in range(n): a[2*i+1]=m[n+i] print(*a) ```
157_D. Suspects
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answe...
```python """ Brandt Smith, Lemuel Gorion and Peter Haddad codeforces.com Problem 156B """ import sys n, m = map(int, input().split(' ')) inp = [] guess = [0] * (n + 1) for i in range(n): temp = int(input()) inp.append(temp) if temp < 0: m -= 1 guess[-temp] -= 1 else: guess...
224_A. Parallelepiped
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers — the areas of the parallelepi...
```python a,b,c=map(int,input().split()) print(int(4*pow(a*c/b,0.5)+4*pow(a*b/c,0.5)+4*pow(b*c/a,0.5))) ```
248_D. Sweets for Everyone!
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her paren...
```python def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 i...
296_B. Yaroslav and Two Strings
Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≤ i, j ≤ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string...
```python #!/usr/bin/python3 def build(n, s, t): ans = 1 for i in range(n): if s[i] == '?' and t[i] == '?': ans = (55 * ans) % (10 ** 9 + 7) elif s[i] == '?': ans = ((ord(t[i]) - ord('0') + 1) * ans) % (10 ** 9 + 7) elif t[i] == '?': ans = ((ord('9') ...
319_E. Ping-Pong
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ...
```python def dfs(G, start, path_exists): s = [start] visited = set([]) if not start in path_exists: path_exists[start] = set([]) while(s): node = s.pop() if not node in visited: visited.add(node) path_exists[start].add(node) a, b = G[node] ...
367_B. Sereja ans Anagrams
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained...
```python from sys import stdin, stdout from math import log, sqrt lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = [int(x) for x in lines[2].split()] def hash_elem(x): x = (x * 1662634645 + 32544235) & 0xf...
40_E. Number Table
As it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n — the number of days in each Berland month, m — the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, wh...
```python import itertools import math n, m = [int(x) for x in input().split()] if n%2 != m%2: print(0) else: k = int(input()) S = [[] for i in range(max(n,m))] for i in range(k): a, b, c = [int(x) for x in input().split()] if n<m: S[b-1].append(c==-1) else: ...
460_A. Vasya and Socks
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve...
```python n, m = map(int, input().split() ) r = 0 t = 1 while n: n -= 1 if t % m == 0: n += 1 t += 1 print(t-1) ```
507_E. Breaking Good
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of...
```python from collections import deque def bfs(n, v, s, t): dis = [n] * n load = [n] * n path = [None] * n q = deque([s]) dis[s] = 0 load[s] = 0 while (q): node = q.popleft() for i in range(len(v[node])): nb = v[node][i][0] status = v[node][i][1] ...
557_A. Ilya and Diplomas
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one...
```python ttl = int(input()) mx1 = [int(i) for i in list(input().split(" "))] mx2 = [int(i) for i in list(input().split(" "))] mx3 = [int(i) for i in list(input().split(" "))] min1 = mx1[0] min2 = mx2[0] min3 = mx3[0] max1 = mx1[1]-min1 max2 = mx2[1]-min2 max3 = mx3[1]-min3 ttl -=(mx1[0]+mx2[0]+mx3[0]) while(ttl>0): ...
604_D. Moodular Arithmetic
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where...
```python MOD = 10**9+7 def f(a,b): if b == 1: return a%MOD elif b % 2 == 0: return f((a*a)%MOD,b//2) else: return (a*f((a*a)%MOD,b//2)) % MOD p,k = map(int,input().split()) if k == 0: print(f(p,p-1)) exit() if k == 1: print(f(p,p)) exit() t = 1 a = k while a != ...
676_C. Vasya and String
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. W...
```python ######### ## ## ## #### ##### ## # ## # ## # # # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # # # # # ##### # # # # ### # # # # # # # # ##### # # # # # # # # # # # # # # # # # # ...
69_C. Game
In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle...
```python # Not really fair, since I already solved this one previously. ;) k, n, m, q = [int(i) for i in input().split()] basic = [input() for i in range(n)] composite = {} for i in range(m): name, items = input().split(":") composite[name] = {} for item in items.split(","): component, cnt = item.split() comp...
742_C. Arpa's loud Owf and Mehrdad's evil plan
As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are a...
```python from math import gcd def DFS(v): re = 0 cur = v while not used[cur]: used[cur] = True re += 1 cur = gr[cur] if re % 2 == 0: re //= 2 return 0 if cur != v else re n = int(input()) used = [False] * (n + 1) gr = [0] + list(map(int, input().split())) res = 1 f...
810_A. Straight «A»
Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one. In school, where Noora is studying, teachers are putting down marks to the online class register, wh...
```python n,k=tuple(int(i) for i in input().strip().split(" ")) a=input().strip().split(" ") sum=0 o=0 for i in a: sum+=int(i) if sum/n>=k-0.5: print(0) exit(0) while sum/n<k-0.5: sum+=k n+=1 o+=1 print(o) ```
835_D. Palindromic characteristics
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes. A string is 1-palindrome if and only if it reads the same backward as forward. A string is k-palindrome (k > 1) if and only if: 1. Its ...
```python def main(): s = input() n = len(s) isPalindrome = [[False for i in range(n + 1)] for i in range(n + 1)] for i in range(n): isPalindrome[i][i] = True for i in range(n - 1, -1, -1): for j in range(i + 1, n): if (s[i] == s[j] and (i + 1 == j or isPalindrome[i + 1][...
926_B. Add Points
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct. Determine the number m — the smallest number of points you should add on the line to make the distances between all neighboring points equal. Input The first line contains a single integer n (3...
```python import math n = int(input()) a = list(map(int, input().split())) a.sort() g = 0 for i in range(n - 1): g = math.gcd(g, a[i + 1] - a[i]) print((a[-1] - a[0]) // g - n + 1) ```
981_B. Businessmen Problems
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the ...
```python drugs_a = {} drugs_b = {} for _ in range(int(input())): n,p = map(int,input().split()) drugs_a[n] = p for _ in range(int(input())): n,p = map(int,input().split()) drugs_b[n] = p try: if drugs_b[n] > drugs_a[n]: del drugs_a[n] else: del drugs_b[n...
p02551 AtCoder Beginner Contest 179 - Simplified Reversi
There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left. Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it. Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it. Q...
```python class SegTree(): def __init__(self, initial, operation, identity): n = len(initial) self.initial = initial self.operation = operation self.identity = identity self.num = 1 << (len(bin(n - 1)) - 2) self.tree = [identity] * (2 * self.num - 1) for i in ...
p02682 AtCoder Beginner Contest 167 - Easy Linear Programming
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s. We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen? Constraints * All values in input are integers. * 0 \leq A, B, C * 1 \leq K \l...
```python A, B, C, K = map(int, input().split()) hoge = max(K - A - B, 0) print(min(A, K) - hoge) ```
p02810 Dwango Programming Contest 6th - Span Covering
Niwango bought a piece of land that can be represented as a half-open interval [0, X). Niwango will lay out N vinyl sheets on this land. The sheets are numbered 1,2, \ldots, N, and they are distinguishable. For Sheet i, he can choose an integer j such that 0 \leq j \leq X - L_i and cover [j, j + L_i) with this sheet. ...
```python N,X=map(int,input().split()) L=sorted(map(int,input().split()),reverse=True) mod=10**9+7 D=[[0]*(X+1) for i in range(N//2+2)] D[1][L[0]]=1 for l in L[1:]: ND=[[0]*(X+1) for i in range(N//2+1)] for c in range(1,N//2+1): for s in range(X+1): if D[c][s]==0: continue...
p02947 AtCoder Beginner Contest 137 - Green Bin
We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a. For example, `greenbin` is an anagram of `beginner`. As seen here, when the same character occurs multiple times, that character must be used that number of times. Given are N strings s_1, s_2, \ldots, s...
```python N = int(input()) from collections import Counter S = [''.join(sorted(input())) for _ in range(N)] ans = 0 for i in Counter(S).values(): ans += i*(i-1)//2 print(ans) ```
p03083 ExaWizards 2019 - Black or White
Today, Snuke will eat B pieces of black chocolate and W pieces of white chocolate for an afternoon snack. He will repeat the following procedure until there is no piece left: * Choose black or white with equal probability, and eat a piece of that color if it exists. For each integer i from 1 to B+W (inclusive), fi...
```python MOD = 10**9+7 MAX = 2*(10**5)+1 fac = [1 for i in range(MAX)] finv = [1 for i in range(MAX)] inv = [1 for i in range(MAX)] b,w = map(int,input().split()) if (b >= w): flag = 0 else: flag = 1 b,w = w,b for i in range(2,MAX): fac[i] = fac[i-1]*i%MOD inv[i] = MOD - inv[MOD%i]*(MOD // i)%MOD ...
p03228 Tenka1 Programmer Beginner Contest - Exchange
In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other pers...
```python A, B, K = map(int,input().split()) for i in range(K): if i % 2 == 0: A -= (A % 2 == 1) A, B = A//2, B+A//2 else: B -= (B % 2 == 1) A, B = A + B//2, B//2 print(A, B) ```
p03376 AtCoder Regular Contest 096 - Sweet Alchemy
Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams o...
```python N, X, D = map(int, input().split()) M = [0]*N M[0] = int(input()) P = [0]*N for i in range(N-1): M[i+1], P[i+1] = map(int, input().split()) C = [1]*N for i in range(N-1, 0, -1): p = P[i]-1 C[p] += C[i] M[p] += M[i] L = [D]*N L[0] = X from collections import deque def solve(N, W, ws, vs, ms)...
p03543 AtCoder Beginner Contest 079 - Good Integer
We call a 4-digit integer with three or more consecutive same digits, such as 1118, good. You are given a 4-digit integer N. Answer the question: Is N good? Constraints * 1000 ≤ N ≤ 9999 * N is an integer. Input Input is given from Standard Input in the following format: N Output If N is good, print `Yes`; ot...
```python n = int(input()) n1 = n//10 n2 = n%1000 print('No' if n1%111 and n2%111 else 'Yes') ```
p03697 AtCoder Beginner Contest 063 - Restricted
You are given two integers A and B as the input. Output the value of A + B. However, if A + B is 10 or greater, output `error` instead. Constraints * A and B are integers. * 1 ≤ A, B ≤ 9 Input Input is given from Standard Input in the following format: A B Output If A + B is 10 or greater, print the string `e...
```python a,s=map(int,input().split()) if a+s>=10: print("error") else: print(a+s) ```
p03852 AtCoder Beginner Contest 049 - UOIAUAI
Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: `a`, `e`, `i`, `o` and `u`. Constraints * c is a lowercase English letter. Input The input is given from Standard Input in the following format: c Output If c is a vowel, print `vowel`. Oth...
```python print(["consonant","vowel"][input() in "aiueo"]) ```
p04019 AtCoder Grand Contest 003 - Wanna go back home
Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction: * North if the i-th letter of S is `N` * West if the i-th letter...
```python s=set(input());print("YNeos"[1 in[(len(s&set(t)))for t in["NS","WE"]]::2]) ```
p00103 Baseball Simulation
Ichiro likes baseball and has decided to write a program which simulates baseball. The program reads events in an inning and prints score in that inning. There are only three events as follows: Single hit * put a runner on the first base. * the runner in the first base advances to the second base and the runner in t...
```python n = int(input()) for i in range(n): out_cnt = 0 score = 0 runner = [0,0,0,0] while True: event = input() if event=="OUT": out_cnt += 1 if out_cnt == 3: break elif event=="HIT": if 1 in runner: for ind...
p00613 A Piece of Cake
In the city, there are two pastry shops. One shop was very popular because its cakes are pretty tasty. However, there was a man who is displeased at the shop. He was an owner of another shop. Although cause of his shop's unpopularity is incredibly awful taste of its cakes, he never improved it. He was just growing hate...
```python while True: K = int(input()) if K == 0: break c = [int(i) for i in input().split()] S = 0 for i in range(len(c)): S = S + c[i] print(int(S/(K-1))) ```
p00889 Find the Multiples
You are given a sequence a0a1...aN-1 digits and a prime number Q. For each i ≤ j with ai ≠ 0, the subsequence aiai+1...aj can be read as a decimal representation of a positive integer. Subsequences with leading zeros are not considered. Your task is to count the number of pairs (i, j) such that the corresponding subseq...
```python from collections import defaultdict def gen(N, S, W): g = S for i in range(N): yield (g//7) % 10 if g % 2 == 0: g //= 2 else: g = (g//2) ^ W def solve(): N, S, W, Q = map(int, input().split()) if N == 0: return False bs = list(gen(N...
p01461 Multi Ending Story
You are a programmer who loves bishojo games (a sub-genre of dating simulation games). A game, which is titled "I * C * P * C!" and was released yesterday, has arrived to you just now. This game has multiple endings. When you complete all of those endings, you can get a special figure of the main heroine, Sakuya. So, y...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) A = [0]*N B = [0]*N for i in range(N-1): a, b = map(int, readline().split()) if not a <= b: a, b = b, a A[i] = a-1 B[i] =...
p01620 King's Inspection
A great king of a certain country suddenly decided to visit the land of a friendly country. The country is famous for trains, and the king visits various stations. There are 52 train stations, each with a single uppercase or lowercase alphabetic name (no overlapping names). The line of this train is circular, with sta...
```python def horizontal_input(T=str): return list(map(T,input().split())) def vertical_input(n,T=str,sep=False,septype=tuple): data=[] if sep: for i in range(n): data.append(septype(map(T,input().split()))) else: for i in range(n): data.append(T(input())) re...
p01907 Fractal Tree
problem AOR Ika likes rooted trees with a fractal (self-similar) structure. Consider using the weighted rooted tree $ T $ consisting of $ N $ vertices to represent the rooted tree $ T'$ with the following fractal structure. * $ T'$ is the addition of a tree rooted at $ x $ and having a tree structure similar to $ T $...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def LF(): return list(map(float, input().split())) def LS(): return input().split() def I(): return int(input())...
p02330 Coin Combination Problem II
You have N coins each of which has a value ai. Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R. Constraints * 1 ≤ K ≤ N ≤ 40 * 1 ≤ ai ≤ 1016 * 1 ≤ L ≤ R ≤ 1016 * All input values are...
```python from bisect import bisect_left, bisect_right from itertools import combinations if __name__ == "__main__": N, K, L, R = map(lambda x: int(x), input().split()) coins = list(map(lambda x: int(x), input().split())) N_half = N // 2 c1 = [list(map(sum, combinations(coins[:N_half], i))) for i in ...
p02475 Division of Big Integers
Division of Big Integers Given two integers $A$ and $B$, compute the quotient, $\frac{A}{B}$. Round down to the nearest decimal. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the quotient in a line. Constraints * $-1 \times 10^{1000} \leq A, B \leq 10^{1000}$ * $...
```python a,b = map(int,input().split()) if(a*b<0): print(abs(a)//abs(b)*-1) else: print(abs(a)//abs(b)) ```
1040_B. Shashlik Cooking
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over. This time Miroslav laid out n skewers parallel to each other, and enumerated them with consecutive integers from 1 to n in order from left to ri...
```python n,k=map(int,input().split()) if n%(2*k+1)==0: print(n//(2*k+1)) for i in range(k+1,n+1,2*k+1): print(i,end=" ") else: if n%(2*k+1)>=k+1: print(n//(2*k+1)+1) for i in range(k+1,n+1,2*k+1): print(i,end=" ") else: print(n//(2*k+1)+1) for i in ra...
1063_B. Labyrinth
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not o...
```python from collections import deque def move(tx, ty, s, left=False): if 0 <= tx < n and 0 <= ty < m: if smap[tx][ty] == '.' and mp[tx][ty] == -1: mp[tx][ty] = s if left: q.appendleft((tx, ty)) else: q.append((tx, ty)) [n, m] = map(int...
1085_A. Right-Left Cipher
Polycarp loves ciphers. He has invented his own cipher called Right-Left. Right-Left cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{n} Polycarp uses the following algorithm: * he writes down s_1, * he appends the current word with s_2 (i.e. writes down s_2 to the right of the current resul...
```python s=str(input()) if len(s)<=2: print(s) else: first=(len(s)-1)//2 s1=(s[first-1::-1]) s2=list(s[first:]) #print(s1,s2) k=2 for i in range(len(s1)): s2.insert(k,s1[i]) k+=2 print(''.join(s2)) ```
1104_D. Game with modulo
This is an interactive problem. Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: * "x", if (x mod a) ≥ (y mod a). ...
```python import sys while True: S = input() if S=='end': sys.exit() if S=='mistake': sys.exit() if S=='start': while True: i=0 print('?',0,1) sys.stdout.flush() T=input() if T=='x': print('!',1) ...
1132_B. Discounts
You came to a local shop and want to buy some chocolate bars. There are n bars in the shop, i-th of them costs a_i coins (and you want to buy all of them). You have m different coupons that allow you to buy chocolate bars. i-th coupon allows you to buy q_i chocolate bars while you have to pay only for the q_i - 1 most...
```python n = int(input()) ar = sorted(list(map(int, input().split()))) r = sum(ar) m = int(input()) br = list(map(int, input().split())) for i in br: print(r - ar[-i]) ```
1152_E. Neko and Flashback
A permutation of length k is a sequence of k integers from 1 to k containing each integer exactly once. For example, the sequence [3, 1, 2] is a permutation of length 3. When Neko was five, he thought of an array a of n positive integers and a permutation p of length n - 1. Then, he performed the following: * Const...
```python from collections import defaultdict, Counter from sys import exit N = int(input()) B = list(map(int, input().split())) C = list(map(int, input().split())) Edge = defaultdict(list) Edc = defaultdict(int) for b, c in zip(B, C): if b > c: print(-1) exit() Edge[b].append(c) Edc[(b, c)]...
1174_C. Ehab and a Special Coloring Problem
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: * For any pair of integers (i,j), if i and j are coprime, a_i ≠ a_j. * The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is call...
```python def main(): buf = input() n = int(buf) prime_map = dict() a = [] for i in range(2, n+1): first_prime = first_prime_factor(i) if first_prime not in prime_map: prime_map[first_prime] = len(prime_map)+1 a.append(prime_map[first_prime]) print(' '.join(l...
1210_A. Anadi and Domino
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set: <image> Also, Anadi ha...
```python def gns(): return list(map(int, input().split())) def ps(st, c, ans): if len(st) == 0: ans.append(tuple(c)) nxt = set(st) for ci in st: c.append(ci) nxt.remove(ci) ps(nxt, c, ans) c.pop() nxt.add(ci) st = set(range(6)) c = [] mine = [] ps(st,...
1230_E. Kamil and Making a Stream
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him? You're given a tree — a connected undirected graph consisting of n vertices conne...
```python from math import gcd from collections import deque from bisect import bisect_left from sys import setrecursionlimit MOD = 1000000007 def main(): n = int(input()) setrecursionlimit(n+100) xx = [0] + [int(x) for x in input().split()] edges = [] neighbors = [[] for _ in range(n+1)] for...
1272_A. Three Friends
Three friends are going to meet each other. Initially, the first friend stays at the position x = a, the second friend stays at the position x = b and the third friend stays at the position x = c on the coordinate axis Ox. In one minute each friend independently from other friends can change the position x by 1 to the...
```python for _ in range(int(input())): a,b,c=[int(x) for x in input().split()] m=max(a,b,c)-min(a,b,c) if m>1:print((m-2)*2) else:print('0') ```
1295_B. Infinite Prefixes
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss ... For example, if s = 10010, then t = 100101001010010... Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal...
```python import math tt=int(input()) for i in range(tt): n,x=map(int,input().split()) s=input() a=1 b={} def bind(x): return -((2*x)-1) if x<0: a=-1 x=-x sbal=0 for i in s: sbal+=(bind(int(i))*a) b[sbal]=b.get(sbal,0)+1 ans=0 if sbal==0: ...
1316_B. String Modification
Vasya has a string s of length n. He decides to make the following modification to the string: 1. Pick an integer k, (1 ≤ k ≤ n). 2. For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through: * qwe...
```python from sys import stdin, stdout input = stdin.readline for _ in " " * int(input()): n = int(input()) s = list(input())[:-1] ans = list(s) ind = 0 for k in range(n): if (n - k) % 2: st = s[k:] + s[:k][::-1] else: st = s[k:] + s[:k] if st < ans: ...
1337_D. Xenia and Colorful Gems
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, ...
```python import bisect def nearest_with_leader(reds, greens, blues): minimum = 10**19*3 for g in greens: bi = bisect.bisect_left(blues, g) ri = bisect.bisect_right(reds, g) if ri == 0 or bi == len(blues): continue b = blues[bi] r = reds[ri-1] minimum...
135_B. Rectangle and Square
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the ...
```python from math import * def a(x1,y1,x2,y2,x3,y3,x4,y4): b=sorted([[x1,y1],[x2,y2],[x3,y3],[x4,y4]]) x1,y1=b[0] x2,y2=b[1] x3,y3=b[2] x4,y4=b[3] a1=sqrt((x1-x2)**2+(y1-y2)**2) a2=sqrt((x4-x2)**2+(y4-y2)**2) a3=sqrt((x4-x3)**2+(y4-y3)**2) a4=sqrt((x1-x3)**2+(y1-y3)**2) return ...
137_C. History
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the Wo...
```python import sys import math n=int(input()) k=[] for i in range(n): a,b=map(int,input().split()) k.append((a,b)) k.sort() t,con=0,0 for (a,b) in k: if(b<t): con+=1 else: t=b print(con) ```
13_C. Sequence
Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of ste...
```python from bisect import insort def min_steps_N(arr): pri_q = [] ans = 0 for n in arr: if pri_q: if pri_q[-1] > n: ans += pri_q[-1] - n pri_q.pop() insort(pri_q, n) insort(pri_q, n) return ans if __name__ == '__main__': ...
1443_E. Long Permutation
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] — are permutations, and [1, 1], [4, 3, 1], [2, 3, 4] — no. Permutation a is lexicographically smaller than permutation b (they have the same length n), if in the first index...
```python from math import factorial def short_perm_to_num(perm, n): # O(n**2), but n <= 70 result = 0 is_used = {} for i in range(n): for j in range(perm[i]): if not (j in is_used): result += factorial(n-1-i) is_used[perm[i]] = True return result def perm_t...
1468_N. Waste Sorting
The progress is not standing still in Berland. Recently all garbage containers in Bertown, the capital of Berland, were replaced by differentiated recycling bins, each accepting some category of waste. While this will definitely improve the ecological situation, for some citizens it's difficult to get used to the habit...
```python def check(c1, c2, c3, v13, v23): if c1 < 0 or c2 < 0 or c3 < 0: return False v13 -= min(v13, c1) v23 -= min(v23, c2) return v13 + v23 <= c3 for i in range(int(input())): c1, c2, c3 = map(int, input().split()) a1, a2, a3, a4, a5 = map(int, input().split()) c1 -= a1 c2 -...
1494_B. Berland Crossword
Berland crossword is a puzzle that is solved on a square grid with n rows and n columns. Initially all the cells are white. To solve the puzzle one has to color some cells on the border of the grid black in such a way that: * exactly U cells in the top row are black; * exactly R cells in the rightmost column ar...
```python def solve(): n, u, r, d, l = map(int, input().split()) for i in range(16): ur = i & 1 dr = bool(i & 1<<1) dl = bool(i & 1<<2) ul = bool(i & 1<<3) uu=u rr=r dd=d ll=l uu -= ur + ul rr -= ur + dr dd -= dr + dl ...
1517_A. Sum of 2050
A number is called 2050-number if it is 2050, 20500, ..., (2050 ⋅ 10^k for integer k ≥ 0). Given a number n, you are asked to represent n as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that. Input The first line contains a single integer T (1≤ T≤ 1...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase #from bisect import bisect_left as bl #c++ lowerbound bl(array,element) #from bisect import bisect_right as br #c++ upperbound br(array,element) def main(): # sys.stdin = open('input.txt', 'r') #...
1543_E. The Final Pursuit
Finally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune an...
```python from collections import deque from sys import stdin import sys tt = int(stdin.readline()) for loop in range(tt): n = int(stdin.readline()) lis = [ [] for i in range(2**n)] for i in range(n*(2**(n-1))): u,v = map(int,stdin.readline().split()) lis[u].append(v) lis[v].ap...
171_G. Mysterious numbers - 2
Input The only line of input contains three integers a1, a2, a3 (1 ≤ a1, a2, a3 ≤ 20), separated by spaces. Output Output a single integer. Examples Input 2 3 2 Output 5 Input 13 14 1 Output 14 Input 14 5 9 Output 464 Input 17 18 3 Output 53
```python f = [0] * 22 f[0], f[1], idx = [int(x) for x in input().split()] for i in range (2, 22) : f[i] = f[i - 1] + f[i - 2] print(f[idx]) ```
215_E. Periodical Numbers
A non-empty string s is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string s from 1 to the string's length and let's denote the i-th character in string s as si. Binary string s with length n is periodical, if there is an integer 1 ≤ k < n such that: * k is a...
```python from itertools import combinations from fractions import gcd #Numeros primos hasta el 59 primos = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59] #Para obtener la cadena binaria de x. def ToBinary(x): if x == 0: return "0" if x == 1: return "1" if x % 2 == 0: return ToBi...
288_C. Polo the Penguin and XOR operation
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive. For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number <image>. Expression <image> means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in al...
```python from bisect import insort,bisect_right,bisect_left from sys import stdout, stdin, setrecursionlimit from math import sqrt,ceil,floor,factorial,gcd,log2,log10 from io import BytesIO, IOBase from collections import * from itertools import * from random import * from string import * from queue import * from hea...