name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p03922 CODE FESTIVAL 2016 Final (Parallel) - Pair Cards
Takahashi is playing with N cards. The i-th card has an integer X_i on it. Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions: * The integers on the two cards are the same. * The sum of the integers on the two cards is a multiple of M. Find the maximum numb...
```python import math N, M = map(int, input().split()) X = list(map(int, input().split())) mod_arr = [{} for i in range(M)] for x in X: d = mod_arr[x % M] if x in d: d[x] += 1 else: d[x] = 1 ans = 0 if M == 1: print(N // 2) exit() def calc_only_one(d): sum_v = sum(d.values()) ...
p00023 Circles Intersection
You are given circle $A$ with radius $r_a$ and with central coordinate $(x_a, y_a)$ and circle $B$ with radius $r_b$ and with central coordinate $(x_b, y_b)$. Write a program which prints: * "2" if $B$ is in $A$, * "-2" if $A$ is in $B$, * "1" if circumference of $A$ and $B$ intersect, and * "0" if $A$ and $B$ do not...
```python n = int(input()) for _ in range(n): xa, ya, ra, xb, yb, rb = map(float, input().split()) dist = ((xa - xb)**2 + (ya - yb)**2)**.5 if ra + rb < dist: print('0') elif abs(ra - rb) <= dist: print('1') elif (rb < ra): print('2') elif (ra < rb): print('-2') ...
p00154 Sum of Cards
Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxu...
```python import sys readline = sys.stdin.readline write = sys.stdout.write ans = [] while 1: M = int(readline()) if M == 0: break P = [list(map(int, input().split())) for i in range(M)] memo = {} def dfs(i, rest): if i == M: return rest == 0 key = (i, rest) ...
p00311 Fishing Competition
The brothers Hiroshi and Kenjiro came to Lake Inawashiro for fishing. The two decided to score as follows and compete with the total score of the fish they caught. * One char is a point * One yamame trout b points * Add c points for every 10 chars * Add d points for every 20 yamame trout Create a program to determi...
```python def main(): h1, h2 = map(int, input().split()) k1, k2 = map(int, input().split()) a, b, c, d = map(int, input().split()) hiroshi = h1 * a + int(h1 / 10) * c + h2 * b + int(h2 / 20) *d kenjiro = k1 * a + int(k1 / 10) * c + k2 * b + int(k2 / 20) *d if hiroshi > kenjiro: print('...
p00475 Exposition
problem JOI City will hold a large-scale exposition. There are two themes for this exposition, and each of the N exhibition facilities in JOI City will exhibit on one of the two themes. The location of the facility is represented by plane coordinates (x, y). To move from the facility at position (x, y) to the facili...
```python # AOJ 0552: Exposition # Python3 2018.7.1 bal4u import sys from sys import stdin input = stdin.readline x, y = [], [] n = int(input()) for i in range(n): a, b = map(int, input().split()) x.append(a+b) y.append(a-b) xmin, xmax = min(x), max(x) ymin, ymax = min(y), max(y) ans1 = ans2 = 0 for i in range(n):...
p00667 11224111122411
My arm is stuck and I can't pull it out. I tried to pick up something that had rolled over to the back of my desk, and I inserted my arm while illuminating it with the screen of my cell phone instead of a flashlight, but I accidentally got caught in something and couldn't pull it out. It hurts if you move it forcibly....
```python def f3(n): a=b=c=0 for _ in range(n): a,b,c=(a+b+c+1)%100000007,a,b return a def f5(n): a=b=c=d=e=0 for _ in range(n): a,b,c,d,e=(a+b+c+d+e+1)%100000007,a,b,c,d return a while 1: s=input() if s=="#":break ans=1 num="_" cnt=1 for n in s+"_":...
p00810 Super Star
During a voyage of the starship Hakodate-maru (see Problem A), researchers found strange synchronized movements of stars. Having heard these observations, Dr. Extreme proposed a theory of "super stars". Do not take this term as a description of actors or singers. It is a revolutionary theory in astronomy. According to...
```python def distance(star, position): return sum([(a - b)**2 for a, b in zip(star, position)])**(1 / 2) def difference(star, position): return [(a - b) for a, b in zip(star, position)] while True: n = int(input()) if n == 0: break stars = [list(map(float, input().split())) for i in ran...
p00941 Do Geese See God?
Example Input crc 1 Output crc
```python from heapq import heappush, heappop def solve(): S = input() K = int(input()) L = len(S) INF = 10**9 cost = [[INF]*(L+1) for i in range(L+1)] cost[0][L] = 0 ss = [] que = [(0, 0, L)] while que: d, a, b = heappop(que) if cost[a][b] < d: continue ...
p01074 Unhappy Class
Problem Yamano Mifune Gakuen's 1st grade G group is a class where female students carrying misfortune gather. They face various challenges every day with the goal of being happy. In their class, they can take practical happiness courses as part of the test of happiness. From Monday to Friday, there are classes from 1...
```python from itertools import product n, m, l = map(int, input().split()) subjects = [[] for _ in range(5)] for _ in range(m): d, a, k, t = map(int, input().split()) subjects[d].append((a, a + k - 1, t)) for i in range(5): subjects[i].sort(key=lambda x:x[1]) #各曜日の科目数ごとの最大幸福 def calcDp(i): #dp[y][x...
p02248 String Search
Find places where a string P is found within a text T. Print all indices of T where P found. The indices of T start with 0. Constraints * 1 ≤ length of T ≤ 1000000 * 1 ≤ length of P ≤ 10000 * The input consists of alphabetical characters and digits Input In the first line, a text T is given. In the second line, a s...
```python s=input();t=input() [print(x) for x in range(len(s)-len(t)+1) if s[x:x+len(t)]==t] ```
p02396 Print Test Cases
In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets. Write a program which reads an integer x and print it as is. Note that multiple datasets are give...
```python i = 0 while True: n = int(input()) i += 1 if n == 0: break print("Case {}: {}".format(i, n)) ```
1015_B. Obtaining the String
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n. You can successively perform the following move any number of times (possibly, zero): * swap any two adjacent (neighboring) characters of s (i.e. for any i = ...
```python n = int(input()) s = input() t = input() if s == t: print(0) elif sorted(s) != sorted(t): print(-1) else: res = list() ls = list(s) lt = list(t) for i in range(n): if ls[i] != lt[i]: pos = ls.index(lt[i], i+1) j = pos-1 while j >= i: ...
1038_F. Wrap Around
You are given a binary string s. Find the number of distinct cyclical binary strings of length n which contain s as a substring. The cyclical string t contains s as a substring if there is some cyclical shift of string t, such that s is a substring of this cyclical shift of t. For example, the cyclical string "00011...
```python n=int(input()) s=[c=='1' for c in input()] m=len(s) z=[[0,0]] for c in s: ind = z[-1][c] z[-1][c] = len(z) z.append(z[ind][:]) assert(len(z) == m+1) z[m][0] = z[m][1] = m # make it sticky # how many things match directly dp = [0 for _ in range(m+1)] dp[0] = 1 for i in range(n): ndp = [0 for _ in range(m+...
1061_B. Views Matter
You came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface. The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m. There is a camera on the cei...
```python n,m=map(int,input().split(' ')) a=list(map(int,input().split(' '))) a.sort() count=0 prev=0 for i in range(n): count+=1 if a[i]>prev: prev+=1 count+=a[n-1]-prev print(sum(a)-count) ```
1083_A. The Fair Nut and the Best Path
The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the pat...
```python import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) adj = [[] for i in range(n)] for i in range(n-1): u, v, w = map(int, input().split()) u -= 1 v -= 1 adj[u].append((v, w)) adj[v].append((u, w)) best = [0] * n ans = 0 def dfs(u): stack = list()...
1102_C. Doors Breaking and Repairing
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are n doors, the i-th door initially has durability equal to a_i. During your move you can try to br...
```python n, x, y = map(int, input().split()) a = list(map(int,input().split())) if x > y: print( n ) else: m = 0 for i in a: if i <= x: m += 1 print( m - m // 2 ) ```
1130_C. Connect
Alice lives on a flat planet that can be modeled as a square grid of size n × n, with rows and columns enumerated from 1 to n. We represent the cell at the intersection of row r and column c with ordered pair (r, c). Each cell in the grid is either land or water. <image> An example planet with n = 5. It also appears i...
```python #complexity - O(n^2) import math import sys sys.setrecursionlimit(2600) class UnionFind(): def __init__(self, num_elements): self.parent = list(range(num_elements)) self.rank = [1] * num_elements def union(self, a, b): par_a = self.find(a) par_b = self.find(b) if par_a == par_b...
1190_A. Tokitsukaze and Discard Items
Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them. These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed o...
```python ##n,m,k=list(map(int,input().split())) ##p=list(map(int,input().split())) ##p.sort() ##import math ##ok=k ##ip=0 ##s=1 ##cnt=0 ##a=False ##for i in p: ## ## if ip<i<=k: ## ## cnt+=1 ## ## a=True ## elif ip<i<=k+cnt: ## ## s+=1 ## k+=cnt+1 ## ...
1209_E1. Rotate Columns (easy version)
This is an easier version of the next problem. The difference is only in constraints. You are given a rectangular n × m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation ...
```python def naiveSolve(): return def main(): t=int(input()) allans=[] for _ in range(t): n,m=readIntArr() grid=[] for __ in range(n): grid.append(readIntArr()) columns=[] for col in range(m): temp=[grid[i][col] for...
1228_D. Complete Tripartite
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected. Let's make a definition. Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}...
```python from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,copy,time sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_str(): return ...
1270_D. Strange Device
This problem is interactive. We have hidden an array a of n pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of k diffe...
```python import sys input = sys.stdin.readline N, K = map(int, input().split()) def inout(A): print("?", end=" ") print(*A) sys.stdout.flush() pos, a = map(int, input().split()) return pos, a dic = {} for k in range(1, K+2): A = list(range(1,k)) + list(range(k+1, K+2)) pos, a = inout(A)...
1293_B. JOE is on TV!
[3R2 - Standby for Action](https://www.youtube.com/watch?v=P2ZVC9aoiKo) Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The sho...
```python n = int(input()) c = 0 while n>0: c += 1/n n -= 1 print(c) ```
1313_B. Different Rules
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be n participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest numb...
```python """ 1 6 3 4 """ n = int(input()) for _ in range(n): nums = list(map(int,input().split())) if nums[0] == 1: print(1,1) continue if nums[1]+nums[2] <= nums[0]: ans = 1 else: ans = min(nums[0], nums[1]+nums[2]-nums[0]+1) res = nums[0] if nums[1]+nums[2] > nums[...
1335_E2. Three Blocks Palindrome (hard version)
The only difference between easy and hard versions is constraints. You are given a sequence a consisting of n positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ...
```python def max_tbp(xs, a, b, O, C): m = 1 occs = O[a] b_cnts = C[b] for i in range(len(occs)//2): st = occs[i] en = occs[len(occs)-1-i] cnt = b_cnts[en-1] - b_cnts[st] m = max(m, (i+1)*2 + cnt) return m t = int(input()) for _ in range(t): n =...
1358_B. Maria Breaks the Self-isolation
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
```python t = int(input()) for i in range(t): n = int(input()) nums = list(map(int, input().split())) ans = False nums.sort() for j in range(n-1, -1,-1): if nums[j] <= j+1: print(j+2) ans = True break if not ans: print(1) ...
1375_G. Tree Modification
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation: 1. Choose three vertices a, b, and c such that b is adjacent to both a and c. 2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add t...
```python import sys input = sys.stdin.readline n=int(input()) graph=[[] for _ in range(n)] for j in range(n-1): x,y=map(int,input().split()) x-=1 y-=1 graph[x].append(y) graph[y].append(x) color=[-1]*n tem=[0] visit=[0]*n color[0]=0 while(tem!=[]): x=tem.pop() for i in graph[x]: i...
1399_C. Boats Competition
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight. So, if there are k teams (a_1, b_1), (a_2, b_2)...
```python from collections import Counter def solve(): n=int(input()) A=list(map(int,input().split())) if n==1: return 0 A.sort() mi=A[0]+A[1] ma=A[-1]+A[-2] a=Counter(A) t=0 q=-1 for i in range(mi,ma+1): t=0 for j in a: if i-j in a: ...
1440_D. Graph Subset Problem
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k. Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it. A subset of vertices ...
```python from __future__ import division,print_function from heapq import* import sys le = sys.__stdin__.read().split("\n")[::-1] af = [] for ezo in range(int(le.pop())): n,m,k = list(map(int, le.pop().split())) ar = [set() for _ in range(n)] for i in range(m): a,b = list(map(int, le.pop().split()...
1468_A. LaIS
Let's call a sequence b_1, b_2, b_3 ..., b_{k - 1}, b_k almost increasing if $$$min(b_1, b_2) ≤ min(b_2, b_3) ≤ ... ≤ min(b_{k - 1}, b_k).$$$ In particular, any sequence with no more than two elements is almost increasing. You are given a sequence of integers a_1, a_2, ..., a_n. Calculate the length of its longest alm...
```python import bisect as bs for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) if n <= 2: print(n) continue stack, m, p = [a[0]], [], [(1000000, 0)] for v in a[1:]: k = bs.bisect_right(m, v) if k == len(m): stack.append(v)...
1515_A. Phoenix and Gold
Phoenix has collected n pieces of gold, and he wants to weigh them together so he can feel rich. The i-th piece of gold has weight w_i. All weights are distinct. He will put his n pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly x, it will ex...
```python import sys input = sys.stdin.readline for i in range(int(input())): n,x = map(int,input().split()) arr = list(map(int,input().split())) if sum(arr)==x: print("NO") else: arr.sort() print("YES") s = 0 temp = -1 for i in range(n): if s+...
18_C. Stripe
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, an...
```python n=int(input()) l=list(map(int,input().split())) s=[0]*n for i in range(n): if i==0: s[i]=l[i] else: s[i]=l[i]+s[i-1] ans=0 for i in range(1,n): if s[i-1]==s[-1]-s[i-1]: ans=ans+1 print(ans) ```
237_C. Primes on Interval
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors. Consider positive integers a, a + 1, ..., b (a ≤ b). You want to find the minimum integer l (1 ≤ l ≤ b - a + 1) such that for any int...
```python p=[1]*(1000005) p[0]=0 p[1]=0 for i in range(2,1001): if p[i]: for j in range(2*i,1000005,i): p[j]=0 for i in range(1,1000001): p[i]+=p[i-1] a,b,k=map(int,input().split()) if p[b]-p[a-1]<k: exit(print(-1)) i=j=a l=0 while j<=b: if p[j]-p[i-1]<k: j+=1 else: ...
262_A. Roma and Lucky Numbers
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got n positive integers....
```python n, k = map(int,input().split()) l = list(map(int,input().split())) a = 0 for i in range(len(l)): c = list(str(l[i])) s = 0 for j in range(len(c)): if c[j] == "7" or c[j] == "4": s += 1 if s <= k: a += 1 print(a) ```
286_A. Lucky Permutation
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n). A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1. You have integer n. Find some lucky permutation p of size n. Input T...
```python n=int(input()) if(n%4>1): print(-1) else: ans=[0]*(n+1) i,j,a,b=1,n,1,n while(i<j and a<=n and b>=1): ans[i],ans[j]=a+1,b-1 ans[i+1],ans[j-1]=b,a i+=2 j-=2 a+=2 b-=2 if(i==j): ans[i]=a for i in range(1,n+1): print(ans[i],e...
311_A. The Closest Pair
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded. The problem is the follows. Given n points in the plane, find a pair of points between...
```python r = input().split(' ') n = int( r[ 0 ] ) k = int( r[ 1 ] ) if n * ( n - 1 ) >> 1 <= k: print( 'no solution' ) else: for i in range( 0 , n ): print( 0 , i + 1 ) ```
37_C. Old Berland Language
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfect...
```python #!/usr/bin/python3 counts = [0]*1024 for x in range(len(counts)): counts[x] = [] N = int(input()) x = [int(t) for t in input().strip().split()] for i,t in enumerate(x): counts[t].append(i) curr = 0 ans = [0]*N for i in range(1,1024): while len(counts[i]) > 0: x = bin(curr)[2:] if len(x) > i: print(...
400_B. Inna and New Matrix of Candies
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload". The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game la...
```python n, m = (int(x) for x in input().split()) st = set() for i in range(n): s = input() g = s.index('G') s = s.index('S') if g > s: print(-1) exit(0) st.add(s - g) print(len(st)) ```
427_C. Checkposts
Your city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions. To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if eit...
```python MOD = int(1e9) + 7 n = int(input()) w = [0] + list(map(int, input().split())) q = [[] for i in range(n+1)] p = [[] for i in range(n+1)] m = int(input()) edges = [list(map(int, input().split())) for _ in range(m)] for u, v in edges: p[u].append(v) q[v].append(u) s, t = 0, 1 r = set(i for i in range(...
450_A. Jzzhu and Children
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies. Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ...
```python import math n,k=map(int,input().split()) l=list(map(int,input().split())) for i in range(n): l[i]=math.ceil(l[i]/k) f=max(l) for i in range(n-1,-1,-1): if f==l[i]: print(i+1) break ```
472_B. Design Tutorial: Learn from Life
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task. Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following...
```python n, k = map(int, input().split()) arr = list(map(int, input().split())) arr.sort() ans = 0 p = 1 i = 0 while n != 0: tp = arr[i] ans += 2 * (tp - p) * (round(n / k + 0.49999999999999)) while n != 0 and arr[i] == tp: n -= 1 i += 1 p = tp print(ans) ```
496_C. Removing Columns
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table abcd edfg hijk ...
```python import sys,heapq,math from collections import defaultdict,deque input=sys.stdin.readline r,c=map(int,input().split()) grid=[] for i in range(r): grid.append(input().strip()) equal=[0 for _ in range(c)] less=[0 for _ in range(c)] for i in range(c): for row in range(1,r): if(gri...
547_B. Mike and Feet
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. <image> A group of bears is a non-empty contiguous segment of the line. The size of ...
```python import math import random class AVLTree(): def __init__(self, x): self.left = None self.rght = None self.val = x self.height = 1 def getHeight0(root): if root==None: return 0 return max(getHeight0(root.left), getHeight0(root.rght))+1 def getHeight(root): ...
595_B. Pasha and Phone
Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits. Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of le...
```python import sys n, k = sys.stdin.readline().split() n = int(n) k = int(k) a = [int(x) for x in sys.stdin.readline().split()] b = [int(x) for x in sys.stdin.readline().split()] MOD = (10 ** 9) + 7 res = 1 for i in range(0, n // k): lo = b[i] * (10 ** (k - 1)) - 1 up = (b[i] + 1) * (10 ** (k - 1)) - 1 t...
616_E. Sum of Remainders
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7). The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1. Input The only line co...
```python from math import floor def range_sum(low, up): return (up * (up + 1)) // 2 - (low * (low + 1)) // 2 # for _ in range(int(input())): mod = int(1e9 + 7) n,m=map(int,input().split()) ans, sqrt_n = m*n, int(floor(n**0.5)) temp = 0 for i in range(1, sqrt_n + 1): up = n // i low = n // (i + 1) u...
689_C. Mike and Chocolate Thieves
Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible! Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly k times more than the previous o...
```python def main(): m = int(input()) if m < 1000000: lo = m*4 hi = m*8 else: lo = int(4.949 * m) hi = int(4.9492 * m) while lo < hi - 1: mid = (lo + hi)//2 nposs = countposs(mid) if nposs < m: lo = mid else: hi = m...
711_A. Bus to Udayland
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied. ZS and Chris are...
```python n = int(input()) result = [] z = 0 for i in range(n): place = input() if place.count('OO') > 0: if z == 0: result.append(place.replace('OO', '++', 1)) z += 1 else: result.append(place) else: result.append(place) if z == 1: print('YES'...
732_A. Buy a Shovel
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ...
```python price, change = map(int, input().split()) ans = 1 total = price while not((total % 10 != 0 and change == total % 10) or (total % 10 == 0)): total += price ans += 1 print(ans) ```
756_B. Travel Card
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare. The fare is constructed in the following manner. There are three types of tickets: 1. a tic...
```python def lower_bound(arr, left, right, target): if arr[right]<target: return right+1 while left < right: mid = (left + right) >> 1 if arr[mid] >= target: right = mid else: left = mid + 1 return left T = int(input()) arr = [0] * T dp = [0] * (T + ...
777_C. Alyona and Spreadsheet
During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables. Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in...
```python import sys, os from io import BytesIO, IOBase from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect # region fastio BUF...
802_A. Heidi and Library (easy)
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n. We will look...
```python n,k=map(int,input().split()) a=list(map(int,input().split())) z=[0]*81 kz,ans=0,0 for i in range(n): if z[a[i]]: continue ans+=1 if k>kz: z[a[i]]=1; kz+=1 else: h=-1 for j in range(1,n+1): if z[j]: m=n+1 for p in range(i,n): ...
822_C. Hacker, pack your bags!
It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha. So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You...
```python from bisect import bisect_left f = lambda: map(int, input().split()) n, x = f() s, t = {}, {} for i in range(n): l, r, c = f() d = r - l if d not in s: s[d] = [] s[d].append((l, c)) for d, p in s.items(): p.sort(key=lambda q: q[0]) q = t[d] = [[l, c] for l, c in p] for i in range(1...
847_H. Load Testing
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send ai requests. Polycarp plans to test Fakebook under a special kind of...
```python n = int(input()) a = list(map(int, input().split())) lp,rp = [0 for i in range(n)],[0 for i in range(n)] lnr, rnr = [a[i] for i in range(n)],[a[i] for i in range(n)] mx = a[0] for i in range(1,n): if a[i] > mx: mx = a[i] lp[i] = lp[i-1] else: mx += 1 lp[i] = lp[i-1] +...
869_C. The Intriguing Obsession
— This is not playing but duty as allies of justice, Nii-chan! — Not allies but justice itself, Onii-chan! With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands! There are three...
```python a,b,c = list(map(int, input().split(' '))) MOD = 998244353 def d(a, b): s = 1 for i in range(a, b+1): s*=i s%=MOD return s def cnk(n,k): s = 1 for i in range(n-k+1, n+1): s*=i for i in range(1,k+1): s/=i return s def factorial(n): s = 1 for i in range(1, n+1): s*=i return s de...
895_B. XK Segments
While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai ≤ aj and there are exactly ...
```python from bisect import bisect_left R=lambda:map(int,input().split()) n,x,k=R() a=sorted(R()) z=zip(a,(((u-1)//x+k)*x for u in a)) print(sum(bisect_left(a,l+x)-bisect_left(a,max(u,l)) for u,l in z)) ```
916_C. Jamie and Interesting Graph
Jamie has recently found undirected weighted graphs with the following properties very interesting: * The graph is connected and contains exactly n vertices and m edges. * All edge weights are integers and are in range [1, 109] inclusive. * The length of shortest path from 1 to n is a prime number. * The su...
```python INF = 1000000 erast = [1] * INF erast[1] = 0 primes = [] for i in range(2, INF): if erast[i] == 1: for j in range(i * 2, INF, i): erast[j] = 0 primes.append(i) # print(primes) lastp = primes[-1] n, m = map(int, input().split()) edges = set() print(lastp, lastp) for i in range(...
939_D. Love Rescue
Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long. This story c...
```python length=int(input()) s1=input() s2=input() connect=[{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25}] tot=0 spells=[] for i in range(0, length): l1=ord(s1[i])-97 l2=ord(s2[i])-97 if not (l1 in connect[l2]): tot=tot+1 ...
965_A. Paper Airplanes
To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes. A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each pe...
```python k, n, s, p = map(int, input().split()) one = (n + s - 1) // s print((one * k + p - 1) // p) ```
992_A. Nastya and an Array
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: * In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to z...
```python n=int(input()) l=list(map(int,input().split())) l=set(l) if 0 in l: print(len(l)-1) else: print(len(l)) ```
p02622 AtCoder Beginner Contest 172 - Minor Change
Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so. Operation: Choose one character of S and replace it with a different character. Constraints * S and T have lengths between 1 and 2\times 10^5 (inclusive). * S and T consists ...
```python S=input() T=input() cc=0 for i in range(len(S)): cc+=int(S[i]!=T[i]) print(cc) ```
p02753 AtCoder Beginner Contest 158 - Station and Bus
In AtCoder City, there are three stations numbered 1, 2, and 3. Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is `A`, Company A operates Station i; if S_i is `B`, Company B operates Station i. To improve t...
```python S = input() print("No" if len(set(S)) == 1 else "Yes") ```
p02888 AtCoder Beginner Contest 143 - Triangles
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i. He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied: * a < b + c * b < c + a * c < a + b How...
```python import bisect N=int(input()) L=sorted(list(map(int,input().split()))) ans=0 for i in range(N-2): for j in range(i+1,N-1): ans+=bisect.bisect_left(L,L[i]+L[j])-j-1 print(ans) ```
p03023 M-SOLUTIONS Programming Contest - Sum of Interior Angles
Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides. Print the answer in degrees, but do not print units. Constraints * 3 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print an integer representing the sum of th...
```python a = int(input()) print(int(a * 180 - 360)) ```
p03164 Educational DP Contest - Knapsack 2
There are N items, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i. Taro has decided to choose some of the N items and carry them home in a knapsack. The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W. Find ...
```python N,W = map(int,input().split()) dp = [0]+[W+1]*(N*10**3) for i in range(N): w,v = map(int,input().split()) for j in range(N*10**3+1-v)[::-1]: dp[j+v] = min(dp[j+v],dp[j]+w) for i in range(N*10**3+1)[::-1]: if dp[i]<=W: print(i) exit() ```
p03306 SoundHound Inc. Programming Contest 2018 -Masters Tournament- - + Graph
Kenkoooo found a simple connected graph. The vertices are numbered 1 through n. The i-th edge connects Vertex u_i and v_i, and has a fixed integer s_i. Kenkoooo is trying to write a positive integer in each vertex so that the following condition is satisfied: * For every edge i, the sum of the positive integers writt...
```python import sys from sys import setrecursionlimit from collections import deque from heapq import heappop, heappush setrecursionlimit(10**9) #input = sys.stdin.readline def inpl(): return map(int, input().split()) INF = 2**31 N, M = inpl() D = [[] for _ in range(N+1)] for _ in range(M): u, v, s = inpl() ...
p03466 AtCoder Grand Contest 020 - Min Max Repetition
Let f(A, B), where A and B are positive integers, be the string satisfying the following conditions: * f(A, B) has length A + B; * f(A, B) contains exactly A letters `A` and exactly B letters `B`; * The length of the longest substring of f(A, B) consisting of equal letters (ex., `AAAAA` or `BBBB`) is as small as possi...
```python T=int(input()) for TT in range(T): a,b,c,d=map(int,input().split(' ')) l,x,y=(a+b)//(min(a,b)+1),0,0 if a*l<=b: y=a+b elif b*l<=a: x=a+b else: x,y=(a*l-b)//(l-1),(b*l-a)//(l-1) #Like G2 tong long out="" for i in range(c,d+1): if i<=x: out+="AB"[i%(l+1)==0] elif a+b-i+1<=y: out+="BA"[(a+...
p03626 AtCoder Beginner Contest 071 - Coloring Dominoes
We have a board with a 2 \times N grid. Snuke covered the board with N dominoes without overlaps. Here, a domino can cover a 1 \times 2 or 2 \times 1 square. Then, Snuke decided to paint these dominoes using three colors: red, cyan and green. Two dominoes that are adjacent by side should be painted by different colors...
```python N = int(input()) grids = [[s for s in input()],[s for s in input()]] MOD = 1000000007 if grids[0][0] == grids[1][0]: prv_row_type = 1 ans = 3 posx = 1 else: prv_row_type = -1 ans = 6 posx = 2 while posx < N: if grids[0][posx] == grids[1][posx]: if prv_row_type == 1: ans *= 2 else: an...
p03786 AtCoder Grand Contest 011 - Colorful Creatures
Snuke found N strange creatures. Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively. Every creature can absorb another creature whose size is at most twice the size of itself. When a creature of size A and color B absorbs another creature of siz...
```python N = int(input()) A = list(map(int, input().split())) A.sort() sumA = sum(A)-A[N-1] memo = 0 for i in range(N-1,-1,-1): if sumA*2<A[i] or i==0: memo = i break sumA -= A[i-1] print(N-memo) ```
p03954 AtCoder Grand Contest 006 - Median Pyramid Hard
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically. <image> A pyramid with N=4 steps Snuke wrote a per...
```python # def makelist(n, m): # return [[0 for i in range(m)] for j in range(n)] N = int(input()) a = [0] + list(map(int, input().split())) def check(n): b = [False]*(len(a)) for i in range(1, len(a)): if a[i] >= n: b[i] = True else: b[i] = False r = int(1e9) l = int(1e9) rb = b[N] lb = b[N] for ...
p00044 Prime Number II
A prime number is an integer that is greater than 1 and can only be divided by itself or 1. For example, 2 is a prime number because it is divisible only by 2 and 1, but 12 is not a prime number because it is divisible by 2, 3, 4, 6 in addition to 12 and 1. When you enter the integer n, write a program that outputs th...
```python from math import sqrt, ceil N = 53000 temp = [True]*(N+1) temp[0] = temp[1] = False for i in range(2, ceil(sqrt(N+1))): if temp[i]: temp[i+i::i] = [False]*(len(temp[i+i::i])) while True: try: n = int(input()) print(n-1-temp[n-1:0:-1].index(True), n+1+temp[n+1:].index(True)) ...
p00176 What Color?
Taro, who aims to become a web designer, is currently training. My senior at the office tells me that the background color of this page is # ffe085, which is a color number peculiar to web design, but I can't think of what kind of color it is. This color number represents the intensity of each of the three primary col...
```python COLOR = { "000000": "black", "0000ff": "blue", "00ff00": "lime", "00ffff": "aqua", "ff0000": "red", "ff00ff": "fuchsia", "ffff00": "yellow", "ffffff": "white" } while True: input_data = input() if len(input_data) == 1: break color_code = "" for firs...
p00332 Japanese Calendar
The "Western calendar" is a concept imported from the West, but in Japan there is a concept called the Japanese calendar, which identifies the "era name" by adding a year as a method of expressing the year on the calendar. For example, this year is 2016 in the Christian era, but 2016 in the Japanese calendar. Both are ...
```python e, y = map(int,input().split()) if e == 0: if y < 1912: a = y - 1867 print("M", a, sep = '') elif y < 1926: a = y - 1911 print("T", a, sep = '') elif y < 1989: a = y - 1925 print("S", a, sep = '') elif y < 2017: a = y - 1988 prin...
p00513 Available Areas
IOI Real Estate rents condominiums. The apartment room handled by this company is 1LDK, and the area is 2xy + x + y as shown in the figure below. However, x and y are positive integers. Figure_Madori In the IOI real estate catalog, the areas of condominiums are listed in ascending order (in ascending order), but it...
```python def check(a): for i in range(2,int(a**(1/2))+1): if a%i == 0: return 1 return 0 n = int(input()) count = 0 for i in range(n): num = int(input()) if check(2*num+1) == 0: count += 1 print(count) ```
p00690 A Long Ride on a Railway
Travelling by train is fun and exciting. But more than that indeed. Young challenging boys often tried to purchase the longest single tickets and to single ride the longest routes of various railway systems. Route planning was like solving puzzles. However, once assisted by computers, and supplied with machine readable...
```python # AOJ 1108: A Long Ride on a Railway # Python3 2018.7.14 bal4u def combi(k, a, w): global len, ans for b in range(1, n+1): if b == a: continue for i in range(m): if not f[i] and ((tbl[i][0] == a and tbl[i][1] == b) or (tbl[i][0] == b and tbl[i][1] == a)): f[i] = 1 tmp[k] ...
p00831 Confusing Login Names
Meikyokan University is very famous for its research and education in the area of computer science. This university has a computer center that has advanced and secure computing facilities including supercomputers and many personal computers connected to the Internet. One of the policies of the computer center is to le...
```python from collections import Counter from itertools import permutations import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False def dist(a, b): LA = len(a); LB = len(b) dp = [[10**18]*(LB+1) for i in range(LA+1)...
p00962 Pizza Delivery
Problem F Pizza Delivery Alyssa is a college student, living in New Tsukuba City. All the streets in the city are one-way. A new social experiment starting tomorrow is on alternative traffic regulation reversing the one-way directions of street sections. Reversals will be on one single street section between two adjac...
```python from heapq import heappush, heappop from collections import deque import sys sys.setrecursionlimit(10**6) n, m = map(int, input().split()) E = [] G = [[] for i in range(n)] RG = [[] for i in range(n)] for i in range(m): a, b, c = map(int, input().split()) E.append((a-1, b-1, c)) G[a-1].append((b-1...
p01095 Bamboo Blossoms
Bamboo Blossoms The bamboos live for decades, and at the end of their lives, they flower to make their seeds. Dr. ACM, a biologist, was fascinated by the bamboos in blossom in his travel to Tsukuba. He liked the flower so much that he was tempted to make a garden where the bamboos bloom annually. Dr. ACM started resea...
```python from bisect import bisect_left def rwh_primes2(n): # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] siev...
p01847 Curtain
curtain Summer is coming soon. You decide to redecorate your room for the summer. It is expected that the sun will be very strong this summer, and it will be a difficult season for you who are not good at dazzling. So you thought about installing a curtain on the window of the room to adjust the brightness of the room...
```python from collections import defaultdict INF = 10**9 while 1: N = int(input()) if N == 0: break P = [list(map(int, input().split())) for i in range(N)] S = defaultdict(list) X = set() x0 = y0 = INF; x1 = y1 = -INF for i in range(4): x, y = map(int, input().split()) ...
p01983 Proof of Knowledge
Proof of knowledge The entrance door of the apartment you live in has a password-type lock. This password consists of exactly four digits, ranging from 0 to 9, and you always use the password P given to you by the apartment manager to unlock this door. One day, you wondered if all the residents of the apartment were ...
```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 ...
p02129 Ghost Legs
Problem There are $ N $ Amidakuji with 3 vertical lines. No matter which line you start from, the Amidakuji that ends at the starting line is considered a good Amidakuji. You can select one or more Amidakuji and connect them vertically in any order. Output "yes" if you can make a good Amidakuji, otherwise output "no"....
```python def amida(): line = list(map(int, input().split()))[1:] res = [0, 1, 2] for i in line: if i: res[1], res[2] = res[2], res[1] else: res[0], res[1] = res[1], res[0] return res def func(x, line, flag): if line == [0, 1, 2] and flag: return Tru...
p02270 Allocation
You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the s...
```python from sys import stdin def binSearch(k, p_min, p_max): global w while p_max-p_min > 1: mid = p_min + (p_max-p_min)//2 if k >= countTrack(w, mid): p_max = mid else: p_min = mid return p_max def countTrack(w, p): rest = [] for wi in w: ...
p02417 Counting Characters
Write a program which counts and reports the number of each alphabetical letter. Ignore the case of characters. Constraints * The number of characters in the sentence < 1200 Input A sentence in English is given in several lines. Output Prints the number of alphabetical letters in the following format: a : The n...
```python import sys x=sys.stdin.read().lower() for i in range(97,123): print(chr(i),':',x.count(chr(i))) ```
1006_B. Polycarp's Practice
Polycarp is practicing his problem solving skill. He has a list of n problems with difficulties a_1, a_2, ..., a_n, respectively. His plan is to practice for exactly k days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip ...
```python # Accepted: isVerbose = False def v(msg): if isVerbose: print(msg) n, k = map(int, input().split()) nums = list(enumerate(map(int, input().split()))) #print(n, k) #print(nums) nums.sort(key=lambda tup:tup[1]) #print(nums) nums_top = nums[-min(k, n):] #print(nums_top) nums_top.sort(key=lambda t...
102_A. Clothes
A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap. Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has i...
```python I=lambda:map(int,input().split()) n,m=I() N=list(I()) p=set() for i in range(m): x,y=I();x-=1;y-=1 p.add((x,y)if x<y else(y,x)) r=1e9 for i in range(n): for j in range(i): for k in range(j): if(j,i)in p and(k,i)in p and(k,j)in p: r = min(r,N[i]+N[j]+N[k]) print(-1 if r>1e8 else r) ```
1051_A. Vasya And Password
Vasya came up with a password to register for EatForces — a string s. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits. But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin l...
```python def check( s, L, R ): for i in s: if i>=L and i<=R: return False return True def ok(s): low = True; for i in s: if i>='a' and i<='z': low = False; break if low : return False low = True; for i in s: if i>='A' and i<='Z': low = False; break if low : return False low ...
1073_B. Vasya and Books
Vasya has got n books, numbered from 1 to n, arranged in a stack. The topmost book has number a_1, the next one — a_2, and so on. The book at the bottom of the stack has number a_n. All numbers are distinct. Vasya wants to move all the books to his backpack in n steps. During i-th step he wants to move the book number...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from functools import * from heapq import * from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') s...
1095_B. Array Stabilization
You are given an array a consisting of n integer numbers. Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i. You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible...
```python input() sequence = [int(i) for i in input().split(' ')] sequence.sort() a, b = sequence[-2] - sequence[0], sequence[-1] - sequence[1] print(a) if a < b else print(b) ```
1114_C. Trailing Loves (or L'oeufs?)
The number "zero" is called "love" (or "l'oeuf" to be precise, literally means "egg" in French), for example when denoting the zero score in a game of tennis. Aki is fond of numbers, especially those with trailing zeros. For example, the number 9200 has two trailing zeros. Aki thinks the more trailing zero digits a n...
```python import math from collections import Counter def checkprime(x): if x==1: return False i=2 while i*i<=x: if x%i==0: return False i+=1 return True def pfactors(n): lt=[] while n % 2 == 0: lt.append(2) n = (n // 2) for i in range(3,in...
1183_E. Subsequences (easy version)
The only difference between the easy and the hard versions is constraints. A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th...
```python R = lambda: map(int, input().split()) n,k = R() s = input() p = [s] ans = 0 d= set() while p: q = p.pop(0) if q not in d: k -= 1 ans += (n-len(q)) if k == 0: print(ans) quit() d.add(q) for i in range(len(q)): t = q[:i]+q[i+1:]...
1200_F. Graph Traveler
Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can h...
```python import io, sys input = lambda f=io.StringIO(sys.stdin.buffer.read().decode()).readline: f().rstrip() LCM = 2520 n = int(input()) k = list(map(int, input().split())) m, e = [0] * n, [None] * n for i in range(n): m[i] = int(input()) e[i] = list(map(int, input().split())) nxt = [] for i in range(n): ...
1284_A. New Year and Naming
Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
```python from sys import stdin, stdout def main(): (n1, n2) = tuple([int(x) for x in stdin.readline().split()]) arr1 = [x for x in stdin.readline().split()] arr2 = [x for x in stdin.readline().split()] q = int(stdin.readline()) res = [] for i in range(0, q): year = int(stdin.readli...
1303_C. Perfect Keyboard
Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all 26 lowercase Latin letters will be arranged in some order. Polycarp uses the same password s on all websites where he is registered (it is bad, but he doesn't care)...
```python ''' Hey stalker :) ''' INF = 10**10 def main(): print = out.append ''' Cook your dish here! ''' st = list(input()) keyboard = [] if len(set(st))>1: adj = defaultdict(set) for i in range(len(st)-1): adj[st[i]].add(st[i+1]) adj[st[i+1]].add(st[i]) ...
1327_D. Infinite Path
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i. Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...). We can also define a multiplication of permutations a a...
```python def monocolor_subcycle(start, divisor): for i in range(start, len(cycle), divisor): v = cycle[i] if c[v] != c[cycle[start]]: return False return True def any_monocolor_subcycle(divisor): for start in range(divisor): if monocolor_subcycle(start, divisor): ...
1368_D. AND, OR and square sum
Gottfried learned about binary number representation. He then came up with this task and presented it to you. You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then a...
```python from sys import stdin input = stdin.readline n = int(input()) a = [*map(lambda x: bin(int(x))[:1:-1], input().split())] c1 = len(max(a, key=len)) a = [x + '0' * (c1 - len(x)) for x in a] b = [sum(c[i] == '1' for c in a) for i in range(c1)] c2 = max(b) ans = 0 for i in range(c2): num = '' for i in range(c1):...
1389_F. Bicolored Segments
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i. Let's call a pair of segments i and j bad if the following two conditions are met: * t_i ≠ t_j; * the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there ex...
```python from operator import add class LazySegmentTree(): def __init__(self,n,init,merge=max,merge_unit=-10**18,operate=add,operate_unit=0): self.merge=merge self.merge_unit=merge_unit self.operate=operate self.operate_unit=operate_unit self.n=(n-1).bit_length() s...
140_C. New Year Snowmen
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any thr...
```python #!/usr/bin/env python3 from heapq import * from collections import defaultdict n = int(input()) r = map(int, input().split()) H = defaultdict(int) for t in r: H[t] += 1 D = [(-1 * v, k) for k, v in H.items()] heapify(D) ret = [] while len(D) > 2: a, b, c = heappop(D), heappop(D), heappop(D) ret...
1430_G. Yet Another DAG Problem
You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i. Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} -...
```python from heapq import heappush, heappop class MinCostFlow: INF = 10**18 def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap, cost): forward = [to, cap, cost, None] backward = forward[3] = [fr, 0, -cost, forward] sel...
1454_C. Sequence Transformation
You are given a sequence a, initially consisting of n integers. You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element). To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any ...
```python for _ in range(int(input())): n = int(input()) x = list(map(int, input().split())) o = {x[0]: [0]} for i in range(1, n): if x[i] in o: o[x[i]].append(i) else: o[x[i]] = [i] m = n if len(o) == 1: print(0) else: for k, l in o.it...
1478_A. Nezzar and Colorful Balls
Nezzar has n balls, numbered with integers 1, 2, …, n. Numbers a_1, a_2, …, a_n are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that a_i ≤ a_{i+1} for all 1 ≤ i < n. Nezzar wants to color the balls using the minimum number of colors, such that the following holds. ...
```python for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = set(a) maxBall = 0 for i in b: if a.count(i)>maxBall: maxBall=a.count(i) print(maxBall) ```
1505_D. Xenolith? Hippodrome?
Input The input contains two integers N, M (1 ≤ N ≤ 1024, 2 ≤ M ≤ 16), separated by a single space. Output Output "YES" or "NO". Examples Input 2 3 Output YES Input 3 2 Output NO Input 33 16 Output YES Input 26 5 Output NO
```python import sys import math import heapq import bisect from collections import Counter from collections import defaultdict from io import BytesIO, IOBase import string class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() ...
1528_D. It's a bird! No, it's a plane! No, it's AaParsa!
There are n cities in Shaazzzland, numbered from 0 to n-1. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa. As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland. AaParsa has planted m transport canno...
```python import sys input = lambda: sys.stdin.readline().rstrip() def dijkstra(n, E, i0=0): D = [1 << 30] * n D[i0] = 0 Q = set([i for i in range(n)]) while Q: d = 1 << 30 for q in Q: if D[q] < d: i = q d = D[q] Q.remove(i) fo...