name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1443_B. Saving the City
Bertown is a city with n buildings in a straight line. The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise. Bertown's best sapper knows how to activate...
```python # ========== //\\ //|| ||====//|| # || // \\ || || // || # || //====\\ || || // || # || // \\ || || // || # ========== // \\ ======== ||//====|| # code def solve(): a,b = map(int, input().split()) ...
1468_K. The Robot
There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding dire...
```python #region Header #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) #endregion # _INPUT = """# paste here... # """ # sy...
1493_E. Enormous XOR
You are given two integers l and r in binary representation. Let g(x, y) be equal to the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all integers from x to y inclusive (that is x ⊕ (x+1) ⊕ ... ⊕ (y-1) ⊕ y). Let's define f(l, r) as the maximum of all values of g(x, y) satisfying l ≤ x ≤ y ≤ r. ...
```python i=int;p=input N=i(p());L=p();R=p() l=i(L,2);r=i(R,2);a=R if l-l%2<r:a=R[:-1]+'1' if i(L[-1])and l+1==r:a=R if L==R:a=L if L[0]<R[0]:a='1'*N print(a) ```
1516_B. AGAGA XOOORRR
Baby Ehab is known for his love for a certain operation. He has an array a of length n, and he decided to keep doing the following operation on it: * he picks 2 adjacent elements; he then removes them and places a single integer in their place: their [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR...
```python for i in range(int(input())): n = int(input()) a = list(map(int, input().split())) r = 0 for j in range(len(a)): r ^= a[j] if not r: print("Yes") else: t = 0 i = 0 s = 0 while i < len(a) and t < 2: s ^= a[i] if s...
1543_C. Need for Pink Slips
After defeating a Blacklist Rival, you get a chance to draw 1 reward slip out of x hidden valid slips. Initially, x=3 and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are c, m, and p, respectively. There...
```python a = 0 def dp(c, m, p, v, h, ans): global a a += h*p*ans if (c > 1e-6): if (m < 1e-6): dp(c-min(c, v), 0, p+min(c, v), v, h+1, ans*c) else: dp(c-min(c, v), m+min(c, v)/2.0, p+min(c, v)/2.0, v, h+1, ans*c) if (m > 1e-6): if (c < 1e-6): ...
171_D. Broken checker
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" — people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy. Input The only line of the input c...
```python vals = [2, 3, 1, 2, 1] i = int(input()) print(vals[i-1]) ```
191_B. Demonstration
In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares. Bertown has n squares, numbered from 1 to n, they are numb...
```python from sys import stdin, stdout n, k = map(int, stdin.readline().split()) value = int(stdin.readline()) prices = list(map(int, stdin.readline().split())) used = {} challengers = prices[:-1] for i in range(n - 1): challengers[i] = (challengers[i], i) challengers.sort(reverse = True) ind = challengers[k -...
215_B. Olympic Medal
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested ...
```python from math import sqrt f = lambda: list(map(int, input().split())) r1 = max(f()[1:]) p1s = f()[1:] p2 = min(f()[1:]) a, b = f() print(str(sqrt(max(b * p1 * r1**2 / float(a * p2 + b * p1) for p1 in p1s)))) ```
239_B. Easy 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] ...
335_C. More Reclamation
In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land. The river area can be represented by a grid with r rows and exactly two columns — each cell represents a rectangular area. The rows are numbered ...
```python r,n = [int(x) for x in input().split()] cells = [[int(x) for x in input().split()] for i in range(n)] cells.sort() #print(cells) out = False res = {True:"WIN",False:"LOSE"} if len(cells) == 0: print(res[r%2 == 1]) else: out = False #print(cells[0][0] > 1) #print(cells[-1][0] < r) for i in ra...
358_C. Dima and Containers
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck. Inna wants her present to show Dima how great a programmer he is. For that, she is going to g...
```python n = int(input()) r = ['popStack', 'popQueue', 'popFront' ] r2 = ['pushStack', 'pushQueue', 'pushFront' ] _ = 0 while _ < n: x = [] i = 0 while _ < n: z = int(input()) _ += 1 if z == 0: break x.append([z, i]) i+=1 if len(x) <= 3: ...
381_B. Sereja and Stairs
Sereja loves integer sequences very much. He especially likes stairs. Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|. For example, sequences [1, 2, 3, 2...
```python from sys import stdin,stdout from math import factorial as f inp=stdin.readline op=stdout.write n=int(inp()) a=list(map(int,inp().split())) a.sort() # op(str(a)) if(len(set(a))==n): op(str(len(a))+"\n") a=[str(i) for i in a] op(' '.join(a[::-1])+"\n") else: temp=float('inf') i=0 rev=[]...
402_A. Nuts
You have a nuts and lots of boxes. The boxes have a wonderful feature: if you put x (x ≥ 0) divisors (the spacial bars that can divide a box) to it, you get a box, divided into x + 1 sections. You are minimalist. Therefore, on the one hand, you are against dividing some box into more than k sections. On the other hand...
```python from math import ceil k, a, b, v = map(int, input().split()) res = 0 c = ceil(a / v) while (b >= k - 1) and (c > 0): res += 1 c -= k b -= k - 1 if c > 0: res += 1 c -= b + 1 if c > 0: res += c print(res) ```
42_B. Game of chess unfinished
Once Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. "Aha, blacks certainly didn't win!", — Volodya said and was right for sure. And your task is to say whether whites had won or not. Pieces on the ch...
```python import sys b = 'sabcdefgh' a1,a2,a3,a4 = map(str,input().split()) x1 = b.index(a1[0])-1 y1 = int(a1[1]) -1 x2 = b.index(a2[0])-1 y2 = int(a2[1]) -1 x3 = b.index(a3[0])-1 y3 = int(a3[1]) -1 x4 = b.index(a4[0])-1 y4 = int(a4[1]) -1 c = [] for i in range(8): c.append([0]*8) pr = 0 pr1 = 0 pr4 = 0 pr3 = 0 for...
474_D. Flowers
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red. But, for a dinner to be tasty...
```python #a, b, c, d = [int(x) for x in stdin.readline().split()] #a, b, c, d = map( int, stdin.readline().split() ) from sys import stdin, stdout modconst=1000000007 n,k=map(int, stdin.readline().split()) f=[0]*100001 ss=[0]*100001 f[0]=0 for i in range(1,k): f[i]=1 f[k]=2 for i in range(k+1,100001): f[i]=(...
498_C. Array and Operations
You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair (ik, jk) meets the following conditions: ik + jk is an odd number and 1 ≤ ik < jk ≤ n. In one operation you can perform a sequence of actions: * ...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def matching(n,m,path): match1 = [-1]*n match2 = [-1]*m for node in range(n): for nei in path[node]: if match2[nei] == -1: match1[node] = nei ...
521_D. Shop
Vasya plays one very well-known and extremely popular MMORPG game. His game character has k skill; currently the i-th of them equals to ai. Also this game has a common rating table in which the participants are ranked according to the product of all the skills of a hero in the descending order. Vasya decided to 'upgra...
```python def euclid(a, b): if b == 0: return (1, 0, a) else: (x, y, g) = euclid(b, a%b) return (y, x - a//b*y, g) def modDivide(a, b, p): (x, y, g) = euclid(b, p) return a // g * (x + p) % p def comb(n, k): return modDivide(fac[n], fac[k] * fac[n-k] % P, P) k, n, m = list(map(int, input().split())) a = l...
549_A. Face Detection
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 ...
```python n, m = [int(i) for i in input().split()] img = [list(input()) for i in range(n)] cnt = 0 for i in range(n - 1): for j in range(m - 1): arr = [img[i][j], img[i + 1][j], img[i][j + 1], img[i + 1][j + 1]] if 'f' in arr and 'a' in arr and 'c' in arr and 'e' in arr: cnt += 1 print(c...
597_A. Divisibility
Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k. Input The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 1018; - 1018 ≤ a ≤ b ≤ 1018). Output Print the required number. E...
```python k, a, b = map(int, input().split()) def Do(a, b,): suma = 0 if a < 0: if b == 0: print(-a // k + 1) if b > 0: suma = 1 a = -a if a % k == 0: if b % k == 0: suma += b // k + a // k ...
618_C. Constellation
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position. In the evening Noku is going to take a look at the night sky. He would like to find three d...
```python f = lambda: list(map(int, input().split())) d = lambda x, y: (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 r = lambda x, y, z: (x[0] - y[0]) * (x[1] - z[1]) == (x[1] - y[1]) * (x[0] - z[0]) n = int(input()) t = [f() for i in range(n)] j = k = -1 b = c = 0 x = t.pop() for i in range(n - 1): a = d(x, t[i]) ...
639_A. Bear and Displayed Friends
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti. Spring is starting and the Winter sleep is ...
```python import sys window = set() n, k, q = [int(x) for x in input().split()] arr = [int(x) for x in input().split()] for i in range(q): a, b = [int(x) for x in input().split()] if (a == 1): if (len(window) < k): window.add(arr[b - 1]) else: window.add(arr[b - 1]) m = min(window) window.remove(m)...
690_A2. Collective Mindsets (medium)
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)? The ...
```python n = int(input()) if n & 1: print(n//2) else: k = 1 while k <= n: k *= 2 print((n - k//2)//2) ```
733_D. Kostya the Sculptor
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangul...
```python n = int(input()) data = {} ans = 0 res = 0 pos = 0 ind = [] for i in range(n): tmp = sorted(list(map(int, input().split()))) if min(tmp) > ans: ans = min(tmp) ind = [i, -1] t = (tmp[1], tmp[2]) if t in data: third, _ = data[t] if min([third + tmp[0], tmp[1], tmp[2]]) > ans: ans = min([third ...
779_B. Weird Rounding
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result ...
```python n , k = map(int,input().split()) n = list(str(n)) counter = 0 zero_counter = 0 if n.count('0') >= k : for i in range(len(n)-1 , -1 , -1): if (n[i] != '0'): counter += 1 if (n[i] == '0'): zero_counter += 1 if (zero_counter == k): break print(counter) else: print(len(n) - 1) ```
802_J. Send the Fool Further! (easy)
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to d...
```python def dfs(u,cur): global ans vis[u]=True flag=True for x in vec[u] : v=x[0] c=x[1] if not vis[v] : dfs(v,cur+c) flag=False if flag: ans=max(cur,ans) ans=0 vec=[] vis=[] i=0 n=int(input()) while(i<n) : vec.append([]) vis.append(F...
825_F. String Compression
Ivan wants to write a letter to his friend. The letter is a string s consisting of lowercase Latin letters. Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string s instead of...
```python def prefix(s): p = [0] for i in range(1, len(s)): j = p[-1] while j > 0 and s[j] != s[i]: j = p[j - 1] if s[i] == s[j]: j += 1 p.append(j) return p s = input() n = len(s) ans = [0] * (n + 1) i = n - 1 while i >= 0: p = prefix(s[i:]) ...
848_D. Shake It!
A never-ending, fast-changing and dream-like world unfolds, as the secret door opens. A world is an unordered graph G, in whose vertex set V(G) there are two special vertices s(G) and t(G). An initial world has vertex set {s(G), t(G)} and an edge between them. A total of n changes took place in an initial world. In e...
```python mod = int(1e9 + 7) n, m = map(int, input().split()) f = [ [0 for i in range(60)] for j in range(60) ] g = [ [0 for i in range(60)] for j in range(60) ] s = [ [0 for i in range(60)] for j in range(60) ] inv = [ 1 ] f[0][0] = s[0][0] = 1 def pow(x, exp) : res = 1 for i in range(0, 31) : if exp ...
870_B. Maximum of Maximums of Minimums
You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get? D...
```python I = lambda: map(int, input().split()) _, k = I() A = list(I()) print(min(A) if k<2 else max(A) if k>2 else max(A[0], A[-1])) ```
897_A. Scarborough Fair
Are you going to Scarborough Fair? Parsley, sage, rosemary and thyme. Remember me to one who lives there. He once was the true love of mine. Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there. Willem asks his friend, Grick for directions, Grick helped...
```python _,m=map(int,input().split()) a=input() for _ in [0]*m: l,r,b,c=input().split();l=int(l)-1;r=int(r) a=a[:l]+a[l:r].replace(b,c)+a[r:] print(a) ```
918_B. Radio Station
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ...
```python a , b = map(int , input().split()) names = dict() for i in range(a): x , y = input().split() names[y] = x for i in range(b): com = input() h = com.split()[-1][:-1] print(f"{com} #{names[h]}") ```
940_B. Our Tanya is Crying Out Loud
Right now she actually isn't. But she will be, if you don't solve this problem. You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations: 1. Subtract 1 from x. This operation costs you A coins. 2. Divide x by k. Can be performed...
```python n = int(input()) k = int(input()) A = int(input()) B = int(input()) ans = 0 if k == 1: print(A*(n-1)) exit(0) while n > 1: subt = (n % k) ans += A * subt n -= (n%k) ans += min(A * (n - (n // k)),B) n //= k if n == 0: ans -= A print(ans) ```
993_E. Nikita and Order Statistics
Nikita likes tasks on order statistics, for example, he can easily find the k-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number x is the k-th number in increasing order on this segment. In other words, you should find the numb...
```python from math import pi from cmath import exp def fft(a, lgN, rot=1): # rot=-1 for ifft N = 1<<lgN assert len(a)==N rev = [0]*N for i in range(N): rev[i] = (rev[i>>1]>>1)+(i&1)*(N>>1) A = [a[rev[i]] for i in range(N)] h = 1 while h<N: w_m = exp((0+1j) * rot * (pi / h)) for k in range(0, ...
p02631 AtCoder Beginner Contest 171 - Red Scarf
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even. Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written. Recently, they learned the operation called xor (exclusive OR). What is xor? For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\...
```python N = int(input()) A = list(map(int, input().split())) temp = A[0] for a in A[1:]: temp ^= a print(*[a^temp for a in A]) ```
p02762 AtCoder Beginner Contest 157 - Friend Suggestions
An SNS has N users - User 1, User 2, \cdots, User N. Between these N users, there are some relationships - M friendships and K blockships. For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i. For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i...
```python N,M,K = map(int,input().split()) fr = [[] for i in range(N+1)] bl = [[] for i in range(N+1)] for _ in range(M): A,B = map(int, input().split()) fr[A].append(B) fr[B].append(A) for _ in range(K): C,D = map(int, input().split()) bl[C].append(D) bl[D].append(C) leader = [0]*(N+1) d = {} ...
p02897 AtCoder Beginner Contest 142 - Odds of Oddness
Given is an integer N. Takahashi chooses an integer a from the positive integers not greater than N with equal probability. Find the probability that a is odd. Constraints * 1 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print the probability that a is odd. Your ...
```python N = int(input()) print((N - N // 2) / N) ```
p03032 AtCoder Beginner Contest 128 - equeue
Your friend gave you a dequeue D as a birthday present. D is a horizontal cylinder that contains a row of N jewels. The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values. In the beginning, you have no jewel in your hands. You can perform at most K operations on...
```python N, K = map(int, input().split()) V = list(map(int, input().split())) ans = 0 for i in range(min(N, K) + 1): for j in range(i+1): Juel = V[:j] + V[N-i+j:] Juel.sort() sum_v = 0 for k in range(min(K-i, i)): Juel[k] = max(Juel[k], 0) ans = max(ans, sum(Jue...
p03173 Educational DP Contest - Slimes
There are N slimes lining up in a row. Initially, the i-th slime from the left has a size of a_i. Taro is trying to combine all the slimes into a larger slime. He will perform the following operation repeatedly until there is only one slime: * Choose two adjacent slimes, and combine them into a new slime. The new sli...
```python from functools import lru_cache N = int(input()) A = list(map(int, input().split())) INF = 1.0e+100 dp = [[[None, INF] for _ in range(N+1)] for _ in range(N+1)] for i in range(N): dp[i][i+1] = [A[i], 0] for g in range(2, N+1): for l in range(N-g+1): r = l + g for i in range(l+1, r)...
p03321 AtCoder Regular Contest 099 - Independence
In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N. M bidirectional roads connect these cities. The i-th road connects City A_i and City B_i. Every road connects two distinct cities. Also, for any two cities, there is at most one road that directly connects them. One day, it ...
```python from collections import deque N, M = map(int, input().split()) adjL = [set(range(N)) for _ in range(N)] for v in range(N): adjL[v].remove(v) for _ in range(M): A, B = map(int, input().split()) A, B = A-1, B-1 adjL[A].remove(B) adjL[B].remove(A) def getSizes(adjList): def bfs(vSt): ...
p03475 AtCoder Beginner Contest 084 - Special Trains
A railroad running from west to east in Atcoder Kingdom is now complete. There are N stations on the railroad, numbered 1 through N from west to east. Tomorrow, the opening ceremony of the railroad will take place. On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i t...
```python N=int(input()) CSF=[[0]]+[list(map(int, input().split())) for _ in range(N-1)] for j in range(1,N): t=0 for i in range(j,N): if t<CSF[i][1]: t=CSF[i][1] elif t%CSF[i][2]!=0: t=t+CSF[i][2]-t%CSF[i][2] t+=CSF[i][0] print(t) print(0) ```
p03640 AtCoder Regular Contest 080 - Grid Coloring
We have a grid with H rows and W columns of squares. Snuke is painting these squares in colors 1, 2, ..., N. Here, the following conditions should be satisfied: * For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W. * For each i (1 ≤ i ≤ N), the squares painted i...
```python h,w=map(int,input().split()) n=int(input()) a=list(map(int,input().split())) p=list() for i in range(n): p.extend([i+1 for j in range(a[i])]) #print(p) for i in range(h): if i%2==0: print(*p[i*w:i*w+w]) else: print(*p[i*w:i*w+w][::-1]) ```
p03796 AtCoder Beginner Contest 055 - Training Camp
Snuke loves working out. He is now exercising N times. Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i. Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7. Constraints * 1 ≤ N ≤ 10...
```python a = 1 for i in range(1,int(input())+1): a = (a*i)%(10**9+7) print(a) ```
p03964 AtCoder Beginner Contest 046 - AtCoDeer and Election Report
AtCoDeer the deer is seeing a quick report of election results on TV. Two candidates are standing for the election: Takahashi and Aoki. The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes. AtCoDeer has checked the report N times, and when he c...
```python N = int(input()) TA = [map(int, input().split()) for _ in range(N)] T, A = 1, 1 for t, a in TA: n = max(-(- T // t), -(- A // a)) T, A = n * t, n * a print(T + A) ```
p00055 Sequence
I have a sequence defined as follows: * All even-numbered terms are equal to the previous term multiplied by 2. * All odd-numbered terms are equal to the previous term divided by 3. Create a program that reads the first term a of this sequence and outputs the sum s (10) from the first term to the tenth term. Inp...
```python while True: try: a1 = float(input()) lst = [a1] for i in range(2,11): if i % 2: a1 /= 3 lst.append(a1) else: a1 *= 2 lst.append(a1) print(sum(lst)) except EOFError: break ```
p00186 Aizu Chicken
In April 2008, Aizuwakamatsu City succeeded in making yakitori with a length of 20 m 85 cm. The chicken used at this time is Aizu local chicken, which is a specialty of Aizu. Aizu local chicken is very delicious, but it is difficult to breed, so the production volume is small and the price is high. <image> Relative...
```python def check(mid, b, c1, c2, q1): if mid + (b - mid * c1) // c2 < q1: return False return True while True: s = input() if s == "0": break q1, b, c1, c2, q2 = map(int, s.split()) max_aizu = min(b // c1, q2) if max_aizu <= 0: print("NA") continue if c2 >= c1: max_norma...
p00341 Cuboid Made with Bars
The educational program (AHK Education) of the Aiz Broadcasting Association broadcasts a handicraft program for children, "Play with Tsukuro". This time I will make a box with sticks, but I would like to see if I can make a rectangular parallelepiped using the 12 sticks I prepared. However, the stick must not be cut or...
```python ls = list(map(int, input().split())) ls.sort() if ls[0]==ls[1]==ls[2]==ls[3] and ls[4]==ls[5]==ls[6]==ls[7] and ls[8]==ls[9]==ls[10]==ls[11]: print('yes') else: print('no') ```
p00537 Railroad Trip
Railroad Trip There are N cities in the JOI country, numbered 1, 2, ..., and N, respectively. In addition, there are N − 1 railroads, which are numbered 1, 2, ..., and N − 1, respectively. The railroad i (1 ≤ i ≤ N − 1) connects the city i and the city i + 1 in both directions. There are two ways to get on the JOI ra...
```python import itertools def main(): n, m = map(int, input().split()) plst = tuple(map(int, input().split())) abclst = [tuple(map(int, input().split())) for _ in range(n - 1)] sec = [0] * n for pi, pi1 in zip(plst, plst[1:]): p1, p2 = min(pi, pi1) - 1, max(pi, pi1) - 1 sec[p1] += 1 sec[p2] -...
p00840 Mobile Computing
There is a mysterious planet called Yaen, whose space is 2-dimensional. There are many beautiful stones on the planet, and the Yaen people love to collect them. They bring the stones back home and make nice mobile arts of them to decorate their 2-dimensional living rooms. In their 2-dimensional world, a mobile is defi...
```python def solve(): from itertools import combinations from sys import stdin f_i = stdin def dfs(base, stones): key = tuple(stones) if key in rec: return set((base + l, base + r) for l, r in rec[key]) edges = set() positions = set() fo...
p01104 Making Lunch Boxes
Making Lunch Boxes Taro has been hooked on making lunch boxes recently. Taro has obtained a new lunch box recipe book today, and wants to try as many of the recipes listed in the book as possible. Enough of the ingredients for all the recipes are at hand, but they all are in vacuum packs of two. If only one of them i...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools import time,random,resource sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 mod2 = 998244353 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)] d...
p01557 ReverseSort
A permutation of N numbers from 1 to N A1, A2, ……, AN is given. You can perform the operation reverse (i, j) to reverse the order of the numbers in the interval [i, j] (1 ≤ i ≤ j ≤ N) for this permutation. For example, if reverse (2, 4) is applied to [1, 2, 3, 4, 5], it becomes [1, 4, 3, 2, 5]. Calculate how many opera...
```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 ...
p01719 Invest Master
After many years of research, Ikta has acquired the ability to predict the future! The time and money he spent on this research was enormous, but it's finally time to be rewarded. To get the money back, Ikta decided to start investing in stocks. Ikta does not currently own any shares, but owns x yen. He has invested i...
```python I=input n,d,x=map(int,I().split()) w=[list(map(int,I().split()))for i in range(d)];d-=1 p=[[w[i+1][j]-w[i][j]for j in range(n)]for i in range(d)] b=x for i in range(d): dp = [False for j in range(b+1)] dp[0]=0 for j in range(n): for k in range(b): if w[i][j]+k<b+1 and id(dp[k])...
p01992 Shiritori Compression
D: Shiritori Compression problem Ebi-chan and Kana-chan did a shiritori. Ebi-chan is looking at the memo of the word that came out in Shiritori. Ebi-chan wants to remove redundant continuous subsequences from this word sequence w_1, w_2, ..., w_N until they no longer exist. The redundant continuous subsequence that ...
```python from collections import deque N = int(input()) idxs = [deque() for i in range(26)] def ctoi(c): return ord(c) - ord('a') cs = [] for i in range(N): c = input()[0] cs.append(c) ci = ctoi(c) idxs[ci].append(i) dp = [i for i in range(N)] dp[0] = 0 for i in range(N): c = cs[i] ci = ...
p02138 U and U
Problem There are $ 2 $ teams, Team UKU and Team Ushi. Initially, Team UKU has $ N $ people and Team Uku has $ M $ people. Team UKU and Team Ushi decided to play a game called "U & U". "U & U" has a common score for $ 2 $ teams, and the goal is to work together to minimize the common score. In "U & U", everyone's phys...
```python def inpl(): return list(map(int, input().split())) N, M = inpl() n2 = N * 1 n1 = N * 1 m1 = M * 1 mall = M * 2 # うくをほろぼす ans1 = 0 while True: mall -= n1 m1 = -(-mall//2) if mall <= 0: break ans1 += 1 if n2 - m1 >= 0: n2 -= m1 else: n1 = n1 + n2 - m1 ...
p02279 Rooted Trees
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs). <image> Fig. 1 A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertic...
```python import sys n = int(input()) nodes = [[-1, None, None] for _ in range(n)] depths = [None for _ in range(n)] for _ in range(n): nid, k, *children = list(map(int, sys.stdin.readline().split())) if k > 0: nodes[nid][1] = children[0] children.append(None) for i in range(k): cid ...
p02426 Bit Mask
A state with $n$ flags of ON or OFF can be represented by a sequence of bits where $0, 1, ..., n-1$ th flag corresponds to 1 (ON) or 0 (OFF). The state can be managed by the corresponding decimal integer, because the sequence of bits is a binary representation where each bit is 0 or 1. On the other hand, a mask is a s...
```python import sys class BitFlag: #ALL_ON = 0xffffffffffffffff ALL_OFF = 0x0000000000000000 def __init__(self, mask_digits): self.FLAGS = self.ALL_OFF self.MaskFor1bit = [1 << i for i in range(64)] self.Masks = [self.make_mask(digits) for digits in mask_digits] @staticmeth...
1011_C. Fly
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1. Flight from x to y consists of two phases: take-off from ...
```python from sys import stdin n=int(stdin.readline()) m=int(stdin.readline()) A=list(map(int,stdin.readline().split())) B=list(map(int,stdin.readline().split())) if 1 in A or 1 in B: print(-1) else: ans=(m*B[0])/(B[0]-1) for i in range(n-1,0,-1): ans=(ans*A[i])/(A[i]-1) ans=(ans*B[i]...
1036_D. Vasya and Arrays
Vasya has two arrays A and B of lengths n and m, respectively. He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, ...
```python from sys import stdin input=stdin.readline n=int(input()) a=list(map(int,input().split())) m=int(input()) b=list(map(int,input().split())) if sum(a)!=sum(b): print(-1) exit() j,k=0,0 sa,sb=0,0 cnt=0 pa,pb=1,1 while j<n and k<m: if pa==1: sa+=a[j] if pb==1: sb+=b[k] if sa==sb: cnt+=1 ...
1059_C. Sequence Transformation
Let's call the following process a transformation of a sequence of length n. If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from t...
```python from math import log2 n = int(input()) if n == 3: print(1,1,3) elif n == 1: print(1) else: num = n // 2 num3 = 2 ** int(log2(num)) * 2 num2 = n % 2 print("1 " * (num2 + num),end="") cur_num = 2 while num > 1: num2 = num % 2 num //= 2 print((str(cur_num)+...
10_D. LCIS
This problem differs from one which was on the online contest. The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n. The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other wo...
```python n = int(input()) a = [0] + list(map(int, input().split())) m = int(input()) b = [0] + list(map(int, input().split())) d = [[0 for j in range(m+1)] for i in range(n+1)] prev = [0] * (n+1) for i in range(1, n+1): for j in range(1, m+1): if a[i] == b[j]: d[i][j] = 1 for k in ...
1121_C. System Testing
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab. There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing p...
```python n,k = map(int,input().split()) a = list(map(int,input().split())) caption = 0 tested = [0 for i in range(n)] interesting = [0 for i in range(n)] ans = 0 while len(a) != 0: m = min(a[0:k]) for j in range(m): for i in range(min(k,len(a))): tested[i] += 1 a[i] -= 1 ...
1148_E. Earth Wind and Fire
There are n stones arranged on an axis. Initially the i-th stone is located at the coordinate s_i. There may be more than one stone in a single place. You can perform zero or more operations of the following type: * take two stones with indices i and j so that s_i ≤ s_j, choose an integer d (0 ≤ 2 ⋅ d ≤ s_j - s_i)...
```python from collections import namedtuple Stone = namedtuple('Stone', ['s', 'i']) def debug(*args, **kwargs): import sys #print(*args, *('{}={}'.format(k, v) for k, v in kwargs.items()), sep='; ', file=sys.stderr) def solve(n, s, t): #debug(s=s, t=t) s = list(map(lambda s_i: Stone(s_i[1], s_i[0...
116_B. Little Pigs and Wolves
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf. A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ...
```python n,m = map(int,input().split()) x,cnt = [],0 for _ in range(n): s = list(map(str,input())) for i in s: x.append(i) if n==m==1: print(0) elif n==1 or m==1: for i in range(len(x)): if x[i]=='W': if i==0: if x[i+1]=='P': x[i+1]='.';cnt+=1 elif i==(len(x)-1): if x[i-1]=='P': x[i-1]='.';cnt+=1 ...
1207_B. Square Filling
You are given two matrices A and B. Each matrix contains exactly n rows and m columns. Each element of A is either 0 or 1; each element of B is initially 0. You may perform some operations with matrix B. During each operation, you choose any submatrix of B having size 2 × 2, and replace every element in the chosen sub...
```python #!/usr/bin/python3 import pdb n, m = map(int, input().split(" ")) matrix = [] for i in range(n): matrix.append(list(map(int, input().split(" ")))) def check_pos(matrix, x, y): if x + 1 >= len(matrix): return False if y + 1 >= len(matrix[0]): return False if matrix[x][y] == 0 or matrix[x+1][y] == 0 o...
1225_C. p-binary
Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer. For example,...
```python if __name__ == '__main__': n, p = map(int, input().split()) aws = 1 while True: min_number = aws * ((2**0) + p) if min_number > n: aws = -1 break elif min_number == n: break elif bin((n - aws * p)).count('1') <= aws: b...
1249_E. By Elevator or Stairs?
You are planning to buy an apartment in a n-floor building. The floors are numbered from 1 to n from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor. Let: * a_i for all i from 1 to n-1 be the time required to go from the i-th floor...
```python N = 2*10**5 + 5; a=[0 for i in range(N)] b=[0 for i in range(N)] dp=[[0 for i in range(2)] for i in range(N)] def main(): n,c=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) dp[0][0] = 0 dp[0][1] = c for i in range(1,n): dp[i][0] ...
1268_B. Domino for Young
You are given a Young diagram. Given diagram is a histogram with n columns of lengths a_1, a_2, …, a_n (a_1 ≥ a_2 ≥ … ≥ a_n ≥ 1). <image> Young diagram for a=[3,2,2,2,1]. Your goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a 1 × 2 or 2 × 1 recta...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n = int(input()) a = list(map(int,input().split())) base,su,bl = 0,sum(a),0 for i in range(n): if not base: bl += (a[i]+1)//2 else: bl +=...
1290_C. Prefix Enlightenment
There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you ...
```python from sys import stdin input = stdin.readline n , k = [int(i) for i in input().split()] pairs = [i + k for i in range(k)] + [i for i in range(k)] initial_condition = list(map(lambda x: x == '1',input().strip())) data = [i for i in range(2*k)] constrain = [-1] * (2*k) h = [0] * (2*k) L = [1] * k + [0] * k dp1...
1333_B. Kind Anton
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
```python # (i, j) 1 <= i < j <= n # Add ai to aj def solvable(a, b): seen_neg = False seen_pos = False for ai, bi in zip(a, b): if ai < bi: if seen_pos: pass else: return False elif ai > bi: if seen_neg: p...
1353_E. K-periodic Garland
You are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k. In one move, you can choose one lamp and change i...
```python for _ in range(int(input())): n,k = map(int,input().split()) l = list(map(int,list(input()))) prf = [] dp = [] ans = 0 for i in range(n): ans += l[i] prf.append(ans) dp.append(0) # print(prf) for j in range(1,n): if j<k: dp[n-1-j] = min(prf[-1]-prf[n-1-j]+(l[n-1-j]^0),prf[-1]-prf[n-j-1]+(l[...
1373_D. Maximum Sum on Even Positions
You are given an array a consisting of n integers. Indices of the array start from zero (i. e. the first element is a_0, the second one is a_1, and so on). You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of a with borders l and r is a[l; r] = a_l, a_{l + 1}, ..., a_...
```python import sys,random input=sys.stdin.readline T=int(input()) for _ in range(T): n=int(input()) A=list(map(int,input().split())) '''n=random.randint(1,10) A=[] for i in range(n): A.append(random.randint(1,10)) print(n) print(*A)''' B=[] C=[] for i in range(0...
1396_C. Monster Invaders
Ziota found a video game called "Monster Invaders". Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns. For the sake of simplicity, we only consider two different types of monsters and three different types of guns. Namely, the two types of monsters are: *...
```python import sys;input=sys.stdin.readline N, a, b, c, k = map(int, input().split()) X = list(map(int, input().split())) dp = [[10**18]*2 for _ in range(N+1)] dp[0][0] = 0 R = 10**18 for i in range(N): dp[i+1][0] = min(dp[i][0] + a*X[i]+c, dp[i][1] + min(a*(X[i]+2), a+b)) dp[i+1][1] = dp[i][0] + min(a*(X[i]+...
1438_E. Yurii Can Do Everything
Yurii is sure he can do everything. Can he solve this task, though? He has an array a consisting of n positive integers. Let's call a subarray a[l...r] good if the following conditions are simultaneously satisfied: * l+1 ≤ r-1, i. e. the subarray has length at least 3; * (a_l ⊕ a_r) = (a_{l+1}+a_{l+2}+…+a_{r-2}...
```python from sys import * input = stdin.readline def solve(n, a, t): ans = 0 for i in range(n): sum = 0 high1 = a[i].bit_length()-1 for j in range(i+1, n-1): high2 = a[j+1].bit_length()-1 sum += a[j] if(sum >= (1<<(high1+1))): break if((a[i]^a[j+1]) == sum and (t == 0 or high1 != high2)): ...
1463_D. Pairs
You have 2n integers 1, 2, ..., 2n. You have to redistribute these 2n elements into n pairs. After that, you choose x pairs and take minimum elements from them, and from the other n - x pairs, you take maximum elements. Your goal is to obtain the set of numbers \\{b_1, b_2, ..., b_n\} as the result of taking elements ...
```python from collections import deque def solve(): n = int(input()) a = list(map(int, input().split())) In_a = [False]*(2*n + 1) for v in a: In_a[v] = True b = [] for v in range(2*n, 0, -1): if In_a[v] == False: b.append(v) def possible(K): tmpa = a[:...
148_D. Bag of mice
The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chanc...
```python w,b = list( map(int, input().split()) ) p = [] for i in range(w+1): p.append([0]*(b+1)) for i in range(1,w+1): p[i][0] = 1 for i in range(1,w+1): for j in range(1,b+1): p[i][j] = i/(i+j) if j>=3: p[i][j] += (j/(i+j)) * ((j-1)/(i+j-1)) * ((j-2)/(i+j-2)) * p[i][j-3] if j...
1512_B. Almost Rectangle
There is a square field of size n × n in which two cells are marked. These cells can be in the same row or column. You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes. For example, if n=4 and a rectangular field looks like this (there are asterisks in ...
```python for _ in range(int(input())): n=int(input()) l=[] r1=-1 c1=-1 c2=-1 r2=-1 for i in range(n): s=input() for j in range(n): if(s[j]=="*"): if(r1==-1): r1=i c1=j else: ...
166_C. Median
A median in an array with the length of n is an element which occupies position number <image> after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17. We define...
```python n, x = map(int, input().split()) a = list(map(int, input().split())) ret = 0 if x not in a: a.append(x) ret += 1 a.sort() while a[(len(a) + 1) // 2 - 1] != x: a.append(x) a.sort() ret += 1 print(ret) ```
208_B. Solitaire
A boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules: * A deck of n cards is carefully shuffled, then all n cards are put on the table in a line from left to right; * Before each move the table has several piles of cards lying ...
```python n = int(input()) arr = list(input().split()) def evl(c1, c2): return c1[0] == c2[0] or c1[1] == c2[1] vt = set() q = [arr[:]] while q: ar = q.pop() vt.add(''.join(ar)) if len(ar) > 3 and evl(ar[-1], ar[-4]): tmp = ar[:len(ar) - 1] tmp[-3] = ar[-1] if ''.join(tmp) no...
282_D. Yet Another Number Game
Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games! Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games. BitLGM and Bi...
```python from math import * n=int(input()) if n==3: li=list(map(int,input().split())) ans=0 flag=0 for i in li: ans^=i if ans==0: print("BitAryo") else: print("BitLGM") elif n==2: li=list(map(int,input().split())) li.sort() phi=(1+sqrt(5))/2 ch=[0]*(785) ...
305_C. Ivan and Powers of Two
Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum o...
```python n = int(input()) a = list(map(int, input().split())) s = set() for i in a: j = i while j in s: s.remove(j) j += 1 s.add(j) print(max(s)-len(s)+1) ```
353_B. Two Heaps
Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube fr...
```python from math import* from random import* n = int(input()) * 2 A = list(map(int, input().split())) amount = [0] * 101 B = [] for i in range(n): if amount[A[i]] < 2: amount[A[i]] += 1 B += [(A[i], i)] B.sort() x, y = [], [] for i in range(len(B)): if(i % 2 == 0): x.append(B[i][1])...
424_A. Squats
Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up. For another exercise, Pasha needs exactly <image> hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster e...
```python n = int(input()) s = str(input()) half = n//2 sit = s.count('x') stand = s.count('X') ans = max(sit, stand) - half t = ans while ans!=0: if sit>stand: temp = s.index('x') s = s[:temp] + 'X' + s[temp+1:] sit = sit-1 stand = stand +1 ans = ans -1 else: tem...
448_D. Multiplication Table
Bizon the Champion isn't just charming, he also is very smart. While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the element on the intersection of the i-th row and j-th column equals i·j (the rows and ...
```python def main(): from math import sqrt m, n, k = map(int, input().split()) if n < m: n, m = m, n lo, hi = 1, k + 1 while lo + 1 < hi: mid = (lo + hi) // 2 t = mid - 1 v = min(int(sqrt(t)), m) tn, tm = (t - 1) // m, t // n vv = [t // i for i in ran...
493_A. Vasya and Football
Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card. Vasya is watching a recorded football match now and makes notes of all the fouls tha...
```python home=input() away=input() n=int(input()) yellows=set() reds=set() s={'h':home,'a':away} while n: x=input().split() time=int(x[0]) team=x[1] shirt=int(x[2]) card=x[3] if card=='y': if (shirt,team) in yellows and (shirt,team) not in reds:#2nd time print(s[team],shirt,...
516_E. Drazil and His Happy Friends
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan. There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and...
```python n, m = (int(x) for x in input().split()) happy_boys = [0 for _ in range(n)] happy_girls = [0 for _ in range(m)] boys = [int(x) for x in input().split()] girls = [int(x) for x in input().split()] if boys[0]: for i in range(1, len(boys)): happy_boys[boys[i]] = 1 if girls[0]: for i in range(1, l...
570_B. Simple Game
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen w...
```python n,m = map(int, input().split()) p = [m+int(m<n),m-int(m>1)] print(p[n-m<=m-1]) ```
613_C. Necklace
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). ...
```python from fractions import gcd from functools import reduce LETTERS = 'abcdefghijklmnopqrstuvwxyz' def necklace_odd(a): oi = next(i for i, ai in enumerate(a) if ai%2) o = a[oi] g = reduce(gcd, a) s = [LETTERS[i] * (a[i]//(2*g)) for i in range(len(a)) if i != oi] return g, (''.join(s) + (LET...
633_C. Spy Syndrome 2
After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique. For a given sentence, the ciphe...
```python import sys p = sys.stdin.read().split() n, t = int(p[0]), p[1][::-1] d = {q.lower(): q for q in p[3:]} k, s = 0, [] l = sorted(set(map(len, d))) while n: k -= 1 if len(l) + k < 0: k, n = s.pop() elif n >= l[k] and t[n - l[k]:n] in d: s.append((k, n)) n -= l[k] k = 0 print(*...
686_A. Free Ice Cream
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
```python x, y = input().split(" ") a = x,y a = list(a) for i in range(len(a)): a[i]=int(a[i]) count=0 num =a[1] for i in range(a[0]): z,f = input().split(" ") char=z inp=int(f) if char == '+': num = num + inp elif char == '-': num = num - inp if num < 0: coun...
730_B. Minimum and Maximum
This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush(). In this problem, you need to find maximal and minimal elements of an ar...
```python import sys T = int(input()) def compare(l,r,arr): print('?',a[l]+1,a[r]+1) sys.stdout.flush() res = input() if (res == '>'): return 1; else: return 0; while (T > 0): T -= 1 Max_a = [] Min_a = [] n = int(input()) a = range(n) for i in range(int(n/2)): if...
774_F. Pens And Days Of Week
Stepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (n + 1)-th day again he uses the pen number 1, on the (n + 2)-th — he uses the pen number 2 and so on. On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses t...
```python import sys def Min(x, y): if x > y: return y else: return x def Gcd(x, y): if x == 0: return y else: return Gcd(y % x, x) def Lcm(x, y): return x * y // Gcd(x, y) n = int(input()) a = [int(i) for i in input().split()] d = [int(0) for i in range(0, n)] o...
81_A. Plug-in
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yy...
```python from collections import deque def plugin(s): # stack for characters to check string_stack = deque() # input string in a list arr_s = [c for c in s] # for each character, append to stack. if for c in arr_s: string_stack.append(c) if len(string_stack) > 1: ...
845_D. Driving Test
Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. * speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type); * overtake is allowed: this sign means th...
```python n = int(input()) events = [] for i in range(n): events.append(list(map(lambda s: int(s), input().split()))) max_speeds = [] overtaking_forbidden = 0 current_speed = 0 ignores = 0 for event in events: if event[0] == 1: current_speed = event[1] while max_speeds and current_speed > ...
892_A. Greed
Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai ≤ bi). Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not! Input The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola...
```python import sys sys.setrecursionlimit(100000000) # def input(): return sys.stdin.readline()[:-1] def iin(): return int(input()) def impin(): return map(int, input().split()) def irrin(): return [int(x) for x in input().split()] def imrin(n): return [int(input()) for _ in range(n)] n = iin() arr = irrin() brr = i...
914_A. Perfect Squares
Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square. A number x is said to be a perfect square if there exists an integer y such that x = y2. Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second ...
```python n = int(input()) a = [int(i) for i in input().split()] p = [] i = 0 while(True): p.append(i*i) i += 1 if(p[-1] > 1000000): break m = -99999999 for i in a: if i not in p: m = max(i,m) print(m) ```
936_C. Lock Puzzle
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock...
```python n = int(input()) t = input()[:n] s = input()[:n] ops =[] def shift(k, cur): if k == 0: return cur return cur[:-k-1:-1] + cur [:-k] def move_to_front(k, curst): if k == n-1: ops.append(1) curst = curst[-1] +curst [:-1] else: ops.append(n-1) ops.appen...
962_A. Equator
Polycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first. On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first...
```python n=int(input()) l=list(map(int,input().split())) s=sum(l)/2 #print(s) i=0; curr=0 while(curr<s): curr+=l[i] i+=1 print(i) ```
98_B. Help King
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive. Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, ...
```python from fractions import * n,L=int(input()),0 while (n%2==0):n,L=n//2,L+1 if (n==1):print('%d/1'%L) else: s,t=1,1 for i in range(n): t=t*2%n s*=2 if (t==1): m=i+1 break r,t,i,ans=s,s*n,L,0 while (r>1): i,t=i+1,t//2 if (r-t>0): ...
p02605 M-SOLUTIONS Programming Contest 2020 - Air Safety
M-kun is a brilliant air traffic controller. On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude. Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the d...
```python def main(): import sys input = sys.stdin.readline N = int(input()) XYU = [list(map(str,input().split())) for _ in range(N)] from collections import deque INF = float('inf') UD = [0] * 200001 LR = [0] * 200001 UR = [0] * 400001 DL = [0] * 400001 DR = [0] * 400001 UL = [0] * 400001 ...
p02736 AtCoder Grand Contest 043 - 123 Triangle
Given is a sequence of N digits a_1a_2\ldots a_N, where each element is 1, 2, or 3. Let x_{i,j} defined as follows: * x_{1,j} := a_j \quad (1 \leq j \leq N) * x_{i,j} := | x_{i-1,j} - x_{i-1,j+1} | \quad (2 \leq i \leq N and 1 \leq j \leq N+1-i) Find x_{N,1}. Constraints * 2 \leq N \leq 10^6 * a_i = 1,2,3 (1 \leq...
```python N = int(input()) a = input() def myc(n): ret = 0 while n % 2 == 0: ret += 1 n //= 2 return ret def func(c): odd = 0 count = 0 if a[0] == c: count += 1 if a[-1] == c: count += 1 for i in range(1, N // 2): odd += myc(N-i) - myc(i) ...
p03005 diverta 2019 Programming Contest 2 - Ball Distribution
Takahashi is distributing N balls to K persons. If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls? Constraints * 1 \leq K \leq N \leq 100 * All values in input are intege...
```python a,b=map(int,input().split()) c=a-b if b!= 1: print(c) else: print(0) ```
p03145 AtCoder Beginner Contest 116 - Right Triangle
There is a right triangle ABC with ∠ABC=90°. Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC. It is guaranteed that the area of the triangle ABC is an integer. Constraints * 1 \leq |AB|,|BC|,|CA| \leq 100 * All values in input are integers. * The area of the triangl...
```python a,b,c=map(int,input().split()) print(str(int(0.5*a*b))) ```