name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p02707 AtCoder Beginner Contest 163 - management
A company has N members, who are assigned ID numbers 1, ..., N. Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number. When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X. You are given the information ...
```python N=int(input()) A=list(map(int,input().split())) b=[0]*N for c in A: b[c-1]+=1 for i in b: print(i) ```
p02836 AtCoder Beginner Contest 147 - Palindrome-philia
Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice. Given is a string S. Find the minimum number of hugs needed to make S palindromic. Constraints * S is a string consisting of lowercase English ...
```python s = input() t = 0 for i in range(len(s)//2): if s[i] != s[-(i+1)]: t += 1 print(t) ```
p02973 AtCoder Beginner Contest 134 - Sequence Decomposing
You are given a sequence with N integers: A = \\{ A_1, A_2, \cdots, A_N \\}. For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied: * If A_i and A_j (i < j) are painted with the same color, A_i < A_j. Find the minimum number of col...
```python import bisect from collections import deque N = int(input()) ans = deque([-1]) for _ in range(N): a = int(input()) i = bisect.bisect_left(ans, a) if i == 0: ans.appendleft(a) else: ans[i-1] = a print(len(ans)) ```
p03109 AtCoder Beginner Contest 119 - Still TBD
You are given a string S as input. This represents a valid date in the year 2019 in the `yyyy/mm/dd` format. (For example, April 30, 2019 is represented as `2019/04/30`.) Write a program that prints `Heisei` if the date represented by S is not later than April 30, 2019, and prints `TBD` otherwise. Constraints * S is...
```python s = input() month = int(s[5:7]) print("Heisei" if month < 5 else "TBD") ```
p03256 AtCoder Grand Contest 027 - ABland Yard
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i. The phantom thief Nusook likes to choose some ...
```python import sys,time sys.setrecursionlimit(10**7) start_time = time.time() N,M = map(int,input().split()) S = input() src = [tuple(map(lambda x:int(x)-1,sys.stdin.readline().split())) for i in range(M)] outdeg = [set() for i in range(2*N)] for x,y in src: if S[x] == S[y]: #A0->A1, B0->B1 outd...
p03409 AtCoder Beginner Contest 091 - 2D Plane 2N Points
On a two-dimensional plane, there are N red points and N blue points. The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i). A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, an...
```python N = int(input()) AB = sorted([[int(_) for _ in input().split()] for _ in range(N)], key=lambda x: x[1], reverse=True) CD = sorted([[int(_) for _ in input().split()] for _ in range(N)]) for i in range(N): for j in range(len(AB)): if AB[j][0] < CD[i][0] and AB[j][1] < CD[i]...
p03727 AtCoder Grand Contest 014 - Blue and Red Tree
There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each edge is painted blue. Takahashi will convert this blue tree into a red tree, by performing the following operation N-1 times: * Select a simple path that consists of only blue edges, and remo...
```python import queue n,q=int(input()),queue.Queue() s=[set() for i in range(n+1)] for i in range(2*n-2): u,v=map(int,input().split()) if v in s[u]: q.put((u,v)) else: s[u].add(v) s[v].add(u) f=[i for i in range(n+1)] def find(x): if f[x]==x: return x else: f[x]=find(f[x]) return f[x] while not q.empt...
p03891 CODE FESTIVAL 2016 Relay (Parallel) - Magic Square 2
A 3×3 grid with a integer written in each square, is called a magic square if and only if the integers in each row, the integers in each column, and the integers in each diagonal (from the top left corner to the bottom right corner, and from the top right corner to the bottom left corner), all add up to the same sum. ...
```python a=int(input()) b=int(input()) c=int(input()) x=[[0,0,0] for _ in range(3)] for i in range(-300,301): x[0][0]=a x[0][1]=b x[1][1]=c x[0][2]=i-a-b x[2][2]=i-a-c x[2][1]=i-b-c x[1][2]=i-x[0][2]-x[2][2] x[1][0]=i-c-x[1][2] x[2][0]=i-x[2][1]-x[2][2] ok = True for j in ra...
p04050 AtCoder Grand Contest 001 - Arrays and Palindrome
Snuke got a present from his mother on his birthday. The present was a pair of two sequences a and b, consisting of positive integers. They satisfied all of the following properties: * The sum of all elements of a is N. * The sum of all elements of b is N. * Any string of length N that satisfies the following two cond...
```python n,m = [int(i) for i in input().split()] a = [int(i) for i in input().split()] breakFlag = False for i in range(1,m-1): if a[i]%2==1: if a[0]%2==1: if a[len(a)-1]%2==1: print("Impossible") breakFlag = True break else: ...
p00129 Hide-and-Seek Supporting System
Taro is not good at hide-and-seek. As soon as you hide, you will find it, and it will be difficult to find the hidden child. My father, who couldn't see it, made an ultra-high performance location search system. You can use it to know exactly where your friends are, including your own. Once you become a demon, you can ...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0129 """ import sys from sys import stdin from math import sqrt, atan2, acos, sin, cos, hypot input = stdin.readline class Point(object): epsilon = 1e-10 def __init__(self, x=0.0, y=0.0): if isinstance(x,...
p00262 Triangle of Blocks
The following sorting operation is repeated for the stacked blocks as shown in Fig. A. 1. Stack all the bottom blocks (white blocks in Figure a) on the right edge (the remaining blocks will automatically drop one step down, as shown in Figure b). 2. If there is a gap between the blocks, pack it to the left to eliminat...
```python tri_nums = [i * (i + 1) // 2 for i in range(1500)] while True: n = int(input()) if n == 0: break blst = list(map(int, input().split())) if sum(blst) not in tri_nums: print(-1) continue end = [i + 1 for i in range(tri_nums.index(sum(blst)))] lenb = n cnt = 0 while blst != end: i...
p00449 Boat Travel
problem There are n islands in JOI, and each island is numbered from 1 to n. Currently, the JOI country is developing a route network connecting each island. You work at a ticket center that handles ship tickets. There are many people in JOI who want to travel between islands by boat, as cheaply as possible, and they...
```python # AOJ 0526: Boat Travel # Python3 2018.7.1 bal4u INF = 0x7fffffff while True: n, k = map(int, input().split()) if n == 0: break fee = [[INF for j in range(101)] for i in range(101)] for i in range(n+1): fee[i][i] = 0 for i in range(k): v = list(map(int, input().split())) a, b = v[1], v[2] if v[0] ...
p00640 Distorted Love
Saying that it is not surprising that people want to know about their love, she has checked up his address, name, age, phone number, hometown, medical history, political party and even his sleeping position, every piece of his personal information. The word "privacy" is not in her dictionary. A person like her is calle...
```python # AOJ 1054: Distorted Love # Python3 2018.7.7 bal4u while True: n = int(input()) if n == 0: break input() # w, h pag, dic = [], {} for i in range(n): nm, k = input().split() dic[nm] = i btn = [] for j in range(int(k)): x1, y1, x2, y2, bnm = input().split() btn.append((int(x1), int(y1), i...
p00916 Count the Regions
There are a number of rectangles on the x-y plane. The four sides of the rectangles are parallel to either the x-axis or the y-axis, and all of the rectangles reside within a range specified later. There are no other constraints on the coordinates of the rectangles. The plane is partitioned into regions surrounded by ...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01049 Array Update
Problem There is an arithmetic progression A with the number of terms N, the first term a, and the tolerance d. Since M statements that update the sequence are given in the following format, find the value of the K item when the sequence A is updated M times in the given order. * The i-th statement is represented by ...
```python n = int(input()) a, d = map(int, input().split()) mem = {} def get_mem(num): if num in mem:return mem[num] else:return num m = int(input()) for _ in range(m): x, y, z = map(int, input().split()) if x == 0: ny, nz = get_mem(y), get_mem(z) mem[y] = nz mem[z] = ny if x == 1: nz ...
p01318 Immortal Jewels
English text is not available in this practice contest. At one point, a nobleman fell in love with a brave princess in a poor country and applied for marriage. The princess has given certain conditions to the aristocrats. The condition was to bring in a large number of jewels called "immortal jewels". Immortal gems ar...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def common_tangent_lines(x1, y1, r1, x2, y2, r2): result = [] xd = x2 - x1; yd = y2 - y1 rr0 = xd**2 + yd**2 if (r1 - r2)**2 <= rr0: cv = r1 - r2 if rr0 == (r1 - r2)**2: bx = r1*cv*xd/rr0 ...
p01486 CatChecker
Example Input mmemewwemeww Output Cat
```python import re b=s=input() while 1: s=re.sub(r'(m|e)mew(e|w)','\\1\\2',s) if b==s:break b=s print(['Rabbit','Cat'][s=='mew']) ```
p01648 Median Tree
Problem Statement You are given a connected undirected graph which has even numbers of nodes. A connected graph is a graph in which all nodes are connected directly or indirectly by edges. Your task is to find a spanning tree whose median value of edges' costs is minimum. A spanning tree of a graph means that a tree ...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01933 Displayed tweets
problem In Ikatta, the SNS used by AOR Ika-chan, posts are called tweets. And in squid, there is a concern that visibility will deteriorate if there are many replies to tweets, so when a tweet meets any of the following rules, the tweet will be displayed on the screen. ing. * Rule 1. No reply to any tweet * Rule 2. ...
```python # AOJ 2833: Displayed tweets # Python3 2018.7.12 bal4u INF = 0x7ffffff N, K = map(int, input().split()) k, f = [INF]*(N+1), [0]*(N+1) a = [0]+[int(input()) for i in range(N)] ans = 0 for i in range(N, 0, -1): re = a[i] if re: if f[i] == 0: v = 0; ans += 1 else: v = k[i] if v < K: ans += 1 v +=...
p02213 Don't Rotate the Dice!
Problem statement I have a grid of $ H $ rows and $ W $ columns. Hereafter, the cells in the $ i $ row and $ j $ column on the grid are written as $ (i, j) $ cells. Each cell in the grid has a number between $ 1 $ and $ 6 $, or the letter `#` in $ 1 $ each. However, `#` is always written in the cell of $ (i, j) $ whe...
```python import sys sys.setrecursionlimit(pow(10, 8)) S = [6, 3, 1, 4, 2, 5] H, W = map(int, input().split()) X = [] for i in range(H): X.append(input().strip()) def migi(S): return [S[1], S[2], S[3], S[0], S[4], S[5]] def hidari(S): return [S[3], S[0], S[1], S[2], S[4], S[5]] def sita(S): return [S[...
p02367 Bridges
Find bridges of an undirected graph G(V, E). A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s...
```python 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 in range(a)] def ceil(x, ...
1033_D. Divisors
You are given n integers a_1, a_2, …, a_n. Each of a_i has between 3 and 5 divisors. Consider a = ∏ a_i — the product of all input integers. Find the number of divisors of a. As this number may be very large, print it modulo prime number 998244353. Input The first line contains a single integer n (1 ≤ n ≤ 500) — the ...
```python from math import gcd def divisors(n, a): d = {} bad = [] for i in range(n): c = a[i] if (int(c ** 0.25 + 0.0001)) ** 4 == c: p = int(c ** 0.25 + 0.0001) if p not in d: d[p] = 4 else: d[p] += 4 elif (int(...
1056_B. Divide Candies
Arkady and his friends love playing checkers on an n × n field. The rows and the columns of the field are enumerated from 1 to n. The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set o...
```python n,m=map(int,input().split()) s=list() for i in range(1,m+1): for j in range(1,m+1): if (i**2+j**2)%m==0: s.append([i,j]) ans=0 for k in s: #print(k) ky=(n-k[0])//(m)+1 my=(n-k[1])//(m)+1 ans+=ky*my print(ans) ```
1099_C. Postcard
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it. Andrey noticed that snowflakes and candy canes always stand af...
```python s=input() k=int(input()) temp="" cnt=0 for i in range(len(s)): if(s[i]=="?" or s[i]=="*"): cnt+=1 continue else: temp+=s[i] #print(temp,len(temp)) if(len(temp)-cnt>k): print("Impossible") elif(len(temp)==k): print(temp) elif(len(temp)<k): req=k-len(temp) temp2="" flag=0 for i in range(len(s)): ...
111_B. Petya and Divisors
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem: You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him. Input The first line contains an int...
```python maxn=100000 div=[0]*(maxn+1) last=[-maxn]*(maxn+1) for i in range(maxn+1): div[i]=list() for i in range(2,maxn+1): for j in range(i,maxn+1,i): div[j].append(i) t=int(input()) for k in range(0,t): x_i,y_i = input().split(" ") x_i=int(x_i) y_i=int(y_i) if y_i==0: prin...
1186_C. Vus the Cossack and Strings
Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings a and b. It is known that |b| ≤ |a|, that is, the length of b is at most the length of a. The Cossack considers every substring of length |b| in string a. Let's call this substring c. He matches the corresp...
```python a=input() b=input() A=[] al=len(a) bl=len(b) A.append(0) count=0 for x in a: if x=='1': count+=1 A.append(count) evencount=0 bcount=0 for x in b: if x=='1': bcount+=1 for i in range((al+1)-bl): acount=A[i+bl]-A[i] if (acount%2)==(bcount%2): evencount+=1 print(evenco...
1205_B. Shortest Cycle
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Find the length of the shortest cycle in this graph or determine th...
```python from collections import * import sys # "". join(strings) def ri(): return int(input()) def rl(): return list(map(int, input().split())) n = ri() aa = rl() zero_cnt = 0 aa = [value for value in aa if value != 0] n = len(aa) edges = set() graph = defaultdict(list) bit_shared...
1248_C. Ivan the Fool and the Probability Theory
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r...
```python N = int(1e5+3) MOD = int(1e9+7) memo = [0] * N def dp(): memo[0] = 2 memo[1] = 2 for i in range(2, N): memo[i] = (memo[i-1] + memo[i-2]) % MOD n, m = map(int, input().split()) dp() print((memo[n] + - 1 + memo[m] - 1) % MOD) ```
1266_G. Permutation Concatenation
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the...
```python n = int(input()) f_n = n cnt = 0 for k in range(n-1, 0, -1): cnt += f_n f_n *= k if f_n >= 998244353: f_n %= 998244353 print((n*f_n-cnt)%998244353) ```
1288_B. Yet Another Meme Problem
Try guessing the statement from this picture <http://tiny.cc/ogyoiz>. You are given two integers A and B, calculate the number of pairs (a, b) such that 1 ≤ a ≤ A, 1 ≤ b ≤ B, and the equation a ⋅ b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11)...
```python for _ in range(int(input())): A, B = list(map(int, input().split())) res = 0 seed = 9 while seed <= B: res += A seed = seed*10 + 9 print(res) ```
1331_E. Jordan Smiley
<image> Input The input contains two integers row, col (0 ≤ row, col ≤ 63), separated by a single space. Output Output "IN" or "OUT". Examples Input 0 0 Output OUT Input 27 0 Output IN Input 0 27 Output OUT Input 27 27 Output IN
```python s = [ "0000000000000000000000000010101111110100000000000000000000000000", "0000000000000000000000101110101010010111110000000000000000000000", "0000000000000000000011101000100011010000100100000000000000000000", "0000000000000000011110101011111000011110101110100000000000000000", "0000000000000000110000001010000...
1351_C. Skier
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively). It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visite...
```python num_lines = int(input()) for _ in range(num_lines): d = input() c = 0 points = set() start_point = (0, 0) for s in d: if s == 'N': end_point = (start_point[0] + 1, start_point[1]) if s == 'S': end_point = (start_point[0] - 1, start_point[1]) ...
1371_E1. Asterism (Easy Version)
This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved. First, Aoi came up with the following idea for the competitive programming problem: Yuzu is a girl who collecting candies. Originally, she has x ...
```python import sys input = sys.stdin.readline n,p=map(int,input().split()) A=sorted(map(int,input().split())) MAX=A[-1] start=max(A[0],MAX-(n-1)) S=[] ind=0 for c in range(start,MAX+1): while ind<n and A[ind]<=c: ind+=1 S.append(ind) #print(S) SS=[S[i]-i for i in range(len(S))] MAX=10**9 MIN=0 fo...
1394_B. Boboniu Walks on Graph
Boboniu has a directed graph with n vertices and m edges. The out-degree of each vertex is at most k. Each edge has an integer weight between 1 and m. No two edges have equal weights. Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a v...
```python from random import randrange import sys input = sys.stdin.buffer.readline def solve(digit, res): ans = 0 if digit == k: return int(res == zob_all) for i in range(digit + 1): ans += solve(digit + 1, res^zob[digit][i]) return ans n, m, k = map(int, input().split()) edges = [l...
1418_G. Three Occurrences
You are given an array a consisting of n integers. We denote the subarray a[l..r] as the array [a_l, a_{l + 1}, ..., a_r] (1 ≤ l ≤ r ≤ n). A subarray is considered good if every integer that occurs in this subarray occurs there exactly thrice. For example, the array [1, 2, 2, 2, 1, 1, 2, 2, 2] has three good subarrays...
```python import random n = int(input()) a = list(map(int, input().split())) a.insert(0, 0) cnt = [0] * (n + 1) cnt2 = [0] * (n + 1) hashs = [0] * (n + 1) r1 = [None] * (n + 1) r2 = [None] * (n + 1) for i in range(1, n + 1): r1[i] = random.randint(1, 1000000000000) r2[i] = random.randint(1, 1000000000000) ...
1436_F. Sum Over Subsets
You are given a multiset S. Over all pairs of subsets A and B, such that: * B ⊂ A; * |B| = |A| - 1; * greatest common divisor of all elements in A is equal to one; find the sum of ∑_{x ∈ A}{x} ⋅ ∑_{x ∈ B}{x}, modulo 998 244 353. Input The first line contains one integer m (1 ≤ m ≤ 10^5): the number of di...
```python import sys input=sys.stdin.readline max_n=10**5+1 mod=998244353 spf=[i for i in range(max_n)] prime=[True for i in range(max_n)] mobius=[0 for i in range(max_n)] prime[0]=prime[1]=False mobius[1]=1 primes=[] for i in range(2,max_n): if(prime[i]): spf[i]=i mobius[i]=-1 primes.appen...
1461_D. Divide and Summarize
Mike received an array a of length n as a birthday present and decided to test how pretty it is. An array would pass the i-th prettiness test if there is a way to get an array with a sum of elements totaling s_i, using some number (possibly zero) of slicing operations. <image> An array slicing operation is conducted...
```python from sys import stdin, stdout input = stdin.readline print = stdout.write s = set() def rec(a): s.add(sum(a)) c = (min(a) + max(a)) / 2 sl = sr = 0 left = [] right = [] for i in a: if i <= c: left += i, sl += i else: right += i, ...
1486_E. Paired Payment
There are n cities and m bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter w. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go f...
```python import sys, io, os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline read = lambda: map(int, input().split()) from heapq import heappush, heappop inf = 1e10 n, m = read() e = {} for _ in range(m): v, u, w = read() v -= 1 u -= 1 if v not in e: e[v] = [] if u not in e: ...
1538_A. Stone Game
Polycarp is playing a new computer game. This game has n stones in a row. The stone on the position i has integer power a_i. The powers of all stones are distinct. Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone...
```python t=int(input()) while t!=0: t-=1 n=int(input())-1 a=list(map(int,input().split())) le=min(a.index(max(a)),a.index(min(a))) ri=max(a.index(max(a)),a.index(min(a))) mid=ri-le-1 ri=n-ri print(sum([le,ri,mid])-max(le,ri,mid)+2) ```
185_B. Mushroom Scientists
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: <ima...
```python a=int(input()) b=list(map(int,input().split())) if sum(b)==0:print(' '.join([str(a/3)]*3)) else:print(' '.join(map(str,map(lambda x:a*x/sum(b),b)))) ```
231_C. To Add or Not to Add
A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array. However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. I...
```python import sys import math as mt input=sys.stdin.buffer.readline #t=int(input()) t=1 for __ in range(t): #n=int(input()) n,k=map(int,input().split()) l=list(map(int,input().split())) l.sort() maxn,maxl=l[0],1 suma=[0]*(n+2) suma[0]=0 for i in range(n): suma[i+1]=suma...
257_B. Playing Cubes
Petya and Vasya decided to play a little. They found n red cubes and m blue cubes. The game goes like that: the players take turns to choose a cube of some color (red or blue) and put it in a line from left to right (overall the line will have n + m cubes). Petya moves first. Petya's task is to get as many pairs of nei...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt'...
280_B. Maximum Xor Secondary
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: <image>. The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is t...
```python #http://codeforces.com/problemset/problem/281/D #SC = TC = o(n) n = int(input()) a = list(map(int, input().strip().split())) stack = [] #decreasing stack max_xor = 0 for k in range(n): #if stack empty if not stack: stack.append(a[k]) #if less than top of stack elif a[k]<stack[-1]: max_xor = max(m...
303_A. Lucky Permutation Triple
Bike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not. A permutation triple of permutations of length n (a, b, c) is called a...
```python n = int(input()) if n % 2 == 0: print(-1) else: print(*range(n)) print(*range(n)) print(*map(lambda x: x * 2 % n, range(n))) ```
32_B. Borze
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. Input The first line contains a nu...
```python x=input() code=x.split() q=[] for i in x: q.append(i) code=q i=0 total="" while i < len(code): if(code[i] == '.'): total = total + '0' elif(code[i] == '-'): if(code[i + 1] == '.'): total =total + '1' elif (code[i+1] == '-'): total = total + '2' ...
350_E. Wrong Floyd
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it. Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, contai...
```python # written with help of editorial n, m, k = map(int, input().split()) ban = list(map(int, input().split())) if k == n or m > n * (n - 1) // 2 - k + 1: print('-1') else: edges = [(i, j) for i in range(1, n + 1) for j in range(i + 1, n + 1)] for i in range(1, k): a = min(ban[i], ban[0]) ...
375_A. Divisible by Seven
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7. Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resultin...
```python # Made By Mostafa_Khaled bot = True a=input() cnt=[0]*10 for i in (1,6,8,9): cnt[i]=-1 for i in a: cnt[int(i)]+=1 mod = [1869, 1968, 9816, 6198, 1698, 1986, 1896, 1869] modCnt=0 for i in range(1,10): for j in range(cnt[i]): modCnt= (modCnt*3 + i)%7 print(str(i)*cnt[i], end='') modCnt=(1000...
397_C. On Number of Decompositions into Multipliers
You are given an integer m as a product of integers a1, a2, ... an <image>. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers. Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, ...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from collections import Counter def factor(x,cou): while not x%2: x /= 2 cou[2] += 1 for i in range(3,int(x**0.5)+1,2): while not x%i: x //= i cou...
41_D. Pawn
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having c...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) k += 1 a = [tuple(map(int, input().rstrip())) for _ in range(n)] empty = -1 dp = [[[empty] * k for _ in range(m)] for _ in range(n)] prev = [[[(-1, -1, '...
446_B. DZY Loves Modification
As we know, DZY loves playing games. One day DZY decided to play with a n × m matrix. To be more precise, he decided to modify the matrix with exactly k operations. Each modification is one of the following: 1. Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the v...
```python """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h import bisect from types import GeneratorType BUFSIZE = 8192 class SortedList: def __init__(self, iterable=[], _load=...
468_C. Hack it!
Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate <image> Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the foll...
```python A = int(input()) F1019 = (45 * 19 * 10**18 + 1) % A r = (-F1019) % A print(r + 1, 10**19 + r) ```
490_C. Hacking Cypher
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won. Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long inte...
```python from sys import stdin c = list(stdin.readline()[:-1:]) a,b = map(int,input().split()) pref = [] pref1 = [] summ = 0 summ1 = 0 boo = 0 x = 1 for i in range(len(c)): summ = summ * 10 + int(c[i]) summ %= a pref.append(summ) for i in range(len(c)-1,-1,-1): summ1 += x * int(c[i]) x *= 10 x ...
514_C. Watto and Mechanism
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mech...
```python from sys import stdin from functools import reduce from collections import defaultdict _data = iter(stdin.read().split('\n')) def input(): while True: return next(_data) n, m = [int(x) for x in input().split()] B = 10007 MOD = 1000000000000000003 h = lambda s: reduce(lambda s, c: (B * s + ord(c)...
540_D. Bad Luck Island
The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper...
```python A, B, C = map(lambda x: int(x)+1, input().split()) M = max(max(A, B), C) p = [[[0] * (M) for i in range(M)] for j in range(M)] for a in range(M): for b in range(M): for c in range(M): val=0 if a == 0 or b == 0: val=0 elif c == 0: ...
58_C. Trees
On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≤ i ≤ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should...
```python from collections import defaultdict as dd n = int(input()) a = list(map(int, input().split())) count = dd(lambda: 0) for i in range(n//2): count[a[i]-i] += 1 count[a[n-i-1] - i] += 1 #print(i, a[i]-i, a[n-i-1]-i) #print([count[k] for k in count.keys()]) if n%2: count[a[n//2]-n//2] += 1 print(n - ...
611_E. New Year and Three Musketeers
Do you know the story about the three musketeers? Anyway, you must help them now. Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength a, Borthos strength b, and Caramis has strength c. The year 2015 is almost over and there are stil...
```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() X=lambda x:print(x)or quit() n=int(Z());a,b,c=sorted(map(int,Z().split()));t=map(int,Z().split());d=[0]*7 B=[a,b]+sorted([a+b,c])+[a+c,b+c,a+b+c] for i in t: for v in range(7): ...
631_B. Print Check
Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the pr...
```python def main(): n, m, k = map(int, input().split()) lst = [[0] * m for _ in range(n)] rows = {} cols = {} for i in range(k): q, idx, a = map(int, input().split()) if q == 1: rows[idx - 1] = (a, i) else: cols[idx - 1] = (a, i) for r in range(...
706_C. Hard problem
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help. Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only ope...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools import random sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, s...
729_E. Subordinates
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate ...
```python n,s = map(int,input().split()) A = list(map(int,input().split())) if A[s-1] != 0: per = 1 A[s-1] = 0 else: per = 0 A.sort() maxs = max(A) ans = [0] * (maxs + 1) answer = maxs + 1 o = -1 for j in range(n): if A[j] == 0: o += 1 if ans[A[j]] == 0: ans[A[j]] = 1 an...
74_A. Room Leader
Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document. In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five proble...
```python arr = [] for _ in range(0,int(input())): arr.append(list(input().split())) ans = [] for i in range(0,len(arr)): sum = int(arr[i][1])*100 - int(arr[i][2])*50 for j in range(3,8): sum += int(arr[i][j]) ans.append(sum) a = max(ans) for i in range(0,len(ans)): if ans[i] == a: print(arr[i][0])...
797_E. Array Queries
a is an array of n positive integers, all of which are not greater than n. You have to process q queries to this array. Each query is represented by two numbers p and k. Several operations are performed in each query; each operation changes p to p + ap + k. There operations are applied until p becomes greater than n. ...
```python from sys import stdin, stdout, setrecursionlimit input = stdin.readline # import string # characters = string.ascii_lowercase # digits = string.digits # setrecursionlimit(int(1e5)) # dir = [-1,0,1,0,-1] # moves = 'NESW' inf = float('inf') from functools import cmp_to_key from collections import defaultdict as...
818_A. Diplomas and Certificates
There are n students who have taken part in an olympiad. Now it's time to award the students. Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and ce...
```python n,k = map(int,input().split()) p = (n // 2) //(k+1) o = p * k l = n - p - o print(str(p)+' '+str(o)+' '+str(l)) ```
843_B. Interactive LowerBound
This is an interactive problem. You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x. More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the int...
```python from random import sample def R(): return map(int, input().split()) def ask(i): print('?', i, flush=True) v, nxt = R() if v < 0: exit() return v, nxt def ans(v): print('!', v) exit() n, s, x = R() mv = -1 i = s S = 800 q = range(1, n + 1) if n > S: q = sample(q, S) ...
889_D. Symmetric Projections
You are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines. Multiset is a set where equal elements are allowed. Multiset is called symmetric, if there is a point P on t...
```python from fractions import Fraction import time class Point: def __init__(self, x, y): self.x = x self.y = y def to_tuple(self): return (self.x, self.y) def __repr__(self): return "Point({}, {})".format(self.x, self.y) def __eq__(self, other): return sel...
912_B. New Year's Eve
Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness. The choice of candies has a direc...
```python def parr(arr): print(*arr, sep=' ') def gcd(a, b): while b: if b % a == 0: break tmp = a a = b % a b = tmp return a # for _ in range(int(input())): n, k = map(int, input().split()) ans = 0 if k == 1: ans = n else: ans = int('1' * (len(bin(n)...
934_B. A Prosperous Lot
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside. Big Banban is hesitating over the amount ...
```python k = int(input()) if(k>36): print(-1) #at max 888888888888888888....10 power 18 , not more than that... #in one 8, two loops ,so 36 loop else: print("8"*(k//2) + "6"*(k%2)) ```
988_A. Diverse Team
There are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 ≤ k ≤ n) such that the ratings of all team members are distinct. If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then pri...
```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = {} for i in range(n): d[a[i]] = i + 1 if len(d) < k: print('NO') else: print('YES') values = list(d.values()) for i in range(k): print(values[i], end=' ') ```
p02724 AtCoder Beginner Contest 160 - Golden Coins
Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.) Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn? (We as...
```python x=int(input()) ans=0 print(500*(x//500)+5*(x//5)) ```
p02855 DISCO Presents Discovery Channel Code Contest 2020 Qual - Strawberry Cakes
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals. The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them. The positions of the strawberries are given to you as H \times W ch...
```python import bisect H,W,K=map(int,input().split()) s=[""]*H ans=[[0]*W for _ in range(H)] St=[0]*H#i行目にイチゴがあるか? St2=[] for i in range(H): s[i]=input() if "#" in s[i]: St[i]=1 St2.append(i) a=1 #i行目,aからスタートして埋める for i in range(H): if St[i]==1: flag=0 ...
p02991 AtCoder Beginner Contest 132 - Hopscotch Addict
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i. First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does th...
```python import sys input = sys.stdin.readline N, M = map(int, input().split()) graph = [[] for _ in range(N)] for _ in range(M): a, b = map(int, input().split()) graph[a-1].append(b-1) #graph[b-1].append(a-1) S, T = map(int, input().split()) S -= 1; T -= 1 D = [[-1]*3 for _ in range(N)] D[S][0] = 0 q = ...
p03132 Yahoo Programming Contest 2019 - Ears
Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions: * He never visits a point with coordinate less than 0, or a point with coordinate greater than L. * He starts walking at a point with integer coordinate, and also finishes walking at a point with ...
```python n=int(input()) zot=lambda x:0 if x==0 else (x+1)%2+1 A=[int(input()) for i in range(n)] D=[0,0,0,0,0] for a in A: d0 = D[0] + a d1 = min(D[:2])+ [2,1,0][zot(a)] d2 = min(D[:3])+ [1,0,1][zot(a)] d3 = min(D[:4])+ [2,1,0][zot(a)] d4 = min(D) + a D=[d0,d1,d2,d3,d4] print(min(D)) ```
p03275 AtCoder Beginner Contest 107 - Median of Medians
We will define the median of a sequence b of length M, as follows: * Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down. For example, the median of (10, 30, 20) is 20; the median of ...
```python N=int(input()) A=list(map(int,input().split())) A_sort=sorted(A) ANSMIN=0 ANSMAX=N-1 cums=[None]*(N+1) def midup(x): cums[0]=0 for i in range(N): if A[i]>=x: cums[i+1]=cums[i]+1 else: cums[i+1]=cums[i]-1 MINS=min(cums) MAXS=max(cums) #print(MINS,...
p03591 CODE FESTIVAL 2017 qual A - Snuke's favorite YAKINIKU
Ringo is giving a present to Snuke. Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things. You are given a string S representing the Japanese name of ...
```python import re s = input() if re.match('YAKI', s): print('Yes') else: print('No') ```
p03910 CODE FESTIVAL 2016 Final - Exactly N points
The problem set at CODE FESTIVAL 20XX Finals consists of N problems. The score allocated to the i-th (1≦i≦N) problem is i points. Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve. As problems with higher scores are harder, he wants to minimize the highest...
```python N = int(input()) for n in range(1, N+1): if n*(n+1)//2 >= N: break d = n*(n+1)//2-N s = set(range(1, n+1)) s.discard(d) for i in s: print(i) #print(sum(s)) ```
p00014 Integral
Write a program which computes the area of a shape represented by the following three lines: $y = x^2$ $y = 0$ $x = 600$ It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles...
```python while 1: try: d=int(input()) ans=0 for i in range(600//d): ans+=d*d*d*i*i print(ans) except:break ```
p00146 Lupin The 4th
The phantom thief "Lupin IV" is told by the beautiful "Fujiko Mine", a descendant of the Aizu clan, that the military funds left by the Aizu clan are sleeping in Aizuwakamatsu city. According to a report by Lupine's longtime companion, "Ishikawa Koshiemon," military funds are stored in several warehouses in a Senryobak...
```python n = int(input()) ids = [] dists = [] weights = [] for _ in range(n): s, d, v = map(int, input().split()) ids.append(s) dists.append(d) weights.append(v * 20) dic = {} INF = 10 ** 20 def score(rest, pos, total_weight, order): if rest == 0: return 0, [] if (rest, pos) in dic: return dic[(re...
p00279 Happy End Problem
Let's write a program related to an unsolved math problem called "Happy End Problem". Create a program to find the smallest convex polygon formed by connecting exactly k points from the N points given on the plane. However, after being given the coordinates of N points, the question is given the number k of the angles ...
```python def cross(z1, z2): return z1.real * z2.imag - z1.imag * z2.real def ccw(p1, p2, p3): return cross(p2 - p1, p3 - p1) > 0 def triangle_area(p1, p2, p3): # returns signed trangle area return cross(p2 - p1, p3 - p1) / 2 from sys import stdin file_input = stdin N = int(file_input.readline()) P ...
p00467 Sugoroku
Sugoroku problem JOI is playing sugoroku alone. There are N squares in a straight line in this sugoroku, and each has a movement instruction written on it. The starting point is the 1st square and the goal is the Nth square. JOI repeats the following until he reaches the goal. Roll the dice and proceed from the curr...
```python for e in iter(input,'0 0'): N,M=map(int,e.split()) S=[int(input())for _ in[0]*N] p=b=1 for i in range(M): d=int(input()) p+=d if N<=p: if b:print(-~i);b=0 continue p+=S[~-p] if(N<=p)*b:print(-~i);b=0 ```
p00659 Popularity Estimation
You are the planning manager of an animation production company. What animation production companies produce these days is not limited to animation itself. Related products, such as figures of characters and character song CDs, are also important sources of revenue. How much this profit can be increased depends solely ...
```python # AOJ 1074: Popularity Estimation # Python3 2018.7.10 bal4u while True: n = int(input()) if n == 0: break f, tbl = [0]*31, [] for i in range(n): a = input().split() nm = a.pop(0) m = int(a.pop(0)) d = list(map(int, a)) tbl.append([0, nm, d]) for i in d: f[i] += 1 for i in range(n): for j i...
p01336 THE BYDOLM@STER
Description THE BY DOLM @ STER is a training simulation game scheduled to be released on EXIDNA by 1rem on April 1, 2010. For the time being, it probably has nothing to do with an arcade game where the network connection service stopped earlier this month. This game is a game in which members of the unit (formation) t...
```python while True: try: n, m = map(int, input().split()) except EOFError: break costs = [] vocals = [] dances = [] looks = [] for _ in range(n): input() c, v, d, l = map(int, input().split()) costs.append(c) vocals.append(v) dances.append(d) looks.append(l) def max_...
p01816 Bit Operation Game
H --Bit Operation Game Given a rooted tree with N vertices. The vertices are numbered from 0 to N − 1, and the 0th vertex represents the root. `T = 0` for the root, but for the other vertices * `T = T & X;` * `T = T & Y;` * `T = T | X` * `T = T | Y` * `T = T ^ X` * `T = T ^ Y` One of the operations is written. Her...
```python from collections import deque from itertools import permutations import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M = map(int, readline().split()) OP = [0]*N ops = ["T=T&X\n", "T=T&Y\n", "T=T|X\n", "T=T|Y\n", "T=T^X\n", "T=T^Y\n"] for i in range(N-1): s...
p02100 Factorization
Problem Mr. ukuku1333 is a little sloppy, so when I expanded the product of the linear expressions of x, I couldn't figure out the original linear expression. Given the nth degree polynomial of x, factor it into the product of the original linear expressions of x. The nth degree polynomial of x is given by the follow...
```python def parse(S): poly = [] t = [] for x in S.split('+'): if '-' in x: t = t + ['-' + a if i != 0 else a for i, a in enumerate(x.split('-'))] else: t.append(x) for x in t: if '^' in x: t = x.split('x^') if len(t[0]) == 0: ...
p02238 Depth First Search
Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving ...
```python from sys import stdin n = int(stdin.readline()) M = [0] + [list(map(int, stdin.readline().split()[2:])) for i in range(n)] sndf = [0] + [[False, i] for i in range(1, n + 1)] tt = 0 def dfs(u): global tt sndf[u][0] = True tt += 1 sndf[u].append(tt) for v in M[u]: if not sndf[v][0]: ...
p02384 Dice II
Construct a dice from a given sequence of integers in the same way as Dice I. You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face. <image> Constraints * $0 \leq $ the integer assigned to a face $ ...
```python def lotate(dic, dire): if dire == 'N': x,y,z,w = dic['up'], dic['back'], dic['bottom'], dic['front'] dic['back'], dic['bottom'], dic['front'], dic['up'] = x,y,z,w elif dire == 'S': x, y, z, w = dic['up'], dic['back'], dic['bottom'], dic['front'] dic['front'], dic['up'],...
1060_B. Maximum Sum of Digits
You are given a positive integer n. Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0. Your task is to find two integers a, b, such that 0 ≤ a, b ≤ n, a + b = n and S(a) + S(b) is the largest possible among all such pairs. Input The only line of input contains a...
```python def digitSum(x): s = 0 while x != 0: s += x % 10 x = (x//10) return s n = int(input()) x = n b = 1 s = 0 while x != 0: num1 = (x - 1)*b + (b-1) num2 = n - num1 ans = digitSum(num1) + digitSum(num2) if ans > s: s = ans x = (x//10) b = b * 10 print(s) ```
1101_B. Accordion
An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code 091), a colon (ASCII code 058), some (possibly zero) vertical line characters (ASCII code 124), another colon, and a ...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- s = input() ans = -1 left = 0 right = len(s) - 1 lok = 1 while left < len(s): if s[left] == '[': lok = 2 left += 1 elif s[left] == ':' and lok == 2: break else: left += 1 rok = 1 while right >= 0: if s[right] == ']'...
114_A. Cifera
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million...
```python n = int(input()) m = int(input()) l = 0 x = n while x<m: l += 1 x *= n if x == m: print("YES") print(l) else: print("NO") ```
1208_E. Let Them Slide
You are given n arrays that can have different sizes. You also have a table with w columns and n rows. The i-th array is placed horizontally in the i-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table. You need to find the maximum sum o...
```python import sys input = sys.stdin.readline from collections import deque def slidemax(X, k): q = deque([]) ret = [] for i in range(len(X)): while q and q[-1][1] <= X[i]: q.pop() deque.append(q, (i+k, X[i])) if q[0][0] == i: deque.popleft(q) if i >...
1227_D2. Optimal Subsequences (Hard Version)
This is the harder version of the problem. In this version, 1 ≤ n, m ≤ 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. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more e...
```python """ Author - Satwik Tiwari . 18th Feb , 2021 - Thursday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io ...
126_A. Hot Bath
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can ...
```python import math def gcd(a,b): if(b==0): return a return gcd(b,a%b) l=input().split() t1=int(l[0]) t2=int(l[1]) x1=int(l[2]) x2=int(l[3]) t0=int(l[4]) num1=t2-t0 num2=t0-t1 if(t1==t2): print(x1,x2) quit() if(num1==0): print(0,x2) quit() if(num2==0): print(x1,0) quit() z=num2...
1312_A. Two Regular Polygons
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). <image> Examples of convex regular polygons Your task is to say if it is poss...
```python for i in range(int(input())): a,b=input().split() if int(b)<=2: print("NO") elif int(a)%int(b)==0: print("YES") else: print("NO") ```
1334_E. Divisor Paths
You are given a positive integer D. Let's build the following graph from it: * each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); * two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; * the weight of an edge i...
```python import sys input = sys.stdin.buffer.readline mod=998244353 d=int(input()) div=[] x=2 di=0 t=0 while d>1 and x*x<=d: if d%x==0: div.append(x) d//=x di+=1 t+=1 while d%x==0: d//=x t+=1 x+=1 if d>1: div.append(d) di+=1 t+=1 fac=[1] for i in ...
1354_G. Find a Gift
This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages. There are n gift boxes in a row, numbered from 1 to n from left to right. It's known that exactly k of them contain valuable gifts — other...
```python from random import randint def ask(l1, r1, l2, r2): print('?', r1 - l1 + 1, r2 - l2 + 1) for i in range(l1, r1 + 1): print(i + 1, end=' ') print() for i in range(l2, r2 + 1): print(i + 1, end=' ') print(flush=True) s = input() if s[0] == 'F': return 0 if s[0] == 'S': return 1 if s[0] == 'E': ...
1374_E2. Reading Books (hard version)
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly m books before all entertainments. Alice and Bob will read ...
```python import sys input = sys.stdin.readline INF = 10 ** 18 n, m, k = map(int, input().split()) B = sorted((tuple(map(int, input().split())) + (i,) for i in range(n)), key=lambda v: v[0]) GB, AB, BB, RB = ([] for _ in range(4)) for t, a, b, i in B: if a and b: GB.append((t, i)) elif a: AB.append((t, i)) elif b...
1398_B. Substring Removal Game
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on. During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them. For example, if the...
```python for i in range(int(input())): s = list(filter(lambda x:x !='',input().split('0'))) s.sort(reverse=True) pr = '' for i in range(0,len(s),2): pr +=s[i] print(len(pr)) ```
1421_C. Palindromifier
Ringo found a string s of length n in his [yellow submarine](https://www.youtube.com/watch?v=m2uTFF_3MaA). The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string s into a palindrome by applying two types of operations to the stri...
```python s=input() n= len(s) print(4) print("L",2) print("R",n) print("R",2) print("R",2*n+1) ```
143_B. Help Kingdom of Far Far Away 2
For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operatio...
```python import math import sys import collections # imgur.com/Pkt7iIf.png def getdict(n): d = {} if type(n) is list: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() if t in ...
1491_A. K-th Largest Value
You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds: * 1 x : Assign to a_x the value 1 - a_x. * 2 k : Print the k-th largest value of the array. As a reminder, k-th largest value of the array b is defined as following: ...
```python n, q = map(int,input().split()) a = list(map(int,input().split())) zero = a.count(0) one = n - zero for _ in range(q): t, x = map(int,input().split()) if t == 1: if a[x-1] == 1: zero += 1 one -= 1 a[x-1] = 0 else: zero -= 1 on...
1513_D. GCD and MST
You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner: * If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_...
```python class UnionFind: def __init__(self, n): self.Id = list(range(n+1)) self.sz = [1]*(n+1) def find(self, node): root = node while root != self.Id[root]: root = self.Id[root] while node != root: nxt = self.Id[node] self.Id[node]...
1540_C2. Converging Array (Hard Version)
This is the hard version of the problem. The only difference is that in this version 1 ≤ q ≤ 10^5. You can make hacks only if both versions of the problem are solved. There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each...
```python def solve(): MOD = 10**9+7 n = int(input()) c = list(map(int, input().split())) b = [0] + list(map(int, input().split())) q = int(input()) queries = list(map(int, input().split())) maxans = 1 for c1 in c: maxans = maxans * (c1+1) % MOD ans = {} for i in range(1,...