name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
725_B. Food on the Plane
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats...
```python s = input() n = int(s[:len(s) - 1]) - 1 time = (n // 4) * 16 k = n % 4 if k in [1,3]: time += 7 a = [4, 5, 6, 3, 2, 1] time += a[ord(s[-1]) - ord('a')] print(time) ```
747_B. Mammoth's Genome Decoding
The process of mammoth's genome decoding in Berland comes to its end! One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is...
```python n, s, g, c, r = int(input()), input(), 'ACGT', [], '===' if n % 4 != 0: exit(print(r)) for i in g: c.append(s.count(i)) if c[-1] > n // 4: exit(print(r)) for i in range(4): for j in range(c[i], n // 4): s = s.replace('?', g[i], 1) print(s) ```
76_E. Points
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points. Input The first line of input contains one integer number N (1 ≤ N ≤ 100 000) — the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≤ X, Y ≤ 10...
```python import math if __name__== '__main__': n = int(input()) n_1= n- 1 totalDistance= 0 Xs= [] Ys= [] xs= [] ys= [] xAddition= 0 yAddition= 0 for _ in range(n): x, y= [int(x) for x in input().split()] Xs.append(n_1* x* x) Ys.append(n_1* y* y) ...
794_B. Cutting Carrot
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangl...
```python from math import sqrt n,hn = list(map(int,input().split())) kn = sqrt(n) h = hn/kn for i in range(1,n): print(h*sqrt(i),end = ' ') ```
815_A. Karen and Game
On the way to school, Karen became fixated on the puzzle game on her phone! <image> The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or col...
```python from itertools import product n, m = map(int, input().split()) matr = [] for i in range(n): matr.append([int(num) for num in input().split()]) def walker(start_row, start_col, dif_row, dif_col): row = start_row col = start_col while 0 <= row < n and 0 <= col < m: yield row, col ...
840_A. Leha and Function
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets. But only function does not interest him. He wan...
```python import operator class pa(): def __init__(self,b,i): self.b = b self.i = i n = int(input()) a = list(map(int,input().strip().split(' '))) b = list(map(int,input().strip().split(' '))) a.sort() m = [] for i in range(n): tp = pa(b[i],i) m.append(tp) m.sort(key=operator.attrgetter('b')) c = [0]*n fo...
860_B. Polycarp's phone book
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for whi...
```python n = int(input()) s, p = {}, [''] * n for k in range(n): p[k] = t = input() for q in [t[i: j] for i in range(9) for j in range(i + 1, 10)]: s[q] = -1 if q in s and s[q] != k else k for q, k in s.items(): if k >= 0 and len(p[k]) > len(q): p[k] = q print('\n'.join(p)) # Made By Mos...
887_A. Div. 64
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
```python n=list(input()) m=len(n) e=0 s=1 if n.count('1')==0: s=0 for i in range(0,m): if n[i]=='1': e=i break k=n[e:] if s==1: if k.count('0')>=6: print('yes') else: print('no') else: print('no') ```
90_A. Cableway
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway. A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them ...
```python rgb = [int(i) for i in input().split()] r = rgb[0] g = rgb[1] b = rgb[2] x = (r+1) // 2 * 3 - 3 y = (g+1) // 2 * 3 - 2 z = (b+1) // 2 * 3 - 1 print(max(x, y, z) + 30) ```
931_D. Peculiar apple-tree
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch...
```python from collections import Counter tree = [] class Node: def __init__(self, num=None): self.length = 0 if num is None else tree[num-1].length + 1 def main(): n = int(input()) global tree tree = [Node()] for x in input().split(): tree.append(Node(int(x))) print(sum([...
958_F2. Lightsabers (medium)
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of th...
```python n, m = map(int, input().split()) c = list(map(int, input().split())) k = list(map(int, input().split())) p = [0] * m c = [i -1 for i in c] s = sum(k) cnt = k.count(0) l = 0 r = 0 while r < n and cnt < m: p[c[r]] += 1 if p[c[r]] == k[c[r]]: cnt += 1 r += 1 if cnt != m: print(-1) exi...
985_D. Sand Fortress
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand o...
```python from math import ceil, sqrt n, H = map(int, input().split(' ')) k = ceil(0.5*(sqrt(8*n+1)-1)) while k*k+k >= 2*n: k -= 1 while k*k+k < 2*n: k += 1 if k <= H: print(k) else: k = ceil(sqrt(2*H*H-2*H+4*n)-H) if (k - H) % 2 == 1: k += 1 a = (k-H)//2 while (H+a)*(H+a+1) + ...
p02577 AtCoder Beginner Contest 176 - Multiple of 9
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9. Determine whether N is a multiple of 9. Constraints * 0 \leq N < 10^{200000} * N is an integer. Input Input is given from Standard Input in the following format: N Output If N is a multi...
```python n = int(input()) if n % 9 is 0: print('Yes') else: print('No') ```
p02708 AtCoder Beginner Contest 163 - Sum of Large Numbers
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N. We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7). Constraints * 1 \leq N \leq 2\times 10^5 * 1 \leq K \leq N+1 * All values in input are integers. Input Input is given from S...
```python n,k=map(int,input().split()) mod=10**9+7 ans=0 for i in range(k,n+2): ans=(ans+(n-i+1)*i+1)%mod print(ans) ```
p02837 AtCoder Beginner Contest 147 - HonestOrUnkind2
There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not. Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony say...
```python n = int(input()) evi = [] for _ in range(n): m = int(input()) evi.append([list(map(int, input().split())) for _ in range(m)]) ans = 0 for i in range(1 << n): for j in range(n): if ((i >> j) & 1) == 1: for x,y in evi[j]: if ((i >> (x-1))&1) != y: ...
p02974 AtCoder Beginner Contest 134 - Permutation Oddness
Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|. Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7. Constraints * All values in input are integers. * 1 \leq n \leq 50 * 0 \leq k \leq n^2 Input Input is given from...
```python def main(): """ convenient functions # for i, a in enumerate(iterable) # q, mod = divmod(a, b) # divmod(x, y) returns the tuple (x//y, x%y) # Higher-order function: reduce(operator.mul, xyz_count, 1) # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f ...
p03110 AtCoder Beginner Contest 119 - Digital Gifts
Takahashi received otoshidama (New Year's money gifts) from N of his relatives. You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either `JPY` or `BTC`, and x_i and u_i represent the content of the otoshidama from the i-th relative. For example, if x_1 = `10000` a...
```python n=int(input()) ans=0 for _ in range(n): x,u=input().split() if u=='JPY': ans+=int(x) else: ans+=float(x)*38e4 print(ans) ```
p03257 AtCoder Grand Contest 027 - Modulo Matrix
You are given an integer N. Construct any one N-by-N matrix a that satisfies the conditions below. It can be proved that a solution always exists under the constraints of this problem. * 1 \leq a_{i,j} \leq 10^{15} * a_{i,j} are pairwise distinct integers. * There exists a positive integer m such that the following h...
```python #!/usr/bin/python3 import random, math, fractions def lcm(a, b): return (a // fractions.gcd(a, b)) * b def is_prime(n): i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True def primes(n): lst = [] for i in range(2, n + 1): if is...
p03413 AtCoder Regular Contest 092 - Both Sides Merger
You have an integer sequence of length N: a_1, a_2, ..., a_N. You repeatedly perform the following operation until the length of the sequence becomes 1: * First, choose an element of the sequence. * If that element is at either end of the sequence, delete the element. * If that element is not at either end of the seq...
```python def examC(): ans = 0 print(ans) return def examD(): ans = 0 print(ans) return def examE(): N = I() A = LI() ans = -inf S = [0]*(N+1) fr = [-1]*N best = -1 for i,a in enumerate(A): S[i] = a for j in range(i): if ((i-j)%2==0): ...
p03573 AtCoder Beginner Contest 075 - One out of Three
You are given three integers, A, B and C. Among them, two are the same, but the remaining one is different from the rest. For example, when A=5,B=7,C=5, A and C are the same, but B is different. Find the one that is different from the rest among the given three integers. Constraints * -100 \leq A,B,C \leq 100 * A, B ...
```python a,b,c=map(int,input().split()) print((b==c)*a+(c==a)*b+(a==b)*c) ```
p03728 AtCoder Grand Contest 014 - Strange Sorting
Takahashi loves sorting. He has a permutation (p_1,p_2,...,p_N) of the integers from 1 through N. Now, he will repeat the following operation until the permutation becomes (1,2,...,N): * First, we will define high and low elements in the permutation, as follows. The i-th element in the permutation is high if the maxi...
```python N = int(input()) P = list(map(int, input().split())) if N == 1: print(0) exit() Pi = [0] * (N + 1) for i, n in enumerate(P, 1): Pi[n] = i T = [0] * N f = [0] * N if Pi[N] > Pi[N - 1]: T[N - 1] = 0 f[N - 1] = N - 1 else: T[N - 1] = 1 f[N - 1] = N for i in range(N - 2, 0, -1): ...
p03892 CODE FESTIVAL 2016 Relay (Parallel) - Segment on Grid Paper
Takahashi is drawing a segment on grid paper. From a certain square, a square that is x squares to the right and y squares above, is denoted as square (x, y). When Takahashi draws a segment connecting the lower left corner of square (A, B) and the lower left corner of square (C, D), find the number of the squares cro...
```python a,b,c,d = (int(i) for i in input().split()) def gcd(x,y): if x%y==0: return y else: return gcd(y,x%y) if a==c or b==d: ans = 0 else: n = gcd(abs(a-c),abs(b-d)) e,f = abs(a-c)//n,abs(b-d)//n ans = (e+f-1)*n print(ans) ```
p04051 AtCoder Grand Contest 001 - BBQ Hard
Snuke is having another barbeque party. This time, he will make one serving of Skewer Meal. He has a stock of N Skewer Meal Packs. The i-th Skewer Meal Pack contains one skewer, A_i pieces of beef and B_i pieces of green pepper. All skewers in these packs are different and distinguishable, while all pieces of beef an...
```python mod = 10**9+7 mod2 = 998244353 rng = 100100 fctr = [1] finv = [1] for i in range(1,rng): fctr.append(fctr[-1]*i%mod) for i in range(1,rng): finv.append(pow(fctr[i],mod-2,mod)) def cmb(n,k): if n<0 or k<0: return 0 else: return fctr[n]*finv[n-k]*finv[k]%mod n = int(input()) ab = [list(map(int,i...
p00130 Train
There are trains with 26 cars or less. Each vehicle has an identification code from lowercase a to z. No vehicle has the same symbol. However, the order in which the vehicles are connected is arbitrary. The conductor patrols the train. The conductor patrolls back and forth in the train, so he may pass through the same ...
```python for _ in range(int(input())): s=list(input()) word,direct=[],"" for i in s: if i.isalpha(): if direct==">": if i not in word:word.append(i) else: if i not in word:word.insert(0,i) elif i=="<" or i==">":direct=i print(*word...
p00263 Kongo Type
Consider a 32-bit real type with 7 bits from the right as the decimal part, the following 24 bits as the integer part, and the leftmost 1 bit as the sign part as shown below (b1, ..., b32). Represents 0 or 1). <image> To translate this format into a decimal representation that is easy for humans to understand, inter...
```python q = int(input()) for _ in range (q): bits = F'{int(input(), 16):32b}' sign = '-' if bits[0] == '1' else '' integer = sum([2**i for i, b in enumerate(bits[1:25][::-1]) if b == '1']) fraction = sum([0.5**i for i, b in enumerate(bits[25:], start=1) if b == '1']) print(sign + str(float(integer...
p00450 Setting Go Stones
problem Play by arranging white and black stones on the table. First, place the stones on the left edge of the table. Then place the stones in the second place from the left. Repeat this n times to arrange n stones in a horizontal row. However, when placing a new i-th go stone, replace the go stone on the table accord...
```python while True: n = int(input()) if n==0: break edge = 0 sq = 0 past = [] for i in range(n): nxt = int(input()) if i==0: edge = nxt if i%2 == 0: if nxt == edge: sq += 1 else: edge = nxt ...
p00641 Huge Family
Mr. Dango's family has extremely huge number of members. Once it had about 100 members, and now it has as many as population of a city. It is jokingly guessed that the member might fill this planet in near future. They all have warm and gracious personality and are close each other. They usually communicate by a phone...
```python # AOJ 1055 Huge Family # Python3 2018.7.7 bal4u # UNION-FIND library class UnionSet: def __init__(self, nmax): self.size = [1]*nmax self.id = [i for i in range(nmax+1)] def root(self, i): while i != self.id[i]: self.id[i] = self.id[self.id[i]] i = self.id[i] return i def connected(self, p, q...
p00917 Clock Hands
We have an analog clock whose three hands (the second hand, the minute hand and the hour hand) rotate quite smoothly. You can measure two angles between the second hand and two other hands. Write a program to find the time at which "No two hands overlap each other" and "Two angles between the second hand and two other...
```python import sys def gcd(m, n): while n: m, n = n, m % n return m readline = sys.stdin.readline write = sys.stdout.write def solve(): f = lambda h, m, s: 3600*h + 60*m + s H, h, m, s = map(int, readline().split()) if H == 0: return False d0 = f(h, m, s) M = f(H, 0, 0) ...
p01050 String Compression
Problem Given the string S, which consists of lowercase letters and numbers. Follow the steps below to compress the length of string S. 1. Change the order of the characters in the character string to any order. Example: "0ig3he12fz99"-> "efghiz012399" 2. Perform the following operations any number of times. * Sele...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import defaultdict S = input() S = sorted(S) S = list(map(ord, S)) ans = 0 while len(S) > 0: mn = S[0] S.remove(mn) nxt = mn + 1 succ = 1 while True: if nxt in S: S.remove(nxt) succ += 1 ...
p01319 Canal: Water Going Up and Down
ACM countries have rivers that flow from east to west in the center. This river flows from the neighboring country in the west through the neighboring country in ACM to the neighboring country in the east, and the total length in ACM is K km. It is planned to install several locks on this river and use it as a canal. ...
```python while True: n, m, k = (int(s) for s in input().split()) if (n, m, k) == (0, 0, 0): break t_out = [0.] * (k + m + 1) tl_east = [0.] * (k + m + 1) tl_west = [0.] * (k + m + 1) for i in range(n): xi, li, fi, di, udi = (int(s) for s in input().split()) if not udi:...
p01487 RabbitWalking
Example Input 8 5 1 2 6 5 6 4 1 3 4 7 Output 11
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M = map(int, readline().split()) G = [[] for i in range(N)] for i in range(M): a, b = map(int, readline().split()) G[a-1].append(b-1) G[b-1].append(a-1) col ...
p01934 Dimension travel
problem Dimension exists from $ 1 $ dimension to $ N $ dimension. AOR Ika can move between dimensions. Specifically, when AOR Ika is in the $ i $ dimension, she can move freely to the $ j $ dimension ($ i> j $), but in the $ k $ dimension ($ i <k $). You need to use magic to move to. AOR Ika can use $ M $ types of ma...
```python # AOJ 2834 Dimension travel # Python3 2018.7.12 bal4u INF = 0x7fffffff import heapq def dijkstra(V, to, start, goal): dist = [INF]*V Q = [] dist[start] = 0 heapq.heappush(Q, (0, start)) while Q: t, s = heapq.heappop(Q) if s == goal: break if dist[s] < t: continue for e in to[s]: nt = t if ...
p02368 Strongly Connected Components
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable. Constraints * 1 ≤ |V| ≤ 10,000 * 0 ≤ |E| ≤ 30,000 * 1 ≤ Q ≤ 100,000 Input A directed graph G(V, E) and a sequence of...
```python def solve(): N, M = map(int, input().split()) edges = [[] for _ in [0]*N] r_edges = [[] for _ in [0]*N] for _ in [0]*M: a, b = map(int, input().split()) edges[a].append(b) r_edges[b].append(a) c = kosaraju(edges, r_edges) group = [0]*N for i in range(len(c...
1013_C. Photo of The Sky
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x...
```python n = int(input()) a = [int(x) for x in input().split()] a.sort() top = [a[0], a[-1]] right = [a[n - 1], a[n]] case2 = abs((top[0] - right[0])*(top[1] - right[1])) case1 = top[-1] - top[0] mny = 10000000000 for i in range(1, n): mny = min(mny, abs(a[i] - a[i + n-1])) #print(mny) case1 *= mny print(m...
1038_A. Equality
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase. A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD...
```python n,k = list(map(int,input().strip().split())) s = input() letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] L = letters[:k] counts = {} for x in L: counts[x] = s.count(x) print(min([counts[j] for j in L])*k) ```
1060_E. Sergey and Subway
Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at nigh...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n = int(input()) path = [[] for _ in range(n)] for _ in range(n-1): a1,b1 = map(lambda xx:int(xx)-1,input().split()) path[a1].append(b1) path[b1].append(a1) ...
1082_C. Multi-Subject Competition
A multi-subject competition is coming! The competition has m different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has n candidates. For the i-th person he knows subject s_i the candidate specializes in and r_i — a skill level in his s...
```python import sys input=sys.stdin.readline n, m = map(int, input().split()) s = [[] for _ in range(m)] size = [0]*m for _ in range(n): si, ri = map(int, input().split()) s[si-1].append(ri) size[si-1] += 1 # print(s) # print(size) sa = max(size) # print(sa) i = 0 ans = [0]*sa # print("ans",ans) for i i...
1101_E. Polycarp's New Job
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). ...
```python import sys amount = int(input()) max_1 = -1 max_2 = -1 ans = "" for i in range(amount): inputs = [s for s in input().split()] x = int(inputs[1]) y = int(inputs[2]) if x > y: x,y = y,x if inputs[0] == '+': if max_1 < x: max_1 = x if max_2 < y: ...
112_C. Petya and Inequiations
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: * a12 + a22 + ... + an2 ≥ x * a1 + a2 + ... + an ≤ y Input The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please d...
```python n, x, y = input().split() n=int(n) x=int(x) y=int(y) a = y-n+1 if a<=0: print(-1) else: if a**2 + n - 1 >= x: print(a) for i in range(n-1): print(1) else: print(-1) ```
114_D. Petr#
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings...
```python from functools import cmp_to_key def calc_lcp(s, sa): rank = [0 for _ in range(len(s))] for i in range(len(s)): rank[sa[i]] = i lcp = [0 for _ in range(len(s) - 1)] h = 0 for i in range(len(s)): if rank[i] < len(s) - 1: while max(i, sa[rank[i] + 1])...
118_A. String Task
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
```python s=input() s=s.lower() for i in range(len(s)): if not(s[i]=='a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u' or s[i]=='y'): print('.{0}'.format(s[i]),end="") ```
1227_F2. Wrong Answer on test 233 (Hard Version)
Your program fails again. This time it gets "Wrong answer on test 233" . This is the harder version of the problem. In this version, 1 ≤ n ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. The problem is to finish n one-choice-questions. Eac...
```python from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from...
1292_C. Xenon's Attack on the Gangs
[INSPION FullBand Master - INSPION](https://www.youtube.com/watch?v=kwsciXm_7sA) [INSPION - IOLITE-SUNSTONE](https://www.youtube.com/watch?v=kwsciXm_7sA) On another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free ti...
```python import sys # Read input and build the graph inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) # Relable to speed up n^2 ...
1312_D. Count the Arrays
Your task is to calculate the number of arrays such that: * each array contains n elements; * each element is an integer from 1 to m; * for each array, there is exactly one pair of equal elements; * for each array a, there exists an index i such that the array is strictly ascending before the i-th element a...
```python MOD = 998244353 def add(x, y): x += y while(x >= MOD): x -= MOD while(x < 0): x += MOD return x def mul(x, y): return (x * y) % MOD def binpow(x, y): z = 1 while(y): if(y & 1): z = mul(z, x) x = mul(x, x) y >>= 1 return ...
1335_A. Candies and Two Sisters
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
```python test = int(input()) for t in range(test): c = int(input()) if c == 0 or c == 1 or c == 2: print(0) elif c % 2 == 0: print((c//2)-1) else: print(c//2) ```
1355_C. Count Triangles
Like any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A ≤ B ≤ C ≤ D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A ≤ x ≤ B ≤ y ≤ C ≤ z ≤ D holds? Yuri is preparing problems for a new contest now, so he is v...
```python a,b,c,d=map(int,input().split(" ")) li=[0]*int(pow(10,6)+2) n=int(pow(10,6)+2) for i in range(a,b+1): li[i+b]+=1 li[i+c+1]-=1 for i in range(1,n): li[i]+=li[i-1] for i in range(1,n): li[i]+=li[i-1] ans=0 for i in range(c,d+1): ans+=li[n-1]-li[i] print(ans) ```
1375_B. Neighbor Grid
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the...
```python def possible(n, m): f = True for i in range(n): row = list(map(int, input().split())) if i == 0 or i == n-1: for j in range(m): if j == 0 or j == m-1: if row[j] > 2: f = False else: ...
1398_E. Two Types of Spells
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be ca...
```python import bisect import sys input = sys.stdin.readline class TreeSet(object): """ Binary-tree set like java Treeset. Duplicate elements will not be added. When added new element, TreeSet will be sorted automatically. """ def __init__(self, elements): self._treeset = [] se...
1422_A. Fence
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four...
```python t = int(input()) for i in range(t): a, b, c = map(int, input().split()) sides = [a, b, c] print(max(sides) + 1) ```
1467_A. Wizard of Orz
There are n digital panels placed in a straight line. Each panel can show any digit from 0 to 9. Initially, all panels show 0. Every second, the digit shown by each panel increases by 1. In other words, at the end of every second, a panel that showed 9 would now show 0, a panel that showed 0 would now show 1, a panel ...
```python for _ in range(int(input())): n=int(input()) if(n==1): print(9) elif(n==2): print(98) else: print(989, end='') a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(n-3): print(a[i%10], end='') print('') ```
1491_D. Zookeeper and The Infinite Zoo
There is a new attraction in Singapore Zoo: The Infinite Zoo. The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled 1,2,3,…. There is a directed edge from vertex u to vertex u+v if and only if u\&v=v, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwis...
```python import sys readline = sys.stdin.readline T = int(readline()) Ans = ['NO']*T limit = 33 for qu in range(T): u, v = map(int, readline().split()) if u <= v: p = 0 for k in range(limit): if (1<<k)&u == (1<<k)&v: continue if (1<<k)&u == 0: ...
1514_A. Perfectly Imperfect Array
Given an array a of length n, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square. A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Input The first line contains an integer t (1 ≤ t ≤ 100) — the...
```python import math rr = input rri = lambda: int(rr()) rrm = lambda: list(map(int, rr().split())) def perfect_square(n): root = math.sqrt(n) if int(root + 0.5) ** 2 == n: return True else: return False def prod(lst): ret = 1 for i in lst: ret *= i return ret def sol...
1541_A. Pretty Permutations
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat ...
```python t = int(input()) for j in range(t): n = int(input()) a = [int(i) for i in range(1, n + 1)] if n % 2 == 0: for i in range(0, n, 2): a[i], a[i + 1] = a[i + 1], a[i] else: for i in range(0, n - 1, 2): a[i], a[i + 1] = a[i + 1], a[i] a[-2], a[-1] = a...
189_C. Permutations
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot. One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the perm...
```python n = int(input()) l1 = [int(x) for x in input().split()] l2 = [int(x) for x in input().split()] used = set() j = len(l1)-1 worst = j for i in range(len(l2)-1, -1, -1): if l2[i] in used: continue if l2[i] == l1[j]: j-=1 else: while l2[i] != l1[j]: used.add(l1[j]...
236_C. LCM Challenge
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th...
```python from math import * n, ans = int(input()), 0 if n < 3: ans = n elif n % 2: ans = n * (n - 1) * (n - 2) else: a = 0 if gcd(n, n - 3) == 1: a = n * (n - 1) * (n - 3) n -= 1 ans = max(n * (n - 1) * (n - 2), a) print(ans) ```
261_A. 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 #!/usr/bin/env python from __future__ import division, print_function import math import os import sys from fractions import * from sys import * from decimal import * from io import BytesIO, IOBase from itertools import * from collections import * # sys.setrecursionlimit(10**5) M = 10 ** 9 + 7 # print(math....
285_A. Slightly Decreasing Permutations
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. The decreasing coefficient of permutation p1, p2, ...,...
```python n,k = map(int,input().strip().split()) a=list(range(1,n+1)) a[:k+1] = a[k::-1] a=[str(i) for i in a] print(' '.join(a)) ```
30_A. Accounting
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a l...
```python import math import sys a,b,c=input().split(' ') a=int(a); b=int(b); c=int(c) for i in range( -abs(b), abs(b)+1): if a*pow(i, c)==b: print(i,end='') sys.exit(0) print("No solution",end='') ```
3_A. Shortest path of the king
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least nu...
```python xi = tuple(input()) xf = tuple(input()) row = [1,2,3,4,5,6,7,8] col = ["a","b","c","d","e","f","g","h"] movelist=[] row_in = int(xi[1]) col_in = xi[0] row_fin = int(xf[1]) col_fin = xf[0] index_ri = row.index(row_in) index_rf = row.index(row_fin) index_ci = col.index(col_in) index_cf = col.index(col_fin) ...
426_C. Sereja and Swaps
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation: <image> A swap operation is the following sequence of actions: * choose two indexes i, j (i ≠ j); * perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Serej...
```python read_line = lambda: [int(i) for i in input().split()] n, k = read_line() x = read_line() print(max(sum(sorted(x[l:r] + sorted(x[:l] + x[r:])[-k:])[l-r:]) for l in range(n) for r in range(l + 1, n + 1))) # Made By Mostafa_Khaled ```
471_B. MUH and Important Things
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order...
```python n = int(input()) ar = [int(i) for i in input().split()] new = sorted((ar[i],i+1) for i in range(n)) res = [new[i][1] for i in range(n)] swap = [] for i in range(n-1): if new[i][0] == new[i+1][0]: swap.append((i,i+1)) if len(swap) == 2: print("YES") print(" ".join(str(i) for i in res)) ...
495_C. Treasure
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the ...
```python s = input() n = s.rfind("#") error = 0 s1 = 0 s2 = 0 s3 = 0 s4 = s.count("(") s5 = s.count(")") s6 = 0 for num in range(n): if s[num]=="(" : s2 += 1 elif s[num]==")": s3 += 1 if s[num]=="#" : s1 += 1 s3 += 1 if s3 > s2: error=1 if s1+s5 < s4: s6 = s4-s5-s1...
51_A. Cheaterius's Problem
Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throu...
```python nro_amu = int(input()) amu = [] for i in range(nro_amu): fila1 = list(input()) fila2 = list(input()) fila1.extend(fila2) amu.append(fila1) if i+1 != nro_amu: _ = input() pilas = [] nro_pilas = 0 for a in amu: existe = False for i in range(nro_pilas): for...
546_B. Soldier and Badges
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the secon...
```python n=int(input());k=0 if n==1:print(0);exit() a=list(map(int,input().split()));b=[];c=[] for i in range(n*n):b.append(0) for i in range(n): if b[a[i]]==0:b[a[i]]=a[i] else:c.append(a[i]) for i in range(len(c)): for j in range(c[i],len(b)): if b[j]==0:k+=b[j-1]-c[i]+1;b[j]=j;break print(k) ```
615_E. Hexagons
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined: <image> <image> Ayrat is searching through the field. He started at point (...
```python import math def main(m): if m == 0: print("0 0") else: x = math.floor(1/6*((12*m - 3)**0.5 + 3)) # Approx ?... while True: d = m - (x**3 - (x-1)**3) if (d < 0): x -= 1 elif (d > x * 6 + 6): x += 1 else: break s,r = divmod(...
635_A. Orchestra
Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count ...
```python import io import sys import time import random #~ start = time.clock() #~ test = '''2 2 1 1 #~ 1 2''' #~ test = '''3 2 3 3 #~ 1 1 #~ 3 1 #~ 2 2''' #~ test = '''3 2 3 2 #~ 1 1 #~ 3 1 #~ 2 2''' #~ sys.stdin = io.StringIO(test) r,c,n,k = map(int,input().split()) # row column number-of-violists data = [ [0 for ...
688_C. NP-Hard Problem
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. <image> or <image>...
```python n,m=map(int,input().split()) flag=False f=[0]*100001 E=[[] for i in range(n+1)] e=[tuple(map(int,input().split())) for _ in range(m)] for u,v in sorted(e): E[u]+=[v]; E[v]+=[u] def bfs(nom,col): ch=[(nom,col)] while ch: v,c=ch.pop() if f[v]==0: f[v]=c for u in E[v]: ...
710_B. Optimal Point on a Line
You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal. Input The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n ...
```python n=int(input()) q=sorted(list(map(int,input().split()))) print(q[(n-1)//2]) ```
731_B. Coupons and Discounts
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
```python n = int(input()) l = list(map(int, input().split())) carrier = 0 for i in range(n): if l[i] == 0 and carrier == 1: print("NO") exit() if l[i] % 2 == 1: if carrier == 0: carrier = 1 else: carrier = 0 if carrier == 0: print("YES")...
755_D. PolandBall and Polygon
PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the followi...
```python import sys inf = (1 << 31) - 1 def solve(): n, k = map(int, input().split()) if k > n - k: k = n - k bit = BinaryIndexedTree([0]*n) s = 0 res = 1 ans = [] for i in range(n): t = (s + k) % n if s < t: res += bit.get_sum(t) - bit.get_sum(s +...
776_E. The Holmes Children
The Holmes children are fighting over who amongst them is the cleverest. Mycroft asked Sherlock and Eurus to find value of f(n), where f(1) = 1 and for n ≥ 2, f(n) is the number of distinct ordered positive integer pairs (x, y) that satisfy x + y = n and gcd(x, y) = 1. The integer gcd(a, b) is the greatest common divi...
```python mod=1e9+7 def Phi(n): phi=n i=2 while i*i<= n: if n%i==0: while n%i==0: n//=i phi-=phi//i i+=1 if n > 1: phi-=phi//n return phi def f(n): return Phi(n) def g(n): return n n,k=map(int,input().split())...
801_A. Vicious Keyboard
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximu...
```python a = input() b = [a.count('VK')] + [0] * len(a) s = a[:] for i in range(len(a)): if a[i] == 'V': if i != len(a) - 1: s = s[:i] + 'K' + s[i + 1:] else: s = s[:i] + 'K' else: if i != len(a) - 1: s = s[:i] + 'V' + s[i + 1:] else: ...
821_C. Okabe and Boxes
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack. Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and thr...
```python n = int(input()) cnt = 1 ans = 0 l = [] for i in range(2*n): a = input() if a[0] == 'a': l.append(int(a[4:])) else: if len(l) == 0: cnt += 1 elif l[-1] == cnt: l.pop() cnt += 1 else: l = [] ans += 1 ...
847_C. Sum of Nestings
Recall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the foll...
```python # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import Counter from bisect import * from math import gcd from itertools import permutations,combinations from math import sqrt,ceil,floor def main(): n,k=map(int,input().spl...
894_B. Ralph And His Magic Field
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or...
```python def main(): N, M, K = [int(i) for i in input().split()] if (N + M) % 2 != 0 and K == -1: print(0) else: P = ((N - 1)*(M - 1)) print(pow(2, P, 1000000007)) main() # 1512152080884 ```
964_A. Splits
Let's define a split of n as a nonincreasing sequence of positive integers, the sum of which is n. For example, the following sequences are splits of 8: [4, 4], [3, 3, 2], [2, 2, 1, 1, 1, 1], [5, 2, 1]. The following sequences aren't splits of 8: [1, 7], [5, 4], [11, -3], [1, 1, 4, 1, 1]. The weight of a split is t...
```python from collections import deque import math import os import random import re import sys #n=list(map(int, input().split())) #n=map(int, input().split()) def main(): n=int(input()) ans=n//2+1 print(ans) main() ```
991_B. Getting an A
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that...
```python #!/usr/bin/env python3 n = int(input().strip()) ais = list(map(int, input().strip().split())) ais.sort() cnt = 0 s = sum(ais) thrs = -((-9 * n) // 2) # ceil(4.5 * n) while s < thrs: s += 5 - ais[cnt] cnt += 1 print (cnt) ```
p02617 AtCoder Beginner Contest 173 - Intervals on Tree
We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i. For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows: * Let S be the set of the vertices numbered L through R. f(L, R) represents the number ...
```python def main(): N = int(input()) edges = [list(map(int, input().split())) for _ in range(N - 1)] ans = N * (N + 1) * (N + 2) // 6 for e in edges: u, v = min(e), max(e) ans -= u * (N - v + 1) print(ans) if __name__ == '__main__': main() ```
p02748 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - Nice Shopping
You are visiting a large electronics store to buy a refrigerator and a microwave. The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen. You have M discount tic...
```python a,b,m=map(int,input().split()) A=list(map(int,input().split())) B=list(map(int,input().split())) ans=min(A)+min(B) for i in range(m): x,y,c=map(int,input().split()) if A[x-1]+B[y-1]-c <ans: ans=A[x-1]+B[y-1]-c print(ans) ```
p02883 AtCoder Beginner Contest 144 - Gluttony
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of ...
```python (_,k),*t=[map(int,t.split())for t in open(0)] A,F=map(sorted,t) o=10**12 g=-1 while o-g>1: m,l=o+g>>1,k for a,f in zip(A,F[::-1]):l-=max(0,a-m//f) if l<0:g=m else:o=m print(o) ```
p03018 AtCoder Grand Contest 034 - ABC
You are given a string s consisting of `A`, `B` and `C`. Snuke wants to perform the following operation on s as many times as possible: * Choose a contiguous substring of s that reads `ABC` and replace it with `BCA`. Find the maximum possible number of operations. Constraints * 1 \leq |s| \leq 200000 * Each char...
```python S = input() T = S.replace('BC','X') res = 0 cnt = 0 for s in T: if s == 'A' : cnt += 1 elif s == 'X': res += cnt else: cnt = 0 print(res) ```
p03158 AISing Programming Contest 2019 - Nearest Card Game
There are N cards. The i-th card has an integer A_i written on it. For any two cards, the integers on those cards are different. Using these cards, Takahashi and Aoki will play the following game: * Aoki chooses an integer x. * Starting from Takahashi, the two players alternately take a card. The card should be chose...
```python import sys input = sys.stdin.readline from itertools import accumulate import bisect n,q = map(int,input().split()) if n%2: a = [0]+list(map(int,input().split())) n += 1 else: a = list(map(int,input().split())) fs = [a[i] if i%2 else 0 for i in range(n)] accss = [0]*n accff = list(accumulate(a)) accfs =...
p03461 AtCoder Regular Contest 089 - GraphXY
AtCoDeer the deer wants a directed graph that satisfies the following conditions: * The number of vertices, N, is at most 300. * There must not be self-loops or multiple edges. * The vertices are numbered from 1 through N. * Each edge has either an integer weight between 0 and 100 (inclusive), or a label `X` or `Y`. *...
```python # seishin.py A, B = map(int, input().split()) D = [list(map(int, input().split())) for i in range(A)] N = 101 F = [[0]*N for i in range(N)] for a in range(N): for b in range(N): res = 0 for x in range(A): for y in range(B): res = max(res, D[x][y] - (x+1)*a - (y...
p03620 AtCoder Grand Contest 019 - Shift and Flip
You have two strings A = A_1 A_2 ... A_n and B = B_1 B_2 ... B_n of the same length consisting of 0 and 1. You can transform A using the following operations in any order and as many times as you want: * Shift A by one character to the left (i.e., if A = A_1 A_2 ... A_n, replace A with A_2 A_3 ... A_n A_1). * Shift A...
```python import sys readline = sys.stdin.readline A = list(map(int, readline().strip())) B = list(map(int, readline().strip())) N = len(A) Ao = A[:] inf = 10**9+7 if sum(B): ans = inf CRo = [None]*N A2 = A + A B2 = B + B pre = None for i in range(2*N-1, N-1, -1): if B2[i]: ...
p03778 AtCoder Beginner Contest 056 - NarrowRectanglesEasy
AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W. If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the ho...
```python W, a, b = map(int, input().split()) abs = max(a, b) - min(a, b) - W print(max(0, abs)) ```
p03949 AtCoder Regular Contest 063 - Integers on a Tree
We have a tree with N vertices. The vertices are numbered 1, 2, ..., N. The i-th (1 ≦ i ≦ N - 1) edge connects the two vertices A_i and B_i. Takahashi wrote integers into K of the vertices. Specifically, for each 1 ≦ j ≦ K, he wrote the integer P_j into vertex V_j. The remaining vertices are left empty. After that, he...
```python #!/usr/bin/python def shortestPath(g,s,dist,prev): n = len(g)-1 Q=[] heapq.heappush(Q,(0,-2,s)) while Q: e = heapq.heappop(Q) if prev[e[2]]!=-1: continue prev[e[2]] = e[1] for f in g[e[2]]: if dist[f[2]] > e[0] + f[0]: dist[f[2]] = e[0] + f[0] heapq.heappush(Q,(e[0]+f[0],f[1],f[2])) im...
p00039 Roman Figure
Counting was a difficult task in ancient Rome. The Arabic numerals 0,1,2,3,…, 9 have not yet been disseminated. Instead, the following symbols were used: Arabic numerals | Roman numerals | Arabic numerals | Roman numerals | Arabic numerals | Roman numerals --- | --- | --- | --- | --- | --- 1 | I | 11 | XI | 30 | XXX |...
```python import sys r={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} for e in sys.stdin: a=0 n=[r[c]for c in e.strip()] for i in range(len(n)): if i+1<len(n)and n[i]<n[i+1]:a-=n[i] else:a+=n[i] print(a) ```
p00500 Unique number
problem JOI decided to play a game with his friends. N players participate in this game. The rules for a single game are as follows: Each player writes a favorite integer from 1 to 100 on the card and submits it. Each player gets the same score as he wrote if no one else wrote the same number. If there is another per...
```python n=int(input()) p=[list(map(int,input().split())) for _ in range(n)] point=[0]*n for j in range(3): r=[row[j] for row in p] for i in range(n): if i==0: if r[i] not in r[1:]: point[0]+=r[i] elif i==n-1: if r[i] not in r[:n-1]: point...
p00684 Calculation of Expressions
Write a program to calculate values of arithmetic expressions which may involve complex numbers. Details of the expressions are described below. In this problem, basic elements of expressions are non-negative integer numbers and the special symbol "`i`". Integer numbers are sequences of digits of arbitrary length and ...
```python OVER = 10000 def factor(): global w, pos if buf[pos] == '(': pos += 1 f, v1 = calc() if not f: return [f, 0] pos += 1 elif buf[pos] == 'i': pos += 1 v1 = complex(0, 1) else: v1 = 0 while pos < w and buf[pos].isdigit(): v1 = 10*v1 + int(buf[pos]) pos += 1 if v1 > OVER: return [Fal...
p00826 Monster Trap
Once upon a time when people still believed in magic, there was a great wizard Aranyaka Gondlir. After twenty years of hard training in a deep forest, he had finally mastered ultimate magic, and decided to leave the forest for his home. Arriving at his home village, Aranyaka was very surprised at the extraordinary des...
```python def string_to_complex(s): a, b, c, d = map(int, s.split()) return (a + b * 1j, c + d * 1j) 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 cross_point(p1, p2, p3, p4): crs1 = cross(p2 - p1, p3 - p1) cr...
p00957 Secret of Chocolate Poles
Problem A Secret of Chocolate Poles Wendy, the master of a chocolate shop, is thinking of displaying poles of chocolate disks in the showcase. She can use three kinds of chocolate disks: white thin disks, dark thin disks, and dark thick disks. The thin disks are $1$ cm thick, and the thick disks are $k$ cm thick. Disk...
```python #!usr/bin/env python3 from collections import defaultdict from collections import deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return list(map(int, sys.stdin.readline().split())) def I(): return int(sys.stdin.readline()) def LS():return list(map(list, ...
p01090 Bridge Construction Planning
Bridge Construction Planning There is a city consisting of many small islands, and the citizens live in these islands. Citizens feel inconvenience in requiring ferry rides between these islands. The city mayor decided to build bridges connecting all the islands. The city has two construction companies, A and B. The m...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M, K = map(int, readline().split()) if N == 0: return False def root(x): if prt[x] == x: return x prt[x] = y = root(prt[x]) return y def u...
p01226 Battle Town
You decide to develop a game with your friends. The title of the game is "Battle Town". This is a game with the theme of urban warfare with tanks. As the first step in game development, we decided to develop the following prototype. In this prototype, the only tanks that appear are the player's tanks, not the enemy ta...
```python def move(act,y,x,direction):#戦車の動き #print("x,y",y,x) #print("M,H",M,H) if x<0 or x == M or y<0 or y == H: return s_map if act == 'U':#Up if y == 0: s_map[y][x] = '^' else: if s_map[y-1][x] == '.':#下が平地なら s_map[y][x],s_map[y-1][x] ...
p01360 Step Step Evolution
Japanese video game company has developed the music video game called Step Step Evolution. The gameplay of Step Step Evolution is very simple. Players stand on the dance platform, and step on panels on it according to a sequence of arrows shown in the front screen. There are eight types of direction arrows in the Step...
```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...
p01542 Lost Number
The time was 3xxx, and the highly developed civilization was in a stagnation period. Historians decided to learn the wisdom of the past in an attempt to overcome this situation. What I paid attention to was the material left by the genius of the early days of computers. The calculation formula is written in this materi...
```python from itertools import product import time def ok(s): if '(+' in s or '(-' in s or '(*' in s or '++' in s or '+-' in s or '-+' in s \ or '--' in s or '**' in s or '*+' in s or '*-' in s: return False if '(' in s or ')' in s: dic={} count=-1 for c in s: if...
p01698 Wish upon a shooting star
Make a wish to a shooting star The mysterious organization JAG (Japanese Alumni Group) holds regular meetings. One day, the agenda was "How to enable participating teams to demonstrate their strength in the upcoming ICPC (International Collegiate Programming Contest) domestic qualifying round." The conclusion of the m...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False P = [list(map(float, readline().split())) for i in range(N)] CS = [] R = [-1]*N for i in range(N): pxi, pyi, pzi, vxi, vyi, vzi, ri, vri = P[i] ...
p01842 Invisible
D --Invisible Problem Statement You are trying to play a card game called "Invisible" with your friends. This card game uses two types of cards, a "scoring card" and a "jamming card". A positive value is written on each score card. The rules of this card game are as follows. * The game is played by two players, play...
```python n, m = [int(i) for i in input().split()] A = [int(i) for i in input().split()] B = [int(i) for i in input().split()] memo = dict() def calc(A, i): if A[i] != -1: return 0 point = 0 for j in range(i - 1, -1, -1): if A[j] == -1: break point += A[j] return p...
p02124 ai1333
Problem In 1333, the greatest scientist in human history, Dr. Ushishi, developed an artificial intelligence with an ID of ai1333 in order to pass on his wisdom to posterity. For the next 100 years, ai1333 brought great benefits to humankind, but on the 100th anniversary of its birth, it created a new artificial intell...
```python x = int(input()) n = x/100 def f(n): if n == 0: return 'ai1333' else: a = f(n-1) b = a+'3' return b print(f(n)) ```
p02264 Queue
Notes Template in C Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 1000 * 1 ≤ timei ≤ 50000 * 1 ≤ length of namei ≤ 10 * 1 ≤ Sum of timei ≤ 1000000 Input n q name1 time1 name2 time2 ... namen timen In the first line the number of processes n and the quantum q are given separated by a single space. In the following n li...
```python import sys from collections import deque s=sys.stdin.readlines() _,q=map(int,s[0].split()) f=lambda x,y:(x,int(y)) d=deque(f(*e.split())for e in s[1:]) t=0 while d: k,v=d.popleft() if v>q: v-=q t+=q d.append([k,v]) else: t+=v print(k,t) ```
p02412 How many ways?
Write a program which identifies the number of combinations of three integers which satisfy the following conditions: * You should select three distinct integers from 1 to n. * A total sum of the three integers is x. For example, there are two combinations for n = 5 and x = 9. * 1 + 3 + 5 = 9 * 2 + 3 + 4 = 9 Note...
```python n, x = map(int, input().split()) while n != 0 or x != 0: count = 0 for i in range(1, n+1): for j in range(i+1, n+1): for k in range(j+1, n+1): if i+j+k == x: count += 1 print(count) n, x = map(int, input().split()) ```