name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
924_B. Three-level Laser
An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: ...
```python import heapq from bisect import bisect_left, bisect_right from collections import Counter from collections import OrderedDict from collections import deque from itertools import accumulate, product import math R = lambda: map(int, input().split()) n, u= R() arr = list(R()) res = -1 for l in range(n): r...
952_D. I'm Feeling Lucky!
<image> You have one chip and one chance to play roulette. Are you feeling lucky? Output Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).
```python print("red") ```
99_A. Help Far Away Kingdom
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there. Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki...
```python import sys import math import itertools import collections def getdict(n): d = {} if type(n) is list or type(n) is str: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() ...
p02538 ACL Beginner Contest - Replace Digits
You have a string S of length N. Initially, all characters in S are `1`s. You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i. After each query, read th...
```python MOD = 998244353 class LazySegmentTree: # from https://atcoder.jp/contests/practice2/submissions/16598122 __slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"] def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator, fu...
p02669 AtCoder Grand Contest 044 - Pay to Win
You start with the number 0 and you want to reach the number N. You can change the number, paying a certain amount of coins, with the following operations: * Multiply the number by 2, paying A coins. * Multiply the number by 3, paying B coins. * Multiply the number by 5, paying C coins. * Increase or decrease the num...
```python from heapq import heapify, heappop, heappush from collections import defaultdict Inf = 10**28 inpl = lambda: list(map(int,input().split())) T = int(input()) for _ in range(T): N, A, B, C, D = inpl() visited = defaultdict(lambda: Inf) ans = Inf pool = [(0,N)] # coin, number while pool: ...
p02798 Keyence Programming Contest 2020 - Swap and Flip
We have N cards numbered 1, 2, ..., N. Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side. Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up. Determine whether it is ...
```python n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) ans = 10**10 for bit in range(1<<n): l = a[:] rev = [0]*n for i in range(n): if bit & 1<<i: rev[i] = 1 l[i] = b[i] if sum(rev) % 2: continue odd = list() even = list() for i in range(n): ...
p02934 AtCoder Beginner Contest 138 - Resistors in Parallel
Given is a sequence of N integers A_1, \ldots, A_N. Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}. Constraints * 1 \leq N \leq 100 * 1 \leq A_i \leq 1000 Input Input is given from Standard Input in the following format: N A_1 A_2 \...
```python n,a=open(0) print(1/sum(1/int(i)for i in a.split())) ```
p03071 AtCoder Beginner Contest 124 - Buttons
There are two buttons, one of size A and one of size B. When you press a button of size X, you get X coins and the size of that button decreases by 1. You will press a button twice. Here, you can press the same button twice, or press both buttons once. At most how many coins can you get? Constraints * All values i...
```python a,b=sorted(map(int,input().split()));print(b+b-1 if b-1>a else b+a) ```
p03213 AtCoder Beginner Contest 114 - 756
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there? Here, a Shichi-Go number is a positive integer that has exactly 75 divisors. Constraints * 1 \leq N \leq 100 * N is an integer. Input Input is given from S...
```python N = int(input()) e = [0 for _ in range(N + 1)] for i in range(2, N + 1): for j in range(2, i + 1): while i % j == 0: i //= j e[j] += 1 c = tuple(filter(lambda x: x > 0, e)) # 素因数の指数 dp = [[0 for _ in range(75 + 1)] for _ in range(len(c) + 1)] # dp[素因数のidx][約数の個数] = 条件を...
p03362 AtCoder Beginner Contest 096 - Five Five Everywhere
Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions: * a_i (1 \leq i \leq N) is a prime number at most 55 555. * The values of a_1, a_2, ..., a_N are all different. * In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite n...
```python print(*[11,31,41,61,71,101,131,151,181,191,211,241,251,271,281,311,331,401,421,431,461,491,521,541,571,601,631,641,661,691,701,751,761,811,821,881,911,941,971,991,1021,1031,1051,1061,1091,1151,1171,1181,1201,1231,1291,1301,1321,1361,1381,1451,1471,1481,1511,1531][:int(input())],sep=" ") ```
p03520 CODE FESTIVAL 2017 Elimination Tournament Round 1 (Parallel) - Ancient Tree Record
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows: * The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1. * Edge i connected Vertex a_i and b_i. * The length of each edge was an integer between 1 and 10^{18} (inclusive). * The sum of the ...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N = int(readline()) data = list(map(int,read().split())) A = data[:N+N-2:2] B = data[1:N+N-2:2] INF = 10 ** 18 + 100 S = [INF] + data[-N:] graph = [[] for _ in range(N+1)] for a,b in zip(A,B):...
p03685 AtCoder Regular Contest 076 - Connected?
Snuke is playing a puzzle game. In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}). The objective is to draw a curve connecting the pair of points where the same integer i...
```python def ri(): return int(input()) def rli(): return list(map(int, input().split())) def rls(): return list(input()) def pli(a): return "".join(list(map(str, a))) R, C, N = rli() lis = [] idx = 0 i = 0 for j in range(N): x1, y1, x2, y2 = rli() if((x1 % R == 0 or y1 % C == 0) and (x2 % R == 0 or y2 % C ==...
p03838 AtCoder Grand Contest 008 - Simple Calculator
Snuke has a calculator. It has a display and two buttons. Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order: * Button A: When pressed, the value on the display is incremented by 1. * Button ...
```python x,y = map(int,input().split()) ans = 10**18 dx = [1,1,-1,-1] dy = [1,-1,1,-1] for i in range(4): tx = x * dx[i] ty = y * dy[i] if tx <= ty: ans = min(ans,ty-tx + (2-dx[i]-dy[i])//2) print(ans) ```
p04005 AtCoder Grand Contest 004 - Divide a Cuboid
We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that: * There is at least one red block and at least one blue block. * The union of all red blocks forms a rectangular parallelepiped. * The union of all blue blocks for...
```python a,b,c=map(int,input().split()) if(a%2==0 or b%2==0 or c%2==0): print(0) else: print(min(a*b,b*c,c*a)) ```
p00091 Blur
There is a "cloth" of 10 × 10 squares as shown in Fig. 1, and the squares are indicated by a pair of X-coordinate and Y-coordinate values ​​as shown in (1 and 2). The coordinate value is an integer starting from 0. For example, the coordinates of ◎ in Figure 1 are (1, 2). Dye is made by adding dye to this "cloth" littl...
```python import itertools dx = (0, 0, 0, 1,-1, 1, 1,-1,-1,-2, 2, 0, 0) dy = (0, 1,-1, 0, 0, 1,-1, 1,-1, 0, 0,-2, 2) dd = (5, 9, 13) def drop(fab, start, used, size_list): for xy in range(start, 100): y = xy%10 x = xy//10 size = size_list[used] for i in range(size): if ...
p00223 Stray Twins
Takayuki and Kazuyuki are good twins, but their behavior is exactly the opposite. For example, if Takayuki goes west, Kazuyuki goes east, and if Kazuyuki goes north, Takayuki goes south. Currently the two are in a department store and are in different locations. How can two people who move in the opposite direction mee...
```python from collections import deque def search(tx, ty, kx, ky, mp): direct = ((-1, 0, 1, 0), (1, 0, -1, 0), (0, -1, 0, 1), (0, 1, 0, -1)) dic = {} dic[(tx, ty, kx, ky)] = 0 que = deque() que.append((0, (tx, ty, kx, ky))) while que: dist, p = que.popleft() tx, ty, kx, ky = p for dtx, dty, dk...
p00737 Twirling Robot
Let's play a game using a robot on a rectangular board covered with a square mesh (Figure D-1). The robot is initially set at the start square in the northwest corner facing the east direction. The goal of this game is to lead the robot to the goal square in the southeast corner. <image> Figure D-1: Example of a boar...
```python import sys from collections import deque from heapq import heappush,heappop d = [(0,1),(1,0),(0,-1),(-1,0)] def bfs(): dist = [[[float("inf")]*4 for i in range(w)] for j in range(h)] dist[0][0][0] = 0 q = [(0,0,0,0)] while q: dn,y,x,c = heappop(q) for di in range(4): ...
p00877 Separate Points
Numbers of black and white points are placed on a plane. Let's imagine that a straight line of infinite length is drawn on the plane. When the line does not meet any of the points, the line divides these points into two groups. If the division by such a line results in one group consisting only of black points and the ...
```python def dot(c1, c2): return c1.real * c2.real + c1.imag * c2.imag def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def on_segment(p, a, b): # whether p is on segment ab v1 = a - p v2 = b - p return cross(v1, v2) == 0 and dot(v1, v2) < 0 def ccw(p0, p1, p2): return cro...
p01008 Last One
Problem You decide to play a weird game with your friend A, who loves gathering. Given a set S of non-negative integers consisting of n elements that can be duplicated. Each element contained in the set S is a non-negative pi-ary number. With Steps 1 to 3 below as one turn for the set S, you and your opponent repeat ...
```python # AOJ 1518: Last One # Python3 2018.7.13 bal4u ans = 0; for i in range(int(input())): p = input().split(); if len(p) == 1: ms = [] else: ms = list(p[1]) s = 0 for m in ms: if m.isdigit(): s += int(m) elif m.isupper(): s += ord(m)-ord('A')+10 else: s += ord(m)-ord('a')+36 ans ^= s print("win" if a...
p01140 Square Route
Square Route Square root English text is not available in this practice contest. Millionaire Shinada, who has decided to build a new mansion, is wondering in which city to build the new mansion. To tell the truth, Mr. Shinada is a strange person who likes squares very much, so he wants to live in a city with as many...
```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(input()) def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) wh...
p01449 Space-Time Sugoroku Road
All space-time unified dimension sugoroku tournament. You are representing the Earth in the 21st century in the tournament, which decides only one Sugoroku absolute champion out of more than 500 trillion participants. The challenge you are currently challenging is one-dimensional sugoroku with yourself as a frame. Sta...
```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 ...
p01755 AI
A robot, a wall, and a goal are installed on the board, and a program that describes the behavior pattern of the robot is given. The given program is represented by the following EBNF. Program: = {statement}; Statement: = if statement | while statement | action statement; if statement: = "[", condition, program, "]"...
```python def main(): H, W = map(int, input().split()) MP = [input() for i in range(H)] for i in range(H): mi = MP[i] for j in range(W): c = mi[j] if c == 's': sx = j; sy = i elif c == 'g': gx = j; gy = i S = input() ...
p02032 Divisor Game
C: Divisor Game problem tsutaj is trying to play about a few games. In a divisor game, a natural number N of 2 or more is given first, and then the game progresses according to the following procedure. * Declare one integer from the divisors of N other than N. However, at this time, it is not possible to declare a ...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' ------------------------ author : iiou16 ------------------------ ''' import copy def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: ...
p02175 Strange Plants
problem A mysterious $ X $ [cm] plant grows in one place. This plant has the following mysterious properties. * Say "nobiro" to this plant and it will grow $ A $ [cm]. * Say "tidime" to this plant and it will grow $ B $ [cm]. * If you say "karero" to this plant, it will be $ 0 $ [cm]. However, this plant does not ...
```python X,A,B = map(int,input().split()) N = int(input()) S = [input() for i in range(N)] for s in S: if s=='nobiro': X += A elif s=='tidime': X += B else: X = 0 if X < 0: X = 0 print(X) ```
p02318 Edit Distance (Levenshtein Distance)
Find the edit distance between given two words s1 and s2. The disntace is the minimum number of single-character edits required to change one word into the other. The edits including the following operations: * insertion: Insert a character at a particular position. * deletion: Delete a character at a particular posi...
```python s1=input() s2=input() dist=[[0 for i in range(len(s1)+1)] for j in range(len(s2)+1)] for i in range(len(s1)+1): dist[0][i]=i for i in range(len(s2)+1): dist[i][0]=i for i in range(1,len(s2)+1): for j in range(1,len(s1)+1): k=1 if s1[j-1]==s2[i-1]:k=0 dist[i][j]=min(dist[i-1...
p02463 Set Union
Find the union of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$. Constraints * $1 \leq n, m \leq 200,000$ * $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$ * $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$ Input The input is given in the following format. $n$ $a_0 \; a_1 \; ... \; a...
```python n = int(input()) nums = set(map(int, input().split())) m = int(input()) nums.update(set(map(int, input().split()))) for n in sorted(nums): print(n) ```
1011_B. Planning The Expedition
Natasha is planning an expedition to Mars for n people. One of the important tasks is to provide food for each participant. The warehouse has m daily food packages. Each package has some food type a_i. Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the sam...
```python '''input 3 9 42 42 42 42 42 42 42 42 42 ''' from collections import Counter n, m = map(int, input().split()) if n > m: print(0) quit() a = list(map(int, input().split())) d = 1 c = Counter(a).values() while True: s = sum([i//d for i in c]) if s >= n: d += 1 else: break print(d - 1) ```
1036_C. Classy Numbers
Let's call some positive integer classy if its decimal representation contains no more than 3 non-zero digits. For example, numbers 4, 200000, 10203 are classy and numbers 4231, 102306, 7277420000 are not. You are given a segment [L; R]. Count the number of classy integers x such that L ≤ x ≤ R. Each testcase contain...
```python def ncr(n, r): return int(fact(n) / (fact(r) * fact(n - r))) # Returns factorial of n def fact(n): res = 1 for i in range(2, n + 1): res = res * i return res def f(s): j=0 ans=0 cnt=0 n=len(s) while(j<n): if int(s[j])!=0: ...
1059_B. Forgery
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of ...
```python import sys, math n, m = map(int, sys.stdin.readline().split()) arr = [list(sys.stdin.readline().rstrip()) for _ in range(n)] ans = [['.'] * m for _ in range(n)] dx = [0,1,0,-1,1,1,-1,-1] dy = [1,0,-1,0,1,-1,1,-1] for i in range(n): for j in range(m): cnt = 0 for k in range(8): ...
1080_D. Olya and magical square
Recently, Olya received a magical square with the size of 2^n× 2^n. It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly k splitting operations. A Splitting operation is an operation during which Olya takes a square with side a and cuts it into 4 equal squares with side a/2. ...
```python t=int(input()) for _ in range(t): n,k=list(map(int,input().split())) if n>=32: print("YES "+str(n-1)) else: ans=-1 for i in range(1,n+1): p=(4**i)-(2**(i+1))+1 p*=(((4**(n-i))-1)//3) g=(((4**i)-1)//3) p+=(((4**i)-1)//3) g=(((4**i)-1)//3)-(((4**(i-1))-1)//3) if g<=k and p>=k: ans...
10_C. Digital Root
Not long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x ...
```python n, ans, a = int(input()), 0, [0] * 10 for i in range(1, n + 1): ans -= int(n/i) a[i % 9] += 1 for i in range(9): for j in range(9): ans += a[i] * a[j] * a[(i * j) % 9] print(ans) ```
1121_B. Mike and Children
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets. Mike has n sweets with sizes a_1, a_2, …, a_n. All his sweets have different sizes. That is, there is no such pair ...
```python n = int(input()) a = list(map(int,input().split())) res = 10**6 * [0] for j in range(0, n): for h in range(j + 1, n): res[a[j] + a[h]] += 1 print(max(res)) ```
1148_D. Dirty Deeds Done Dirt Cheap
You are given n pairs of integers (a_1, b_1), (a_2, b_2), …, (a_n, b_n). All of the integers in the pairs are distinct and are in the range from 1 to 2 ⋅ n inclusive. Let's call a sequence of integers x_1, x_2, …, x_{2k} good if either * x_1 < x_2 > x_3 < … < x_{2k-2} > x_{2k-1} < x_{2k}, or * x_1 > x_2 < x_3 >...
```python import sys input=sys.stdin.readline n=int(input()) li=[] for i in range(n): li.append(list(map(int,input().split()))+[i+1]) li.sort(key=lambda x:x[0],reverse=True) ans1=0 xx1=[] for i in range(n): if(li[i][1]>li[i][0]): ans1+=1 xx1.append(li[i][2]) ans2=0 xx2=[] for i in range(n): ...
116_A. Tram
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
```python n = int(input()) tram = [] current = [] curr = 0 for i in range(0, n): tram.extend([int(x) for x in input().split()]) for i in range(0, 2*n, 2): curr -= tram[i] curr += tram[i+1] current.append(curr) print(max(current)) ```
1188_A1. Add on a Tree
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al...
```python n = int(input()) # n, k = map(int, input().split()) # a = [int(i) for i in input().split()] d = [0 for i in range(n + 1)] for i in range(n - 1): a, b = map(int, input().split()) d[a] += 1; d[b] += 1 for val in d: if val == 2: print("NO") exit() print("YES") ```
1207_A. There Are Two Types Of Burgers
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ...
```python t = int(input()) for case in range(t): profit = 0 buns, beef_patties, cutlets = [int(b) for b in input().split()] beef_price, cutlet_price = [int(h) for h in input().split()] possible_burgers = buns // 2 if beef_price >= cutlet_price: if beef_patties > possible_burgers: beef_patties = possible_bur...
1225_B2. TV Subscriptions (Hard Version)
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day. The...
```python t = int(input()) for _ in range(t): n, k, d = map(int, input().split()) c = [int(x) for x in input().split(' ')] e = {} a = d for i in range(n): if i >= d: a = min(a, len(e.keys())) x = e.get(c[i-d]) if len(x) == 1: del(e[c[i-d]]) ...
1249_D2. Too Many Segments (hard version)
The only difference between easy and hard versions is constraints. You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i. The integer point is called bad...
```python import heapq n,k = map(int,input().split()) llis = [ [] for i in range(2 * (10**5) + 1) ] rlis = [ [] for i in range(2 * (10**5) + 1) ] flag = [0] * (2 * (10**5) + 1) for i in range(n): l,r = map(int,input().split()) llis[l].append([i+1,r]) rlis[r].append([i+1,l]) now = 0 rq = [] ans = [...
1268_A. Long Beautiful Integer
You are given an integer x of n digits a_1, a_2, …, a_n, which make up its decimal notation in order from left to right. Also, you are given a positive integer k < n. Let's call integer b_1, b_2, …, b_m beautiful if b_i = b_{i+k} for each i, such that 1 ≤ i ≤ m - k. You need to find the smallest beautiful integer y,...
```python '''input 3 2 354 ''' s=list(map(int,input().split())) x,k=s[0],s[1] s=input() m=x-k print(x) if k<m: abc=s[0:k] p=(m//k)+1 abc=abc*p abc=abc[0:m] abd=abc[::-1] abc=abc+abd[0:k][::-1] if int(abc)>=int(s): print(abc) else: abc=str(int(s[0:k])+1) p=(m//k)+1 abc=abc*p abc=abc[0:m] abd=abc[::-1...
1290_B. Irreducible Anagrams
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t. Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k ≥ 2 and 2k non-empty strings s_1, t_1, s_...
```python s = input() n = len(s) # print(ord('b')) # print("s: {}".format(s)) prefix_letter_occurence = [[0 for i in range(n+1)] for i in range(26)] for i in range(1, n+1): cur_letter = s[i-1] for l in range(26): prefix_letter_occurence[l][i] = prefix_letter_occurence[l][i-1] + int(l == ord(cur_letter) - 97) # ...
1333_A. Little Artem
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n × m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
```python case = int(input()) for i in range(case): a = list(map(int, input().rstrip().split())) column = a[1] row = a[0] l = [["W"] * a[1] for _ in range(a[0])] b = ((a[1] * a[0]) // 2)+1 w = b - 1 x = 0 y = 0 while (b > 0 and y < row): l[y][x] = "B" x += 2 i...
1353_D. Constructing the Array
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears: 1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; 2. Let ...
```python import sys input = sys.stdin.readline from collections import * from heapq import * t = int(input()) for _ in range(t): n = int(input()) a = [-1]*n pq = [(n, 0, n-1)] now = 1 while now<=n: _, l, r = heappop(pq) if (r-l)%2==0: m = (l+r)//2 els...
1373_C. Pluses and Minuses
You are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0 for init = 0 to inf cur = init ok = true for i = 1 to |s| res = res + 1 ...
```python for _ in range(int(input())): arr=list(input()) n=len(arr) fix=1;mis=0;plus=0 ans=0 for i in range(n): if(arr[i]=="-"): if(plus>0): plus-=1 continue else: ans+=(i+1) if(arr[i]=="+"): plus+=1...
1396_B. Stoned Game
T is playing a game with his friend, HL. There are n piles of stones, the i-th pile initially has a_i stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th...
```python def win(a, last = -1): for i, el in enumerate(a): a2 = a[:] a2[i] -= 1 if i != last and el > 0 and not win(a2, i): return True return False def solve(a): s = sum(a) for i in a: if i > s - i: return True return s % 2 == 1 for t in ra...
141_D. Take-off Ramps
Vasya participates in a ski race along the X axis. The start is at point 0, and the finish is at L, that is, at a distance L meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second. Besides, there are n take-off ramps on the track, ea...
```python from heapq import * n, L = [int(i) for i in input().split()] dots = [0, L] tr, ind = {}, {} for i in range(n): x, d, t, p = [int(i) for i in input().split()] if x - p < 0 or t >= d: continue tr.setdefault(x - p, []) tr[x - p].append((x + d, p + t, i)) dots.append(x - p) dot...
1438_D. Powerful Ksenia
Ksenia has an array a consisting of n positive integers a_1, a_2, …, a_n. In one operation she can do the following: * choose three distinct indices i, j, k, and then * change all of a_i, a_j, a_k to a_i ⊕ a_j ⊕ a_k simultaneously, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwi...
```python from sys import stdin, stdout import math,sys,heapq from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict from os import path import random import bisect as bi def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #------------------Su...
1463_C. Busy Robot
You have a robot that can move along a number line. At time moment 0 it stands at point 0. You give n commands to the robot: at time t_i seconds you command the robot to go to point x_i. Whenever the robot receives a command, it starts moving towards the point x_i with the speed of 1 unit per second, and he stops when...
```python import sys import bisect input=sys.stdin.readline t=int(input()) for you in range(t): n=int(input()) l=[] for i in range(n): z=input().split() u=int(z[0]) v=int(z[1]) l.append((u,v)) l.append((10**18,0)) counter=0 currtime=0 currpos=0 reqtime=0 ...
148_C. Terse princess
«Next please», — the princess called and cast an estimating glance at the next groom. The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous on...
```python n,ohh,wow= list(map(int , input().split())) if(wow==0): if(n>=ohh+2): print(1,end=" ") print(1,end=" ") for i in range(1,ohh+1): print(i+1,end=" ") for i in range(n-ohh-2): print(ohh+1,end=" ") elif(ohh==0): for i in range(n): ...
1512_A. Spy Detected!
You are given an array a consisting of n (n ≥ 3) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array [4, 11, 4, 4] all numbers except one are equal to 4). Print the index of the element that does not equal others. The numbers in the array are numbered f...
```python t=int(input()) for i in range(t): n=int(input()) arr=[int(x) for x in input().split()] my_list=[] my_list1=[] for j in range(len(arr)): c_count=arr.count(arr[j]) my_list.append(arr[j]) my_list1.append(c_count) mid= min(my_list1) req=(my_list1.index(mid)) req1=my_list[req] for k in range(len(arr...
1539_E. Game with Cards
The Alice's computer is broken, so she can't play her favorite card game now. To help Alice, Bob wants to answer n her questions. Initially, Bob holds one card with number 0 in the left hand and one in the right hand. In the i-th question, Alice asks Bob to replace a card in the left or right hand with a card with nu...
```python import sys input = sys.stdin.readline n, m = map(int, input().split()) K, A0, B0, A1, B1 = [], [], [], [], [] for _ in range(n): k = int(input()) a0, b0 = map(int, input().split()) a1, b1 = map(int, input().split()) K.append(k) A0.append(a0) B0.append(b0) A1.append(a1) B1.appe...
166_B. Polygons
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecu...
```python def convex_hull(points): points = sorted(set(points)) if len(points) <= 1: return points def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) lower = [] for p in points: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) ...
208_A. Dubstep
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
```python word = input() word = str.replace(word,'WUB',' ') list1 = word.split() print(' '.join(list1)) ```
233_D. Table
John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points. John Doe wondered, how many distinct ways to fill the table with points are there, provided that...
```python n,m,k=map(int,input().split()) M=int(1e9+7) N=n*n iv=[0]*(N+1) iv[1]=1 for i in range(2, N+1): iv[i]=M-M//i*iv[M%i]%M f1=[1]*(N+1) for i in range(1, N+1): f1[i]=f1[i-1]*i%M f2=[1]*(N+1) for i in range(1, N+1): f2[i]=f2[i-1]*iv[i]%M left=m%n #m/n+1, m/n def powM(b, p): r=1 while p>0: ...
259_C. Little Elephant and Bits
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper. To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ...
```python s=list(input()) for i in range(len(s)): if s[i]=='0': break del(s[i]) print("".join(s)) ```
282_C. XOR and OR
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string. A Bitlandish string is a string made only of characters "0" and "1". BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish ...
```python def helper(a,b): n=len(a) m=len(b) if n!=m: return 'NO' if a==b: return 'YES' if a=='0'*n or b=='0'*m: return'NO' return 'YES' a=input() b=input() print(helper(a,b)) ```
305_B. Continued Fractions
A continued fraction of height n is a fraction of form <image>. You are given two rational numbers, one is represented as <image> and the other one is represented as a finite fraction of height n. Check if they are equal. Input The first line contains two space-separated integers p, q (1 ≤ q ≤ p ≤ 1018) — the numerat...
```python #import math def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) p, q = map(int, input().split()) n = int(input()) data = list(map(int, input().split())) a = 1 b = data[-1] for i in range(2, n + 1): a = b * data[n - i] + a a, b = b, a a, b = b, a nod = gcd(p, q) p = p // nod ...
353_A. Domino
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even. To do t...
```python n=int(input()) (eo,sl,su)=(0,0,0) for i in range(0,n): (a,b)=map(int,input().split(" ")) sl=sl+b su=su+a if (a%2==0 and b%2==1)or(a%2==1 and b%2==0): eo=1 if sl%2==0 and su%2==0: print(0) elif((sl%2==1 and su%2==1)): if eo: print(1) else: print(-1) else:...
377_B. Preparing for the Contest
Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the ...
```python from sys import stdin import heapq n,m,s = [int(x) for x in stdin.readline().split()] bugs = [int(x) for x in stdin.readline().split()] bugs = sorted([(bugs[x],x) for x in range(m)]) order = [x[1] for x in bugs] bugs = [x[0] for x in bugs] students = [int(x) for x in stdin.readline().split()] rate = [int(...
421_E. Cup Trick
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble...
```python import io import os # List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py class UnsortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" value...
448_C. Painting Fence
Bizon the Champion isn't just attentive, he also is very hardworking. Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one...
```python import sys sys.setrecursionlimit(10000) # hago n-1 llamadas recursivas para largo n, por default el limit es 1000 creo def cantidad_de_brochazos(izq,der,altura): """ :param izq: limite izquierdo de la zona a pintar :param der: limite derecho de la zona a pintar :param altura: altura hasta la...
46_D. Parking Lot
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of...
```python l, b, f = map(int, input().split()) p = [[-b, -b, -192], [l + f, l + f, -38]] n = int(input()) for i in range(1, n + 1): a, h = map(int, input().split()) if a == 1: k = False for w in range(len(p) - 1): if p[w + 1][0] - p[w][1] >= b + f + h: p.insert(w + 1, ...
492_E. Vanya and Field
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell <image>. The following condition is satisfi...
```python n,m,dx,dy = map(int,input().split()) x=y=0 a=[0]*n c=[0]*n for i in range(1,n): x = (x+dx)%n y = (y+dy)%n a[x]=y for i in range(m): x,y = map(int,input().split()) index = (y-a[x]+n)%n; c[index] += 1 ans = 0 for i in range(n): if c[i] > c[ans]: ans = i print(0, ans) ```
543_D. Road Improvement
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that...
```python class Graph: def __init__(self, n_vertices, edges, directed=True, weighted=False): self.n_vertices = n_vertices self.edges = edges self.directed = directed self.weighted = weighted @property def adj(self): try: return self._adj except ...
570_A. Elections
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate. The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each...
```python N, M = [int(x) for x in input().split()] results = [0] * N for i in range(M): city_results = [int(x) for x in input().split()] city_max = max(city_results) city_max_idx = city_results.index(city_max) results[city_max_idx] += 1 max_result = max(results) max_index = results.index(max_result)...
591_D. Chip 'n Dale Rescue Rangers
A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road. We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at poi...
```python #d = list(map(int,input().split())) #V,T = map(int,input().split()) #v = tuple(map(int,input().split())) #w = tuple(map(int,input().split())) #o = d[0:2] #d = d[2:4] #l,r = 0, 1000000000 #for i in range(300): # m,e = (l+r)/2, o[:] # if m <= T: # e[0] += m * v[0] # e[1] += m * v[1] # el...
613_B. Skills
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai — the current skill level. All skills have the same maximum level A. Along with...
```python n,A,cf,cm,mN = map(int,input().split()) a = list(map(int,input().split())) aCOPY = [] for elem in a: aCOPY.append(elem) a.sort() aPartialSum = [0] for elem in a: aPartialSum.append(aPartialSum[-1] + elem) maxScore = 0 ansMAXIBound = 0 ansMAXI = 0 ansMIN = 0 for MAXI in range(n + 1): currentSco...
633_B. A Trivial Problem
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem? Input The only line of input contains ...
```python from math import log n = int(input()) def fivetorization(n): cnt = 0 while n%5==0: cnt+=1 n//=5 return cnt res=0 for i in range(5, 500001, 5): res+=fivetorization(i) if res==n: print(5) print(*[j for j in range(i, i+5)]) quit() print(0) ```
730_A. Toda 2
A group of n friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the i-th friend is ri. The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consist...
```python # -*- coding: utf-8 -*- """ Created on Thu Nov 2 13:36:10 2017 @author: savit """ def sum1(b): sum1=0 for i in range(len(b)): sum1+=b[i][0] return sum1 n=int(input()) a=list(map(int,input().split())) if(n!=2): do=True b=[] min2=min(a) for i in range(n): a[i]-...
774_E. Big Number and Remainder
Stepan has a very big positive integer. Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203...
```python s = input() m = int(input()) mn = m ttt = 0 t = 0 ttt = 1 for i in range(1,len(s)): ttt = (ttt * 10) % m for i in range(0,len(s)): t = (t * 10 + ord(s[i]) - ord('0')) % m for i in range(0,len(s)): if s[i] != '0': mn = min(mn,t) t = t - (((ord(s[i])- ord('0')) * ttt) % m) if t < 0: ...
819_E. Mister B and Flight to the Moon
In order to fly to the Moon Mister B just needs to solve the following problem. There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles. We are sure that Mister B will solve the problem soon and will fly to the Mo...
```python #!/usr/bin/env python3 from collections import defaultdict DEBUG = False def main(): if DEBUG: test() n = int(input()) paths = cycles(n) print(len(paths)) for p in paths: print('%d %s' % (len(p), ' '.join([str(v) for v in p]))) def cycles(n): """Builds a set of...
845_C. Two TVs
Polycarp is a great fan of television. He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri. Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given mom...
```python num_shows = int(input()) showtimes = [] for i in range(num_shows): showtime = [int(i) for i in input().split(" ")] showtimes.append((showtime[0], showtime[1])) showtimes = sorted(showtimes) tv1 = -1 tv2 = -1 start_time = min(st[0] for st in showtimes) end_time = max(st[1] for st in showtimes) fai...
936_B. Sleepy Game
Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't m...
```python import sys data = sys.stdin.readlines() n, m = map(int, data[0].split()) g = {} for i, line in enumerate(data[1:-1], 1): g[i] = list(map(int, line.split()[1:])) mk = {} start = int(data[-1]) queue = [(start, 0, -1, 1)] cycle = False while len(queue) > 0: v, player, prev, color = queue.pop() if c...
961_G. Partitions
You are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as <image>. The weight of some partition R of a given set into k subsets is <image> (recall that a partition of a given set is a set of its subsets such that every element of the ...
```python def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x...
98_A. Help Victoria the Wise
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that. The box's lock is constructed...
```python from functools import reduce def factorial(n): return reduce(lambda x, y: x*y, range(1,n+1)) colors = { 'R' : 0, 'O' : 0, 'Y' : 0, 'G' : 0, 'B' : 0, 'V' : 0 } for c in list(input()): colors[c] += 1 amount = list(reversed(sorted([(colors[key], key) for key in colors]))) amo...
p02604 M-SOLUTIONS Programming Contest 2020 - M's Solution
New AtCoder City has an infinite grid of streets, as follows: * At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point. * A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coor...
```python import sys input = sys.stdin.readline def main(): n = int(input()) l = [list(map(int,input().split())) for i in range(n)] xcal = [[0]*n for i in range(1<<n)] ycal = [[0]*n for i in range(1<<n)] for i in range(1<<n): for j in range(n): xcal[i][j] = abs(l[j][0]) ...
p02735 AtCoder Grand Contest 043 - Range Flip Find Route
Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left. Each square is painted black or white. The grid is said to be good if and only if the following condition is satisfied: * From (1, 1), we can reach (H, W) by moving one sq...
```python h, w = map(int, input().split()) s = [list(input()) for _ in range(h)] dp = [[h * w] * w for _ in range(h)] dp[0][0] = 0 if s[0][0] == "." else 1 for x0 in range(w): for y0 in range(h): for i, j in [(0, 1), (1, 0)]: x = x0 + i y = y0 + j if x < w and y < h: ...
p02869 NIKKEI Programming Contest 2019-2 - Non-triangular Triplets
Given are positive integers N and K. Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples. * For every integer i from 1 to N, a_...
```python n,k=map(int,input().split()) if 2*k-1>n: print(-1) else: a=[i for i in range(k,k+n)] A=[] for i in range(len(a)): if i%2==0: A.append(a[i]) for i in range(len(a)): if i%2==1: A.append(a[i]) b1=[i for i in range(k+n,k+n+(n+1)//2)] b2=[i for i in range(k+n+(n+1)//2,k+2*n)] b1...
p03004 AtCoder Beginner Contest 130 - Minimum Bounding Box
There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:...
```python INF = float('inf') N = int(input()) xConstMin, xConstMax = INF, -INF xAscMin, xAscMax = INF, -INF xDescMin, xDescMax = INF, -INF yConstMin, yConstMax = INF, -INF yAscMin, yAscMax = INF, -INF yDescMin, yDescMax = INF, -INF for _ in range(N): x, y, d = input().split() x, y = int(x), int(y) if d ==...
p03288 AtCoder Beginner Contest 104 - Rated for Me
A programming competition site AtCode regularly holds programming contests. The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200. The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800. The contest after the ARC is called AG...
```python v = int(input()) if v < 1200: print('ABC') elif v < 2800: print('ARC') else: print('AGC') ```
p03444 AtCoder Petrozavodsk Contest 001 - Generalized Insertion Sort
You are given a rooted tree with N vertices. The vertices are numbered 0, 1, ..., N-1. The root is Vertex 0, and the parent of Vertex i (i = 1, 2, ..., N-1) is Vertex p_i. Initially, an integer a_i is written in Vertex i. Here, (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). You can execute the followi...
```python from collections import deque def get_children(ps): children = [set() for _ in range(n)] for i, p in enumerate(ps): children[p].add(i + 1) return children def make_levels(cs): levels_set = [] levels_dict = {} queue = deque([(0, 0)]) while queue: i, l = queue.pop...
p03604 AtCoder Regular Contest 083 - Collecting Balls
There are 2N balls in the xy-plane. The coordinates of the i-th of them is (x_i, y_i). Here, x_i and y_i are integers between 1 and N (inclusive) for all i, and no two balls occupy the same coordinates. In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B. Then, he placed the type-A r...
```python import sys input = sys.stdin.readline MOD = 10**9 + 7 N = int(input()) ball = (tuple(int(x) for x in row.split()) for row in sys.stdin.readlines()) # x座標を1,2,...,N # y座標をN+1,N+2,...,N+N graph = [set() for _ in range(N+N+1)] for x,y in ball: graph[x].add(y+N) graph[y+N].add(x) visited = [False] * ...
p03765 AtCoder Regular Contest 071 - TrBBnsformBBtion
Let us consider the following operations on a string consisting of `A` and `B`: 1. Select a character in a string. If it is `A`, replace it with `BB`. If it is `B`, replace with `AA`. 2. Select a substring that is equal to either `AAA` or `BBB`, and delete it from the string. For example, if the first operation is ...
```python import sys input = sys.stdin.readline s, t, q = list(input()), list(input()), int(input()) ssum, tsum = [0], [0] for i in range(len(s)): if s[i]=="A": ssum.append(ssum[-1]+1) else: ssum.append(ssum[-1]+2) for i in range(len(t)): if t[i]=="A": tsum.append(tsum[-1]+1) else: tsum.append(tsum[-1]+...
p00026 Dropping Ink
As shown in the following figure, there is a paper consisting of a grid structure where each cell is indicated by (x, y) coordinate system. We are going to put drops of ink on the paper. A drop comes in three different sizes: Large, Medium, and Small. From the point of fall, the ink sinks into surrounding cells as sho...
```python board = [[0]*10 for _ in range(10)] while True: try: x, y, size = map(int, input().split(',')) except: break small = [(-1, 0), (0, -1), (0, 0), (0, 1), (1, 0)] med = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)] large =...
p00157 Russian Dolls
<image> Matryoshka is a wooden doll in the shape of a female figure and is a typical Russian folk craft. Matryoshka has a nested structure in which smaller dolls are contained inside a large doll, and is composed of multiple dolls of different sizes. In order to have such a nested structure, the body of each doll has ...
```python while True: n = int(input()) if n == 0: break hr_lst = [] for _ in range(n): h, r = map(int, input().split()) hr_lst.append((h, r)) m = int(input()) for _ in range(m): h, r = map(int, input().split()) hr_lst.append((h, r)) hr_lst.sort(reverse=True) r_lst = [[] for _ ...
p00314 Programming Contest
A programming contest will be held at White Tiger University this year as well. There are several questions in the contest, each of which is assigned a score according to the difficulty level. The executive committee decided to calculate the score for each team based on the following rules, taking into account both th...
```python n = int(input()) p = list(map(int, input().split())) def count(l, n): ans = 0 for i in l: if i >= n: ans += 1 return ans for i in reversed(range(max(p)+1)): if count(p, i) >= i: print(i) break ```
p00484 Books
There is a long-established secondhand bookstore called JOI secondhand bookstore in your town, and you often use the JOI secondhand bookstore. Each book has a standard price, and you can buy it at that price if you go to the JOI secondhand bookstore. At the JOI secondhand bookstore, books are classified into 10 genres...
```python def solve(): n, k = map(int,input().split()) group_num = 10 book_map = [[] for i in range(group_num)] acc_map = [[0] for i in range(group_num)] for i in range(n): c, g = map(int,input().split()) book_map[g - 1].append(c) for i in range(group_num): bmi = book_map[i] bmi.sort(re...
p00670 Spellcasters
There are n wizards. They are numbered from 1 to n, and the i-th wizard has the magical power ri (1 ≤ i ≤ n). Now they are confronting a powerful wizard, whose enemy's magical power is S. n Wizards are good at fighting together, especially two people. When two wizards cooperate, the magical power is simply the sum, and...
```python while 1: n,s=map(int,input().split()) if n==0:break r=[0]*101 for _ in [0]*n:r[int(input())]+=1 a=0 for i in range(101): if i*2>s:a+=(r[i]**2-r[i])//2 a+=r[i]*sum(r[j] for j in range(max(i+1,s+1-i),101)) print(a) ```
p01829 Change a Password
Example Input 201 Output 701
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x i...
p02111 Clock
Problem Gaccho has his favorite watch. One day the minute hand of the clock came off and I lost it somewhere. However, Gaccho wants to keep using the watch and wants to read the time with only the short hand. Output the time (hour h, minute m) for the information θ of the short hand. A clock is a so-called analog clo...
```python t = int(input())*2 print(t//60, t%60) ```
p02251 Change Making
You want to make change for $ n $ cents. Assuming that you have infinite supply of coins of 1, 5, 10 and / or 25 cents coins respectively, find the minimum number of coins you need. Constraints * $ 1 \ le n \ le 10 ^ 9 $ Input $ n $ The integer $ n $ is given in a line. output Print the minimum number of coins...
```python import heapq from collections import deque from enum import Enum import sys import math from _heapq import heappush, heappop BIG_NUM = 2000000000 MOD = 1000000007 EPS = 0.000000001 COIN = [25,10,5,1] N = int(input()) ans = 0 for i in range(len(COIN)): ans += N//COIN[i] N %= COIN[i] print("%d"%(a...
p02399 A / B Problem
Write a program which reads two integers a and b, and calculates the following values: * a ÷ b: d (in integer) * remainder of a ÷ b: r (in integer) * a ÷ b: f (in real number) Constraints * 1 ≤ a, b ≤ 109 Input Two integers a and b are given in a line. Output Print d, r and f separated by a space in a line. For ...
```python a,b = map(int,input().split()) print('%d %d %.5f'%(a/b,a%b,a/b)) ```
1005_E1. Median on Segments (Permutations Edition)
You are given a permutation p_1, p_2, ..., p_n. A permutation of length n is a sequence such that each integer between 1 and n occurs exactly once in the sequence. Find the number of pairs of indices (l, r) (1 ≤ l ≤ r ≤ n) such that the value of the median of p_l, p_{l+1}, ..., p_r is exactly the given number m. The ...
```python n, m = map(int, input().split(' ')) aa = list(map(int, input().split(' '))) def countMoreLess(vs, value): #print(vs) cur = 0 res = { cur: 1 } for v in vs: cur += 1 if v > value else -1 res[cur] = res.get(cur, 0) + 1 #print(res) return res pos = aa.index(m) leftCount...
1029_C. Maximal Intersection
You are given n segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. The intersection of a sequence of segments is such a maximal set of points (not necesserily having...
```python def intersect(x, y): if x < y: return (y[0], x[1]) else: return (x[0], y[1]) def solve(iv): first = {} second = {} for x, y in iv: first[x] = first.get(x, 0) + 1 second[y] = second.get(y, 0) + 1 max1, max2 = reversed(sorted([x for x, _ in iv])[-2:]) ...
104_B. Testing Pants for Sadness
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to ...
```python n = int(input()) l = list(map(int,input().split())) if len(set(l)) == 1 and l[0] == 1 or n == 1 : print(sum(l)) else: cnt = l[0] for i in range(1 , n): cnt += l[i] + (l[i]-1) * i print(cnt) ```
1071_C. Triple Flips
You are given an array a of length n that consists of zeros and ones. You can perform the following operation multiple times. The operation consists of two steps: 1. Choose three integers 1 ≤ x < y < z ≤ n, that form an arithmetic progression (y - x = z - y). 2. Flip the values a_x, a_y, a_z (i.e. change 1 to 0...
```python def solve(a): l = len(a) d = sum(a[i] * 2 ** i for i in range(l)) if d == 0: return [] usable = [] if l >= 3: for i in range(l - 2): usable.append(0b111 << i) if l >= 5: for i in range(l - 4): usable.append(0b10101 << i) if l >= 7: ...
1141_G. Privatization of Roads in Treeland
Treeland consists of n cities and n-1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree. There are some private road companies in Treeland. The government decided to sell roads to t...
```python from __future__ import print_function import os,sys,atexit if sys.version_info[0] < 3: range = xrange from cStringIO import StringIO as BytesIO sys.stdout = BytesIO() else: from io import BytesIO sys.stdout = BytesIO() _write = sys.stdout.write sys.stdout.write = lambda s: _write(...
1162_B. Double Matrix
You are given two n × m matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly...
```python # !/usr/bin/env python3 # encoding: UTF-8 # Modified: <04/May/2019 11:12:46 PM> # ✪ H4WK3yE乡 # Mohd. Farhan Tahir # Indian Institute Of Information Technology (IIIT),Gwalior # ///==========Libraries, Constants and Functions=============/// import sys def get_array(): return list(map(int, sys.stdin.rea...
1183_A. Nearest Interesting Number
Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4. ...
```python def fun(x): s=0 org=x while(x): s+=x%10 x=x//10 temp=s%4 if temp : org+=1 return fun(org) else : return org x=int(input()) print(fun(x)) ```
1200_B. Block Adventure
Gildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column. Gildong plays the g...
```python t = int(input()) for _ in range(t): n, m, k = map(int, input().split()) h = list(map(int, input().split())) for i in range(n - 1): m += h[i] - max(0, (h[i + 1] - k)) if m < 0: print("NO") break if(m >= 0): print("YES") ```
1242_A. Tile Painting
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles wit...
```python from sys import stdin import math n=int(stdin.readline()) if n<3: k=n else: d=0 g=n for i in range(2,int(math.sqrt(n))+1): if n%i==0: d+=1 g=math.gcd(g,i) if i*i!=n: d+=1 g=math.gcd(g,n//i) if d==0: k=n ...