name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
702_C. Cellular Network
You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from t...
```python import bisect import sys EPS = sys.float_info.epsilon LENGTH = 10 matrix = [[] for i in range(LENGTH)] array = [0] * LENGTH if __name__ == "__main__": n, m = map(int, sys.stdin.readline().split()) a = list(map(int, sys.stdin.readline().split())) b = list(map(int, sys.stdin.readline().split()))...
724_D. Dense Subsequence
You are given a string s, consisting of lowercase English letters, and the integer m. One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen...
```python from collections import Counter from string import ascii_lowercase as asc m, s = int(input()), input() g = Counter(s) def solve(c): p = 0 for q in ''.join(x if x >= c else ' ' for x in s).split(): i, j = 0, -1 while j + m < len(q): j = q.rfind(c, j + 1, j + m + 1) ...
746_D. Green and Black Tea
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black. Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing...
```python n,k,a,b = [int(i) for i in input().split()] check = False if (a>b): a,b = b,a check = True res = "" cr = 1 cA = True while (a > 0 or b > 0): if (a==b): break #print(a,b) if (cr==1): if a <= b: u = min(k, b - a) b -= u res += u * '1' ...
769_D. k-Interesting Pairs Of Integers
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs ...
```python from collections import defaultdict n, k = [int(i) for i in input().split()] A = [int(i) for i in input().split()] A_dict = defaultdict(int) for i in A: A_dict[i] += 1 def bitCount(x): cur = 0 while x > 0: if x % 2: cur += 1 x //= 2 return cur mask = [] for i in ...
793_D. Presents in Bankopolis
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office. The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lan...
```python import sys from functools import lru_cache input = sys.stdin.readline # sys.setrecursionlimit(2 * 10**6) def inpl(): return list(map(int, input().split())) @lru_cache(maxsize=None) def recur(v, s, e, k): """ vから初めて[s, e]の都市をk個まわる最小値は? """ if k == 0: return 0 elif k > e - s ...
814_A. An abandoned sentiment from past
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed. To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long t...
```python def checker(L): return all(x<y for x, y in zip(L, L[1:])) R = lambda: map(int,input().split()) n, k = R() a = list(R()) b = list(R()) b.sort(reverse=True) for i in range(n): if a[i] in b: exit(print('No')) if a[i] == 0: a[i] = b[0] del b[0] print('No' if checker(a) else 'Yes') ```
83_A. Magical Array
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutel...
```python from collections import defaultdict n = int(input()) arr = list(map(int,input().split())) cur = arr[0] cnt = 1 d = defaultdict(int) for i in range(1,n): if arr[i]==cur: cnt+=1 else: d[cnt]+=1 cur = arr[i] cnt = 1 if cnt!=0: d[cnt]+=1 ans = 0 for i in d: freq = d[i] cnt = (i*(i+1))//2 cnt = cnt*f...
85_B. Embassy Queue
In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order. For each action several separate windows are...
```python q = zip(map(int, input().split()), map(int, input().split())) n = int(input()) c = list(map(int, input().split())) d = c[:] for k, t in q: for i in range(min(k, n)): c[i] += t for i in range(k, n): c[i] = max(c[i], c[i - k]) + t print(max(c[i] - d[i] for i in range(n))) ```
886_B. Vlad and Cafes
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes h...
```python from sys import stdin as fin # fin = open("tc173b.in", "r") n = int(fin.readline()) # n, k = map(int, fin.readline().split()) arr = list(map(int, fin.readline().split())) # s = fin.readline().rstrip() s = dict() for i in range(n): x = arr[i] s[x] = (i, x) # print(tuple(s.items())) print(min(s.items(...
909_B. Segments
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be <image> of them. You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endp...
```python n=int(input()) print(((n//2)+1)*(n-(n//2))) ```
984_D. XOR-pyramid
For an array b of length m we define the function f as f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] ⊕ b[2],b[2] ⊕ b[3],...,b[m-1] ⊕ b[m]) & otherwise, \end{cases} where ⊕ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6...
```python n = int(input()) a = list(map(int, input().split())) dp = [[0 for x in range(n+1)] for y in range(n+1)] for i in range(n): dp[0][i] = a[i] for i in range(1, n): for j in range(0, n - i + 1): dp[i][j] = dp[i - 1][j + 1] ^ dp[i - 1][j] for i in range(1, n): for j in range(0, n - i): dp[i]...
p02572 AtCoder Beginner Contest 177 - Sum of product of pairs
Given are N integers A_1,\ldots,A_N. Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7). Constraints * 2 \leq N \leq 2\times 10^5 * 0 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 \ldot...
```python s =0 r =0 n = int(input()) l = list( map( int , input().split() )) for e in l: r += e*s s += e mod =int(1e9+7) print( r %mod ) ```
p02703 AtCoder Beginner Contest 164 - Two Currencies
There are N cities numbered 1 to N, connected by M railroads. You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket. The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare....
```python n,m,s = map(int,input().split()) import collections g = [[] for _ in range(n+1)] dic = {} for _ in range(m): u,v,a,b = map(int,input().split()) g[u].append(v) g[v].append(u) dic[(u,v)]=(a,b) dic[(v,u)]=(a,b) arr = [[0,0]]+[list(map(int,input().split())) for _ in range(n)] cost =[[float('in...
p02832 AtCoder Beginner Contest 148 - Brick Break
We have N bricks arranged in a row from left to right. The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it. Among them, you can break at most N-1 bricks of your choice. Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of t...
```python N=int(input()) a=list(map(int,input().split())) now=1 cnt=0 for i in range(N): if(a[i]==now): now+=1 print(N-now+1 if now!=1 else -1) ```
p02969 AtCoder Beginner Contest 134 - Dodecagon
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2. Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r. Constraints * 1 \leq r \leq 100 * r is an integer. Input Input is given from Standard Input in the following format: r Output ...
```python x = int(input()) print(3*pow(x,2)) ```
p03105 AtCoder Beginner Contest 120 - Favorite Sound
Takahashi likes the sound when he buys a drink from a vending machine. That sound can be heard by spending A yen (the currency of Japan) each time. Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time. How many times will he h...
```python A,B,C = map(int,input().split()) print(min((B//A),C)) ```
p03252 AtCoder Beginner Contest 110 - String Transformation
You are given strings S and T consisting of lowercase English letters. You can perform the following operation on S any number of times: Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1. Determine if S and T can ...
```python from collections import Counter s1 = sorted(list(dict(Counter(input())).values())) t1 = sorted(list(dict(Counter(input())).values())) print(['No', 'Yes'][s1 == t1]) ```
p03405 AtCoder Regular Contest 093 - Bichrome Spanning Tree
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X. Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, mo...
```python import sys input=sys.stdin.readline def find_parent(x): y=parent[x] if y<0: return x parent[x]=find_parent(y) return parent[x] def connect(a,b): c=find_parent(a) d=find_parent(b) if c==d: return if parent[c]<parent[d]: parent[c]+=parent[d] pare...
p03568 CODE FESTIVAL 2017 qual C - Similar Arrays
We will say that two integer sequences of length N, x_1, x_2, ..., x_N and y_1, y_2, ..., y_N, are similar when |x_i - y_i| \leq 1 holds for all i (1 \leq i \leq N). In particular, any integer sequence is similar to itself. You are given an integer N and an integer sequence of length N, A_1, A_2, ..., A_N. How many ...
```python n = int(input()) a = list(map(int, input().split())) evens = len(list(filter(lambda x: x % 2 == 0, a))) print(3 ** n - 2 ** evens) ```
p03723 AtCoder Grand Contest 014 - Cookie Exchanges
Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below: * Each person simultaneously divides his cookies in half and gives one half to each of the other two persons. This action will be repeated until there is a person ...
```python A, B, C = map(int, input().split()) if A == B == C: print(0 if A%2 else -1) else: cnt = 0 while A%2==0 and B%2==0 and C%2==0: A, B, C = (B+C)//2, (C+A)//2, (A+B)//2 cnt += 1 print(cnt) ```
p03886 CODE FESTIVAL 2016 Grand Final(Parallel) - 90 and 270
Construct an N-gon that satisfies the following conditions: * The polygon is simple (see notes for the definition). * Each edge of the polygon is parallel to one of the coordinate axes. * Each coordinate is an integer between 0 and 10^9, inclusive. * The vertices are numbered 1 through N in counter-clockwise order. * ...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import itertools from heapq import heappop, heapify N,*A = map(int,read().split()) n90 = sum(x == 90 for x in A) if n90 - (N-n90) != 4: print(-1) exit() x = 0 temp = list(itertools.a...
p04044 AtCoder Beginner Contest 042 - Iroha Loves Strings (ABC Edition)
Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L. She will concatenate all of the strings in some order, to produce a long string. Among all strings that she can produce in this way, find the lexicographically smallest one. Here, a string s=s_1s_2s_3...s_n is lexicographically sma...
```python print("".join(sorted([input()for _ in[""]*int(input().split()[0])]))) ```
p00125 Day Count
Create a program that takes two dates as input and outputs the number of days between the two dates. Date 1 (y1, m1, d1) is the same as or earlier than date 2 (y2, m2, d2). Date 1 is included in the number of days, not date 2. Also, take the leap year into account when calculating. The leap year conditions are as foll...
```python # AOJ 0125 Day Count # Python3 2018.6.18 bal4u def ut2jd(year, month, day): if month <= 2: year -= 1 month += 12 s = 3 + year//4 - year//100 + year//400 s += 1720994 + year*365 + (month+1)*30 + (month+1)*3//5 + day; return s while True: y1, m1, d1, y2, m2, d2 = list(map(int, input().split())) if y...
p00258 Beat Panel
Yuta is addicted to the popular game "Beat Panel" at a nearby arcade. The game consists of a total of 16 panel-type buttons, 4x4, arranged in a grid as shown. <image> As shown in the figure, the buttons are arranged in the order of button 1, button 2,…, button 16 from the upper left to the lower right. In the game, ...
```python # using DP # time complexity: O(n * (2^16) * c) # 1 <= n <= 30, 1 <= c <= 30 # worst case: 30 * (2^16) * 30 = 58982400 bc = [bin(i).count('1') for i in range(65536)] # bitcount def solve(): from sys import stdin f_i = stdin while True: n, c = map(int, f_i.readline().split()) ...
p00445 JOI and IOI
problem Create a program that counts the number of consecutive JOI or IOI characters in a given character string. The character string consists only of uppercase letters of the alphabet. For example, the character string "JOIOIOI" in the figure below contains JOI in one place and IOI in two places. <image> input ...
```python while True: try: j = input() p=0 q=0 for i in range(len(j)-2): if j[i:i+3] == 'JOI': p += 1 elif j[i:i+3] == 'IOI': q += 1 else: pass print(p) print(q) except EOFError: break ```
p00636 The Last Dungeon
Brave Ponta has finally arrived at the final dungeon. This is a dark wilderness in front of the fort of the evil emperor Boromos, with fairly strong monsters guarding their territories. <image> Figure 1: Wilderness As shown in Fig. 1, the wilderness is represented by a 4 × 4 square region with the southwest as the ...
```python # AOJ 1050 The Last Dungeon # Python3 2018.7.7 bal4u import math import heapq EPS = 1e-8 pp0 = [0j, 4+0j, 4+4j, 4j] def EQ(a,b): return abs(a-b)<EPS def PPeQ(a,b): return EQ(a.real, b.real) and EQ(a.imag, b.imag) def dcmp(x): if PPeQ(x, 0): return 0 return -1 if x <= 0 else 1 def cross(a, b): return a.re...
p00910 Let There Be Light
Suppose that there are some light sources and many spherical balloons. All light sources have sizes small enough to be modeled as point light sources, and they emit light in all directions. The surfaces of the balloons absorb light and do not reflect light. Surprisingly in this world, balloons may overlap. You want th...
```python from itertools import product from sys import stdin, stdout readline = stdin.readline write = stdout.write def dist2(x0, y0, z0, x1, y1, z1): return (x0 - x1)**2 + (y0 - y1)**2 + (z0 - z1)**2 def dot(x0, y0, z0, x1, y1, z1): return x0*x1 + y0*y1 + z0*z1 def cross2(x0, y0, z0, x1, y1, z1): return...
p01044 Puzzle and Hexagons
Backgorund The super popular game "Puzzle & Hexagons" has finally been released. This game is so funny that many people are addicted to it. There were a number of people who were certified as addicted by doctors because of their excessive enthusiasm. Volunteers from around the world have created a "Puzzle & Hexagons" ...
```python class Simulator: def __init__(self, mp, width, height): self.mp = mp self.width = width self.height = height self.vec = [((1, 1), (1, 0), (0, -1), (-1, 0), (-1, 1), (0, 1)), ((1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (0, 1))] self.checked = No...
p01314 Sum of Consecutive Integers
You survived several months of exam wars and were able to enter ICPC University on a sunny day. On the day of admission, there was an enthusiastic recruitment of circles on the campus of the university, and you received a large number of pamphlets and returned. When you return to your room, you find one of the pamphlet...
```python while True: N=int(input()) if(N==0): break ans=0 for i in range((N//2)+1,0,-1): SUM=i k=i-1 while SUM<=N and k>0: SUM+=k if SUM==N: ans+=1 k-=1 print(ans) ```
p01795 ICPC Teams
Example Input 2 2 1 2 0 3 4 1 Output 2
```python from itertools import product from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): MOD = 10**9 + 9 N, M = map(int, readline().split()) K = 3*N fact = [1]*(K+1) rfact = [1]*(K+1) r = 1 for i in range(1, K+1): fact[i] =...
p02209 Are Cards Snacks?
Does the card fit in a snack? (Are Cards Snacks?) square1001 You have $ N $ cards. Each of these cards has an integer written on it, and the integer on the $ i $ th card is $ A_i $. square1001 Your random number today is $ K $. square1001 You want to choose some of these $ N $ cards so that they add up to $ K $. E8...
```python from itertools import * from bisect import * from math import * from collections import * from heapq import * from random import * from decimal import * import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(...
p02363 All Pairs Shortest Path
Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 9900 * -2 × 107 ≤ di ≤ 2 × 107 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E). |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi...
```python # -*- coding: utf-8 -*- import sys import os import pprint """???????????£????????????????????¨??????""" MAX = 100 d = [[None for i in range(MAX)] for j in range(MAX)] for i in range(MAX): for j in range(MAX): if i == j: d[i][j] = 0 else: d[i][j] = float('inf') ...
1041_C. Coffee Break
Recently Monocarp got a job. His working day lasts exactly m minutes. During work, Monocarp wants to drink coffee at certain moments: there are n minutes a_1, a_2, ..., a_n, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). ...
```python #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict BUFSIZE = 8192 class FastIO(...
1064_B. Equations of Mathematical Magic
Colossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for. Arkadi and Boris Strugatsky. Monday starts on Saturday Reading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: a - (a ⊕ x) - x = 0 for some given a, where ⊕ stands for...
```python def countSetBits(n): if(n==0): return(0) else: return((n&1)+countSetBits(n>>1)) t=int(input()) for _ in range(0,t): a=int(input()) x=countSetBits(a) print(pow(2,x)) ```
1105_E. Helping Hiasat
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle. Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequen...
```python import time def find_max_clique(remain, size, max_, index, maxs): # print(remain, size, max_) result = max_ if size + len(remain) <= result: # print('pruning (1)...') return result if not remain: # print('trivial') return size while remain: candidat...
1133_A. Middle of the Contest
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha...
```python s=input() h1=int(s[:2]) m1=int(s[3:]) s=input() h2=int(s[:2]) m2=int(s[3:]) #print(h1,m1,h2,m2) m=(m2-m1)+(h2-h1)*60; ma=(m1+m/2)%60; ha=(h1+(m1+m/2)/60); print('0'*(2-len(str(int(ha))))+str(int(ha))+':'+'0'*(2-len(str(int(ma))))+str(int(ma))) ```
1153_D. Serval and Rooted Tree
Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree. A tree is a connected graph without cycles. A rooted tree has a special vertex ca...
```python R = lambda: map(int, input().split()) n = int(input()) fcs = [0] + list(R()) ps = [0, 0] + list(R()) cs = [1] * (n + 1) for i in range(2, n + 1): cs[ps[i]] = 0 nc = sum(cs) - 1 for i in range(n, 1, -1): if fcs[ps[i]] == 0: cs[ps[i]] += cs[i] else: if not cs[ps[i]]: cs[p...
1175_C. Electrification
At first, there was a legend related to the name of the problem, but now it's just a formal statement. You are given n points a_1, a_2, ..., a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible. The function f_k(x) can be described in the following way: ...
```python def main(): inp = readnumbers() ii = 0 T = inp[ii] ii += 1 for _ in range(T): n = inp[ii] ii += 1 k = inp[ii] ii += 1 a = inp[ii:ii+n] ii += n ans = min((a[i] - a[i - k], a[i]) for i in range(k, n)) sys.stdout.bu...
1194_B. Yet Another Crosses Problem
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting...
```python for _ in range(int(input())): n,m=map(int,input().split()) g=[input() for _ in range(n)] a=[0]*n b=[0]*m for i in range(n): for j in range(m): if '*'==g[i][j]: a[i]+=1 b[j]+=1 ans=0 for i in range(n): for j in range(m): ans=max(ans,a[i]+b[j]-(g[i][j]=='*')) ...
1231_E. Middle-Out
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out. You are given two strings s and t of the same length n. Their characters are numbered from 1 to n from left to right (i.e. from...
```python # your code goes here t =int(input()) for h in range(t): ans = 1000000000 n = int(input()) a = str(input()) b = str(input()) if sorted(a) != sorted(b): ans = -1 else: ans = 10000000000000 for i in range(n): ...
1276_A. As Simple as One and Two
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ...
```python t=int(input()) for _ in range(t): answer=[] s=input() n=len(s) i=0 while i<(n-2): if s[i:i+3]=='one': answer.append(i+2) i+=3 elif s[i:i+3]=="two": if (i+4)<n and s[i:i+5]=="twone": answer.append(i+3) i+=5 ...
1296_B. Food Buying
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ...
```python #1296B for i in range(int(input())): n=input() b=0 z=0 while (len(n)>1): b=int(n[0])*(10**(len(n)-1)) z+=b n=str(int(n[1:])+b//10) z+=int(n) print(z) ```
131_B. Opposites Attract
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of cust...
```python c=[0]*50 n=int(input()) a=[0]*2000001 a=[int(i) for i in input().split()] for i in range(n): c[int(a[i]+10)]+=1; r=0 for i in range(10): r+=int(c[int(i)]*c[int(20-i)]) r+=(c[10]*(c[10]-1))//2; r=int(r) print(r) ```
1338_D. Nested Rubber Bands
You have a tree of n vertices. You are going to convert this tree into n rubber bands on infinitely large plane. Conversion rule follows: * For every pair of vertices a and b, rubber bands a and b should intersect if and only if there is an edge exists between a and b in the tree. * Shape of rubber bands must be ...
```python import os import sys input = sys.stdin.buffer.readline #sys.setrecursionlimit(int(3e5)) from collections import deque from queue import PriorityQueue import math import copy # list(map(int, input().split())) ##################################################################################### class CF(obje...
1360_C. Similar Pairs
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not. You are given an array a of n (n is even) positive in...
```python for i in range(int(input())): k=int(input()) a=list(map(int,input().split())) a.sort() c,d=0,0 i=1 e=0 for j in range(len(a)): if(a[j]%2==0): c+=1 else: d+=1 if(c%2==0 and d%2==0): print("YES") else: c,d=0,0 wh...
1380_D. Berserk And Fireball
There are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct. You have two types of spells which you may cast: 1. Fireball: you spend x mana and destroy exactly k consecutive warriors; 2. Berserk: you spend y mana, choose two consecutive warriors, and the warrior with gr...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self...
1400_D. Zigzags
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that: * 1 ≤ i < j < k < l ≤ n; * a_i = a_k and a_j = a_l; Input The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains a single integer n (4 ≤ n ≤ ...
```python # Problem Link :- https://codeforces.com/contest/1400/problem/D import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) de...
1469_F. Power Sockets
// We decided to drop the legend about the power sockets but feel free to come up with your own :^) Define a chain: * a chain of length 1 is a single vertex; * a chain of length x is a chain of length x-1 with a new vertex connected to the end of it with a single edge. You are given n chains of lengths l_1,...
```python import sys input = sys.stdin.readline import math n, k = map(int, input().split()) B = sorted(map(int, input().split()), reverse=True) N = 5 * (n + max(B)) A = [0] * N A[0] = 1 A[1] = -1 ans = float("inf") total = 0 j = 0 for i in range(N - 1): total += A[i] A[i + 1] += A[i] if total + A[i + 1] >...
1495_B. Let's Go Hiking
On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper. A permutation p is written from left to right on the paper. First Qingshan chooses an integer index x (1≤ x≤ n) and tells it to Daniel. After that, D...
```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...
1517_G. Starry Night Camping
At the foot of Liyushan Mountain, n tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky. The i-th tent is located at the point of (x_i, y_i) and has a weight of w_i. A tent is important ...
```python import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() Y=lambda:map(int,Z().split()) INF=float("inf");big=10**13 class D: def __init__(self, n): self.lvl = [0] * n self.ptr = [0] * n self.q = [0] * n self.adj...
193_A. Cutting Figure
You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected. A set of painted squares is called connected, if for every two s...
```python def add(vertex,neighbour): if vertex in graph: graph[vertex].append(neighbour) else: graph[vertex]=[neighbour] if neighbour in graph: #####for undirected part remove to get directed graph[neighbour].append(vertex) else: graph[neighbour]=[vertex] def dfs(gra...
217_A. Ice Skating
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves...
```python n = int(input()) g = [] for i in range(n): t = input().split() g.append([ int(t[0]), int(t[1]), False ]) def visita(i): g[i][2] = True for j in range(n): if g[j][2] == False and (g[i][0] == g[j][0] or g[i][1] == g[j][1]): visita(j) cnt = -1 for i in range(n): if g[i][...
240_A. Cinema
Overall there are m actors in Berland. Each actor has a personal identifier — an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information fo...
```python import sys try: sys.stdin = open('input.txt') sys.stdout = open('output.txt', 'w') except: pass def compl(n, s): return set(filter(lambda x: x not in s, range(1, n + 1))) m, k = list(map(int, input().split())) id = list(map(int, input().split())) n = int(input()) favorite = ...
265_D. Good Sequences
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good. Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions: * The sequence is strictly increasing, i.e. xi < xi + 1 f...
```python # Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import Counter def seieve_prime_factorisation(n): p, i = [1] * (n + 1), 2 while i * i <= n: if p[i] == 1: for j in range(i * i, n + 1, i): ...
289_D. Polo the Penguin and Houses
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou...
```python MOD = 10 ** 9 + 7 n, k = map(int, input().split()) ans = pow(n - k, n - k, MOD) * pow(k, k - 1, MOD) print(ans % MOD) ```
337_A. Puzzles
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
```python n,m = map(int,input().split()) f = list(map(int,input().split())) f.sort() a = [] for i in range(m-n+1): a.append(f[i+n-1]-f[i]) print(min(a)) ```
35_C. Fire Again
After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it N rows with M trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the j-th tree in the i-th row would have the coordinates of (i, j). However a terrible thing happened and...
```python ''' ___ ____ ____ _____ _____/ (_)_ ______ ____ _____/ / /_ __ ______ ___ __ / __ `/ __ `/ __ / / / / / __ \/ __ `/ __ / __ \/ / / / __ `/ / / / / /_/ / /_/ / /_/ / / /_/ / /_/ / /_/ / /_/ / / / / /_/ / /_/ / /_/ / \__,_/\__,_/\__,_/_/\__,_...
383_A. Milking cows
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi...
```python #! usr/bin/env python3 # coding:UTF-8 # wdnmd UKE # wcnm UKE ans = 0 cnt = 0 N = input() t = input().split() for i in t: if(int(i) == 1): cnt += 1 else: ans += cnt print(ans) ```
431_A. Black Square
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
```python #!/usr/bin/env python3 a=list(map(int,input().split())) s=input() print(a[0]*s.count('1') + a[1]*s.count('2') + a[2]*s.count('3') + a[3]*s.count('4')) ```
453_C. Little Pony and Summer Sun Celebration
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. <im...
```python import sys readline = sys.stdin.readline N, M = map(int, readline().split()) Edge = [[] for _ in range(N)] for _ in range(M): u, v = map(int, readline().split()) u -= 1 v -= 1 Edge[u].append(v) Edge[v].append(u) Pr = list(map(int, readline().split())) Po = Pr[:] if sum(Pr) == 0: prin...
476_A. Dreamoon and Stairs
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
```python n,m = map(int, input().split()) if n < m: print(-1) else: if n % 2 == 0: b = n//2 else: b = (n//2)+1 while b % m != 0: b = b + 1 print(b) ```
49_B. Sum
Vasya studies positional numeral systems. Unfortunately, he often forgets to write the base of notation in which the expression is written. Once he saw a note in his notebook saying a + b = ?, and that the base of the positional notation wasn’t written anywhere. Now Vasya has to choose a base p and regard the expressio...
```python a,b=list(map(int,input().split())) k=int(max(str(a)+str(b)))+1 carry=0 l=max(len(str(a)),len(str(b))) for itr in range(l): if a%10+b%10+carry<k: carry=0 else: carry=1 a//=10 b//=10 #print(a,b) if carry: print(l+1) else: print(l) ```
523_D. Statistics of Recompressing Videos
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network. We know that each server takes one second to recompress a one ...
```python import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def main(): import heapq n, k = [int(i) ...
54_B. Cutting Jigsaw Puzzle
The Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one. Soon the Hedgehog came up with a brilliant idea: ins...
```python def rotate(puzzle): n_puzzle = [] for y in range(len(puzzle) - 1, -1, -1): n_puzzle.append(puzzle[y]) result = [] for x in range(len(puzzle[0])): col = [] for y in range(len(puzzle)): col.append(n_puzzle[y][x]) result.append(col) return result ...
599_A. Patrick and Shopping
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ...
```python d=list(map(int,input().split())) d.sort() print(min(d[0]*2+d[1]*2,d[0]+d[1]+d[2])) ```
61_E. Enemy is weak
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number. In Shapur's opinion the weaknes...
```python from sys import stdin class order_tree: def __init__(self, n): self.tree, self.n = [[0, 0] for _ in range(n << 1)], n # get interval[l,r) def query(self, r, col): res = 0 l = self.n r += self.n while l < r: if l & 1: res += se...
63_D. Dividing Island
A revolution took place on the Buka Island. New government replaced the old one. The new government includes n parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island. The island can be conventionally represented as two re...
```python # https://codeforces.com/problemset/problem/63/D def solve(x0, y0, dx, X): for i, x in enumerate(X): while x > 0: x-=1 m[y0][x0] = i x0 += dx if x == 0 and i == len(X)-1: break if x0 == -1: y0...
669_B. Little Artem and Grasshopper
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him. The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grassh...
```python # python3 # utf-8 field_size = int(input()) field_idx___dir = input() field_idx___jump_len = [int(x) for x in input().split()] field_idx___was_visited = [False for x in range(field_size)] curr_field_idx = 0 while 0 <= curr_field_idx < field_size: if field_idx___was_visited[curr_field_idx]: prin...
690_D2. The Wall (medium)
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC2 (Handbook of Crazy Constructions) and looks for the right chapter: How to build a wall: 1. Take a set of bricks. 2. Select one of the possibl...
```python result=0 mod=10**6 +3 n,C=map(int,input().split()) #recibimos la entrada #calc n! def fact(n): fact=1 for i in range(1,n+1): #1*2*3*...*n = n*(n-1)*(n-2)...*1 fact=(fact*i)%mod # return fact def pow(a,b): #Algoritmo de Exponenciacion binaria exp=1 # Caso base a^1=a x=a % mod ...
735_A. Ostap and Grasshopper
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gras...
```python n,k=[int(x) for x in input().split()] s=input() if s.index('G')>s.index('T'):s=s[::-1] x=s.index('G') for i in range(x,n): x+=k if x>n-1 or s[x]=='#':print("NO");break elif s[x]=='T':print("YES");break ```
75_A. Life Without Zeros
Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a...
```python a = input () b = input () c = str (int (a) + int (b)) a = a.replace ("0", "") b = b.replace ("0", "") c = c.replace ("0", "") if int (a) + int (b) == int (c): print ("YES") else: print ("NO") ```
77_E. Martian Food
Have you ever tasted Martian food? Well, you should. Their signature dish is served on a completely black plate with the radius of R, flat as a pancake. First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of r and is located as close to the edge of the plate as possible...
```python #!/usr/bin/env python3 def solve(R,r,k): # Thanks to Numberphile's "Epic circles" video # Use the formula for radii of circles in Pappus chain r = r / R n = k answer = ((1-r)*r)/(2*((n**2)*((1-r)**2)+r)) # Note that in a Pappus chain the diameter of the circle is 1, so we need to scale up: answ...
803_D. Magazine Ad
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this: There are space-separated non-empty words of lowercase and uppercase Latin letters. There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more th...
```python def f(r): prev, ofs = -1, -1 s = list() while True: try: ofs = r.index(' ', ofs + 1) except ValueError: s.append(len(r) - 1 - prev) return s s.append(ofs - prev) prev = ofs n = int(input()) s = f(input().replace('-', ' ')) def can...
828_B. Black Square
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square. You are to determine the minimum possible ...
```python h,l=[int(i) for i in input().split()] a=[] for i in range(h): a.append(list(input())) left,right,down,up=[l-1,0,0,h-1] gg=True for i in range(h): for j in range(l): if a[i][j]=='B': gg=False if i<up: up=i if i>down: down=i if j>right: right=j ...
84_C. Biathlon
Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section. Of course, biathlon as any sport, proved very difficult in practice. I...
```python def main(): from array import array from bisect import bisect from sys import stdin input = stdin.readline O = -1 n = int(input()) xr = [] for i in range(n): xi, ri = map(int, input().split()) xr.append((xi, ri ** 2, i)) xr.sort() cur = 1 res1 = 0 ...
898_E. Squares and not squares
Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i. Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new ...
```python n=int(input()) p=[] m=list(map(int,input().split())) from math import floor,ceil for i in m: if i**0.5%1==0: p.append(0) else: p.append(min(i-floor(i**0.5)**2,ceil(i**0.5)**2-i)) a=p.count(0) am=m.count(0) if n//2<=a: x=a-n//2 dif=a-am if dif >= x: print(x) else...
946_E. Largest Beautiful Number
Yes, that's another problem with definition of "beautiful" numbers. Let's call a positive integer x beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since i...
```python import sys t = int(sys.stdin.buffer.readline().decode('utf-8')) ans = ['']*t for _ in range(t): a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').rstrip())) n = len(a) parity = [0]*10 for x in a: parity[x] ^= 1 psum = sum(parity) for i, free in zip(range(n-1, -1,...
975_C. Valhalla Siege
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle. Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The fir...
```python import bisect n,q=map(int,input().split()) a=list(map(int,input().split())) s=[0,] for i in a: s.append(s[-1]+i) k=list(map(int,input().split())) tb=0 for i in range(q): tb+=k[i] if tb>=s[-1]: tb=0 print(n) else: ans=bisect.bisect_right(s,tb) print(n-ans+1) `...
995_B. Suit and Tie
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m...
```python input() a=list(map(int,input().split())) cnt=0 while a: i=a.index(a.pop(0)) cnt+=i a.pop(i) print(cnt) ```
p02641 AtCoder Beginner Contest 170 - Forbidden List
Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N. Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, repo...
```python X, N = map(int, input().split()) p = list(map(int, input().split())) ans = 0 for i in range(102): if i not in p: if abs(i-X)<abs(ans-X): ans = i print(ans) ```
p02771 AtCoder Beginner Contest 155 - Poor
A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers. You will be given three integers A, B, and C. If this triple is poor, print `Yes`; otherwise, print `No`. Constraints * A, B, and C are all integers between 1 and 9 (inclusive). Input...
```python *l, = map(int, input().split()) print("Yes" if len(set(l)) == 2 else "No") ```
p02906 AtCoder Grand Contest 038 - Unique Path
Snuke's mother gave Snuke an undirected graph consisting of N vertices numbered 0 to N-1 and M edges. This graph was connected and contained no parallel edges or self-loops. One day, Snuke broke this graph. Fortunately, he remembered Q clues about the graph. The i-th clue (0 \leq i \leq Q-1) is represented as integers...
```python class UnionFind: def __init__(self, n): self.par = [i for i in range(n+1)] self.rank = [0] * (n+1) # search def find(self, x): if self.par[x] == x: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] # uni...
p03041 AtCoder Beginner Contest 126 - Changing a Character
You are given a string S of length N consisting of `A`, `B` and `C`, and an integer K which is between 1 and N (inclusive). Print the string S after lowercasing the K-th character in it. Constraints * 1 ≤ N ≤ 50 * 1 ≤ K ≤ N * S is a string of length N consisting of `A`, `B` and `C`. Input Input is given from Standa...
```python a, b = map(int, input().split(' ')) c = input() print(c[:b-1]+c[b-1:b].lower()+c[b:]) ```
p03183 Educational DP Contest - Tower
There are N blocks, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), Block i has a weight of w_i, a solidness of s_i and a value of v_i. Taro has decided to build a tower by choosing some of the N blocks and stacking them vertically in some order. Here, the tower must satisfy the following condition: * For eac...
```python import sys input = lambda : sys.stdin.readline().strip() n = int(input()) wsv = [list(map(int, input().split())) for i in range(n)] wsv.sort(key=lambda x: x[0]+x[1]) max_s = 10**4 DP = [-float("inf")]*(2*max_s+1) DP[0] = 0 for i in range(n): w,s,v = wsv[i] nxt = DP[:] for j in range(s+1): ...
p03330 AtCoder Beginner Contest 099 - Good Grid
There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left. These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}. We say the grid is a good grid when the following...
```python n,c=map(int,input().split()) D=[] for i in range(c): D.append(list(map(int,input().split()))) C=[] for i in range(n): C.append(list(map(int,input().split()))) A=[[0]*c for i in range(3)] for i in range(n): for j in range(n): a=(i+j)%3 A[a][C[i][j]-1]+=1 ans=10**100 for a0 in ...
p03489 AtCoder Regular Contest 087 - Good Sequence
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence. Here, an sequence b is a good sequence when the following condition holds true: * For each element x in b, the value x occurs exactly x times in...
```python hm={} n=int(input()) ans=n arr=[int(i) for i in input().split()] for i in arr: hm[i]=hm.get(i,0)+1 for i in hm: if hm[i]!=i: if hm[i]>i: ans-=hm[i]-i else: ans-=hm[i] print(n-ans) ```
p03651 AtCoder Grand Contest 018 - Getting Difference
There is a box containing N balls. The i-th ball has the integer A_i written on it. Snuke can perform the following operation any number of times: * Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written....
```python n, k = map(int, input().split()) a = list(map(int, input().split())) def f(l, s): return s if l % s == 0 else f(s, l % s) z = f(max(a), min(a)) for i in a: z = f(i, z) if max(a) >= k and k % z == 0: print('POSSIBLE') else: print('IMPOSSIBLE') ```
p03807 AtCoder Grand Contest 010 - Addition
There are N integers written on a blackboard. The i-th integer is A_i. Takahashi will repeatedly perform the following operation on these numbers: * Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them. * Then, write a new integer on the blackboard ...
```python N = int(input()) A = map(int, input().split(" ")) oe = [a%2 for a in A] if sum(oe)%2 == 0: print("YES") else: print("NO") ```
p03975 Kyoto University Programming Contest 2016 - A Barricade
Summer vacation ended at last and the second semester has begun. You, a Kyoto University student, came to university and heard a rumor that somebody will barricade the entrance of your classroom. The barricade will be built just before the start of the A-th class and removed by Kyoto University students just before the...
```python N,A,B=map(int,input().split()) t=[int(input()) for i in range(N)] ans=0 for i in range(N): if A<=t[i]<B: continue else: ans+=1 print(ans) ```
p00064 Secret Number
The new PIN is hard to remember. I was told that I shouldn't take notes, but I don't think I can remember them. Therefore, I decided to embed a numerical value in the text and make a note of the PIN. Here, the sum of all the numbers is the PIN. Create a program that reads the memorandum and outputs the PIN code. In...
```python import re l=0 try: while True: x=input() for i in re.findall(r'\d+',x): l+=int(i) except: print(l) ```
p00196 Baseball Championship
Japan achieved the second straight victory in the national baseball competition WBC !! A baseball tournament was held at Aizu Gakuen High School as baseball became more popular. In this tournament, a round-robin league match will be held and the ranking will be decided in the following ways. 1. The team with the most ...
```python while 1: n = int(input()) if n == 0: break result = [] for i in range(n): data = list(map(str, input().split())) name = data.pop(0) win = data.count("0") lose = data.count("1") result.append([name, win, lose]) result = sorted(result, key=la...
p00350 String Game
You gave the twins Ai and Zu a program of games using strings. In this game, Ai and Zu each select a substring from the character string, compare them, and the person who chooses the smaller one will get points. The two competed and played the game many times. However, I got tired of playing games for the same string m...
```python def solve(): from sys import stdin f_i = stdin N = int(f_i.readline()) U = f_i.readline() U Q = int(f_i.readline()) ans = [] for i in range(Q): query = f_i.readline().split() if query[0] == 'set': x, y = map(int, query[1:3]) x -...
p00546 Zombie Island
problem The island where JOI lives has been invaded by zombies. JOI decided to escape to the shelter, which is set as the safest shelter on the island. The island where JOI lives consists of N towns from town 1 to town N, and the towns are connected by roads. There are M roads on the island, all of which connect two ...
```python from collections import deque from heapq import heappop,heappush inf=float("INF") dq=[] n,m,k,s=map(int,input().split()) p,q=map(int,input().split()) c=[0]*k z_dist=[inf]*n for i in range(k): c[i]=int(input())-1 z_dist[c[i]]=0 heappush(dq,(0,c[i])) g=[[] for i in range(m)] a=[0]*m b=[0]*m f...
p00710 Hanafuda Shuffle
There are a number of ways to shuffle a deck of cards. Hanafuda shuffling for Japanese card game 'Hanafuda' is one such example. The following is how to perform Hanafuda shuffling. There is a deck of n cards. Starting from the p-th card from the top of the deck, c cards are pulled out and put on the top of the deck, a...
```python while True: n, r = map(int, input().split()) if n == 0: break else: cards = list(reversed(range(n))) for _ in range(r): p, c = map(int, input().split()) for i,x in enumerate(cards): if 0 <= x < p-1: cards[i] += c ...
p01113 Floating-Point Numbers
Floating-Point Numbers In this problem, we consider floating-point number formats, data representation formats to approximate real numbers on computers. Scientific notation is a method to express a number, frequently used for numbers too large or too small to be written tersely in usual decimal form. In scientific no...
```python import math import sys ma = 1<<53 #53ビット表現限界 while 1: n = int(sys.stdin.readline()) if n == 0: break s = list(sys.stdin.readline()[:-1]) """aを先頭の1を含む53ビットとして保存""" a = 1 for i in range(52): a <<= 1 a += int(s[i]) ans = a e = 0 """「切り下げながら足し算」→「aを適時右シ...
p01412 Power of Power
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to perform a very large number of calculations to improve the calculation power and raise awareness. Exponentiation is an operation that easily produces large numbers....
```python from collections import Counter import sys readline = sys.stdin.readline write = sys.stdout.write def check(N, A): if N == 1: return A A.sort() C = Counter(A) c0 = C.get(0, 0) if c0 == N: return A c1 = C.get(1, 0) rest = A[c0+c1:] back = [] if c0 > 0: ...
p01866 Hamming Distance
Problem statement There is an unsigned $ 2 $ decimal integer $ X $ with $ N $ in digits including Leading-zeros. Output the largest non-negative integer that can be expressed in $ 2 $ base in $ N $ digits where the Hamming distance from $ X $ is $ D $. The Hamming distance between integers expressed in $ 2 $ is the n...
```python # -*- coding: utf-8 -*- N = int(input()) X = input() D = int(input()) ans = list(X) done = [False] * N for i in range(N): if D == 0: break if ans[i] == "0": ans[i] = "1" done[i] = True D -= 1 for i in range(N)[::-1]: if D == 0: break if ans[i] == "1" ...
p02003 Board
problem Given the squares of $ R * C $. Each square is either an empty square or a square with a hole. The given square meets the following conditions. * The cells with holes are connected. (You can move a square with a hole in the cross direction to any square with a hole) * Empty cells are connected. You can gen...
```python # -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i ...
p02288 Maximum Heap
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values ...
```python H = int(input()) A = [0] for i in input().split(): A.append(int(i)) def maxHeapify(i): l = 2*i r = 2*i+1 if l <= H and A[l] > A[i]: L = l else: L = i if r <= H and A[r] > A[L]: L = r if L != i: A[i],A[L] = A[L],A[i] maxHeapify(L) for i in range(1,H//2+1)[::-1]: maxHea...
p02435 Stack
Stack is a container of elements that are inserted and deleted according to LIFO (Last In First Out). For $n$ stack $S_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations. * push($t$, $x$): Insert an integer $x$ to $S_t$. * top($t$): Report the value which should be deleted next from $S_t$. If $...
```python n, q = list(map(int, input().split())) ss = [] for i in range(n): ss.append([]) for i in range(q): a = list(map(int, input().split())) k = a[0] if k == 0: ss[a[1]].append(a[2]) if k == 1: if len(ss[a[1]]) != 0: print(ss[a[1]][-1]) else: ...