name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
769_A. Year of University Entrance
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups f...
```python n = int(input()) a = list(map(int, input().split())) a.sort() if n % 2: print(a[n//2]) ```
793_A. Oleg and shares
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg...
```python n,k=map(int,input().split()) l=list(map(int,input().split())) K=min(l) for i in range(n): if (l[i]-K)%k!=0: print(-1) exit() Sum=sum(l) K=K*n Sum=Sum-K print(Sum//k) ```
813_D. Two Melodies
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. ...
```python import sys n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] dp = [[0]*n for _ in range(n)] maxnum = [0]*(10**5+10) ans = 0 for i in range(n): maxmod = [0]*7 for j in range(n): maxnum[a[j]] = 0 for j in range(i): maxnum[a[j]] = max(maxnum...
839_C. Journey
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them....
```python from queue import * n = int(input()) g = [[] for x in range(n)] for i in range(n-1): a, b = map(int, input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) used = [0]*n anw = 0 def solve(v, d, r): global anw q = Queue() q.put((v, d, r)) while not q.empty(): v, d, r = q.get(v) ...
908_G. New Year and Original Order
Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555. Given a number X, compute <image> modulo 109 + 7. Input The first line of input will contain the integer X (1 ≤ X ≤ 10700). Output Print a single integer, the answer to ...
```python # Problem G num = input() num_list = [] for i in range(len(num)): num_list.append(int(num[i])) myMod = (10 ** 9) + 7 length = len(num_list) f = [0] * (length + 1) t = [1] * (length + 1) for i in range(length): f[i+1] = (f[i] * 10 + 1) % myMod t[i+1] = (t[i] * 10) % myMod ans = 0 for i in range(1, 1...
930_A. Peculiar apple-tree
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch...
```python from collections import defaultdict,Counter,deque as dq from sys import stdin input=stdin.readline n=int(input()) g=defaultdict(list) w=list(map(int,input().strip().split())) for i in range(len(w)): g[w[i]-1].append(i+1) g[i+1].append(w[i]-1) # print(g) q=dq([0]) d=[-1]*(n) d[0]=1 cnt=defaultdict(int) cn...
984_A. Game
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t...
```python x = int(input()) l = [int(n) for n in input().split()] l.sort() i = 0 while len(l) > 1: if i % 2 == 0: l = l[0:len(l) - 1] else: l = l[1:len(l)] i = i + 1 print(l[0]) ```
p02569 AtCoder Library Practice Contest - Lazy Segment Tree
You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N. Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i. * T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i. * T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A...
```python import sys input = lambda: sys.stdin.readline().rstrip() class LazySegmentTree(): def __init__(self, init, unitX, unitA, f, g, h): self.f = f # (X, X) -> X self.g = g # (X, A, size) -> X self.h = h # (A, A) -> A self.unitX = unitX self.unitA = unitA self.f...
p02700 AtCoder Beginner Contest 164 - Battle
Takahashi and Aoki will have a battle using their monsters. The health and strength of Takahashi's monster are A and B, respectively, and those of Aoki's monster are C and D, respectively. The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ... Here, an attack decreases ...
```python a,b,c,d = map(int,input().split()) print('Yes' if (c+b-1)//b <= (a+d-1)//d else 'No') ```
p02829 AtCoder Beginner Contest 148 - Round One
Takahashi is solving quizzes. He has easily solved all but the last one. The last quiz has three choices: 1, 2, and 3. With his supernatural power, Takahashi has found out that the choices A and B are both wrong. Print the correct choice for this problem. Constraints * Each of the numbers A and B is 1, 2, or 3. * ...
```python A = int(input()) B = int(input()) print(1+2+3 -A-B) ```
p02966 AtCoder Grand Contest 036 - Negative Cycle
We have a weighted directed graph with N vertices numbered 0 to N-1. The graph initially has N-1 edges. The i-th edge (0 \leq i \leq N-2) is directed from Vertex i to Vertex i+1 and has a weight of 0. Snuke will now add a new edge (i → j) for every pair i, j (0 \leq i,j \leq N-1,\ i \neq j). The weight of the edge wi...
```python N = int(input()) A = [[0] * N for _ in range(N)] Al = [[0] * (N+1) for _ in range(N+1)] Ar = [[0] * (N+1) for _ in range(N+1)] for i in range(N) : a = [int(i) for i in input().split()] for j in range(N) : if i < j : A[i][j] = a[j-1] elif i > j : A[i][j] = ...
p03101 AtCoder Beginner Contest 121 - White Cells
There are H rows and W columns of white square cells. You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns. How many white cells will remain? It can be proved that this count does not depend on what rows and columns are chosen. Constraints * All values i...
```python #!/usr/bin/env python3 h, w, x, y = map(int, open(0).read().split()) print((h-x)*(w-y)) ```
p03249 AtCoder Regular Contest 103 - Distance Sums
You are given a sequence D_1, D_2, ..., D_N of length N. The values of D_i are all distinct. Does a tree with N vertices that satisfies the following conditions exist? * The vertices are numbered 1,2,..., N. * The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i. * For each vertex i, the sum of ...
```python #!/usr/bin/env python3 import sys sys.setrecursionlimit(101010) def dfs(v, adj_list, depth, visited): visited[v] = True x = depth for w in adj_list[v]: if not visited[w]: x += dfs(w, adj_list, depth + 1, visited) return x def solve(n, d): if n < 7: print(-...
p03400 AtCoder Beginner Contest 092 - Chocolate
Some number of chocolate pieces were prepared for a training camp. The camp had N participants and lasted for D days. The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on. As a result, there were X ...
```python n=int(input()) d,x=map(int,input().split()) a=[int(input()) for _ in range(n)] c=0 for ai in a: c+=1+(d-1)//ai print(c+x) ```
p03565 AtCoder Beginner Contest 076 - Dubious Document 2
E869120 found a chest which is likely to contain treasure. However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters. He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with `?`. One more t...
```python S = input() T = input() ls = len(S) lt = len(T) for i in range(ls-lt,-1,-1): for j in range(lt): if S[i+j] != T[j] and S[i+j] != '?': break else: print((S[:i] + T + S[i+lt:]).replace('?','a')) break else: print('UNRESTORABLE') ```
p03720 AtCoder Beginner Contest 061 - Counting Roads
There are N cities and M roads. The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally. There may be more than one road that connects the same pair of two cities. For each city, how many roads are connected to the city? Constraints * 2≤N,M≤50 * 1≤a_i,b_i≤N * a_i ≠ b_i * All input values a...
```python n,m = map(int,input().split()) l = [0]*n for i in range(0,m): for j in list(map(int,input().split())): l[j-1]+=1 for i in range(0,n): print(l[i]) ```
p03880 CODE FESTIVAL 2016 Grand Final(Parallel) - Cheating Nim
A cheetah and a cheater are going to play the game of Nim. In this game they use N piles of stones. Initially the i-th pile contains a_i stones. The players take turns alternately, and the cheetah plays first. In each turn, the player chooses one of the piles, and takes one or more stones from the pile. The player who ...
```python from functools import reduce from operator import xor N = int(input()) As = [int(input()) for _ in range(N)] dXORs = set([A ^ (A-1) for A in As]) XOR = reduce(xor, As) ans = 0 for i in reversed(range(30)): if XOR & (1<<i): d = ((1<<(i+1)) - 1) if d in dXORs: XOR ^= d ...
p04041 AtCoder Regular Contest 058 - Iroha and Haiku
Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order. Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences. Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many ...
```python from heapq import heappush, heappop from collections import deque,defaultdict,Counter import itertools from itertools import permutations,combinations import sys import bisect import string #import math #import time #import random def I(): return int(input()) def MI(): return map(int,input().split()) ...
p00122 Summer of Pyonkichi
The University of Aizu has a park covered with grass, and there are no trees or buildings that block the sunlight. On sunny summer days, sprinklers installed in the park operate to sprinkle water on the lawn. The frog Pyonkichi lives in this park. Pyonkichi is not good at hot weather, and on summer days when the sun is...
```python move = [[-1, 2], [0, 2], [1, 2], [-1, -2], [0, -2], [1, -2], [2, 1], [2, 0], [2, -1], [-2, 1], [-2, 0], [-2, -1]] spraing_range = [[-1, 1], [0, 1], [1, 1], [-1, 0], [0, 0], [1, 0], [-1, -1], [0, -1], [1, -1]] def main(): while True: px, ...
p00255 Salary for a Plumber
I am a pipe tie craftsman. As long as you get the joints and pipes that connect the pipes, you can connect any pipe. Every day, my master gives me pipes and joints, which I connect and give to my master. But if you have too many pipes, you can't connect them all in one day. Even in such a case, the master smiles and gi...
```python # -*- coding: utf-8 -*- """ Salary for a Plumber http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0260 """ import sys def solve(n): pipes = [int(p) for p in input().split()] joints = sorted([int(j) for j in input().split()]) total_length = sum(pipes) record = total_length * n w...
p00441 The Oldest Site
problem Once upon a time there were settlements and many people lived there. People built buildings of various shapes and sizes. But those buildings have already been lost, only the literature and the pillars found in the ruins. Was a clue to the location of the building. There is a description of the temple in the l...
```python def main(): while True: n = int(input()) if not n: break ps = [list(map(int,input().split())) for i in range(n)] dic = set() for t in ps: dic.add((t[0],t[1])) ans = 0 for i in range(n): for j in range(n): p1 = ps[i] p2 = ps[j] p1x = p1...
p00632 Ghost Buster!
The city is full of ghosts, something the average person doesn't know about. Most of them are harmless, but the trouble is that there are quite a few evil spirits that curse people. There was a girl who fought against such evil spirits. She goes to high school with a faceless face during the day, but at night she walk...
```python from collections import deque while True: h, w = map(int, input().split()) if h == 0: break mp = [list("X" + input() + "X") for _ in range(h)] mp.insert(0, ["X"] * (w + 2)) mp.append(["X"] * (w + 2)) for y in range(h + 2): for x in range(w + 2): if mp[y][x] == "A": ax, ay ...
p00776 Encryption System
Encryption System A programmer developed a new encryption system. However, his system has an issue that two or more distinct strings are `encrypted' to the same string. We have a string encrypted by his system. To decode the original string, we want to enumerate all the candidates of the string before the encryption....
```python from itertools import chain alph = "abcdefghijklmnopqrstuvwxyz" # s = input() def solve1(s): cands = [s] for c in reversed(alph[:-1]): cands = chain.from_iterable( [candidates(s, c) for s in cands] ) cands = list(cands) cands.sort() print(len(cands)) if l...
p00907 Find the Outlier
Professor Abacus has just built a new computing engine for making numerical tables. It was designed to calculate the values of a polynomial function in one variable at several points at a time. With the polynomial function f(x) = x2 + 2x + 1, for instance, a possible expected calculation result is 1 (= f(0)), 4 (= f(1)...
```python from itertools import combinations def build(X, Y): A = [] for x in X: res = 1 for xi in X: if x == xi: continue res *= x - xi A.append(Y[x] / res) return A def calc(X, A, x): base = 1 for xi in X: base *= i - xi ...
p01479 Chicken or the Egg
Time Limit: 8 sec / Memory Limit: 64 MB Example Input eggchickenegg Output egg
```python s=input() i=c=p=0;b='' while i<len(s): if s[i]==b: if c > p:r=b;p=c c=0 b=s[i] i+=[3,7][s[i]=='c'] c+=1 if c>p:r=b print(['chicken','egg'][r=='e']) ```
p02206 Prize
Prize Segtree entered a programming contest with a team of $ N $ and won a $ K $ yen prize! I'm trying to distribute this prize now. Each $ N $ team member, including Segtree, is numbered from $ 1 $ to $ N $ in order of ability. Segtree is $ 1 $. If the prize amount of $ i $'s teammate $ (i \ geq 2) $ is less than "...
```python n,k = map(int,input().split()) ok,ng = 0,k+1 while ng-ok>1: mid = (ng+ok)//2 s = 0 m = mid for i in range(n): s += m m //= 2 if m == 0: break if s <= k: ok = mid else: ng = mid print(ok) ```
p02360 The Maximum Number of Overlaps
Given a set of $N$ axis-aligned rectangular seals, find the number of overlapped seals on the region which has the maximum number of overlapped seals. Constraints * $ 1 \leq N \leq 100000 $ * $ 0 \leq x1_i < x2_i \leq 1000 $ * $ 0 \leq y1_i < y2_i \leq 1000 $ * $ x1_i, y1_i, x2_i, y2_i$ are given in integers Input ...
```python #!/usr/bin/env python3 # DSL_5_B: The Maximum Number of Overlaps from itertools import accumulate import sys if __name__ == '__main__': n = int(input()) ys = [0] * 1001 rects = [None] * 2 * n i = 0 for line in sys.stdin: x1, y1, x2, y2 = [int(j) for j in line.split()] r...
1045_B. Space Isaac
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a num...
```python import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) a = list(map(int, input().split())) + [0]*500000 ans_S = 0 a[n] = a[0] + m s = [0]*600600 for i in range(n): s[i] = a[i + 1] - a[i] s[n] = -1 for i in range(n): s[2*n - i] = s[i]...
1068_B. LCM
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa...
```python b=int(input()) out=[1] n=b i=0 while n%2==0: i=i+1 out.append(2**i) n=int(n/2) out1=[] for i in range (1,int(n**0.5)+1,2): if n%i==0: out1.append(i) out1.append(int(n/i)) out2=set() for i in out: for j in out1: out2.add(i*j) #print (out2) print (len(out2)) ``...
1139_A. Even Substrings
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9. A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some subs...
```python n = int(input()) s = input() k = 0 for i in range(1, n + 1): d = int(s[i - 1]) if d % 2 == 0: k += i print(k) ```
1157_B. Long Number
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi...
```python n = int(input()) a = list(input()) a = [int(x) for x in a] d = {} replacements = list(map(int, input().split())) for i in range(9): d[i+1] = replacements[i] b = [d[x] for x in a] ans = "" flag = False i = 0 j = 0 k = 0 for i in range(len(a)): if(a[i] >= b[i]): ans += str(a[i]) else: flag = True break...
1197_E. Culture Code
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i). You don't have much free spac...
```python from sys import stdin, stdout mod = 10**9+7 n = int(input()) dolls = [] for i in range(n): o, i = map(int, stdin.readline().split()) dolls.append((o, i)) dolls.sort() dolls = [(i, o) for (o, i) in dolls] #print(dolls) def bin_search(i): lo = -1 hi = n-1 while lo+1 < hi: mid = ...
1237_H. Balanced Reversals
You have two strings a and b of equal even length n consisting of characters 0 and 1. We're in the endgame now. To finally make the universe perfectly balanced, you need to make strings a and b equal. In one step, you can choose any prefix of a of even length and reverse it. Formally, if a = a_1 a_2 … a_n, you can ch...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.bu...
1256_A. Payment Without Change
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
```python from fractions import gcd from datetime import date, timedelta from heapq import* import math from collections import defaultdict, Counter, deque import sys from bisect import * import itertools import copy sys.setrecursionlimit(10 ** 7) MOD = 10 ** 9 + 7 def main(): q = int(input()) for i in range(...
127_A. Wasted Time
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers. Mr. Scrooge's signature can be represented as a polyline ...
```python n,k = list(map(int,input().split())) ans = 0 for i in range(n): if i==0: x,y= list(map(int,input().split())) else: X,Y = list(map(int,input().split())) d = ((X-x)**2+(Y-y)**2)**(1/2) x,y=X,Y ans += d ans=((ans*k)/50) print('%.9f'%ans) ```
1323_B. Count Subrectangles
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n × m formed by following rule: c_{i, j} = a_i ⋅ b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too. How many subrectangles of size (area) k con...
```python n, m, k = map(int, input().split()) def intervals(arr): res = [] curr = 0 for e in arr: if e == 1: ...
1342_A. Road To Zero
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
```python def to_list(s): return list(map(lambda x: int(x), s.split(' '))) def solve(x,y,a,b): cost = 0 if b <= 2*a: min_val = min(x,y) cost += b*min_val x -= min_val y -= min_val max_val = max(x,y) cost += max_val*a else: cost = (x+y)*a print...
1364_A. XXXXX
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several...
```python t = int(input()) for tc in range(t): n = int(input()) a = list(map(int, input().split())) s = set(a) print(len(s)) ```
1384_B2. Koa and the Beach (Hard Version)
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved. Koa the Koala is at the beach! The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the sho...
```python import sys import os,io input = sys.stdin.readline # input_all = sys.stdin.read # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # input_all = io.BytesIO(os.read(0,os.fstat(0).st_size)).read def read_int(): return map(int, input().split()) def read_list(): return list(map(int, input().split()))...
1405_D. Tree Tag
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
```python for t in range(int(input())): n, a, b, da, db = map(int, input().split()) graph = [set() for i in range(n + 1)] for i in range(n - 1): u, v = map(int, input().split()) graph[u].add(v) graph[v].add(u) visited = {1} last_visits = set() visit_now = {1} while len(visited) < n: while visit_now: ...
1426_F. Number of Subsequences
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?". Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and...
```python n=int(input()) s=input() a=[[0,0,0] for i in range(4)] k=s.count('?') b=[1] for i in range(k): b.append(b[i]*3%1000000007) for i in range(n): if s[i]=='a': a[0][0]+=1 elif s[i]=='b': a[0][1]+=a[0][0] a[1][1]+=a[1][0] elif s[i]=='c': a[0][2]+=a[0][1] a[1]...
1473_E. Minimum Path
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_...
```python import io import os # import __pypy__ def dijkstra(*args): # return dijkstraHeap(*args) # 2979 ms return dijkstraHeapComparatorWrong(*args) # 2823 ms # return dijkstraHeapComparator(*args) # 2370 ms # return dijkstraSegTree(*args) # 2417 ms with inf=float('inf), 2995 ms with inf=-1 ...
1521_E. Nastia and a Beautiful Matrix
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The...
```python def cheak(x): return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx for test in range(int(input())): m,k=(int(i) for i in input().split()) a=[int(i) for i in input().split()] mx=max(a) z=0;y=m*4 while z!=y: x=(z+y)//2 if cheak(x): y=x else: ...
1550_E. Stringforces
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark. You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized. Let f_i be the maximum length substring of str...
```python import sys input = sys.stdin.readline n, k = map(int, input().split()) s = input()[:-1] left, right = 0, n while left < right: mid = right - (right - left) // 2 A = [[0] * (n + 2) for _ in range(k)] for c in range(k): A[c][n] = A[c][n + 1] = n + 1 L = 0 for i in range(n -...
177_B1. Rectangular Game
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. ...
```python n=int(input()) r=n+1 i=2 s=n**0.5 while i<=s: if n%i==0: r+=n//i n//=i s=n**0.5 i=1 i+=1 print(r) ```
221_A. Little Elephant and Function
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: ...
```python n=int(input()) l=list(range(1,n+1)) l=sorted(l) l.insert(0,l[-1]) l.pop() print(*l) ```
245_B. Internet Address
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: * <protocol> can equal either "http" (without the quotes) or "ftp" (without the q...
```python s = input() if s[:3] == "ftp": pre = "ftp://" s = s[3:] elif s[:4] == "http": pre = "http://" s = s[4:] index = s[1:].index("ru")+1 if index == len(s)-2: s = pre+s[:index]+"."+s[index:] else: s = pre+s[:index]+"."+s[index:index+2]+"/"+s[index+2:] print(s) ```
26_E. Multithreading
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1 end repeat Here y is a shared variable. Everything else is local for the process. All actions on a given row are a...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w = map(int, input().split()) a = [0] + list(map(int, input().split())) total = sum(a) def ng(): print('No') exit() def ok(a): print('Yes') print(*a) exit() if ...
340_E. Iahub and Permutations
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the resea...
```python #lahub and Permutations import sys readline = sys.stdin.buffer.readline def even(n): return 1 if n%2==0 else 0 mod = 10**9+7 def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗) res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod ...
388_A. Fox and Box Accumulation
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For exampl...
```python I=lambda:list(map(int,input().split())) n,=I() l=I() l.sort() ans=0 i=0 k=1 while i<n: if l[i]<i//k: k+=1 i+=1 print(k) ```
408_D. Long Path
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (...
```python n = int(input()) a = list(map(int,input().split())) values = [0 for k in range(n)] for k in range(n) : back = a[k] if a[k] == k+1 : values[k] = 2 else : values[k] += 2 for t in range(a[k]-1,k) : values [k] += values[t] values[k] %= int(1e9 +7...
459_A. Pashmak and Garden
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al...
```python #!/usr/bin/env python3 import atexit import io import sys import bisect _I_B = sys.stdin.read().splitlines() input = iter(_I_B).__next__ _O_B = io.StringIO() sys.stdout = _O_B @atexit.register def write(): sys.__stdout__.write(_O_B.getvalue()) def main(): x1,y1,x2,y2=map(int,input().split()) i...
47_E. Cannon
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is di...
```python import sys from array import array # noqa: F401 from math import pi, sin, cos from bisect import bisect_left def input(): return sys.stdin.buffer.readline().decode('utf-8') n, v = map(int, input().split()) v = float(v) alpha = [float(input()) for _ in range(n)] m = int(input()) wall = sorted(tuple(ma...
554_A. Kyoya and Photobooks
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
```python s = input() l = list(s) a = 'abcdefghijklmnopqrstuvwxyz' for i in range(len(s)+1): for j in a: l.insert(i, j) print(len(l)-2*len(s)) ```
624_B. Making a String
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: * the i-th letter occurs in the string no more than ai times; * the number of occurrences of each letter in the string must be distinct for all the lette...
```python n = int(input()) m = list(map(int, input().split())) m.sort(reverse = True) ans = m[0] last = m[0] for i in range(1, len(m)): last = max(min(last - 1, m[i]), 0) ans += last print(ans) ```
672_D. Robin Hood
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to t...
```python import sys sys.stderr = sys.stdout def hood(n, k, C): C.sort() m, r = divmod(sum(C), n) m1 = (m + 1) if r else m c_lo = C[0] k_lo = k for i, c in enumerate(C): if c_lo == m: break c_m = min(c, m) dc = c_m - c_lo dk = i * dc if k_lo...
763_B. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different...
```python n = int(input()) coordinates = [] for i in range(n): coordinates.append([int(x) % 2 for x in input().split()]) print('YES') for coordinate in coordinates: x1, y1, x2, y2 = coordinate print(2*x2 + y2 + 1) ```
808_C. Tea Party
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w ≤ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that: * Every cup will contain tea for at least hal...
```python import math import re n, w = map(int, input().split()) a = list(map(int, input().split())) a1 = [math.ceil(el/2) for el in a] s = w - sum(a1) if s < 0: print(-1) elif s == 0: print(' '.join(map(str, a1))) else: for i in range(n): if a[i] == 1: a1[i] = 0 a[i] = 0...
832_D. Misha, Grisha and Underground
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other. The boys decided to have fun and came up with a plan. Namely, in some day in the morning M...
```python import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mo...
853_B. Jury Meeting
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for...
```python from bisect import * from sys import * n,m,k=[int(i) for i in input().split()] pln=[] if m==0: print(-1) exit(0) for i in range(m): pln.append([int(i) for i in input().split()]) pln.sort() grp=[[pln[0]]];gt=0; for i in range(1,m): if pln[i][0]!=pln[i-1][0]: gt=gt+1 grp.append(...
877_F. Ann and Books
In Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems. Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price. Ann decided that she wants to buy such non-empty subsegment t...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" no...
901_B. GCD of Polynomials
Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way: <image> This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder o...
```python """ NTC here """ import sys inp= sys.stdin.readline input = lambda : inp().strip() flush= sys.stdout.flush # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(2**25) def iin(): return int(input()) def lin(): return list(map(int, input().split())) # range = xrange # input = raw_input d...
952_A. Quirky Quantifiers
Input The input contains a single integer a (10 ≤ a ≤ 999). Output Output 0 or 1. Examples Input 13 Output 1 Input 927 Output 1 Input 48 Output 0
```python b=int(input()) if b%2==0: print(0) else: print(1) ```
979_C. Kuro and Walking Route
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choos...
```python def calculate_max_paths(edges, node, dest, par, cnt): ans = 1 for child in edges.get(node, []): if child != par: ans += calculate_max_paths(edges, child, dest, node, cnt) if dest == node: cnt[0] = ans return ans def main(): from collections import defaul...
999_D. Equalize the Remainders
You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n. In a single move, you can choose any position i between 1 and n and increase a_i by 1. Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by ...
```python from collections import deque import sys input = sys.stdin.readline n, m = map(int, input().split()) a = list(map(int, input().split())) cnt = [0] * m x = [[] for _ in range(m)] for i in range(n): ai = a[i] % m cnt[ai] += 1 x[ai].append(i) l = n // m q = deque() for i in range(m): if cnt[i] <...
p02534 ACL Beginner Contest - Repeat ACL
You are given an integer K. Print the string obtained by repeating the string `ACL` K times and concatenating them. For example, if K = 3, print `ACLACLACL`. Constraints * 1 \leq K \leq 5 * All values in input are integers. Input Input is given from Standard Input in the following format: K Output Print the s...
```python K=int(input()) print("ACL"*K) ```
p02666 NOMURA Programming Competition 2020 - Urban Planning
There are N towns numbered 1, 2, \cdots, N. Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns. In the planning of construction, each town chooses one town different from itself and requests the following: roads are built...
```python def modfac(n, MOD): f = 1 factorials = [1] for m in range(1, n + 1): f *= m f %= MOD factorials.append(f) inv = pow(f, MOD - 2, MOD) invs = [1] * (n + 1) invs[n] = inv for m in range(n, 1, -1): inv *= m inv %= MOD invs[m - 1] = inv ...
p02795 Keyence Programming Contest 2020 - Painting
We have a grid with H rows and W columns, where all the squares are initially white. You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions: * Choose one row, then paint all the squares in that row black. * Choose one column, then paint all the s...
```python h = int(input()) w = int(input()) n = int(input()) print(min([(n+h-1)//h, (n+w-1)//w])) ```
p02931 Japanese Student Championship 2019 Qualification - Card Collector
There are N cards placed on a grid with H rows and W columns of squares. The i-th card has an integer A_i written on it, and it is placed on the square at the R_i-th row from the top and the C_i-th column from the left. Multiple cards may be placed on the same square. You will first pick up at most one card from eac...
```python import sys readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) N,H,W = map(int,readline().split()) RCA = [tuple(int(x) for x in line.split()) for line in readlines()] RCA.sort(key = lambda x: -x[2]) RCA root = list(range(H+W)) size = [0] * (H+W) no_cy...
p03067 Tenka1 Programmer Beginner Contest 2019 - On the Way
There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively. Print `Yes` if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print `No` otherwise. Constraints * 0\leq A,B,C\leq 100 * A, B and C are distinct integers. I...
```python a, b, c = map(int, input().split()) if (c-a)*(c-b) < 0: print("Yes") else: print("No") ```
p03210 AtCoder Beginner Contest 114 - 753
Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children. Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time? Constraints * 1 ≤ X ≤ 9 * X is an integer. Input Input is given from...
```python a=int(input()) print('YES' if a in [3,5,7] else 'NO') ```
p03359 AtCoder Beginner Contest 096 - Day of Takahashi
In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year. For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year. In this country, a date is called Takahashi when the month and the day are equal as numbers. For exam...
```python a, b = map(int, input().split()) print(a if (a <= b) else a - 1) ```
p03517 CODE FESTIVAL 2017 Elimination Tournament Round 2 (Parallel) - Colorful MST
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i. Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in whic...
```python class Unionfindtree: def __init__(self, number): self.par = [i for i in range(number)] self.rank = [0] * (number) def find(self, x): # 親を探す if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] ...
p03680 AtCoder Beginner Contest 065 - Trained?
Takahashi wants to gain muscle, and decides to work out at AtCoder Gym. The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It ...
```python n=int(input()) l=[int(input()) for i in range(n)] a=1 ans=0 while a!=2: a=l[a-1] ans+=1 if ans==n+1: ans=-1 break print(ans) ```
p03835 AtCoder Beginner Contest 051 - Sum of Three Integers
You are given two integers K and S. Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K. How many different assignments of values to X, Y and Z are there such that X + Y + Z = S? Constraints * 2≤K≤2500 * 0≤S≤3K * K and S are integers. Input The input is given from Standard Input in the following for...
```python k,s=map(int,input().split());r=range;print(sum(1for x in r(k+1)for y in r(k+1)if 0<=s-x-y<=k)) ```
p04000 AtCoder Beginner Contest 045 - Snuke's Coloring
We have a grid with H rows and W columns. At first, all cells were painted white. Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column. Compute the following: * For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the gr...
```python from collections import defaultdict H,W,N=map(int,input().split()) ans=[(H-2)*(W-2)]+[0]*9 blacks=defaultdict(int) for i in range(N): a, b = map(int,input().split()) for dx in [-1,0,1]: for dy in [-1,0,1]: if 2<=a+dx<H and 2<=b+dy<W: ans[blacks[(a+dx,b+dy)]]-=1 ans[blacks[(a+dx,...
p00088 The Code A Doctor Loved
Dr .: Peter, I've finally done it. Peter: What's wrong, Dr. David? Is it a silly invention again? Dr .: This table, this table. | Character | Sign --- | --- (Blank) | 101 '| 000000 , | 000011 -| 10010001 . | 010001 ? | 000001 A | 100101 B | 10011010 | Character | Sign --- | --- C | 0101 D | 0001 E | 110 F | 01001 G |...
```python # Aizu Problem 0088: The Code A Doctor Loved # import sys, math, os # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input.txt", "rt") def bin5(k): b = bin(k)[2:] while len(b) < 5: b = '0' + b return b CODE1 = {' ': '101', "'": '000000', ","...
p00220 Binary Digit A Doctor Loved
"What are your shoe sizes?" Suddenly, the doctor asked me when I met him for the first time. "It's 23.5" "Oh, that's a really nice number. It's 2 to the 4th power plus 2 to the 2nd power, 2 to the 1st power, 2 to the 0th power, and 2 to the 1st power." Then the doctor asked. "You, how tall are you?" "Yes, it's 158....
```python def ans(N): # N:foat n=int(N) d=N-n ans_l=bin(n)[2:] ans_r='' for _ in range(4): ans_r+=str(int(d*2)) d=d*2-int(d*2) if n>=256 or d!=0: return 'NA' else: return '0'*(8-len(ans_l))+ans_l+'.'+ans_r while True: INP=float(input()) if INP<0: brea...
p00382 Taxi
PCK Taxi in Aizu city, owned by PCK company, has adopted a unique billing system: the user can decide the taxi fare. Today as usual, many people are waiting in a queue at the taxi stand in front of the station. In front of the station, there are $N$ parking spaces in row for PCK taxis, each with an index running from ...
```python from heapq import heappush, heappop def main(): n = int(input()) que = [] for i in range(n): lst = sorted(list(map(int, input().split()))[1:], reverse=True)[:i+1] heappush(que, lst[-1]) for v in lst[:-1]: heappush(que, v) heappop(que) print(sum(que)) main() ```
p00598 Operations with Finite Sets
Let A, B, C, D, E be sets of integers and let U is a universal set that includes all sets under consideration. All elements in any set are different (no repetitions). u - union of two sets, AuB = {x ∈ U : x ∈ A or x ∈ B} is the set of all elements which belong to A or B. i - intersection of two sets, AiB = {x ∈ U : x...
```python import sys def rpn(str): r = [] stack = [] for i in range(0, len(str)): c = str[i] if c in "idsu": while len(stack) > 0: if stack[-1] in "idsuc": a = stack.pop() r.extend(a) else: ...
p00734 Equal Total Scores
Taro and Hanako have numbers of cards in their hands. Each of the cards has a score on it. Taro and Hanako wish to make the total scores of their cards equal by exchanging one card in one's hand with one card in the other's hand. Which of the cards should be exchanged with which? Note that they have to exchange their ...
```python while True: n,m = map(int,input().split()) if n == 0: exit() t = [] h = [] ans = [] for i in range(n): t.append(int(input())) for i in range(m): h.append(int(input())) for i in range(n): for j in range(m): if (sum(t) - t[i] + h[j]) ==...
p00874 Cubist Artwork
International Center for Picassonian Cubism is a Spanish national museum of cubist artworks, dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed in front of the facade of the museum building. The artwork is a collection of cubes that are piled up on the ground and is intended...
```python while True: w,d = map(int,input().split()) if w == 0 and d == 0: break h = list(map(int,input().split())) m = list(map(int,input().split())) hl = [0] * 30 ml = [0] * 30 for i in h: hl[i] += 1 for i in m: ml[i] += 1 ans = 0 for i in range(30...
p01137 Space Coconut Grab
Space Coconut Crab Space coconut crab English text is not available in this practice contest. Ken Marine Blue is a space hunter who travels through the entire galaxy in search of space coconut crabs. The space coconut crab is the largest crustacean in the universe, and it is said that the body length after growth is...
```python import math def solve(e): k = 2 ** 32 for z in range(100, -1, -1): z3 = z * z * z if z3 > e: continue e2 = e - z3 ylm = int(math.sqrt(e2)) xzlm = 3 * z * z + 3 * z + 1 for y in range(ylm, -1, -1): y2 = y * y if e2 ...
p01752 Prowler
Mr. A and Mr. B live in an N × M rectangular grid area. Each square is either a road, a wall, or a house. Since this area is famous for the frequent occurrence of molestation damage due to the complicated and intricate roads, the boundary between this area and the outside is completely surrounded by walls and isolated....
```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 = 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 ...
p01892 SNS
Problem statement AOR Ika-chan is in a bad mood lately. Apparently, I don't like the ratio of the number of followers to the number of followers of "Ikatta". Currently, AOR Ika-chan has $ A $ followers, $ B $ followers, and a ratio of $ A: B $. Therefore, AOR Ika decided to increase or decrease the number of follower...
```python a, b, n = map(int, input().split()) score = abs(a - b) for x in range(1, n + 1): for y in range(1, n + 1): if b * x % y == 0: new_a = b * x // y score = min(score, abs(a - new_a)) print(score) ```
p02312 Intersection of a Circle and a Polygon
Find the area of intersection between a circle $c$ and a polygon $g$. The center coordinate of the circle is ($0, 0$). The polygon $g$ is represented by a sequence of points $p_1$, $p_2$,..., $p_n$ where line segments connecting $p_i$ and $p_{i+1}$ ($1 \leq i \leq n−1$) are sides of the polygon. The line segment conne...
```python import cmath import itertools import math from collections import defaultdict INF = float("inf") PI = cmath.pi TAU = cmath.pi * 2 EPS = 1e-10 class Point: """ 2次元空間上の点 """ # 反時計回り側にある CCW_COUNTER_CLOCKWISE = 1 # 時計回り側にある CCW_CLOCKWISE = -1 # 線分の後ろにある CCW_ONLINE_BACK = 2 # 線分の前にある CCW_ONLINE_FRO...
p02460 Map: Delete
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique. * insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. * get($key$): Print the value with the specified $...
```python import sys d = {} input() for q in sys.stdin: q = q.split() if q[0] == '0': d[q[1]] = q[2] elif q[0] == '1': print(d.get(q[1], 0)) else: if q[1] in d: del d[q[1]] ```
1004_D. Sonya and Matrix
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit. Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers ...
```python def get(n,m,a,b,t): freq=[0]*(t+1) for i in range(n): for j in range(m): val=abs(i-a)+abs(j-b) freq[val]+=1 return freq t=int(input()) a=list(map(int,input().split())) mx=max(a) f=[0]*(t+1) for i in a: f[i]+=1 b=1 for i in range(1,mx+1): if f[i]!=4*i: ...
1028_D. Order book
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price. At every moment of time, every SELL offer has higher price than every BUY offer. In th...
```python from sys import stdin import heapq MOD = pow(10, 9) + 7 n=int(stdin.readline()) a=[] for i in range(n): x=stdin.readline().split() if x[0]=='ADD': a.append((0,int(x[1]))) else: a.append((1,int(x[1]))) next_accept=[-1]*n accept = -1 for i in range(n-1, -1, -1): if a[i][0]== 1: ...
1092_D2. Great Vova Wall (Version 2)
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches. The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th par...
```python n=int(input()) a=list(map(int,input().split())) down=[] good=True for guy in a: if len(down)==0: down.append(guy) elif down[-1]>guy: down.append(guy) elif down[-1]==guy: down.pop() else: good=False break if not good: print("NO") elif len(down)>1: ...
1111_C. Creative Snap
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base. Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the...
```python def solve (l,r,y) : if (len(y) == 0) : return a if (l == r) : return b*len(y) c = [] d = [] m = (l+r)//2 for i in y : if i <= m : c += [i] else : d += [i] return min(b*(r-l+1)*len(y) , solve(l,m,c) + solve(m+1,r,d)) n,k,a...
1141_A. Game 23
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves. Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so. It is easy to prove that any way to trans...
```python def fun(a,b): if a % b != 0: return -1 temp = 0 m = a/b while m % 2 == 0: m = m / 2 temp += 1 while m % 3 == 0: m = m/3 temp += 1 if m == 1: return temp else : return -1 a,b = map(int,input().split()) print(fun(b,a)) ```
1217_C. The Number Of Good Substrings
You are given a binary string s (recall that a string is binary if each character is either 0 or 1). Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4. The substring s_{...
```python #!/usr/bin/env python3 #Educational Codeforces Round 72 C import sys import math import bisect sys.setrecursionlimit(1000000000) from heapq import heappush, heappop,heappushpop from collections import defaultdict from itertools import accumulate from collections import Counter from collections import deque f...
1260_A. Heating
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house. Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but ...
```python n=int(input()) for i in range(n): x = list(map(int, input().split(" "))) print(((x[1]%x[0])*((x[1]//x[0]+1)**2))+(((x[1]//x[0])**2)*(x[0]-(x[1]%x[0])))) ```
1282_B1. K for the Price of One (Easy Version)
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store...
```python """ Author : thekushalghosh Team : CodeDiggers """ import sys,math input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(s[:len(s) ...
1326_B. Maximums
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0. For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}. Then, she calculated an array, b_1, b_2, …, b_n: ...
```python input() b = list(map(int,input().split())) a = list() sumnum = 0 negnum = 0 for i in range(len(b)): sumnum += b[i] a.append(sumnum+abs(negnum)) if b[i]<0: negnum += b[i] print(*a) ```
1345_A. Puzzle Pieces
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below. <image> The jigsaw puzzle is considered solved if the following conditions hold: 1. The pieces are arranged into a grid with n rows and m columns. 2. For any two pieces that sh...
```python import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log2, ceil from collections import defaultdict from bisect import bisect_left as bl, bisect_right as br from collections import Counter from collections import deque ip = lambda : int(stdin.readline()) inp ...
1408_G. Clusterization Counting
There are n computers in the company network. They are numbered from 1 to n. For each pair of two computers 1 ≤ i < j ≤ n you know the value a_{i,j}: the difficulty of sending data between computers i and j. All values a_{i,j} for i<j are different. You want to separate all computers into k sets A_1, A_2, …, A_k, suc...
```python # import itertools as it # import functools as ft import math teststring = """4 0 3 4 6 3 0 2 1 4 2 0 5 6 1 5 0 """ online = __file__ != "/home/jhli/py/Grakn/Problem_G2.py" true, false = True, False if True: def spitout(): for c in teststring.splitlines(): yield c _ito = spito...
142_A. Help Farmer
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simple...
```python import math n = int(input()) mx = 0 mn = 4 * 10**18 for A in range(1, n+1): if A * A * A > n: break if n % A: continue nn = n // A for B in range(1, nn+1): if B * B > nn: break if nn % B: continue C = nn // B mn = min(mn, (A + 1) * (B + 2) * (C + 2) - n) mx = max(mx, (A + 1) * (B +...
1452_E. Two Editorials
Berland regional ICPC contest has just ended. There were m participants numbered from 1 to m, who competed on a problemset of n problems numbered from 1 to n. Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to exactly k consecutive tasks of the proble...
```python # Enter your code here. Read input from STDIN. Print output to STDOUT# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io ...