name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
784_B. Kids' Riddle
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it? Input The input contains a single integer n (0 ≤ n ≤ 2000000000). Output Output a single integer. Examples Input 11 Output 2 Input 14 Output 0 Input 61441 Output 2 Input 571576 Output 10 Input 2128506 Output 3
```python a=str(hex(int(input()))) b=0 for i in range(2,len(a)): if a[i]=="0" or a[i]=="4" or a[i]=="6" or a[i]=="9" or a[i]=="a" or a[i]=="d": b+=1 elif a[i]=="8" or a[i]=="b": b+=2 print(b) ```
805_A. Fake NP
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times. Solve...
```python n, k=map(int ,input().split()) if n==k and n%2==1: print(n) else: print(2) ```
830_A. Office Keys
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the mi...
```python o=lambda:[int(f)for f in input().split()] n,k,p=o() a=sorted(o()) b=sorted(o()) print(min(max(abs(b[i + d] - a[i]) + abs(b[i + d] - p) for i in range(n)) for d in range(k - n + 1))) ```
851_B. Arpa and an exam about geometry
Arpa is taking a geometry exam. Here is the last problem of the exam. You are given three points a, b, c. Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c....
```python ax,ay,bx,by,cx,cy=map(int,input().split()) ab=(ax-bx)**2+(ay-by)**2 bc=(bx-cx)**2+(by-cy)**2 if ab==bc and (ay-by)*(bx-cx)!=(by-cy)*(ax-bx): print("Yes") else: print("No") ```
920_E. Connected Components?
You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. ...
```python n,m=map(int,input().split()) non=[{i} for i in range(n)] for i in range(m): u,v=map(int,input().split()) u,v=u-1,v-1 non[u].add(v) non[v].add(u) vertex=set(range(n)) ans=[] while(vertex): a=next(iter(vertex)) vertex.remove(a) stk=[a] cou=1 while(stk): v=stk.pop() ...
949_C. Data Center Maintenance
BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!). Main feature of services offered by BigData Inc. is the access availability guarantee even under the ci...
```python from collections import deque import sys input = sys.stdin.readline n, m, MOD = map(int, input().split()) u = list(map(int, input().split())) info = [list(map(int, input().split())) for i in range(m)] graph = [[] for i in range(n)] rev_graph = [[] for i in range(n)] set_ = set() INF = 10 ** 9 for a, b in i...
977_B. Two-gram
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams. You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ...
```python n = int(input()) k = str(input()) Max = 0 for i in range(n-1): t=k[i]+k[i+1] z=0 for j in range(0,n-1): s=k[j]+k[j+1] if (s==t): z=z+1 #print(z) if (z>Max): Max=z res=t print(res) ```
996_F. Game
Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n → R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a mo...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time (n, r) = (int(i) for i in input().split()) c = [int(i) for i in input().split()] start = time.time() s = sum(c) n2 = 2**n ans = [s/n2] for i in range(r): (k, new) = (int(i) for i in input().split()) s += new - c[k] c[k] ...
p02652 AtCoder Grand Contest 045 - 01 Unbalanced
Given is a string S, where each character is `0`, `1`, or `?`. Consider making a string S' by replacing each occurrence of `?` with `0` or `1` (we can choose the character for each `?` independently). Let us define the unbalancedness of S' as follows: * (The unbalancedness of S') = \max \\{ The absolute difference be...
```python from itertools import accumulate S = input() N = len(S) A = [0] + list(accumulate(1 if s == "1" else -1 for s in S)) ma = max(A) cur = A[-1] C = [ma - cur] for a in reversed(A): cur = max(a, cur) C.append(ma - cur) d, e = 0, 0 D, E = A[:], A[:] for i, (s, c) in enumerate(zip(S, reversed(C[:-1])), ...
p02781 AtCoder Beginner Contest 154 - Almost Everywhere Zero
Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten. Constraints * 1 \leq N < 10^{100} * 1 \leq K \leq 3 Input Input is given from Standard Input in the following format: N K Output Print the count. Examples Input 100 1 Output 19 Inpu...
```python import functools import sys @functools.lru_cache(None) def doit(n, k): if len(n) == 0 or k < 0: return k == 0 d = int(n[0]) return sum(doit(n[1:] if i == d else '9' * (len(n) - 1), k - 1 if i > 0 else k) for i in range(d + 1)) sys.setrecursionlimit(404) print(doit(input(), int(input())...
p02916 AtCoder Beginner Contest 140 - Buffet
Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once. The i-th dish (1 \leq i \leq N) he ate was Dish A_i. When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points. Additionally, when he eats Dish i+1 just after eating Dish i (1 \...
```python N=int(input()) A=list(map(int,input().split())) B=list(map(int,input().split())) C=list(map(int,input().split())) pnt=sum(B) for i in range(N-1): if A[i+1]==A[i]+1: pnt+=C[A[i]-1] print(pnt) ```
p03194 CADDi 2018 for Beginners - Product and GCD
There are N integers a_1, a_2, ..., a_N not less than 1. The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P. Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N. Constraints * 1 \leq N \leq 10^{12} * 1 \leq P \leq 10^{12} Input Input is...
```python import math import collections # 試し割法 N, P = map(int, input().split()) def trial_division(n): # 素因数を格納するリスト factor = [] # 2から√n以下の数字で割っていく tmp = int(math.sqrt(n)) + 1 for num in range(2, tmp): while n % num == 0: n //= num factor.append(num) # リストが空なら...
p03343 AtCoder Regular Contest 098 - Range Minimum Queries
You are given an integer sequence A of length N and an integer K. You will perform the following operation on this sequence Q times: * Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one ...
```python N, K, Q = map(int, input().split()) X = list(map(int, input().split())) r = 10**18 for y in X: tmp = [] tmp2 = [] for x in X: if x < y: tmp.sort() tn = len(tmp) if len(tmp) > K-1: tmp2 += tmp[:tn-K+1] tmp = [] con...
p03503 AtCoder Beginner Contest 080 - Shopping Street
Joisino is planning to open a shop in a shopping street. Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those ...
```python n = int(input()) f = [[int(x) for x in input().split()] for i in range(n)] p = [[int(x) for x in input().split()] for i in range(n)] t={i:0 for i in range(1,2**10)} for i in range(1,2**10): d, b={j:0 for j in range(n)}, format(i, "010b") for j in range(n): for k in range(10): if (i>>k)%2&f[j][k]...
p03664 AtCoder Regular Contest 078 - Mole and Abandoned Mine
Mole decided to live in an abandoned mine. The structure of the mine is represented by a simple connected undirected graph which consists of N vertices numbered 1 through N and M edges. The i-th edge connects Vertices a_i and b_i, and it costs c_i yen (the currency of Japan) to remove it. Mole would like to remove som...
```python n, m = map(int, input().split()) g = [[0 for j in range(n)] for i in range(n)] for i in range(m): u, v, w = map(int, input().split()) g[u - 1][v - 1] = g[v - 1][u - 1] = w e = [sum(g[i][j] for i in range(n) if S >> i & 1 for j in range(i + 1, n) if S >> j & 1) for S in range(1 << n)] dp = [[-10 **...
p03819 AtCoder Regular Contest 068 - Snuke Line
Snuke has decided to play a game, where the player runs a railway company. There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train. For example, if d = 3, the train stops at station 0, 3, 6...
```python class BIT: def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def add(self, k, x): while k <= self.n: self.bit[k] += x k += k & -k def sum(self, k): s = 0 while k > 0: s += self.bit[k] k -= k & -k ...
p03986 AtCoder Grand Contest 005 - STring
We have a string X, which has an even number of characters. Half the characters are `S`, and the other half are `T`. Takahashi, who hates the string `ST`, will perform the following operation 10^{10000} times: * Among the occurrences of `ST` in X as (contiguous) substrings, remove the leftmost one. If there is no occ...
```python x=input() s=0;t=0 for i in range(len(x)): if x[i]=='S':s+=1 elif s==0:t+=1 else:s-=1 print(s+t) ```
p00074 Videotape
There is a 120 minute videotape with standard recording. When I set the VCR counter to 00:00:00 with the tape completely rewound and recorded in standard recording mode, I got a certain counter value. Enter this counter value (hours, minutes, seconds), find the length of the remaining tape (recordable time), and create...
```python def time(sec): h = sec // 3600 ti = sec % 3600 m = ti // 60 s = ti % 60 return [h,m,s] while True: t,h,s = map(int,input().split()) if t == h == s == -1: break sec = t*3600 + h * 60 + s sec = 7200 - sec ans = time(sec) t_ans = time(3 * sec) if ans[2] < ...
p00206 Next Trip
You want to go on a trip with a friend. However, friends who have a habit of spending money cannot easily save travel expenses. I don't know when my friends will go on a trip if they continue their current lives. So, if you want to travel early, you decide to create a program to help your friends save in a planned mann...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0206 """ import sys from sys import stdin input = stdin.readline def main(args): while True: L = int(input()) if L == 0: break ans = 'NA' for i in range(1, 12+1): ...
p00365 Age Difference
A trick of fate caused Hatsumi and Taku to come to know each other. To keep the encounter in memory, they decided to calculate the difference between their ages. But the difference in ages varies depending on the day it is calculated. While trying again and again, they came to notice that the difference of their ages w...
```python y1,m1,d1 = map(int, input().split()) y2,m2,d2 = map(int, input().split()) if y1 > y2 or (y1 == y2 and (m1 > m2 or ( m1 == m2 and d1 > d2 ))): y1, y2 = y2, y1 m1, m2 = m2, m1 d1, d2 = d2, d1 if m1 < m2 or (m1 == m2 and d1 < d2): print(y2 - y1 + 1) else: print(y2 - y1) ```
p00720 Earth Observation with a Mobile Robot Team
A new type of mobile robot has been developed for environmental earth observation. It moves around on the ground, acquiring and recording various sorts of observational data using high precision sensors. Robots of this type have short range wireless communication devices and can exchange observational data with ones ne...
```python from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, T, R = map(int, readline().split()) if N == T == R == 0: return False S = [None]*N TS = [None]*N for i in range(N): s = readline().strip() S[i] = s ...
p00991 Grid
Two coordinates (a1, a2) and (b1, b2) on a two-dimensional grid of r × c are given. The cost of moving from a cell (e, f) to one of the cells (e + 1, f), (e-1, f), (e, f + 1), (e, f-1) is 1. And. You can also move between (e, c-1) and (e, 0), and between (r-1, f) and (0, f) at a cost of 1. At this time, find the number...
```python # Edit: 2014/09/17 # Lang: Python3 # Time: 00.04s from math import factorial if __name__ == "__main__": r, c, ar, ac, br, bc = map(int, input().strip("\n").split(" ")) maxans = 100000007 # 100,000,007 # tate Row dr = min(abs(br - ar), r - abs(br - ar)) if 2 * dr == r: gainr = 2...
p01422 Beautiful Currency
KM country has N kinds of coins and each coin has its value a_i. The king of the country, Kita_masa, thought that the current currency system is poor, and he decided to make it beautiful by changing the values of some (possibly no) coins. A currency system is called beautiful if each coin has an integer value and the...
```python # coding:utf-8 import sys input = sys.stdin.readline INF = float('inf') MOD = 10 ** 9 + 7 def inpl(): return list(map(int, input().split())) def solve(N): A = inpl() dp = [INF] * (A[0] * 2) for i in range(A[0]//2, A[0]*2): dp[i] = abs(i - A[0]) / A[0] # A[0]の価格を変えたときのconfusion rati...
p02298 Is-Convex
For a given polygon g, print "1" if g is a convex polygon, "0" otherwise. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of the polygon. The line segment con...
```python from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inp(): return int(input()) def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) #############...
p02445 Swap
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and swap specified elements by a list of the following operation: * swapRange($b, e, t$): For each integer $k$ ($0 \leq k < (e - b)$, swap element $(b + k)$ and element $(t + k)$. Constraints * $1 \leq n \leq 1,000$ * $-1,000,000,0...
```python n = int(input()) num = list(map(int, input().split())) q = int(input()) for _ in range(q): b, e, t = map(int, input().split()) for i in range(e-b): num[b+i], num[t+i] = num[t+i], num[b+i] print(' '.join(str(n) for n in num)) ```
1012_B. Chemical table
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table. Recently scientists discovered that for every four...
```python class UnionFind: def __init__(self, n): self.par = [-1]*n self.rank = [0]*n def Find(self, x): if self.par[x] < 0: return x else: self.par[x] = self.Find(self.par[x]) return self.par[x] def Unite(self, x, y): x = self.Fi...
1037_B. Reach Median
You are given an array a of n integers and an integer s. It is guaranteed that n is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s. The median of the array with odd length is the ...
```python # -*- coding: utf-8 -*- # @Date : 2018-09-03 08:46:01 # @Author : raj lath (oorja.halt@gmail.com) # @Link : http://codeforces.com/contest/1037/problem/B # @Version : 1.0.0 import os from sys import stdin max_val=int(10e12) min_val=int(-10e12) def read_int() : return int(stdin.readline()) def re...
105_C. Item World
Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res). Each item belongs to one class. In this problem we will only consider three of such...
```python # written with help of failed tests def searchBest(iType, number, rType, countResidents): global items, equipped best = 0 ret = None for item, params in items.items(): if params[0] == iType: val = int(params[number]) if countResidents: for resid ...
1081_D. Maximum Distance
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago. You are given a connected undirected graph with n vertices and m weighted edges. There are k special vertices: x_1, x_2, …, x_k. Let's define the cost of the path as the maximum weight of the edges in it. And th...
```python """ @author: phamv """ ####Function Definition def find(x): while f[x] != x : f[x] = f[f[x]] x = f[x] return x def merge(u, v) : u, v = map(find, (u, v)) f[u] = v; if u == v: return False ret = s[u] > 0 and s[v] > 0 s[v] += s[u] return ret ###########...
1129_A2. Toy Train
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit afte...
```python #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 ...
1149_B. Three Religions
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The Word of Uni...
```python n, q = map(int, input().split()) s = '!' + input() nxt = [[n + 1] * (n + 2) for _ in range(26)] for i in range(n - 1, -1, -1): c = ord(s[i + 1]) - 97 for j in range(26): nxt[j][i] = nxt[j][i + 1] nxt[c][i] = i + 1 w = [[-1], [-1], [-1]] idx = lambda i, j, k: i * 65536 + j * 256 + k dp = ...
1189_A. Keanu Reeves
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem. Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa...
```python n = int(input()) s = str(input()) c = 0 for i in range(len(s)): if s[i]=='0': c+=1 else: c-=1 if c!=0: print("1"+ "\n" + s) else: print("2" + "\n" + s[0:-1],s[-1]) ```
1208_A. XORinacci
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: * f(0) = a; * f(1) = b; * f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de...
```python import sys from collections import defaultdict as dd from collections import deque from functools import * from fractions import Fraction as f from copy import * from bisect import * from heapq import * from math import * from itertools import permutations ,product def eprint(*args): print(*args, file=...
1227_A. Math Problem
Your math teacher gave you the following problem: There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], …, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l ≤ x ≤ r. The length of the segment [l; r] is equal to r - l. Two segments [a; b] and [c; d] have a common point (inters...
```python t = int(input()) for i in range(t): n = int(input()) x = [] y = [] for i in range(n): a, b = map(int, input().split()) x.append(a) y.append(b) if n == 1: print(0) elif min(y) > max(x): print(0) else: print(abs(max(x)-min(y))) ```
124_D. Squares
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is cons...
```python #!/usr/bin/python3 def cds(a, b, x, y): return (x + y) // (2 * a), (x - y) // (2 * b) def norm(x, y): return max(x, y) a, b, x1, y1, x2, y2 = map(int, input().split()) xp1, yp1 = cds(a, b, x1, y1) xp2, yp2 = cds(a, b, x2, y2) print(norm(abs(xp1 - xp2), abs(yp1 - yp2))) ```
1269_B. Modulo Equality
You are given a positive integer m and two integer sequence: a=[a_1, a_2, …, a_n] and b=[b_1, b_2, …, b_n]. Both of these sequence have a length n. Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [...
```python import sys input=sys.stdin.readline from collections import deque n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() b.sort() a=deque(a) b=deque(b) ans=0 for _ in range(n): if a==b: break f=1 for j in range(n-1): if b[j+1]-a[j+1]!=b[j]-a[j]: f=0 ...
1291_B. Array Sharpening
You're given an array a_1, …, a_n of n non-negative integers. Let's call it sharpened if and only if there exists an integer 1 ≤ k ≤ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: * The arrays [4], [0, 1], [...
```python t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) rok = True rrok = True if n == 2 and a[0] == 0 and a[1] == 0: print("No") else: if n%2 == 0: ar = [0]*n for i in range(n//2): ...
1311_C. Perform the Combo
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again. You know that you ...
```python from sys import stdin from bisect import bisect_left from collections import Counter for k in range(int(stdin.readline())): n,m=[int(x) for x in stdin.readline().split()] s=input() d=Counter(s) l=list(map(int,stdin.readline().split())) l.sort() ans=[0 for j in range(0,26)] for j in...
1334_A. Level Statistics
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level. All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases...
```python T=int(input()) list=[] c=-1 d=-1 for i in range(T): n=int(input()) k="Yes" for j in range(n): a,b=map(int,input().split()) if a>=b and c<=a and d<=b and (b-d)<=(a-c): g=0 else: k="No" c=a d=b c=-1 d=-1 list.append(k) for i in range(len(list)): print(list[i]) `...
1354_C2. Not So Simple Polygon Embedding
The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
```python # Why do we fall ? So we can learn to pick ourselves up. from math import pi,cos t = int(input()) for _ in range(0,t): n = int(input()) theta = pi/4 delta = pi/n maxi,mini,x = 0,0,0 for i in range(0,2*n): x += cos(theta) theta -= delta maxi = max(maxi,x) mi...
1374_B. Multiply by 2, divide by 6
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
```python t=int(input()) for i in range(t): n=int(input()) if n==1: print(0) else: if n%3!=0: print(-1) else: threes=0 twos=0 while n%3==0: threes+=1 n=n//3 while n%2==0: twos+...
1397_C. Multiples of Length
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can...
```python from sys import stdin def inp(): return stdin.buffer.readline().rstrip().decode('utf8') def itg(): return int(stdin.buffer.readline()) def mpint(): return map(int, stdin.buffer.readline().split()) # ############################## import # ############################## main # for __ in ran...
1420_D. Rescue Nibel!
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened. Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional de...
```python import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)] def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in...
1466_C. Canine poetry
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades. Orpheus, a famous poet, and musician plans to calm Cerberus with his poe...
```python import math t=int(input()) for i in range(t): s=input() s=list(s) l=len(s) if l==1: print(0) elif l==2: if s[0]==s[1]: print(1) else: print(0) else: j=0 c=0 while(j<l): if j==l-1: break ...
1490_D. Permutation Transformation
A permutation — is a sequence of length n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] — permutations, and [2, 3, 2], [4, 3, 1], [0] — no. Polycarp was recently gifted a permutation a[1 ... n] of length n. Polycarp likes trees more than permutations, s...
```python import sys input=sys.stdin.readline I = lambda : list(map(int,input().split())) t,=I() for _ in range(t): n,=I() l=I() an=[0]*n for i in range(n): x=y=0 j=i+1 x=l[i] while j<n: if l[j]>x: an[i]+=1 x=l[j] if l[j]==n: break j+=1 j=i-1 x=l[i] while j>-1: if l[j]>x: ...
167_C. Wizards and Numbers
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — a and b. The order of the numbers is not important. Let's consider a ≤ b for the sake of definiteness. The players can cast one of the two spells in turns: * Replace b with b - ak. Number k can be chosen by...
```python def solve(a, b): if a == 0: return False if solve(b % a, a): b //= a return not (b % (a + 1) & 1) return True n = int(input()) for _ in range(n): a, b = [int(x) for x in input().split()] if a > b: a, b = b, a if solve(a, b): print("First") ...
209_B. Pixels
Flatland is inhabited by pixels of three colors: red, green and blue. We know that if two pixels of different colors meet in a violent fight, only one of them survives the fight (that is, the total number of pixels decreases by one). Besides, if pixels of colors x and y (x ≠ y) meet in a violent fight, then the pixel t...
```python a = list(map(int,input().split())) def calc(a): return int((((a[1]-a[0])+(a[1]+a[0]))/2)) a.sort() if a[1] % 2 == 0 and a[0] % 2 == 0: print(calc(a)) elif a[1] % 2 == 0 or a[0] % 2 == 0: print(a[2]) else: print(calc(a)) ```
235_A. LCM Challenge
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th...
```python import sys, math input = sys.stdin.readline def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) import collections as col import m...
25_D. Roads not only in Berland
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way r...
```python ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College ''' from os import path import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,...
306_C. White, Black and White Again
Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to ta...
```python import sys MOD = int(1e9) + 9 def inv(n): return pow(n, MOD - 2, MOD) def combo(n): rv = [0 for __ in range(n + 1)] rv[0] = 1 for k in range(n): rv[k + 1] = rv[k] * (n - k) % MOD * inv(k + 1) % MOD return rv with sys.stdin as fin, sys.stdout as fout: n, w, b = map(int, nex...
378_C. Maze
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth...
```python import random, math, sys from copy import deepcopy as dc from bisect import bisect_left, bisect_right from collections import Counter input = sys.stdin.readline # Function to take input def input_test(): n, m, k = map(int, input().strip().split(" ")) grid = [] for i in range(n): grid.append(lis...
39_E. What Has Dirichlet Got to Do with That?
You all know the Dirichlet principle, the point of which is that if n boxes have no less than n + 1 items, that leads to the existence of a box in which there are at least two items. Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. T...
```python a, b, L = list(map(int, input().split())) memo = {} #10^9 rougly equals 31700 * 31700 memo[(31701, 1)] = ((L - 31701) + 1)% 2 #2**30 > 10^9 memo[(1, 30)] = -1 for i in range(31700, a - 1, -1): for j in range(29, b - 1, -1): if i**j>=L: continue s = set() if...
425_A. Sereja and Swaps
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation: <image> A swap operation is the following sequence of actions: * choose two indexes i, j (i ≠ j); * perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Serej...
```python #!/usr/local/bin/python3 n, k = map(int, input().split()) a = list(map(int, input().split())) r_sum = a[0] for l in range(n): for r in range(l, n): inside = sorted(a[l:r+1]) outside = sorted(a[:l] + a[r+1:], reverse=True) t_sum = sum(inside) for i in range(min(k, len(inside), len(outside))): if ou...
449_D. Jzzhu and Numbers
Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y deno...
```python import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) # zeta mebius def zeta_super(val, n): # len(val)==2^n out = val[:] for...
494_A. Treasure
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the ...
```python #!/usr/bin/env python3 s = input() count = 0 res = [] last = s.rfind("#") for i, c in enumerate(s): if c == '(': count += 1 elif c == ')': count -= 1 else: if i < last: res.append(1) count -= 1 else: num = max(1, 1 + s.count("("...
518_E. Arthur and Questions
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n. This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, ...
```python import sys n, k = map(int, input().split()) a = input().split() INF = 10 ** 9 + 7 OK = True for i in range(n): if a[i] == "?": a[i] = INF else: a[i] = int(a[i]) for i in range(len(a)): if a[i] == INF: j = i + k while j < len(a) and a[j] == INF: j += k...
544_E. Remembering Strings
You have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i....
```python from sys import stdin n,m=map(int,stdin.readline().strip().split()) s=[] for i in range(n): s.append(list(map(ord,list(stdin.readline().strip())))) for j in range(m): s[-1][j]=s[-1][j]-97 ct=[tuple(map(int,stdin.readline().strip().split())) for i in range(n)] mc=[[0 for i in range(22)] for j i...
571_B. Minimization
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n. You need to permute the array elements so that value <image> became minimal possible. In particular, it is allowed not to change order of elements at all. Input The first line contains two integers n,...
```python f = lambda: map(int, input().split()) n, k = f() p = sorted(f()) m, d = n // k, n % k u, v = d + 1, k - d + 1 g = [0] * u * v i = 0 for a in range(u): j = a * m + a - 1 for b in range(v): x = g[i - 1] + p[j] - p[j - m + 1] if b else 9e9 y = g[i - v] + p[j] - p[j - m] if a else 9e9 ...
614_C. Peter and Snow Blower
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
```python import math import sys def calculate_area(n, x, y, vertices): r_max = -sys.maxsize r_min = sys.maxsize last_d = -1 for v in vertices: d = distance_two_points(v, (x, y)) if d > r_max: r_max = d if d < r_min: r_min = d last_v = vertices[0] ...
687_A. NP-Hard Problem
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. <image> or <image>...
```python M=lambda:map(int,input().split()) n,m=M() graph=[set() for i in range(n)] for _ in range(m): a,b=M() graph[a-1].add(b-1) graph[b-1].add(a-1) visited=[-1 for i in range(n)] stack=[] for i in range(n): if visited[i]==-1 and len(graph[i])>0: visited[i]=True stack+=[i] whil...
730_G. Car Repair Shop
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order...
```python t, p = 1, [] for i in range(int(input())): l, d = map(int, input().split()) if t > l: for i, q in enumerate(p, 1): if q[0] <= l <= q[1] - d: p.insert(i, [l + d, q[1]]) q[1] = l break else: for q in p: ...
754_B. Ilya and tic-tac-toe game
Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making...
```python from sys import exit l1 = input() l2 = input() l3 = input() l4 = input() grid = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0]] cross = 0 dots = [] for i in range(0, 4): if l1[i] == ".": dots += [[0+2, i...
774_K. Stepan and Vowels
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa". Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowe...
```python import math from sys import stdin, stdout fin = stdin fout = stdout n = int(fin.readline().strip()) s = fin.readline().strip() ans = [] gl = frozenset({'a', 'e', 'i', 'y', 'o', 'u'}) met = False cdel = False for i in range(n): if i > 0: if s[i] != s[i - 1]: met = False ...
820_A. Mister B and Book Reading
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second —...
```python c,v0,v1,a,l = list(map(int, input().split(" "))) count=1 sum=v0 while sum<c: sum+=min(v0+count*a-l,v1-l) count+=1 print(count) ```
846_B. Math Show
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him tj minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order. By solving s...
```python n, k, m = list(map(int, input().split())) t = sorted(map(int, input().split())) res = 0 for x in range(min(m//sum(t),n)+1): rem = m - x*sum(t) r = x*(k+1) for i in range(k): div = min(rem//t[i], n-x) rem -= div*t[i] r += div res = max(res, r) print(res) ```
893_A. Chess For Three
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three. So they play with each other according to following rules: ...
```python num=int(input()) spectator=3 p1=1 p2=2 yes=True for i in range(0,num): winner=int(input()) if winner is spectator: print("NO") yes=False break if p1 is winner: temp=spectator spectator=p2 p2=temp else: temp=spectator spectator=p1 ...
937_D. Sleepy Game
Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't m...
```python n,m = map(int, input().split()) g = [[] for i in range(n)] fs = set() for i in range(n): a = list(map(int , input().split())) c = a[0] if c == 0: fs.add(i) continue for j in range(1,c+1): g[i].append(a[j]-1) s = int(input())-1 prev0 = [None for i in range(n)] prev1=[No...
990_B. Micro-World
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constan...
```python n, m = map(int, input().split()) l = sorted(map(int, input().split())) t, b = l[::-1], -m for a in l: while b < a: if a <= b + m: n -= 1 b = t.pop() print(n) ```
p02610 AIsing Programming Contest 2020 - Camel Train
We have N camels numbered 1,2,\ldots,N. Snuke has decided to make them line up in a row. The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise. Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel. Solve this probl...
```python import sys from heapq import heappush, heappop from operator import itemgetter sys.setrecursionlimit(10 ** 7) rl = sys.stdin.readline def solve(): N = int(rl()) res = 0 camel_left, camel_right = [], [] for _ in range(N): K, L, R = map(int, rl().split()) res += min(L, R) ...
p02741 Panasonic Programming Contest 2020 - Kth Term
Print the K-th element of the following sequence of length 32: 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51 Constraints * 1 \leq K \leq 32 * All values in input are integers. Input Input is given from Standard Input in the following format: K Output Print ...
```python n = [1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51] K = int(input()) print(n[K-1]) ```
p02876 AtCoder Grand Contest 040 - Balance Beam
We have N balance beams numbered 1 to N. The length of each beam is 1 meters. Snuke walks on Beam i at a speed of 1/A_i meters per second, and Ringo walks on Beam i at a speed of 1/B_i meters per second. Snuke and Ringo will play the following game: * First, Snuke connects the N beams in any order of his choice and m...
```python import sys input = sys.stdin.readline def gcd(a, b): while b: a, b = b, a % b return a N = int(input()) S = 0 Y = [] for i in range(N): a, b = map(int, input().split()) if b > a: S += b-a Y.append((b, b)) else: Y.append((a, b)) Y = sorted(Y) YY = [0] * (N+1) for i...
p03010 diverta 2019 Programming Contest 2 - Diverta City
Diverta City is a new city consisting of N towns numbered 1, 2, ..., N. The mayor Ringo is planning to connect every pair of two different towns with a bidirectional road. The length of each road is undecided. A Hamiltonian path is a path that starts at one of the towns and visits each of the other towns exactly once...
```python from itertools import combinations, permutations N = int(input()) # 整数列の生成 # s = [1] # while len(s) < 10 : # i = s[-1] + 1 # while True : # path = s.copy() + [i] # flag = True # for comb in combinations(s + [i], 2) : # if not sum(comb) in path : ...
p03150 KEYENCE Programming Contest 2019 - KEYENCE String
A string is called a KEYENCE string when it can be changed to `keyence` by removing its contiguous substring (possibly empty) only once. Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string. Constraints * The length of S is between 7 and 100 (inclusive). * S consists of lowerc...
```python S = input() k = "keyence" n = len(S)-7 for i in range(len(S)-n+1): if S[:i]+S[i+n:] == k: print("YES") break else: print("NO") ```
p03294 AtCoder Beginner Contest 103 - Modulo Summation
You are given N positive integers a_1, a_2, ..., a_N. For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N). Here, X\ mod\ Y denotes the remainder of the division of X by Y. Find the maximum value of f. Constraints * All values in input are integers. * 2 \leq N \leq 3000 * 2 ...
```python N=int(input()) S=sum(list(map(int,input().split(' ')))) print(S-N) ```
p03452 AtCoder Regular Contest 090 - People on a Line
There are N people standing on the x-axis. Let the coordinate of Person i be x_i. For every i, x_i is an integer between 0 and 10^9 (inclusive). It is possible that more than one person is standing at the same coordinate. You will given M pieces of information regarding the positions of these people. The i-th piece of...
```python def inpl(): return [int(i) for i in input().split()] def find(x): if par[x] == x: return x else: par[x],dist[x] = find(par[x]),dist[x]+dist[par[x]] return par[x] N, M = inpl() par = list(range(N+1)) dist = [0 for _ in range(N+1)] for _ in range(M): l, r, d = inpl() fl ...
p03612 AtCoder Beginner Contest 072 - Derangement
You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N. You can perform the following operation any number of times (possibly zero): Operation: Swap two adjacent elements in the permutation. You want to have p_i ≠ i for all 1≤i≤N. Find the minimum required number of operations to achieve this. Constraint...
```python N = int(input()) p = list(map(int, input().split())) p.append(0) cnt = 0 for i in range(N): if p[i] == i + 1: p[i], p[i+1] = p[i+1], p[i] cnt += 1 print (cnt) ```
p03940 AtCoder Grand Contest 007 - Shik and Game
Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a c...
```python import sys readline = sys.stdin.readline class Segtree: def __init__(self, A, intv, initialize = True, segf = max): self.N = len(A) self.N0 = 2**(self.N-1).bit_length() self.intv = intv self.segf = segf if initialize: self.data = [intv]*self.N0 + A + [i...
p00032 Plastic Board
There is a factory that inputs the data of the side and diagonal lengths to the machine and cuts out the plastic plate. At this factory, we cut out only parallelogram molds, although they vary in size. You have been ordered by your boss to count the number of rectangles and rhombuses produced among the parallelograms t...
```python rect = 0 loze = 0 while True: try: n, m, o = map(int, input().split(',')) if n ** 2 + m ** 2 == o ** 2: rect += 1 if n == m: loze += 1 except: print(rect) print(loze) break ```
p00163 Highway Toll
In 20XX, the Aizu Chuo Road, which has a total distance of 58km and 6 sections from Atsushiokanomachi, Kitakata City to Minamiaizucho, is scheduled to be completed and opened. For half a year after opening, the toll will be halved for vehicles that pass the departure IC or arrival IC between 17:30 and 19:30 and have a...
```python # Aizu Problem 00163: Highway Tooll # import sys, math, os, bisect # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input.txt", "rt") M = [[0, 300, 500, 600, 700,1350,1650], [6, 0, 350, 450, 600,1150,1500], [13, 7, 0, 250, 400,1000,1350], [18,...
p00320 Cuboid
The educational program (AHK Education) of the Aiz Broadcasting Corporation broadcasts a program called "Play with Tsukuro" for children. Today is the time to make a box with drawing paper, but I would like to see if the rectangular drawing paper I prepared can make a rectangular parallelepiped. However, do not cut or ...
```python lst = [set(map(int, input().split())) for _ in range(6)] rec = [] while lst: x = lst[0] count = lst.count(x) if count % 2 == 1: print("no") break rec.append((count, x)) for _ in range(count): lst.pop(lst.index(x)) else: if len(rec) == 1: if len(rec[0][1]) == 1: print("yes") ...
p00490 Best Pizza
problem Chairman K is a regular customer of the JOI pizza shop in the center of JOI city. For some reason, he decided to start a life-saving life this month. So he wanted to order the pizza with the highest calories per dollar among the pizzas he could order at the JOI pizza store. Let's call such a pizza the "best pi...
```python #C N = int(input()) A,B = map(int,input().split()) C = int(input()) T = [int(input()) for i in range(N)] T.sort(reverse=True) cal = C cost = A for t in T: if cal/cost < (cal+t)/(cost+B): cal+=t cost+=B else: break print(cal//cost) ```
p00676 KND is So Sexy
Problem KND is a student programmer at the University of Aizu. His chest is known to be very sexy. <image> For simplicity, the part of the skin that can be seen from the chest is represented by the isosceles triangle ABC in the figure. However, due to the slack in the clothes, the two sides AC and BC (where these l...
```python import math while True: try: a,l,x=map(int, input().split()) temp=(l+x)/2 except EOFError: break def heron(i,j,k): d = (i+j+k)/2 return math.sqrt(d*(d-i)*(d-j)*(d-k)) print((str(heron(a,l,l)+heron(l,temp,temp)*2))) ```
p00819 Unreliable Message
The King of a little Kingdom on a little island in the Pacific Ocean frequently has childish ideas. One day he said, “You shall make use of a message relaying game when you inform me of something.” In response to the King’s statement, six servants were selected as messengers whose names were Mr. J, Miss C, Mr. E, Mr. A...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split...
p00950 Infallibly Crack Perplexing Cryptarithm
Example Input ACM Output 0
```python from itertools import permutations base = "=+-*()01" s = input() l = len(s) mapping = {} counter = {} cnt = 0 for c in s: if c in base: continue if c not in mapping: mapping[c] = cnt cnt += 1 v = mapping[c] counter[v] = counter.get(v, 0) + 1 if cnt > 8: print(0) ...
p01353 Rabbit Plays Games!
A rabbit is playing a role-playing game. Just before entering the castle, he was ambushed by an enemy! It was a battle between one hero operated by a rabbit and n enemies. Each character has four stats, health hi, attack power ai, defense power di, and agility si. I = 0 is the information of the main character, 1 ≤ i ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) ha, aa, da, sa = map(int, readline().split()) ans = 0 S = [] for i in range(N): hi, ai, di, si = map(int, readline().split()) m0 = max(ai - da, 0) if si > sa: ...
p01835 Donut Decoration
Example Input 3 2 3 1 2 1 2 3 2 3 3 1 Output 1
```python import sys class Set: __slots__ = ["data", "one", "N", "N0", "size"] def __init__(self, N): self.data = [0]*(N+1) self.one = [0]*(N+1) self.N = N self.N0 = 2**(N.bit_length()-1) self.size = 0 def __get(self, k): s = 0 data = self.data ...
p01970 The Diversity of Prime Factorization
D: The Diversity of Prime Factorization Problem Ebi-chan has the FACTORIZATION MACHINE, which can factorize natural numbers M (greater than 1) in O ($ \ log $ M) time! But unfortunately, the machine could display only digits and white spaces. In general, we consider the factorization of M as p_1 ^ {e_1} \ times p_2 ...
```python from collections import defaultdict MAX = 1000000 ROOT = 1000 MOD = 1000000007 is_prime = [True] * (MAX + 1) is_prime[0] = is_prime[1] = False for i in range(2, ROOT + 1): if is_prime[i]: for j in range(i * i, MAX + 1, i): is_prime[j] = False n = int(input()) qlst = list(map(int, input().split())...
p02257 Prime Numbers
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7. Write a program which reads a list of N integers and prints the number of prime numbers in the list. Constraints 1 ≤ N ≤ 10000 2 ≤ an element of the ...
```python import math n = int(input()) count = 0 for i in range(n): t = int(input()) a = int(t ** (1 / 2)) end = 0 for j in range(2, a + 1): if t % j == 0: end = 1 break if end == 0: count += 1 print(count) ```
p02405 Print a Chessboard
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Constraints * 1 ≤ H ≤ 300 * 1...
```python while True: a,b = map(int, input().split()) if a==b == 0: break for i in range(a): s = "" for j in range(b): s += "#" if (i+j) % 2 == 0 else "." print(s) print("") ```
1030_E. Vasya and Good Sequences
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 10...
```python #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque impo...
1075_D. Intersecting Subtrees
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected su...
```python from collections import deque import sys t = int(input()) for i in range(t): n = int(input()) edge = {} for j in range(1,n+1): a = set() edge[j] = a for k in range(n-1): a,b = map(int,input().split()) edge[a].add(b) edge[b].add(a) k1 = int(input()) ...
1096_E. The Top Scorer
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are p players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability. They have just finished the...
```python base=998244353; def power(x, y): if(y==0): return 1 t=power(x, y//2) t=(t*t)%base if(y%2): t=(t*x)%base return t; def inverse(x): return power(x, base-2) f=[1] iv=[1] for i in range(1, 5555): f.append((f[i-1]*i)%base) iv.append(inverse(f[i])) def C(n, k): re...
1144_B. Parity Alternated Deletions
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
```python n=int(input()) arr=list(map(int,input().split())) arr.sort() even=[] odd=[] e=0 o=0 for i in arr: if (i%2)==0: even=even+[i] e=e+1 else: odd=odd+[i] o=o+1 if (e>o) and (e-o)>1: print(sum(even[:(e-o-1)])) elif (o>e) and (o-e)>1: print(sum(odd[:(o-e-1)])) else: print(0) ```
1165_A. Remainder
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
```python n,x,y = map(int,input().split()) s = input()[-x:] if(y == 0): num = s[:-(y+1)].count('1') else: num = s[:-(y+1)].count('1') + s[-y:].count('1') if(s[-(y+1)] == "0"): num = num + 1 print(num) ```
1202_C. You Are Given a WASD-string...
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: * 'W' — move one cell up; * 'S' — move one cell down; * 'A' — move one cell left; * 'D' — move one cell right. Let Grid(s) be the grid of minimum possibl...
```python def lim(s): now = 0 up, down = 0, 0 for i in s: now += i up = max(up, now) down = min(down, now) return up, down def f(a): return a[0] - a[1] + 1 def upg(s): t = lim(s) up, down = t[0], t[1] arr = [1, 1] now = 0 for i in range(len(s) - 1): ...
1244_C. The Football Season
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in ...
```python import sys from sys import argv def extendedEuclideanAlgorithm(old_r, r): negative = False s, old_t = 0, 0 old_s, t = 1, 1 if (r < 0): r = abs(r) negative = True while r > 0: q = old_r // r #MCD: r, old_r = old_r - q * r, r #Coefic...
1264_A. Beautiful Regional Contest
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n. Help the jury distrib...
```python '''input 5 12 5 4 4 3 2 2 1 1 1 1 1 1 4 4 3 2 1 1 1000000 20 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 32 64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11 ''' t=int(input()) for i in range(t): n=int(input()) s=list(map(int,input().split())) if n//2<3:...
1285_C. Fadi and LCM
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers. LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6. O...
```python def LMC(a, b): n = a * b while a != 0 and b != 0: if a > b: a = a % b else: b = b % a nod = a + b nok = n // nod return nok from math import sqrt, ceil n = int(input()) dividers = [] for i in range(1, ceil(sqrt(n))): if n % i == 0: div...
1304_E. 1-Trees and Queries
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree? Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wan...
```python import sys, os class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1...
1328_F. Make k Equal
You are given the array a consisting of n elements and the integer k ≤ n. You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: * Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ...
```python n, k = map(int, input().split()) a = sorted(list(map(int, input().split()))) cnt = dict() sum = dict() res = n * 20 for x in a: y = x cur = 0 while True: if y == 0: break if y not in cnt: cnt[y] = 0 sum[y] = 0 if cnt[y] < k: ...