name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
682_C. Alyona and the Tree
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on. The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call ver...
```python n=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(n+1)] for i in range(n-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] ans=0 ch=[(1,0,0)] while ch: nom,pre,l=ch.pop() if l>a[nom]: continue ans+=1 for x,c in E[nom]: if x!=pre: ch+=[...
705_B. Spider Man
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex. Initially t...
```python n = int(input()) sum = 0 for i in input().split(): sum += int(i) - 1 if sum % 2 == 0: print(2) else: print(1) ```
817_A. Treasure Hunt
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure. Bottle with potion has two values x and y written on it. These values define four moves which can be performed...
```python a, b, c, d = map(int, input().split()) x, y = map(int, input().split()) if abs(c - a) % abs(x) == 0 and abs(c - a) / abs(x) % 2 == abs(d - b) / abs(y) % 2 and abs(d - b) % abs(y) == 0: print("YES") else: print("NO") ```
842_A. Kirill And The Game
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number. For each two integer numbers ...
```python IL = lambda: list(map(int, input().split())) IS = lambda: input().split() I = lambda: int(input()) S = lambda: input() l, r, x, y, k = IL() for i in range(max(l, x*k), min(r, y*k) + 1): if i%k == 0: print("YES") quit() print("NO") ```
863_A. Quasi-palindrome
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left. For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin...
```python s=input() if s==s[::-1]: print("YES") else: news="" c=0 start=0 end=len(s) for i in range(len(s)): if s[i]!="0": start=i break for i in range(len(s)-1,-1,-1): if s[i]!="0": end=i+1 break news=s[start:end] if ne...
888_E. Maximum Subsequence
You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 ≤ b1 < b2 < ... < bk ≤ n) in such a way that the value of <image> is maximized. Chosen sequence can be empty. Print the maximum possible value of <image>. Input The first l...
```python import bisect import array n,m=list(map(int,input().split())) a=list(map(int,input().split())) a1,a2=array.array('L'),array.array('L') n1=n//2 def sums1(i,sum=0): if i==n1: a1.append(sum) else: sums1(i+1,(sum+a[i])%m) sums1(i+1,sum) def sums2(i,sum=0): if i==n: ...
911_C. Three Garlands
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on. When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if i-th garland is switched on during x-th secon...
```python k1, k2, k3 = map(int, input().split()) ans = 'NO' if [k1, k2, k3].count(2) >= 2: ans = 'YES' if 1 in [k1, k2, k3]: ans = 'YES' if [k1, k2, k3].count(3) >= 3: ans = 'YES' if 2 in [k1, k2, k3] and [k1, k2, k3].count(4) == 2: ans = 'YES' print(ans) ```
933_A. A Twisty Movement
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon. A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, th...
```python # -*- coding: utf-8 -*- # Watashi wa ARUGONEKO wo tsukatteru. [algoneko.github.io] # I hate python --RedCat from math import * import re n = int(input()) a = list(map(int, input().split())) d1, d2, d3, d4 = [0]*n, [0]*n, [0]*n, [0]*n d1[0] = d3[0] = (1 if a[0] == 1 else 0) d2[0] = d4[0] = (1 if a[0] == 2 els...
95_C. Volleyball
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can...
```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...
987_A. Infinity Gauntlet
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
```python stone = {'purple': 'Power', 'green': 'Time', 'blue': 'Space','orange': 'Soul','red': 'Reality','yellow': 'Mind'} color = {} n = int(input()) for _ in range(0, n): c = input() if c in stone: del stone[c] print(6-n) print('\n'.join(stone.values())) ```
p02587 AtCoder Beginner Contest 175 - Making Palindrome
We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N. Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice. The cost of using the string S_i once is C_i, and t...
```python from collections import defaultdict from heapq import heappush, heappop, heapify def main(): N = int(input()) SC = [] SCrev = [] for _ in range(N): s, c = input().split() c = int(c) SC.append((s, c)) SCrev.append((s[::-1], c)) dist = defaultdict(lambda: 10**...
p02718 AtCoder Beginner Contest 161 - Popular Vote
We have held a popularity poll for N items on sale. Item i received A_i votes. From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes. If M popular items can be selected, print `Yes`; otherwise, print `No`. Constraints * 1 \...
```python n,m=map(int,input().split()) a=list(map(int,input().split())) c=len([i for i in a if i>=sum(a)/(4*m)]) print("Yes" if c>=m else "No") ```
p02847 AtCoder Beginner Contest 146 - Can't Wait for Holiday
Given is a string S representing the day of the week today. S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively. After how many days is the next Sunday (tomorrow or later)? Constraints * S is `SUN`, `MON`, `TUE`, `WED`, `THU`,...
```python s=input() A=["","SAT","FRI","THU","WED","TUE","MON","SUN"] print(A.index(s)) ```
p02984 AtCoder Beginner Contest 133 - Rain Flows into Dams
There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number. Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1). When Mountain i (1 \leq i \l...
```python n = int(input()) a = list(map(int,input().split())) ans = [0] * n ans[0] = sum(a) - sum(a[1::2])*2 for i in range(1,n): ans[i] = a[i-1]*2 - ans[i-1] print(' '.join(map(str,ans))) ```
p03126 AtCoder Beginner Contest 118 - Foods Loved by Everyone
Katsusando loves omelette rice. Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone. To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not. The i-th person answered that he/she only l...
```python N,M=map(int,input().split()) a=[0]*(M+1) for i in range(N): l=list(map(int,input().split())) for j in range(l[0]): a[l[j+1]]+=1 print(a.count(N)) ```
p03268 AtCoder Regular Contest 102 - Triangular Relationship
You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. The order of a,b,c does matter, and some of them can be the same. Constraints * 1 \leq N,K \leq 2\times 10^5 * N and K are integers. Input Input is given from ...
```python n,k = map(int, input().split()) ans=(n//k)**3 if k%2==0: ans+=((n+k//2)//k)**3 print(ans) ```
p03426 AtCoder Beginner Contest 089 - Practical Skill Test
We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j). The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}. You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by...
```python h,w,d = map(int,input().split()) a = [0]*h for i in range(h): a[i] = list(map(int,input().split())) num = [[] for i in range(w*h+1)] for i in range(h): for j in range(w): num[a[i][j]].append([i,j]) s = [0]*(h*w+1) for i in range(1,h*w-d+1): s[d+i] = s[i] + abs(num[d+i][0][0]-num[i][0][0]) ...
p03583 Tenka1 Programmer Contest - 4/N
You are given an integer N. Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w. If there are multiple solutions, any of them will be accepted. Constraints * It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500. Inputs Input is given from Stan...
```python a = int(input()) for b in range(1,3501): for c in range(1,3501): if ((4*b*c)/a)-c-b == 0: continue k = b*c/(((4*b*c)/a)-c-b) if k <= 0: continue if k == int(k): print(b,c,int(k)) exit() ```
p03740 AtCoder Beginner Contest 059 - Alice&Brown
Alice and Brown loves games. Today, they will play the following game. In this game, there are two piles initially consisting of X and Y stones, respectively. Alice and Bob alternately perform the following operation, starting from Alice: * Take 2i stones from one of the piles. Then, throw away i of them, and put the...
```python print('ABlriocwen'[-2<eval(input().replace(' ','-'))<2::2]) ```
p03902 CODE FESTIVAL 2016 Elimination Tournament Round 2 (Parallel) - Takahashi the Magician
Takahashi is a magician. He can cast a spell on an integer sequence (a_1,a_2,...,a_M) with M terms, to turn it into another sequence (s_1,s_2,...,s_M), where s_i is the sum of the first i terms in the original sequence. One day, he received N integer sequences, each with M terms, and named those sequences A_1,A_2,...,...
```python import sys readline = sys.stdin.readline from math import log2 from itertools import accumulate N, M = map(int, readline().split()) A = [list(map(int, readline().split())) for i in range(N)] B = max(max(Ai) for Ai in A) if M == 1: if N == 1 or all(A[i][0] < A[i+1][0] for i in range(N-1)): print("0...
p00008 Sum of 4 Integers
Write a program which reads an integer n and identifies the number of combinations of a, b, c and d (0 ≤ a, b, c, d ≤ 9) which meet the following equality: a + b + c + d = n For example, for n = 35, we have 4 different combinations of (a, b, c, d): (8, 9, 9, 9), (9, 8, 9, 9), (9, 9, 8, 9), and (9, 9, 9, 8). Input ...
```python import sys answer = [0] * 51 for a in range(10): for b in range(10): for c in range(10): for d in range(10): answer[a + b + c + d] += 1 for line in sys.stdin: try: print(answer[int(line)]) except: break ```
p00140 Bus Line
There is a bus route as shown in Figure 1. There are 10 stops, each numbered 0-9. The bus turns back at stop 0, but the other side is a circulation route, which circulates in the order of 5 → 6 → 7 → 8 → 9 → 5 as shown in the figure. <image> For this bus route, create a program that inputs the stop to get on and the...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0140 """ import sys from sys import stdin input = stdin.readline def solve(start, goal): path = [] # ?????????n??????????????????????????????????????? # ????????????????????¨????????´?????¨?????...
p00273 Admission Fee
Aiz Onsen has a bathhouse and a pool. To use the bathhouse, you need to buy a bathing ticket, and to use the pool, you need to buy a pool ticket. Prices for these tickets may vary from day to day. In addition, Aiz Onsen has the following rules. * Tickets are valid only once on the day of purchase. * If you buy 5 or mo...
```python n=int(input()) for i in range(n): a,b,c,d=map(int,input().split()) q,w,e,r,g=0,0,0,0,0 q,w=a*c,b*d e=q+w f=[] f.append(e) if c<5 and d<2: g=(a*5+b*2)*0.8 f.append(g) if c<5 and d>=2: g=(a*5+b*d)*0.8 f.append(g) if c>=5 and d<2: g=(a*c...
p00461 IOIOI
problem For the integer n (1 ≤ n), let Pn be a string of n + 1 I's and n O's starting with I and alternating, where I and O are the uppercase Ai and O, respectively. is there. P1 | IOI --- | --- P2 | IOIOI P3 | IOIOIOI |. | |. | |. | Pn | IOIOIO ... OI (n O) Figure 1-1 Character string considered in this question...
```python # -*- coding: utf-8 -*- """ IOIOI http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0538 """ import sys import re def solve(n, s): ans = 0 p = '(I(?:OI){' + str(n) + ',})' for f in re.findall(p, s): repeat = len(f) // 2 if repeat >= n: ans += (repeat - n + 1) ...
p00927 Space Golf
Example Input 100 1 0 50 100 Output 14.57738
```python import math d, n, b = map(int, input().split()) O = [list(map(int, input().split())) for i in range(n)] def solve(b): l = d / (b+1) idx = 0 vx2 = 10**9 for i in range(b+1): while idx < n and O[idx][0]*(b+1) <= d*(i+1): p, h = O[idx] p -= l*i vx2 = m...
p01060 Product Sale Lines
Problem Uniqlo Uzuki and Rin Meguro are coming to SEARIGHT LIVE FES for sale. As shown in the figure below, the product sales line consists of two lines, with W people in the horizontal direction and H people in the vertical direction, forming a U-shape. The person at the top of the line is removed from the line after...
```python w,h = map(int, input().split()) n = int(input()) p = list(map(int, input().split())) u = m = cnt = 0 for i in range(n): if p[i] == 0: u += 1 else: m += 1 if u <= w-2: if u == m: cnt += 1 elif w <= u <= w+h-3: if u == m+2: cnt += 1 eli...
p01497 Bubble Puzzle
A browser-based puzzle game called "Bubble Puzzle" is now popular on the Internet. The puzzle is played on a 4 × 4 grid, and initially there are several bubbles in the grid squares. Each bubble has a state expressed by a positive integer, and the state changes when the bubble gets stimulated. You can stimulate a bubbl...
```python from functools import reduce import operator def solve(): L = 4; M = 5 MP = [list(map(int, input().split())) for i in range(L)] memo = {(0,)*(L**2): 0} dd = ((-1, 0), (0, -1), (1, 0), (0, 1)) INF = 10 def dfs(k, R): key = reduce(operator.add, map(tuple, R)) if key in me...
p01810 Jail
prison There are an infinite number of prisoners. Initially, the prisoners are numbered 0, 1, 2, .... Do the following N times: * Release the 0th prisoner and execute the k, 2k, 3k, ... th prisoners. * Then renumber the remaining prisoners. At this time, the prisoners with the smallest original numbers are numbered ...
```python #!/usr/bin/env python3 n, k = map(int, input().split()) a = 0 for i in range(n-1): a = a * k // (k - 1) + 1 print(a) ```
p01945 Star in Parentheses
You are given a string $S$, which is balanced parentheses with a star symbol '*' inserted. Any balanced parentheses can be constructed using the following rules: * An empty string is balanced. * Concatenation of two balanced parentheses is balanced. * If $T$ is balanced parentheses, concatenation of '(', $T$, and ')'...
```python S = list(input()) S_l = len(S) n=0 l = [] r = [] f_l, f_r = 0,0 for n in range(S.index('*')): if S[n]== '(': f_l += 1 elif S[n]== ')': f_l -= 1 for n in range(S_l - S.index('*')): if S[S_l-n-1] == ')': f_r += 1 elif S[S_l-n-1]== '(': f_r -= 1 print(min(f_r, f_l)...
p02378 Bipartite Matching
A bipartite graph G = (V, E) is a graph in which the vertex set V can be divided into two disjoint subsets X and Y such that every edge e ∈ E has one end point in X and the other end point in Y. A matching M is a subset of edges such that each node in V appears in at most one edge in M. Given a bipartite graph, find ...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 3 4 6 0 0 0 2 0 3 1 1 2 1 2 3 output: 3 """ import sys def generate_adj_table(_edges): for edge in _edges: vx, vy = map(int, edge) init_adj_table[vx].add(vy) return init_adj_table def graph_dfs(current, matching, visited)...
1015_D. Walking Between Houses
There are n houses in a row. They are numbered from 1 to n in order from left to right. Initially you are in the house 1. You have to perform k moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current h...
```python import math def main(): n, k, s = [int(x) for x in input().split()] if (n - 1) * k < s: print('NO') return if k > s: print('NO') return curr = 1 print('YES') while s > 0: d = min(n - 1, s - k + 1) s -= d k -= 1 if cur...
1039_B. Subway Pursuit
This is an interactive problem. In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontr...
```python import sys,random n,k=map(int,input().split()) l=1 r=n count=0 while True: if l+200<r: try1=(l+r)//2 print(l,try1,flush=True) s=input() if s=='Yes': r=min(try1+10,n) l=max(1,l-10) else: l=max(1,try1-10) r=min(n,r+10) else: guess=random.randint(l,r) print...
1061_D. TV Shows
There are n TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The i-th of the shows is going from l_i-th to r_i-th minute, both ends inclusive. You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you...
```python from bisect import bisect_right n, x, y = map(int, input().split(' ')) s=[0]*n e=[0]*n v=[0]*n c=0 for i in range(n): s[i],e[i]=map(int, input().split(' ')) c+=x+(e[i]-s[i])*y s.sort() e.sort() for i in range(n-2,-1,-1): k=bisect_right(s,e[i]) while (k < n) and (v[k]==1) and (s[k]-e[i]) * y <...
1102_E. Monotonic Renumeration
You are given an array a consisting of n integers. Let's denote monotonic renumeration of array a as an array b consisting of n integers such that all of the following conditions are met: * b_1 = 0; * for every pair of indices i and j such that 1 ≤ i, j ≤ n, if a_i = a_j, then b_i = b_j (note that if a_i ≠ a_j, i...
```python import os import sys from io import BytesIO, IOBase import math from queue import Queue import collections import itertools import bisect import heapq # sys.setrecursionlimit(100000) # ^^^TAKE CARE FOR MEMORY LIMIT^^^ import random def main(): pass BUFSIZE = 8192 class FastIO(IOBase): newlines =...
1130_D2. Toy Train
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit afte...
```python n, m = map(int, input().split()) def dist(a, b): return (n + b - a) % n def main(): inp1 = [0] * (n + 1) inp2 = [n] * (n + 1) for _ in range(m): a, b = map(int, input().split()) inp1[a] += 1 inp2[a] = min(inp2[a], dist(a, b)) inp = tuple((((r1 - 1) * n + r2) for...
1151_A. Maxim and Biology
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG". Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of a...
```python Answer = 'ACTG' MIN = 10 ** 6 input() X = input() for i in range(0, len(X) - 3): Temp = X[i:i + 4] Index, Count = 0, 0 for j in Temp: tmp = 0 if ord(j) > ord(Answer[Index]): tmp += 26 + ord(Answer[Index]) - ord(j) else: tmp += 26 + ord(j) - ord(Answe...
1190_C. Tokitsukaze and Duel
"Duel!" Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started. There are n cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping card...
```python n, k = map(int,input().split()) s= input() fir0 = -1 last0 = -1 fir1 = -1 last1 = -1 for i in range(n): if(s[i] == '0'): if(fir0 == -1): fir0 = i last0 = i else: if(fir1 == -1): fir1 = i last1 = i d0 = last0 - fir0 d1 = last1 - fir1 if(min(d...
1228_F. One Node is Gone
You have an integer n. Let's define following tree generation as McDic's generation: 1. Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactl...
```python #!/usr/bin/python3 import array import math import os import sys DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) def solve(N, M, G): if N == 2: return [0, 1] ...
1293_D. Aroma's Search
[THE SxPLAY & KIVΛ - 漂流](https://soundcloud.com/kivawu/hyouryu) [KIVΛ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives) With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space. The space can be considered a 2D plane,...
```python x,y,a,b,c,d,xs,ys,t,maxx = [0]*10 arr = [] #must run now def abs(x): if x < 0: return 0 - x return x def max(x,y): if x > y: return x return y def dfs(idx,left,currx,curry,dir,cnt): global arr,maxx if dir == 0: if idx < 0: maxx = max(maxx,cnt) return else: if abs(currx - arr[...
1313_C2. Skyscrapers (hard version)
This is a harder version of the problem. In this version n ≤ 500 000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the compan...
```python import sys input=sys.stdin.readline n=int(input()) m=[int(i) for i in input().split()] copy=m[:] def maxsumchecker(arr): stack,lr=[],[0]*(n) for i in range(n): while stack and stack[-1][1]>m[i]: stack.pop() if stack: j=stack[-1][0] lr[i]=lr[j]+(i-j)*...
1336_A. Linova and Kingdom
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. <image> There are n cities and n-1 two-way roads connecting pairs of cities in the ki...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.wri...
1358_D. The Best Vacation
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha. You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly x days and that's the exact number of d...
```python def sm(a, b): val = (a + b) * (b - a + 1) // 2 return (val) n, x = [int(x) for x in input().split()] d = [int(x) for x in input().split()] * 2 mx, i, j, day, hug = 0, 0, 0, 0, 0 while(i < n): if day + d[j] <= x: day += d[j] hug += sm(1, d[j]) j += 1 else: mx =...
1399_E1. Weights Division (easy version)
Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last differ...
```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 from heapq import heappush,heappop,heapify...
1423_B. Valuable Paper
The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper. ...
```python def hopcroft_karp(graph, n, m): """ Maximum bipartite matching using Hopcroft-Karp algorithm, running in O(|E| sqrt(|V|)) """ assert (n == len(graph)) match1 = [-1] * n match2 = [-1] * m # Find a greedy match for possible speed up for node in range(n): for nei in graph...
1442_A. Extreme Subtraction
You are given an array a of n positive integers. You can use the following operation as many times as you like: select any integer 1 ≤ k ≤ n and do one of two things: * decrement by one k of the first elements of the array. * decrement by one k of the last elements of the array. For example, if n=5 and a=[3...
```python t = int(input()) for case in range(t): n = int(input()) a = list(map(int, input().split())) x = 0 low = a[0] works = True for i in range(1, n): if a[i] < x: print("NO") works = False break next_low = low if a[i] - x < low: ...
1468_C. Berpizza
Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently. At the start of the working day, there are no customers at the Berpizza. They come there one by one. W...
```python from sys import stdin from heapq import * Q = int(stdin.readline()) customer_id = 1 pq = [] first = 1 ans = [] served = set() for q in range(Q): args = stdin.readline().split() if args[0] == "1": heappush(pq, [-1*int(args[1]), customer_id]) customer_id += 1 elif args[0] == "2": ans.append...
1492_B. Card Deck
You have a deck of n cards, and you'd like to reorder it to a new one. Each card has a value between 1 and n equal to p_i. All p_i are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. p_1 stands for the bottom card, p_n is the top card. In each step you pick some integer k > 0, take the top ...
```python for t in range(int(input())): n = int(input()) a = list(map(int, input().split())) look = [0] * n look[0] = a[0] for i in range(1, n): look[i] = max(look[i - 1], a[i]) j = n ans = [] for i in range(n - 1, -1, -1): if look[i] == a[i]: ans.extend(a[i:j]) j = i print(*ans)...
1515_C. Phoenix and Towers
Phoenix has n blocks of height h_1, h_2, ..., h_n, and all h_i don't exceed some value x. He plans to stack all n blocks into m separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than x. P...
```python import heapq import sys input = iter(sys.stdin.read().splitlines()).__next__ def solve(): n, m, x = map(int, input().split()) h = list(map(int, input().split())) # greedy; put on shortest tower towers = [(0, i+1) for i in range(m)] y = [] for h_i in h: height, tower = heapq.h...
1542_B. Plus and Multiply
There is an infinite set generated as follows: * 1 is in this set. * If x is in this set, x ⋅ a and x+b both are in this set. For example, when a=3 and b=6, the five smallest elements of the set are: * 1, * 3 (1 is in this set, so 1⋅ a=3 is in this set), * 7 (1 is in this set, so 1+b=7 is in this set...
```python import sys input=sys.stdin.readline t=int(input()) for i in range(t): n,a,b=map(int,input().split()) if(a==1): if((n-1)%b==0): print('YES') else: print('NO') continue; t=1 flag=0 while(t<=n): if((n-t)%b==0): flag=1 ...
16_B. Burglar and Matches
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task i...
```python """ read: 1:01 think: 2:46 code: 10:48 debug: --:-- status: TL """ n, m = map(int, input().split()) c = [list(map(int, input().split())) for i in range(m)] c.sort(key=lambda x: x[1], reverse=True) mx = 0 i = 0 while n > 0 and i < m: add = min(n, c[i][0]) mx += add * c[i][1] n -= add i += 1 ...
18_E. Flag 2
According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set: * In each row at most two different colours can be used. * No two adjacent squares can be painted the same c...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m = map(int, input().split()) flag = [tuple(map(lambda c: ord(c) - 97, input().rstrip())) for _ in range(n)] dp = [[[m] * 26 for _ in range(26)] for _ in range(n)] for i in range(n): ...
237_E. Build String
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: 1. choose any non-empty string from strings s1, s2, ..., sn; 2. ch...
```python class Edge: def __init__(self, to, cost, capacity, next_edge): self.to = to self.cost = cost self.origin_cost = cost self.capacity = capacity self.next_edge = next_edge self.pair = None class MinCostMaxFlow: def __init__(self, max_node): self.n...
262_C. Maxim and Discounts
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the term...
```python m=int(input()) q=list(map(int,input().split())) n=int(input()) a=list(map(int,input().split())) q.sort() a.sort() j=n-1 i=0 ans=0 while j>=0: for i in range(q[0]): ans=ans+a[j] j=j-1 if j<0: break j=j-2 print(ans) ```
334_A. Candy Bags
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so th...
```python n=int(input())**2 k=0 for i in range(n//2): print(i+1,n-i,end=' ') k+=1 if k%2==0: print() ```
357_A. Group of Students
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 po...
```python m=int(input()) l=list(map(int,input().split())) x,y=map(int,input().split()) theI=0 for i in range(len(l)): first_sum=sum(l[0:i]) second_sum=sum(l[i:]) if (first_sum>=x and first_sum<=y) and (second_sum>=x and second_sum<=y): theI=i+1 print(theI) ```
400_D. Dima and Bacteria
Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are nu...
```python #!/usr/bin/env python3 from sys import stdin from bisect import bisect_left, bisect_right INF = int(1e9) def find(par, a): if par[a] == a: return a par[a] = find(par, par[a]) return par[a] def union(par, rnk, a, b): a = find(par,a) b = find(par,b) if a==b: return...
427_E. Police Patrol
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one. As you are going to be in charge of this new pol...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in...
450_C. Jzzhu and Chocolate
Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements: * each cut should be straight (horizontal or vertical); * each cut should go along edges of unit squares (it is prohibited to divide any unit choc...
```python #!/usr/bin/env python3 from itertools import * def read_ints(): return map(int, input().strip().split()) n, m, k = read_ints() def val(x, k, n, m): Y = x+1 Z = k-x+1 if Y>0 and Z>0: return (n//(x+1)) * (m//(k-x+1)) def sym(n, m, k): x = min(n-1, k) return val(x, k, n, m) def...
472_D. Design Tutorial: Inverse the Problem
There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example. Now ...
```python # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n=int(input()) arr=[] for _ in range(n): arr.append(list(map(int,input().split()))) if n==1: if arr[0][0]==0: ...
520_B. Two Buttons
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so...
```python n, m = [int(x) for x in input().split()] s = 0 while(n < m): s += 1 + (m % 2) m = (m + m % 2) // 2 print(s + n - m) ```
547_D. Mike and Fish
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish. <image> He has marked n distinct points in the plane. i-th point is point (xi, yi). He wants to put exactly one fish in each of these points such tha...
```python n = int(input()) edges = [] from collections import defaultdict edges_dico = {} count = defaultdict(int) graph = defaultdict(lambda: defaultdict(int)) edges = [] for _ in range(n): u, v = map(int, input().split()) count[u] += 1 count[-v] += 1 graph[u][-v] = 1 graph[-v][u] = 1 edges.ap...
574_A. Bear and Elections
Limak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland. There are n candidates, including Limak. We know how many citizens are going to vote for each candidate. Now i-th candidate would get ai votes. Limak is candidate number 1. To win in elections, he...
```python n=int(input()) a=list(map(int,input().split(" "))) lim=a[0] a[1:]=sorted(a[1:]) # print(a,a[-1]) t=0 while(a[0] <= a[-1]): a[0]=a[0]+1 a[-1]=a[-1]-1 t+=1 a[1:]=sorted(a[1:]) print(t) ```
595_D. Max and Bike
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions. He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight lin...
```python from math import * def solve(dist,spd): z=floor(dist/(2*pi)) ans=z*2*pi/spd dist=(dist-z*2*pi)/2 st,cur=3/spd,0 while st>=2e-7: if spd*(cur+st)+sin(spd*(cur+st))<=dist: cur+=st st/=2 return ans+cur*2 n,rd,v=map(int,input().split()) for i in range(n): l,r...
617_A. Elephant
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
```python if __name__ == '__main__': c = int(input()) x = [5,4,3,2,1] count = 0 while x!=[]: m = max(x) while c>=max(x): c=c-m count+=1 x.pop(0) print (count) ```
637_B. Chat Order
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then...
```python n = int(input()) chat_list = [] names = set() for i in range(n): name = input() if name not in names: names.add(name) chat_list.append(name) x = len(names) for i in chat_list[::-1]: if i in names: print(i) names.remove(i) x -= 1 if x == 0: br...
665_B. Shopping
Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order. Due to the...
```python user,item,total=map(int,input().split()) items=list(map(int,input().split())) to=0 for i in range(user): a=list(map(int,input().split())) for j in a: to+=items.index(j)+1 items.pop(items.index(j)) items=[j]+items print(to) ```
689_E. Mike and Geometry Problem
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that <image>). You are given two integers n and k and n closed intervals [li, ri] on OX axis an...
```python MOD = 10**9 + 7 from sys import stderr def readints(): return [int(fld) for fld in input().strip().split()] def combk(n, k, MOD=MOD, tbl=[]): if len(tbl) < k: tbl += [0] * k + [1] while n >= len(tbl): tbl.append(tbl[-1] * len(tbl) * pow(len(tbl) - k, MOD-2, MOD) % MOD) retur...
711_C. Coloring Trees
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right. Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m dif...
```python import math dp=[[[math.inf for i in range(105)] for i in range(105)] for i in range(105)] #dp[x][y][z] denote index x , beauty y , using paint z #dp[x][y][z] denotes cost of it n,m,k=map(int,input().split()) k+=1 z=list(map(int,input().split())) matrix=[] for i in range(n): ans=list(map(int,input().spl...
732_C. Sanatorium
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes ho...
```python mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) a,b,c=sorted(il(),reverse=True) sm=0 if a!=b: sm+=max(0,(a-b-1))+max(0,(a-c-1)) else: ...
777_E. Hanoi Factory
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strang...
```python aux = [(9e9, 0, 0)] n = int(input()) for i in range(n): a, b, h = map(int, input().split()) aux.append((b, a, h)) #sort padrao eh pelo item 0 da tupla aux.sort(reverse=True) s, p = [0], [0] *(n + 1) for i in range(1, n + 1): while aux[s[-1]][1] >= aux[i][0]: s.pop() p[...
965_C. Greedy Arkady
k people want to split n candies between them. Each candy should be given to exactly one of them or be thrown away. The people are numbered from 1 to k, and Arkady is the first of them. To split the candies, Arkady will choose an integer x and then give the first x candies to himself, the next x candies to the second ...
```python n, k, m, d = map(int, input().split()) ans = 0 for i in range(d + 1): w = 0 if i > 0: w = n // (k * i) if w > m: w = m res = w * i if n - k * i * w >= w and i + 1 <= d: res += w ans = max(ans, res) w = n // (k * i + 1) if w > m: w = m res =...
992_C. Nastya and a Wardrobe
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month). Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with ...
```python #------------------------template--------------------------# import os import sys # from math import * from collections import * # from fractions import * from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output....
p02624 AtCoder Beginner Contest 172 - Sum of Divisors
For a positive integer X, let f(X) be the number of positive divisors of X. Given a positive integer N, find \sum_{K=1}^N K\times f(K). Constraints * 1 \leq N \leq 10^7 Input Input is given from Standard Input in the following format: N Output Print the value \sum_{K=1}^N K\times f(K). Examples Input 4 O...
```python N=int(input()) ans=0 for i in range(1,N+1): n=N//i ans+=n*(n+1)*i//2 print(ans) ```
p02755 AtCoder Beginner Contest 158 - Tax Increase
Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.) Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded d...
```python A,B=map(int,input().split());v=max(A*25+1>>1,B*10);print(v if v<min(A*25+26>>1,B*10+10)else-1) ```
p02890 AtCoder Beginner Contest 143 - Distinct Numbers
Takahashi has N cards. The i-th of these cards has an integer A_i written on it. Takahashi will choose an integer K, and then repeat the following operation some number of times: * Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.) For...
```python import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 input=lambda :sys.stdin.readline().rstrip() def resolve(): from collections import Counter n=int(input()) A=list(Counter(map(int,input().split())).values()) A.sort() m=len(A) S=[0]*(m+1) # cumulative distribution...
p03025 M-SOLUTIONS Programming Contest - Best-of-(2n-1)
Takahashi and Aoki will play a game. They will repeatedly play it until one of them have N wins in total. When they play the game once, Takahashi wins with probability A %, Aoki wins with probability B %, and the game ends in a draw (that is, nobody wins) with probability C %. Find the expected number of games that wi...
```python M=10**9+7 N,A,B,C=map(int,input().split()) f=[1] for i in range(1,2*N): f.append(f[-1]*i%M) t=pow(A+B,M-2,M) A*=t B*=t a=pow(A,N,M) b=pow(B,N,M) z=0 for i in range(N): z+=(N+i)*100*pow(100-C,M-2,M)*f[N+i-1]*pow(f[N-1]*f[i],M-2,M)*(a+b) z%=M a=a*B%M b=b*A%M print(z) ```
p03166 Educational DP Contest - Longest Path
There is a directed graph G with N vertices and M edges. The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i. G does not contain directed cycles. Find the length of the longest directed path in G. Here, the length of a directed path is the num...
```python import sys sys.setrecursionlimit(1000000) n, m = map(int, input().split()) g = [[] for _ in range(n)] for _ in range(m): x, y = map(int, input().split()) x, y = x -1, y-1 g[x].append(y) # dp[v]: ノードvを起点にしたときの、Gの有効パスの長さの最大値 dp = [-1]*n def rec(v): if dp[v] != -1: return dp[v] else: res...
p03309 AtCoder Beginner Contest 102 - Linear Approximation
Snuke has an integer sequence A of length N. He will freely choose an integer b. Here, he will get sad if A_i and b+i are far from each other. More specifically, the sadness of Snuke is calculated as follows: * abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N)) Here, abs(x) is a function that returns the...
```python n=int(input()) a=list(map(int,input().split())) for i in range(n): a[i]-=i+1 a.sort() m=a[n//2] sum=0 for x in a: sum+=abs(x-m) print(sum) ```
p03630 AtCoder Regular Contest 081 - Flip and Rectangles
We have a board with an H \times W grid. Each square in the grid is painted in black or white. The square at the i-th row from the top and j-th column from the left is black if the j-th character in S_i is `#`, and white if that character is `.`. Snuke can perform the following operation on the grid any number of time...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines """ ・2x2内の偶奇が不変量。これが偶数なら、そこは単色でとれる ・単色でとれる領域を調べる -> 色変更なしに大きい長方形をとる問題になる ・ベースラインを固定すると、ヒストグラムの長方形の問題(アリ本) """ H,W = map(int,readline().split()) grid = read().replace(b'\r',b'').replace(b'\n',b...
p03788 AtCoder Grand Contest 011 - Half Reflector
Takahashi has a lot of peculiar devices. These cylindrical devices receive balls from left and right. Each device is in one of the two states A and B, and for each state, the device operates as follows: * When a device in state A receives a ball from either side (left or right), the device throws out the ball from the...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) from collections import deque # f(AX) = XB # f(BX) = flip(X) + A = flip(XB) N,K = map(int,readline().split()) S = read().rstrip() S = deque(0 if x == b'A'[0] el...
p00046 Differential
There is data that records the altitude of mountains that have been climbed so far. Create a program that reads this data and outputs the elevation difference between the highest and lowest mountains. Input The input is given in the following format: Mountain height ... ... The height of the mountain is given o...
```python minv = 10000000 maxv = 0 while 1: try: n = float(input()) if minv > n: minv = n if maxv < n: maxv = n except: break print(maxv-minv) ```
p00178 TETORIS
Tetris is a game in which falling blocks are lined up on the board and erased. Here, let's consider a game that arranges it a little. The size of the board of this game is 5 frames wide, and it is high enough to accommodate all the blocks that appear. The falling blocks are straight and come in two types, landscape an...
```python while 1: N = int(input()) if N == 0: break L = 5000 MP = [[0]*L for i in range(5)] cs = [L]*5 us = [] U = [0]*L for i in range(N): d, p, q = map(int, input().split()); q -= 1 if d == 1: y = L for j in range(p): y =...
p00334 Geometric Data
Computer graphics uses polygon models as a way to represent three-dimensional shapes. A polygon model is a model that creates a surface by giving the coordinates of vertices and how to connect those vertices. A general polygon model can handle any polygon, but this time we will consider a polygon model consisting of t...
```python N = int(input()) l = [] count = 0 for _ in range(N): p = set(map(int, input().split())) if p in l: count+=1 else: l.append(p) print(count) ```
p00519 Taxis
problem The IOI country consists of N towns from town 1 to town N, and the towns are connected by roads. The IOI country has K roads, all of which connect two different towns. Cars can move freely in both directions on the road, but they cannot go from one town to another through anything other than the road. JOI, wh...
```python from heapq import heappop as pop from heapq import heappush as push def main(): n, k = map(int, input().split()) clst = [] rlst = [] for i in range(n): c, r = map(int, input().split()) clst.append(c) rlst.append(r) edges = [[] * n for i in range(n)] for i in range(k): ...
p00692 Patience
As the proverb says, > "Patience is bitter, but its fruit is sweet." Writing programs within the limited time may impose some patience on you, but you enjoy it and win the contest, we hope. The word "patience" has the meaning of perseverance, but it has another meaning in card games. Card games for one player are ca...
```python # AOJ 1110: Patience # Python3 2018.7.8 bal4u pair = [[1,4,5], [2,4,5,6], [3,5,6,7], [6,7], [5,8,9], [6,8,9,10], [7,9,10,11], [10,11], [9,12,13], [10,12,13,14], [11,13,14,15], [14,15], [13,16,17], [14,16,17,18], [15,17,18,19], [18,19], [17], [18], [19]] def combi(cd, n): global ans ans = min(ans, n) i...
p00833 Color the Map
You were lucky enough to get a map just before entering the legendary magical mystery world. The map shows the whole area of your planned exploration, including several countries with complicated borders. The map is clearly drawn, but in sepia ink only; it is hard to recognize at a glance which region belongs to which ...
```python def main(): while 1: N = int(input()) if N == 0: break D = {} G = [set() for i in range(N)] cur = 0 K = [] PS = [] for i in range(N): ps = [] s = input() if s in D: k = D[s] ...
p00965 Starting a Scenic Railroad Service
Problem I Starting a Scenic Railroad Service Jim, working for a railroad company, is responsible for planning a new tourist train service. He is sure that the train route along a scenic valley will arise a big boom, but not quite sure how big the boom will be. A market survey was ordered and Jim has just received an ...
```python n = int(input()) ab = [list(map(int, input().split())) for _ in range(n)] pol1 = 0 pol2 = 0 ft = [[0] * 2 for _ in range(100000)] for i in ab: ft[i[0] - 1][0] += 1 ft[i[1] - 1][1] += 1 ftsum = [[0] * 2 for _ in range(100000)] ftsum[0][0] = ft[0][0] for i in range(1, len(ft)): ftsum[i][0] = ft...
p01097 3D Printing
3D Printing We are designing an installation art piece consisting of a number of cubes with 3D printing technology for submitting one to Installation art Contest with Printed Cubes (ICPC). At this time, we are trying to model a piece consisting of exactly k cubes of the same size facing the same direction. First, usi...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools input = sys.stdin.readline INF = 10**20 EPS = 1.0 / 10**10 MOD = 10**9 + 7 def LI(): return [int(x) for x in input().split()] def LF(): return [float(x) for x in input().split()] def LS(): return input().sp...
p01367 Operator
The customer telephone support center of the computer sales company called JAG is now in- credibly confused. There are too many customers who request the support, and they call the support center all the time. So, the company wants to figure out how many operators needed to handle this situation. For simplicity, let u...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def check(N, C, T, x): used = [0]*N S = [0]*(T+1) cap = x f = 0 for t in range(T): cap += S[t] if cap == 0: continue for i in range(f, N): if used[i]: continue ...
p01549 Zero Division Checker
Mr. Morishita was in trouble ... I had Mr. Anehara write a program, but the program crashed. Mr. Anehara wrote a program that reads the formula in Reverse Polish Notation and outputs the calculation result. According to the crash log, it seems that the cause was that it was divided by 0. This may be because Mr. Morish...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01705 Square in Circles
Problem Statement Circles Island is known for its mysterious shape: it is a completely flat island with its shape being a union of circles whose centers are on the $x$-axis and their inside regions. The King of Circles Island plans to build a large square on Circles Island in order to celebrate the fiftieth anniversa...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False C = [list(map(int, readline().split())) for i in range(N)] e = 2**.5/2 r_min = max(r*e for x, r in C) r_max = max(r for x, r in C) H = [] for i in ...
p01849 The Most Powerful Bed
My futon You bought N futons in preparation for your new life. The i-th futon has the warmth supply capacity of si. From the temperature forecast for the next M days, the warmth demand of dj is expected on the jth day. If the warmth is not enough or too much, the comfort will be impaired, so the absolute value of the ...
```python from collections import deque while 1: n, m = map(int, input().split()) if n == m == 0: break *S, = map(int, input().split()) D = sorted(map(int, input().split())) SA = sum(S) rest = sum(d-SA for d in D if SA <= d) memo = {2**n-1: rest} def dfs(state, su, idx): ...
p01985 Divide and Conquer
Divide and rule Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads. One day, Taro and Hanako finally made a mistake and decided to share the city and go...
```python import sys input = sys.stdin.readline def main(): while True: N, M = map(int, input().split()) if N == 0: break path = [[False] * N for i in range(N)] for i in range(M): u, v = map(int, input().split()) u -= 1; v -= 1; path[u...
p02272 Merge Sort
Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function. Merge(A, left, mid, right) n1 = mid - left; n2 = right - mid; create array L[0...n1], R[0...n2] for i = 0 to n1-1 do L[i] = A[left + i] for i = 0 to n2-1 do R[i] =...
```python count = 0 def merge(a, left, mid, right): global count l = a[left:mid] r = a[mid:right] l.append(10**9+1) r.append(10**9+1) i = 0 j = 0 for k in range(left, right): count += 1 if l[i] <= r[j]: a[k] = l[i] i += 1 else: ...
p02419 Finding a Word
Write a program which reads a word W and a text T, and prints the number of word W which appears in text T T consists of string Ti separated by space characters and newlines. Count the number of Ti which equals to W. The word and text are case insensitive. Constraints * The length of W ≤ 10 * W consists of lower cas...
```python A=0 W=str(input()) while True: t=str(input()) if t=='END_OF_TEXT': break t=(t.lower().split()) a=(t.count(W)) A=A+a print(A) ```
1041_E. Tree Reconstruction
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is...
```python # def solve(): n = int(input()) d = {} for _ in range(n-1): u, v = map(int, input().split()) min_ = min(u, v) max_ = max(u, v) if max_ != n: return False, None if min_ not in d: d[min_] = 0 d[min_] += ...
1064_D. Labyrinth
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not o...
```python #!/usr/bin/env python3 import sys from collections import deque from math import inf def rint(): return map(int, sys.stdin.readline().split()) #lines = stdin.readlines() def bfs(sr, sc): global ans q = deque() q.append((x, y, sr, sc)) visit[sr][sc] = 1 ans += 1 while q: l...
1086_B. Minimum Diameter Tree
You are given a tree (an undirected connected graph without cycles) and an integer s. Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible. Let's define the diameter of...
```python n, s = map(int, input().split()) a = [0] * n if n == 2: xc, xd = map(int, input().split()) print(s) exit() for i in range(n - 1): xc, xd = map(int, input().split()) a[xd - 1] += 1 a[xc - 1] += 1 cnt = 0 for i in range(n): if a[i] == 1: cnt += 1 print(2 * round(s / cnt, 10))...
1106_B. Lunar New Year and Food Ordering
Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's". The restaurant "Alice's" serves n kinds of food. The cost for the i-th kind is always c_i. Initially, the restaurant has enough ingredients for serving exactly a_i dishes of the i-th kind. In the New Year's Eve, m customers w...
```python n, m = map(int, input().split()) dish = list(map(int, input().split())) cost = list(map(int, input().split())) scost = [] for i in range(n): scost.append([cost[i], dish[i], i]) scost = sorted(scost) # print(scost) cur = 0 for i in range(m): x, y = map(int, input().split()) x -= 1 # print(x, ...
1133_C. Balanced Team
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i. You have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maxi...
```python n=int(input().strip()) numbers=list(map(int,input().strip().split(" "))) numbers.sort() start=0 current=0 l=[] tot=0 while (current<len(numbers) and start<len(numbers)): if(numbers[current]-numbers[start]>5): start=start+1 l.append(tot) tot-=1 else: tot+=1 curre...