name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p01459 Light Road
There is an evil creature in a square on N-by-M grid (2 \leq N, M \leq 100), and you want to kill it using a laser generator located in a different square. Since the location and direction of the laser generator are fixed, you may need to use several mirrors to reflect laser beams. There are some obstacles on the grid ...
```python from collections import deque N, M, A = map(int, input().split()) MP = [[0]*M for i in range(N)] sx = sy = gx = gy = -1 for i in range(N): for j, c in enumerate(input()): if c == '#': MP[i][j] = 1 elif c == 'S': sx = j; sy = i elif c == 'G': gx =...
p01905 Tournament
problem AOR Ika and you came to the tournament-style table tennis tournament singles section for reconnaissance. For AOR Ika-chan, who wants to record all the games, you decide to ask for the number of games that will be played in this tournament. There are $ N $ players in the tournament, each with a uniform number ...
```python N,M = map(int, input().split()) l = [] for i in range(M): l.append(int(input())) count = N - 1 - M print(count) ```
p02328 Largest Rectangle in a Histogram
A histogram is made of a number of contiguous bars, which have same width. For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area. Constraints * $1 \leq N \leq 10^5$ * $0 \leq h_i \leq 10^9$ Input The inp...
```python """ Writer:SPD_9X2 http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C&lang=ja ヒストグラム上の最大長方形 またdpかな…? 参考: http://algorithms.blog55.fc2.com/blog-entry-132.html """ #最後に要素0を追加してくこと def Largest_rectangle_in_histgram(lis): stk = [] ans = 0 N = len(lis) for i in range(N): ...
p02473 Difference of Big Integers
Difference of Big Integers Given two integers $A$ and $B$, compute the difference, $A - B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the difference in a line. Constraints * $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample O...
```python A, B = map(int, input().split()) print(A - B) ```
1016_A. Death Note
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course yo...
```python (n,m) = tuple(map(int, input().split(" "))) x = list(map(int, input().split(" "))) nib = 0 ans = [] cou = 0; for i in x: nib+=i if (nib<m): ans.append(nib//m) else: ans.append(nib//m) nib-=(nib//m)*m print (*ans) ```
103_A. Testing Pants for Sadness
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to ...
```python import sys,math s = int(input()) arr = list(map(int,input().split(' '))) m = 0 for i in range(0,s): m+=(arr[i]-1)*(i+1)+1 print(m) ''' 2 2 2 1+1 2 1+1+1 3 (1+1+1,1) 4 3 3 1+1+1 3 1+1+1+1+1 5 1+1+1,1+1+1,1 7 3 2 4 1 1+1 1+1+1+1+1+1+1 1 1+1+1+1 ''' ```
1062_B. Math
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times: * mul x: multiplies n by x (where x is an arbitrary positive integer). * sqrt: replaces n with √...
```python import math def sieve(n): mark = [0]*(n+1) prime = [] for i in range(3, n+1, 2): if not mark[i]: for j in range(3*i, n+1, i+i): mark[j] = 1 prime.append(2) for i in range(3, n+1, 2): if not mark[i]: prime.append(i) return prime...
1084_A. The Fair Nut and Elevator
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided ...
```python n = int(input()) arr = list(map(int, input().split())) cur = 0 ans = 100000000 for x in range(n): cur = 0 for i in range(n): summ = 0 summ += abs(x - i) summ += i summ += x summ += x summ += i summ += abs(x - i) summ *= arr[i] cu...
1131_C. Birthday
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing n...
```python n = int(input()) arr = [int(i) for i in input().split()] arr1, arr2 = [], [] arr.sort(reverse = True) for i in range(n): if i%2==0: arr1.append(arr[i]) else: arr2.append(arr[i]) arr2.reverse() for i in arr2: arr1.append(i) print(*arr1) ```
1151_E. Number of Components
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two in...
```python n = int(input()) + 1 res = 0 a = tuple(map(int, input().split())) for ai in a: res += ai * (n - ai) for ai, aj in map(sorted, zip(a, a[1:])): res -= ai * (n - aj) print(res) # ```
1173_D. Nauuo and Circle
Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points o...
```python import sys n = int(sys.stdin.readline().strip()) D = [0] * n p = 998244353 for i in range (0, n - 1): u, v = list(map(int, sys.stdin.readline().strip().split())) D[u-1] = D[u-1] + 1 D[v-1] = D[v-1] + 1 ans = n for i in range (0, n): for j in range (0, D[i]): ans = (ans * (j + 1)) % p...
1191_A. Tokitsukaze and Enhancement
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is ...
```python n=int(input()) d={} d[0]='1 A' d[1]='0 A' d[2]='1 B' d[3]='2 A' x=n%4 print(d[x]) ```
122_D. Lucky Transformation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of d...
```python n, k = map(int, input().split()) s = list(input()) cnt = 0 for i in range(n - 1): if cnt == k: break if s[i] == '4' and s[i + 1] == '7': if i & 1: if s[i - 1] == '4': if (cnt - k) & 1: s[i] = '7' print(''.join(s)) ...
1251_C. Minimize The Integer
You are given a huge integer a consisting of n digits (n is between 1 and 3 ⋅ 10^5, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032...
```python # -*- coding: utf-8 -*- """ Created on Fri Nov 1 14:39:37 2019 @author: uditg """ ans={} test=int(input()) for each in range(test): num=input() n=len(num) num={i:int(num[i]) for i in range(n)} output={} even={} odd={} even_count=0 odd_count=0 for i in range(n): if...
1271_A. Suits
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets. The store does not sell single clothing items — instead, it sells suits of two types: * a suit of the first type consists of one tie and one jacket; * a suit of the second type ...
```python a = int(input()) b = int(input()) c = int(input()) d = int(input()) c1 = int(input()) c2 = int(input()) p = 0 if c2 > c1: m = min(b,c,d) b -= m c -= m d -= m p += m * c2 if d > 0: p += (min(a,d) * c1) else: m = min(a,d) a -= m d -= m p += m * c1 if d > 0: p +=...
1294_B. Collecting Packages
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
```python t=int(input()) for q in range(t): n=int(input()) a=[list(map(int,input().split())) for i in range(n)] a.sort() ans="" x,y=0,0 f=0 for i in range(n): if a[i][0]>=x and a[i][1]>=y: ans+='R'*(a[i][0]-x) x=a[i][0] ans+='U'*(a[i][1]-y) y=a[i][1] else: f=1 print('NO') break if f==0:...
1315_B. Homecoming
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string s of length n, where s_i = A, if there is...
```python t = int(input()) for _ in range(t): a, b, p = map(int, input().split()) s = input() d = {'A': a, 'B': b} i = len(s)-1 prev = len(s)-1 while i >= 0: i -= 1 curr = s[i] while s[i] == curr and i >= 0: i -= 1 i += 1 p -= d[curr] ...
1336_E1. Chiori and Doll Picking (easy version)
This is the easy version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved. Chiori loves dolls and now she is going to decorate her bedroom! <image> As a doll collector, Chiori has got n dolls. The i-th doll has a non-negati...
```python import sys MOD = 998244353 BOUND = 21 n, m = map(int, input().split()) l = list(map(int,input().split())) basis = [] for p in range(m-1,-1,-1): p2 = pow(2,p) nex = -1 for i in range(n): if l[i] >= p2: nex = l[i] break if nex != -1: basis.append(nex) ...
1359_B. New Theatre Square
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav...
```python cases=input() for i in range(0,int(cases)): inss=input() list=inss.split(' ') n=int(list[0]) m=int(list[1]) x=int(list[2]) y=int(list[3]) price=0 if 2*x > y: lame=True else: lame=False for count in range(0,n): data=input() ###print(data...
1379_D. New Passenger Trams
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of h hours, and each hour consists of m minutes, where m is an even number. Currently, there are n freight trains, and they depart every day at the same time: i-th train departs at h_i hours and m_i minutes. The gover...
```python from collections import defaultdict import sys input=sys.stdin.readline n,h,m,k=map(int,input().split()) l=[] a=[] start=0 for i in range(n): H,M=map(int,input().split()) M=M%(m//2) a.append(M) l.append((M+1,1,i)) l.append(((M+k)%(m//2),-1,i)) if (M+1)>(M+k)%(m//2): start+=1 l....
139_B. Wallpaper
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris cho...
```python #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = By...
1423_F. Coins
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them: All of them take a sit at their round table, some of them with the golde...
```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.bu...
1468_G. Hobbits
The hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains. The mountain relief can be represented as a polyline with n points (x_i, y_i), numbered from 1 to n (x_i < x_{i + 1} for 1 ≤ i ≤ n - 1). Hobbits start their journey at the point ...
```python import sys input = sys.stdin.readline n, H = map(int, input().split());points = [tuple(map(int, input().split())) for _ in range(n)];eye = (points[-1][0], points[-1][1] + H);peak = points[-1];out = 0 def dot(a,b): return a[0] * b[0] + a[1] * b[1] def sub(a,b): return (a[0] - b[0], a[1] - b[1]) def norm(...
1493_A. Anti-knapsack
You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line c...
```python t=int(input()) for i in range(t): n,k = map(int,input().split()) ans=[] if n==1 and k==1: print(0) continue else: if k%2==0: for j in range(k//2,k): ans.append(j) for j in range(k+1,n+1): ans.append(j) else: for j in range(k//2+1,k): ans.append(j) for j in range(k+1,n+1):...
1515_G. Phoenix and Odometers
In Fire City, there are n intersections and m one-way roads. The i-th road goes from intersection a_i to b_i and has length l_i miles. There are q cars that may only drive along those roads. The i-th car starts at intersection v_i and has an odometer that begins at s_i, increments for each mile driven, and resets to ...
```python import sys from sys import stdin import math from collections import deque import sys class scc_graph: def __init__(self, N): self.N = N self.edges = [] def csr(self): self.start = [0]*(self.N+1) self.elist = [0]*len(self.edges) for e in self.edges: ...
171_A. Mysterious numbers - 1
Input The input contains two integers a1, a2 (0 ≤ ai ≤ 109), separated by a single space. Output Output a single integer. Examples Input 3 14 Output 44 Input 27 12 Output 48 Input 100 200 Output 102
```python from math import floor x, y = input().split() x = int(x) y = int(y) rev = 0 while y > 0: a = int(y % 10) rev = rev * 10 + a y = floor(y / 10) b = x + rev print(b) ```
190_D. Non-Secret Cypher
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the informati...
```python def answer(): ans,count,j=0,0,0 d=dict() for i in range(n): while(j==0 or d[a[j-1]] < k): if(j==n): j+=1 break try:d[a[j]]+=1 except:d[a[j]]=1 count += 1 m=n-count+1 j+=1 ...
238_D. Tape Programming
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. * Current character pointer (CP); *...
```python n, q = map(int, input().split()) s = input() for _ in range(q): l, r = map(int, input().split()) t = list(s[l-1:r]) p, d = 0, 1 res = [0] * 10 while 0 <= p < len(t): if '0' <= t[p] <= '9': k = int(t[p]) res[k] += 1 if k > 0: t[p] ...
263_B. Squares
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square. Vasya wants to find such...
```python def ans(k,a): a.sort() if(k>len(a)): return "-1" else: if(k!=0): return a[len(a)-k] n,k=map(int,input().split(" ")) arr=list(map(int,input().split(" "))) if (ans(k,arr)=="-1"): print("-1") else: print(ans(k,arr)," ",ans(k,arr)) ...
287_B. Pipeline
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on...
```python n, k = map(int, input().split()) def prod(n): if n%2: return n*((n+1)//2) else: return (n//2)*(n+1) def total_count(n, k): if k >= n: return (0, 0, 1) else: count = 0 l = 1; r = k s = prod(k) while l <= r: mid = (l+r)//2 if n > s - prod(mid) + mid: r = mid-1 else: l = mid+...
312_B. Archer
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner. Output the probability th...
```python a, b, c, d = map(int, input().split(' ')) x = a/b y = c/d print(x / (1-(1-x) * (1-y))) ```
401_C. Team
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
```python mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) n0, n1 = f() s='0'*(n0+n1) if n1<n0-1: print(-1) elif n1==n0-1 or n1==n0: s=s.replac...
429_D. Tricky Function
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be t...
```python import os import math cumsum = [int(x) for x in os.read(0, os.fstat(0).st_size).split()] n = cumsum[0] cumsum[0] = 0 for i in range(n): cumsum[i+1] += cumsum[i] def work(besta, i, sqrtbesta, lowerbound, upperbound, cumsumi): for j in range(i+1, min(n, i - 1 + sqrtbesta) + 1): if lowerbound <...
451_B. Sort the Array
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly:...
```python # coding=utf-8 if __name__ == '__main__': n = int(input()) line = str(input()).split() line = [int(it) for it in line] temp_line = line.copy() temp_line.sort() ptr_head = 0 ptr_tail = n - 1 while line[ptr_head] == temp_line[ptr_head]: if ptr_head == ptr_tail: break ptr_head += 1 while line[p...
474_A. Keyboard
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move...
```python move=input() ans="" s=input() keyboard=["qwertyuiop","asdfghjkl;","zxcvbnm,./"] if move =="R": for i in range(len(s)): for j in range(len(keyboard)): if s[i] in keyboard[j]: ans+=keyboard[j][keyboard[j].index(s[i])-1] elif move =="L": for i in range(len(s)): ...
521_A. DNA Alignment
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in whic...
```python # problem statement: https://codeforces.com/problemset/problem/520/C modulo = 1000000007 n = int(input()) char_count = [0] * 256 s = input() for i in range(n): char_count[ord(s[i])] += 1 max_char_count = max(char_count) num_max_char = 0 for i in range(256): if char_count[i] == max_char_count: num_max_cha...
596_C. Wilbur and Points
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set. Now Wilbur wants to number the points in the set he has, that is ...
```python from collections import defaultdict def solve(): N = int(input()) maxx = 0 maxy = 0 WS = defaultdict(list) for i in range(N): x, y = map(int, input().split()) WS[y - x].append((x, y)) maxx = max(maxx, x) maxy = max(maxy, y) for w in WS: WS[w...
617_E. XOR and Favorite Number
Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k. Input The first line of the input contains i...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" no...
638_B. Making Genome in Berland
Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct En...
```python n = int(input()) genom = dict() heads = set() for i in range(n): part = input() heads.add(part[0]) for i in range(len(part)): prev = None next = None if i - 1 >= 0: prev = part[i - 1] if i + 1 < len(part): next = part[i + 1] if pa...
712_B. Memory and Trident
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: * An 'L' indicates he should move one unit left. * An 'R' indicates he should move one unit right. * A 'U' indicates he should move one unit up. * A 'D' indicates he shoul...
```python s = input() ud = lr = 0 for ch in s: if(ch=='R'): lr = lr+1 if(ch=='L'): lr = lr-1 if(ch=='U'): ud = ud+1 if(ch=='D'): ud = ud-1 if((abs(lr) + abs(ud))%2==1): print(-1) else: print(int((abs(lr) + abs(ud))/2)) ```
733_A. Grasshopper And the String
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
```python def solve(a): l = [0] li = [] j = 0 for i in range(len(a)): if a[i] == "A" or a[i] == "E" or a[i] == "I" or a[i] == "O" or a[i] == "U" or a[i] == "Y": l.append(i + 1) j += 1 li.append(l[j] - l[j-1]) l.append(i + 1) j += 1 li.append(l[...
757_B. Bash's Big Day
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, ...
```python def function1(n,s): if n==1: return 1 pokemonj=0 pokecage=[0 for i in range(100001)] for i in range(n): pokecage[s[i]]+=1 maxyincage=min(pokecage[1],1) a = [i for i in range(100001)] a[1] = 0 i = 2 while i <= 100000: if a[i] != 0: poke...
778_D. Parquet Re-laying
Peter decided to lay a parquet in the room of size n × m, the parquet consists of tiles of size 1 × 2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it. The workers decided that removing entire parquet and then laying it again is v...
```python #!/usr/bin/env python3 board = [] n, m = 0, 0 def rotate(x, y): if board[x][y] == 'L': board[x][y] = board[x][y+1] = 'U' board[x+1][y] = board[x+1][y+1] = 'D' else: board[x][y] = board[x+1][y] = 'L' board[x][y+1] = board[x+1][y+1] = 'R' def fix(x, y, moves): if b...
802_G. Fake News (easy)
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... In...
```python li = list(input()) def f(n,s): global li while True: if li[n] != s: li.pop(n) else: break try: f(0,'h') f(1,'e') f(2,'i') f(3,'d') f(4,'i') except: print("NO") else: print("YES") ```
825_C. Multi-judge Solving
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). M...
```python n,k=map(int,input().split()) ar=sorted(list(map(int,input().split()))) ans=0 for x in ar: if k <= x <= k*2: k=x while x/2 > k: ans+=1 k*=2 if k <= x <= k*2: k=x print(ans) ```
848_A. From Y to Y
From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t...
```python # def ap(l): # d = set() # for i in range(1, len(l)): # d.add(l[i]-l[i-1]) # if(len(d) == 1): # return d.pop() # else: # return "re" # def app(ll, oo, nm, ooo): # k = [] # for j in range(n): # if(j%oo !=0): # k.append(ll[j]) # if(ap(k) ...
967_B. Watering System
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour A liters of water into the pipe. After that,...
```python n, a, b = [int(i) for i in input().split(' ')] sizes = [int(i) for i in input().split(' ')] st = sum(sizes) s = (sizes[0] * a) / b sb = st - s blockable = sorted(sizes[1:], reverse=True) blocked_no = 0 blocked_amount = 0 for i in range(len(blockable)): if blocked_amount < sb: blocked_no += 1 ...
993_B. Open Communication
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set ...
```python import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,m=map(int,input().split()) possible1=[set() for _ in range(200)] possible2=[set() for _ in range(200)] weird=[0]*15 p1=list(map(int,input().split())) p2=list(map(int,input().split())) for i in range(n): for j in range(m): a=sor...
p02628 AtCoder Beginner Contest 171 - Mix Juice
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.) Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits. Constraints * 1 \leq K \leq N \leq 1000 * 1 \leq...
```python _,K,*P=map(int,open(0).read().split()) print(sum(sorted(P)[:K])) ```
p02759 AtCoder Beginner Contest 157 - Duplex Printing
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper. At least how many sheets of paper does he need? Constraints * N is an integer. * 1 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print the a...
```python N = int(input()) print(str(N//2+N%2)) ```
p02894 AtCoder Grand Contest 039 - Incenters
Given are N points on the circumference of a circle centered at (0,0) in an xy-plane. The coordinates of the i-th point are (\cos(\frac{2\pi T_i}{L}),\sin(\frac{2\pi T_i}{L})). Three distinct points will be chosen uniformly at random from these N points. Find the expected x- and y-coordinates of the center of the circ...
```python from math import cos, sin, pi from itertools import combinations N, L = map(int, input().split()) T = [int(input()) for _ in range(N)] PI2oL = 2*pi/L csum, ssum = 0, 0 count = 0 for i, j in combinations(range(N), 2): count += 1 mid1, num2 = (T[i] + T[j]) / 2, j - i - 1 mid2, num1 = (mid1 + L/2) %...
p03029 AtCoder Beginner Contest 128 - Apple Pie
We have A apples and P pieces of apple. We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan. Find the maximum number of apple pies we can make with what we have now. Constraints * All values in input are integers. * 0 \leq A, P \leq 100 Input Input is g...
```python A, P = map(int, input().split()) print(((A*3)+P)//2) ```
p03170 Educational DP Contest - Stones
There is a set A = \\{ a_1, a_2, \ldots, a_N \\} consisting of N positive integers. Taro and Jiro will play the following game against each other. Initially, we have a pile consisting of K stones. The two players perform the following operation alternately, starting from Taro: * Choose an element x in A, and remove e...
```python n, k = [int(i) for i in input().split()] A = [int(i) for i in input().split()] DP = [False] * (k + 1) for i in range(1, k+1): DP[i] = any(not DP[i-a] for a in A if i - a >= 0) print('First' if DP[k] else 'Second') ```
p03315 AtCoder Beginner Contest 101 - Eating Symbols Easy
There is always an integer in Takahashi's mind. Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is `+` or `-`. When he eats `+`, the integer in his mind increases by 1; when he eats `-`, the integer in his mind decreases by 1. The symbols Takahashi is going t...
```python s=list(input()) print(s.count("+")*2-4) ```
p03472 AtCoder Beginner Contest 085 - Katana Thrower
You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order: * Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of dam...
```python import math N,H=map(int,input().split()) ab=[[int(x) for x in input().split()] for _ in range(N)] a,_=max(ab) B=sorted([b for _,b in ab if b > a], reverse=True) sb=sum(B) if sb < H: print(len(B)+math.ceil((H-sb)/a)) else: B.insert(0, 0) for i in range(1, len(B)): B[i] += B[i-1] if B[i] >= H: break ...
p03634 AtCoder Beginner Contest 070 - Transit Tree Path
You are given a tree with N vertices. Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices. The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i. You are also given Q queries and an integer K. In the j-th qu...
```python import sys input = sys.stdin.readline N = int(input()) G = [[] * N for _ in range(N)] for _ in range(N - 1): a, b, c = map(int, input().split()) G[a - 1].append((b - 1, c)) G[b - 1].append((a - 1, c)) Q, K = map(int, input().split()) D = [-1] * N s = [(K - 1, 0)] while s: v, c = s.pop() D[v] = c...
p03792 Mujin Programming Challenge 2017 - Row to Column
There is a square-shaped grid with N vertical rows and N horizontal columns. We will denote the square at the i-th row from the top and the j-th column from the left as (i,\ j). Initially, each square is either white or black. The initial color of the grid is given to you as characters a_{ij}, arranged in a square sha...
```python def main(): n = int(input()) grid = [input() for _ in [0]*n] for i in grid: if "#" in i: break else: print(-1) return ans = 10**20 # i行目に何個黒があるか black_cnt = [0]*n # i列目に黒が一つでもあればTrue exist = [False]*n for i in range(n): for j ...
p03961 CODE FESTIVAL 2016 qual C - Encyclopedia of Permutations
One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgo...
```python import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") M = 10**9+7 n = int(input()) p = list(map(int, input().split())) g1 = [None]*(n+10) v = 1 g1[0] = 1 for i in range(1,len(g1)): v *= i v %= M g1[i] = v ...
p00052 Factorial II
n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1 Is called the factorial of n. For example, the factorial of 12 12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600 And there are two consecutive 0s at the end. Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of...
```python import sys f = sys.stdin while True: n = int(f.readline()) if n == 0: break zero_count = 0 while n: n //= 5 zero_count += n print(zero_count) ```
p00338 Programming Contest II
White Tiger University holds a programming contest every year. The contest starts with a score of 0 for all teams, and points are added according to the answer status. In this contest, rankings will be made in descending order of score. When the total number of teams is N, each team is assigned a number from 1 to N. If...
```python from bisect import bisect_left as bl def main(): n, c = map(int, input().split()) ranking = [(0, i) for i in range(n)] points = [0 for _ in range(n)] for _ in range(c): com = input().split() if com[0] == "1": m = int(com[1]) - 1 print(ranking[m][-1] + 1, -ranking[m][0]) else: ...
p00837 Book Replacement
The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have to copy pages of many reference books in the library. All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain a copy of a reference book’s page, a student should ask the librarian to...
```python def solve(): from collections import deque from sys import stdin f_i = stdin ans = [] while True: m, c, n = map(int, f_i.readline().split()) if m == 0: break book_pos = dict() studens = deque() shelf = m + 1 ...
p00969 Arithmetic Progressions
Arithmetic Progressions An arithmetic progression is a sequence of numbers $a_1, a_2, ..., a_k$ where the difference of consecutive members $a_{i+1} - a_i$ is a constant ($1 \leq i \leq k-1$). For example, the sequence 5, 8, 11, 14, 17 is an arithmetic progression of length 5 with the common difference 3. In this pro...
```python #!/usr/bin/python3 import os import sys def main(): N = read_int() V = read_ints() print(solve(N, V)) def solve(N, V): V.sort() pos = {} for i, a in enumerate(V): pos[a] = i best = 2 done = [[False] * N for _ in range(N)] for i in range(N): a = V[i] ...
p01101 Taro's Shopping
Taro's Shopping Mammy decided to give Taro his first shopping experience. Mammy tells him to choose any two items he wants from those listed in the shopping catalogue, but Taro cannot decide which two, as all the items look attractive. Thus he plans to buy the pair of two items with the highest price sum, not exceedin...
```python while True: n,m = map(int,input().split(" ")) if n == 0: break items = [] for i in input().split(" "): items.append(int(i)) #全探索 items2 = items sums = [] for i in range(len(items)): for j in range(len(items)): if i == j: co...
p01400 Seishun 18 Kippu
Problem C: Seishun 18 Kippu A student at R University, sirokurostone, was about to attend a training camp at Atsu University. Other members plan to use the Shinkansen, but sirokurostone was going to use the Seishun 18 Ticket. Similarly, a person who likes 2D with a youth 18 ticket was also trying to participate in the...
```python from heapq import heappush, heappop while True: n, m = map(int, input().split()) if n == 0:break s, p, g = input().split() edges = {} for _ in range(m): a, b, d, t = input().split() if a not in edges:edges[a] = [] if b not in edges:edges[b] = [] d = int(d) t = int(t) edges[a]...
p01553 Hakone
Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station....
```python #!/usr/bin/env python3 import sys import math from bisect import bisect_right as br from bisect import bisect_left as bl sys.setrecursionlimit(2147483647) from heapq import heappush, heappop,heappushpop from collections import defaultdict from itertools import accumulate from collections import Counter from ...
p01854 Pots
Problem statement Here are N mysteriously shaped vases. The i-th jar is a shape in which K_i right-sided cylinders are vertically connected in order from the bottom. The order in which they are connected cannot be changed. Mr. A has a volume of water of M. Pour this water into each jar in any amount you like. It does ...
```python def main(): n, m = map(int, input().split()) height = [] for _ in range(n): lst = list(map(int, input().split())) k = lst[0] ss = lst[1::2] hs = lst[2::2] v_acc = 0 h_acc = 0 index = 0 s, h = ss[0], hs[0] save = [] for i in range(m + 1): if i < v_acc + s * h...
p01989 Internet Protocol Address
A: IP Address (Internet Protocol Address) problem Since one number string is given, find the number of valid delimiters for IPv4 IP addresses. However, the effective delimiters for IPv4 IP addresses are as follows. * The sequence of numbers is divided into four, and each of the separated columns satisfies all of the...
```python def check(num): if num == "":return False if num[0] == "0":return num == "0" return 0 <= int(num) <= 255 s = input() ans = 0 for i in range(1, 4): for j in range(1, 4): for k in range(1, 4): n1 = s[:i] n2 = s[i:i+j] n3 = s[i+j:i+j+k] n4 = s[i+j+k:] if check(n1) and ch...
p02276 Partition
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I...
```python def partition(A, p, r): i = p - 1 x = A[r] for j in range(p,r): if A[j] <= x: i += 1 A[i], A[j] = A[j], A[i] A[i+1], A[r] = A[r], A[i+1] return i n = int(input()) A = list(map(int, input().split())) i = partition(A, 0, n-1) str_A = list(map(str,A)) ...
p02423 Bit Operation I
Given a non-negative decimal integer $x$, convert it to binary representation $b$ of 32 bits. Then, print the result of the following operations to $b$ respecitvely. * Inversion: change the state of each bit to the opposite state * Logical left shift: shift left by 1 * Logical right shift: shift right by 1 Constraint...
```python x = int(input()) print('{:032b}'.format(x)) print('{:032b}'.format(~x & (2 ** 32 - 1))) print('{:032b}'.format(x << 1 & (2 ** 32 - 1))) print('{:032b}'.format(x >> 1)) ```
1027_A. Palindromic Twist
You are given a string s consisting of n lowercase Latin letters. n is even. For each position i (1 ≤ i ≤ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi...
```python def get_mask(inp): return(5 << ord(inp) - ord('a')) n = int(input()) for i in range(0, n): input() st = input() ls = [] for j in st: ls.append(get_mask(j)) for j in range(0, len(ls) // 2): if(ls[j] & ls[-1 * (j + 1)] == 0): print("NO") brea...
106_D. Treasure Island
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map. The treasure map can be represented as a rectangle n × m in size. Each cell stands for an islands' square (the square's side length equals...
```python #!/usr/bin/env python3 from sys import stdin n, m = map(int, stdin.readline().rstrip().split()) island = [] pos = {} for i in range(n): island.append(stdin.readline().rstrip()) for j, c in enumerate(island[i]): if c >= 'A' and c <= 'Z': pos[c] = [i, j] l_reach = [[-1 for j in ra...
1091_C. New Year and the Sphere Transmission
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well. The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes th...
```python n=int(input()) a={1} for i in range(2,int(n**0.5)+1): if n%i==0: a.add(i) a.add(n//i) ans=[1] a=list(a) for i in a: term=n//i ans.append((term*(2+(term-1)*i))//2) ans.sort() print(*ans) ```
1110_A. Parity
You are given an integer n (n ≥ 0) represented with k digits in base (radix) b. So, $$$n = a_1 ⋅ b^{k-1} + a_2 ⋅ b^{k-2} + … a_{k-1} ⋅ b + a_k.$$$ For example, if b=17, k=3 and a=[11, 15, 7] then n=11⋅17^2+15⋅17+7=3179+255+7=3441. Determine whether n is even or odd. Input The first line contains two integers b and...
```python b,k=map(int,input().split()) arr=list(map(int,input().split())) arr.insert(0,0) s=0 for i in range(1,len(arr)): s=s+(arr[-i]*pow(b,i-1,1000000000)) if(s&1): print("odd") else: print("even") ```
1158_B. The minimal unique substring
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010...
```python # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code if __name__ == "__main__": n,k = map(int,input().split()) a = (n - k)//2 ps = '0'*a + '...
1180_A. Alex and a Rhombus
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 × 1 (i.e just a cell). A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
```python n = int(input()) print(sum(range(n)) * 4 + 1) ```
1199_A. City Day
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct. The mayor k...
```python import sys,heapq,math from collections import deque,defaultdict printn = lambda x: sys.stdout.write(x) inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) DBG = True # and False R = 10**9 + 7 def ddprint(x): if DBG: print(x) n,x,y ...
1215_F. Radio Stations
In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of ...
```python # ------------------- fast io -------------------- import os import sys input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack...
1239_A. Ivan the Fool and the Probability Theory
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r...
```python n, m = map(int, input().split()) mod = 10**9+7 a = [] a.append(0) a.append(2) a.append(4) for i in range(3, max(n, m)+1): a.append((a[i-1]+a[i-2])%mod) print((a[m]-2 + a[n])%mod) ```
1257_C. Dominated Subarray
Let's call an array t dominated by value v in the next situation. At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1...
```python import collections ii = lambda: int(input()) iia = lambda: list(map(int,input().split())) isa = lambda: list(input().split()) t = ii() for i in range(t): n = ii() x = iia() if(n==1): print('-1') else: dist = collections.defaultdict(lambda : n) last = collections.defaultdict(lambda : -1) mini = n...
1300_C. Anu Has a Function
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to r...
```python import sys,os,io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) a = [int(i) for i in input().split()] m = 0 mi = 0 b = [-1]*(35) for i in range (len(a)): bi = bin(a[i])[2:][::-1] for j in range (len(bi)): if bi[j]=='1': if b[j]==-1: ...
1324_D. Pair of Topics
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students. The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher). Your task is to find the number...
```python R = lambda:map(int,input().split()) n = int(input()) a = list(R()) b = list(R()) dif = [(b[i] - a[i], 1) for i in range(n)] for x in dif: if x[0] < 0: dif.append((-x[0], 0)) dif = sorted(dif) count = 0 ans = 0 for i in range(1, len(dif)): if dif[i][1] == 1: count += 1 if dif[i][1] == 0: ...
1343_C. Alternating Subsequence
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [...
```python t = int(input()) for tt in range(t): n = int(input()) arr = list(map(int,input().split())) mx = arr[0] sm = 0 for j in range(n): if (arr[j] * mx < 0 ): sm += mx mx = arr[j] else: mx = max(mx , arr[j]) print(sm + mx) ```
1365_D. Solve The Maze
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following: * Empty — '.' * Wall — '#' * Good person — 'G' * Bad person — 'B' The only escape from the maze is at cell (n, m). A person can move to a cell only if it shares a...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in...
1385_D. a-Good String
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The lengt...
```python import sys input = sys.stdin.readline def print(val): sys.stdout.write(str(val) + '\n') def solve(s,l,r,c): if l+1 == r: return int(s[l] != c) replace1 = replace2 = 0 for i in range(l,(l+r)//2): if s[i] != c: replace1 += 1 for i in range((l+r)//2, r): if...
1407_B. Big Vova
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro...
```python import sys,bisect,string,math,time,functools,random,fractions from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby rep=range;R=range def Golf():n,*t=map(int,open(0).read().split()) def I():return int(input()) def S...
1474_F. 1 2 3 4 ...
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard. Igor generated sequence p using the following algorithm: 1. initially, p = [x]; 2. for each 1 ≤ i ≤ n he did the following operation |d_i| times: * if d_i ≥ 0, then he looke...
```python import sys, io, os if os.environ['USERNAME']=='kissz': inp=open('in55.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def debug(*args): pass def mexp(size,power): A=[] for i in range(size)...
14_C. Four Segments
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the progr...
```python def is_rect(es): v = set([]) for e in es: if not ((e[0] == e[2]) or (e[1] == e[3])): return False v.add((e[0], e[1])) v.add((e[2], e[3])) if len(v) != 4: return False xs = set([]) ys = set([]) for vi in v: xs.add(vi[0]) ys...
156_B. 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 n, m = map(int, input().split()) t = [int(input()) for i in range(n)] s, p = 0, [0] * (n + 1) for i in t: if i < 0: m -= 1 p[-i] -= 1 else: p[i] += 1 q = {i for i in range(1, n + 1) if p[i] == m} if len(q) == 0: print('Not defined\n' * n) elif len(q) == 1: j = q.pop() print('\n...
177_F1. Script Generation
The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series. There are n single men and n single women among the main characters. An opinion poll showed that viewers lik...
```python I=lambda:list(map(int,input().split())) n,k,T=I() t=[I()for _ in '0'*k] def b(h,w,r,a): if h>n:a+=[r] else: b(h+1,w,r,a) for f,s,v in t: if f==h and s in w:b(h+1,w-set([s]),r+v,a) return a print(sorted(b(1,set(range(1,n+1)), 0,[]))[T-1]) ```
199_C. About Bacteria
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high. At the beginning of the first experiment there is a single bacterium in the test tub...
```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'...
222_D. Olympiad
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances. ...
```python from sys import stdin from collections import deque n,x = [int(x) for x in stdin.readline().split()] s1 = deque(sorted([int(x) for x in stdin.readline().split()])) s2 = deque(sorted([int(x) for x in stdin.readline().split()])) place = 0 for score in s1: if s2[-1] + score >= x: place += 1 ...
246_B. Increase and Decrease
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: * he chooses two elements of the array ai, aj (i ≠ j); ...
```python x=int(input()) sm=sum(list(map(int,input().split())))%x if sm==0: print(x) else: print(x-1) ```
271_C. Secret
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presup...
```python import sys; class MyReader: # file = null; def __init__(self): filename = "file.in"; if self.isLocal(): self.file = open(filename); self.str = [""]; self.ind = 1; def isLocal(self): return len(sys.argv) > 1 and sys.argv[1] == "SCHULL...
318_C. Perfect Pair
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number...
```python from sys import stdin from math import ceil x, y, m = map(int, stdin.readline().split()) ans = 0 if x >= m or y >= m: print(ans) elif x + y > min(x, y): ma, mi = max(x, y), min(x, y) ans += ((ma - mi) // ma) # + ((ma - mi) % ma) mi, ma = min(ma, mi + ans * ma), max(ma, mi + ans * ma) w...
342_C. Cupboard and Balloons
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius r (the cupboard's top) and two walls of height h (the cupboard's sides). The cupboard's depth is r, that is, it looks like a rectangle with base r and height h + r from the sides. The figure below shows what...
```python if __name__=='__main__': inp = input() arr = inp.split(" ") r = int(arr[0]) h = int(arr[1]) ans = 2*(h//r) d = h%r if d*2>=r: ans+=2 if 4*d*d >= 3*r*r: ans+=1 else: ans+=1 print(ans) ```
389_D. Fox and Minimal path
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output...
```python n, m, cnt = int(input()), 148, 0 ans = [['N'] * m for i in range(m)] def edge(i, j): ans[i][j] = ans[j][i] = 'Y' def node(*adj): global cnt i = cnt cnt += 1 for j in adj: edge(i, j) return i start, end, choice = node(), node(), node() if n&1: edge(choice, end) for i in r...
409_G. On a plane
Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of points on a plane. Each of the next n lines contains two real coordinates xi and yi of the <image> point, specified with exactly 2 fractional digits. All coordinates are between - 1000 and 1000, inclusive. Output Output a single real...
```python n = int(input()) ab = 0 for i in range(n): x, y = map(float, input().split()) ab += y print(5 + ab / n) ```
437_B. The Child and Set
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks. Fortunately, Picks remembers something about his set S: * its elements were distinct integers from 1 to limit; * the value of <ima...
```python s, limit = list(map(int, input().split())) ans = [] for i in range(limit, 0, -1): k = i & (i ^(i-1)) if s >= k: s-=k ans.append(i) if s: print(-1) else: print(len(ans)) print(*ans) ```
45_D. Event Dates
On a history lesson the teacher asked Vasya to name the dates when n famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [li, ri] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose...
```python # http://codeforces.com/contest/45/problem/D from sys import stdin inFile = stdin tokens = [] tokens_next = 0 def next_str(): global tokens, tokens_next while tokens_next >= len(tokens): tokens = inFile.readline().split() tokens_next = 0 tokens_next += 1 return tokens[tokens_...
52_B. Right Triangles
You are given a n × m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input...
```python n, m = map(int, input().split()) grid = [input() for _ in range(n)] a = [[0 for _ in range(m)] for i in range(n)] b = [[0 for _ in range(m)] for i in range(n)] for i in range(n): for j in range(m): a[i][j] = a[i][j - 1] + (grid[i][j] == '*') if i: b[i][j] = b[i - 1][j] ...