name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1368_B. Codeforces Subsequences
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
```python k = int(input()) cur = 10**18 best = [] for p in range(1, 41): for q in range(1, 41): for i in range(1, 10): res = (p**i)*(q**(10-i)) if res >= k: temp = p*i+q*(10-i)-10 if temp <= cur: cur = temp best...
1389_D. Segment Intersections
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n]. Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2]. In one step, you can choose one segment (either from the first or fro...
```python from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from...
140_A. New Year Table
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the ta...
```python import math x=[int(i) for i in input().split()] n,R,r=x[0],x[1],x[2] if r>R: print('NO') raise SystemExit if 2*r>R: if n>1: print('NO') raise SystemExit else: print('YES') raise SystemExit z=2*n*math.asin(r/(R-r)) if z>2*math.pi+0.0000000001: print('NO')...
1430_E. String Reversal
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the str...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write i...
1454_A. Special Permutation
You are given one integer n (n > 1). Recall that a permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2, 3, 1, 5, 4] is a permutation of length 5, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation (...
```python def lip(): return list(map(int,input().split())) def splip(): return map(int,input().split()) def intip(): return int(input()) for _ in range(intip()): n = intip() l = [i for i in range(1,n+1)] l = l[::-1] mid = n//2 if n==2: print(*l) elif n%2!=0: l[mid] , l[mid-1] =...
1505_A. Is it rated - 2
Interaction This is an interactive problem. You need to read participants' queries from standard input and print your responses to standard output. You don't know the number of queries upfront, so you'll need to process them as you get them; you'll know you're done once you reach the end of the file. In each query,...
```python try: while(1): a=input() print("NO") except EOFError as e: pass ```
1528_B. Kavi on Pairing Duty
Kavi has 2n points lying on the OX axis, i-th of which is located at x = i. Kavi considers all ways to split these 2n points into n pairs. Among those, he is interested in good pairings, which are defined as follows: Consider n segments with ends at the points in correspondent pairs. The pairing is called good, if fo...
```python import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop #from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations...
15_A. Cottage Village
A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other. The architect bureau, where Pe...
```python n,t=list(map(int,input().split())) amount=2 houses=[] for i in range(n): c,l=list(map(int,input().split())) l=l/2 start,end=c-l,c+l houses.append([start,end]) houses.sort(key=lambda x:x[0]) prev_end=houses[0][0] for start,end in houses: gap=start-prev_end if gap>t: amount+=2 ...
201_D. Brand New Problem
A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's probl...
```python import itertools def count_inversions(enumerate_seq): tmp = list(enumerate_seq[:]) result = 0 for i in range(len(tmp)): for j in range(len(tmp) - 1): if tmp[j][0] > tmp[j + 1][0]: result += 1 tmp[j], tmp[j + 1] = tmp[j + 1], tmp[j] return r...
250_A. Paper Work
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is n...
```python from math import ceil n=int(input()) reports = list(map(int,input().split())) k=0 count=0 lst=[] for i in reports: count += 1 if i<0: if k+1 > 2: lst.append(count-1) count=1 k=1 else: k+=1 lst.append(count) print(len(lst)) for i in lst: ...
275_B. Convex Shape
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the pa...
```python n,m = map(int, input().split()) row, col_sum, row_sum, black = [], [], [], [] for i in range(n): row.append(input()) t = [0] for j in range(m): t += [t[j] + (row[i][j] == 'B')] row_sum += [t] d = [[0,1], [1,0], [-1,0], [0,-1]] for i in range(n): for j in range(m): if row[...
298_D. Fish Weight
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds. Polar bears Alice and Bob each have caught some fish, and they are g...
```python n, m, k = [int(x) for x in input().split()] alice = [int(x) for x in input().split()] bob = [int(x) for x in input().split()] alice.sort() bob.sort() balance = 0 i = n - 1 j = m - 1 while i >= 0 and j >= 0: if alice[i] > bob[j]: balance += 1 i -= 1 elif alice[i] < bob[j]: ba...
321_B. Ciel and Duel
Fox Ciel is playing a card game with her friend Jiro. Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack. Now is Ciel's battle phase, Ciel can do the following ope...
```python n, m = map(int, input().split()) (a, d, my) = ([], [], []) for i in range(n): t, val = input().split() (a if t == 'ATK' else d).append(int(val)) my = sorted([int(input()) for i in range(m)]) a.sort() d.sort() def solve1(): ret = 0 used = [False] * m for val in d: for i in rang...
391_C3. The Tournament
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points. Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined,...
```python m = 301000 ns = [0] * m es = [0] * m c = [0] * m b = [0] * m t = [0] * m P = 0 def add(b, k): k = t[k] while k: e = es[k] if b[-1] > e: b[-1] = e b[e] += 1 k = ns[k] def delete(b): for i in range(b[m - 1], m + 1): if b[i]: b[i] -= 1 b[-...
440_A. Forgotten Episode
Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n. Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which epi...
```python import sys input=sys.stdin.buffer.readline n=int(input()) arr=list(map(int,input().split())) arr.sort() z=0 for i in range(0,n-1): if arr[i]==i+1: continue else: print(i+1) z=1 break if z==0: print(n) ```
462_C. Appleman and Toastman
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
```python import heapq n=int(input()) a=list(map(lambda x:-int(x),input().split())) heapq.heapify(a) ans=0 for i in range(n-1): x=heapq.heappop(a) y=heapq.heappop(a) ans+=x+y heapq.heappush(a,x+y) print(-ans-sum(a)) ```
486_B. OR in Matrix
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: <image> where <image> is equal to 1 if some ...
```python from sys import stdin input = stdin.readline from heapq import heapify,heappush,heappop,heappushpop from collections import defaultdict as dd, deque as dq,Counter as C from math import factorial as f ,ceil,gcd,sqrt,log from bisect import bisect_left as bl ,bisect_right as br from itertools import combinations...
50_A. Domino piling
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
```python #domino piling M,N=map(int,input().split()) d=(M*N)//2 print(d) ```
534_C. Polycarpus' Dice
Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of...
```python n, a = [int(i) for i in input().split()] t = [int(i) for i in input().split()] s = 0 for i in t: s+=i k = [] for i in range(n): k.append(0) if s-a < t[i]: k[i]+=t[i]-s+a-1 if t[i] - (a - n+1) > 0: k[i]+=(t[i] - (a - n+1)) print(*k) ```
559_C. Gerald and Giant Chess
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of gia...
```python from sys import stdin input = stdin.buffer.readline f, inv = [1], [1, 1] mod = 1000000007 def c(n, k): return f[n] * inv[k] * inv[n - k] % mod h, w, n = map(int, input().split()) for i in range(1, 200001): f.append(f[i - 1] * i % mod) for i in range(2, 200001): inv.append((-(mod // i) * inv[mod % i]) % mod...
585_A. Gennady the Dentist
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office. All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with...
```python from sys import stdin def input(): return stdin.readline() from collections import deque as d class Child: def __init__(self, cry, leave, cond): self.cry = cry self.leave = leave self.cond = cond self.alive = True N = int(input()) queue = d() for i in range(N): ...
607_A. Chain Reaction
There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti...
```python import sys input = sys.stdin.readline from bisect import * n = int(input()) ab = [tuple(map(int, input().split())) for _ in range(n)] ab.sort(key=lambda k: k[0]) a = [-10**18]+[ai for ai, _ in ab] dp = [0]*(n+1) for i in range(1, n+1): j = bisect_left(a, ab[i-1][0]-ab[i-1][1])-1 dp[i] = dp[j]+i-j-1 ...
653_A. Bear and Three Balls
Limak is a little polar bear. He has n balls, the i-th ball has size ti. Limak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy: * No two friends can get balls of the same size. * No two friends can get balls of sizes that di...
```python n = int(input()) s = map(int, input().split()) l = [] a = 'NO' for i in s: if i not in l: l += [i] l = sorted(l) if len(l) >= 3: for i in range(len(l) - 2): if l[i] + 2 == l[i + 1] + 1 == l[i + 2]: a = 'YES' print(a) ```
678_E. Another Sith Tournament
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each b...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n = int(input()) p = [list(map(float,input().split())) for _ in range(n)] y = 1<<n dp = [[0]*y for _ in range(n)] # dp[i][j] is prob of 0 win when j fought and i left ...
723_A. The New Year: Meeting Friends
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to...
```python a=list(map(int,input().split())) a.sort() if len(a)%2!=0: s=a[int(len(a)/2)] count=0 for x in a: count+=abs(x-s) print(count) ```
768_B. Code For 1
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam s...
```python ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineering College Date:08/06/2020 ''' from os import path import sys from functools import cmp_to_key as ctk from collections import deque,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,ins...
792_A. New Bus Route
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct. It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to bui...
```python n = int(input()) array = list(map(int, input().split())) array = sorted(array) mink = array[-1] - array[0] count = 0 for i in range(1, len(array)): if mink > array[i] - array[i-1]: mink = array[i] - array[i-1] count = 1 elif mink == array[i] - array[i-1]: count += 1 print(mink...
812_C. Sagheer and Nubian Market
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost ...
```python n,m1=map(int,input().split()) lp=list(map(int,input().split())) l=0 r=n while l<r : m=(l+r+1)//2 l1=lp[::] for i in range(n) : l1[i]=lp[i]+((i+1)*m) l1=sorted(l1) s=sum(l1[:m]) if s>m1 : r=m-1 else : l=m l1=lp[::] for i in range(n) : l1[i]=lp[i]+((i+1)*l...
908_A. New Year and Counting Cards
Your friend has n cards. You know that each card has a lowercase English letter on one side and a digit on the other. Currently, your friend has laid out the cards on a table so only one side of each card is visible. You would like to know if the following statement is true for cards that your friend owns: "If a car...
```python s = list(input()) d = {'a', 'u', 'o', 'e', 'i', '1', '3', '5', '7', '9'} ans = 0 for i in s: if i in d: ans += 1 print(ans) ```
928_D. Autocompletion
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor. Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-e...
```python # python3 # utf-8 class Trie: def __init__(self): self.letter___node = {} self.words_nr = 0 def add_word(self, word): word = word + '$' curr_node = self for letter in word: if letter not in curr_node.letter___node: curr_node.letter_...
958_A1. Death Stars (easy)
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Tw...
```python n=int(input()) a=[] b=[] for i in range(n): a.append(input()) for i in range(n): b.append(input()) def h(d): c=[] for i in range(n): c.append(d[n-i-1]) return c def r(d): c=[] for i in range(n): temp="" for j in range(n): temp+=d[j][n-i-1] ...
p02563 AtCoder Library Practice Contest - Convolution
You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353. Constraints * 1 \leq N, M \leq 524288 * 0 \leq a_i, b_i < 998244353 * All values in Input are integer. Input...
```python #Convolution_998244353 MOD = 998244353 ROOT = 3 sum_e = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 0, 0, 0, 0, 0, 0, 0, ...
p02694 AtCoder Beginner Contest 165 - 1%
Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank. The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.) Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or abo...
```python x=int(input()) a=100 b=0 while a<x: b=b+1 a=(a*1.01)//1 print(b) ```
p02823 AtCoder Grand Contest 041 - Table Tennis Training
2N players are running a competitive table tennis training on N tables numbered from 1 to N. The training consists of rounds. In each round, the players form N pairs, one pair per table. In each pair, competitors play a match against each other. As a result, one of them wins and the other one loses. The winner of the...
```python N,A,B=map(int,input().split()) if (A+B)%2==0: ans=(B-A)//2 else: ans=min(A-1,N-B)+1+(B-A-1)//2 print(ans) ```
p02959 AtCoder Beginner Contest 135 - City Savers
There are N+1 towns. The i-th town is being attacked by A_i monsters. We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters. What is the maximum total number of monsters the heroes can cooperate to defeat? Constraints * All values in input are i...
```python N = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) res = 0 for n in range(N): b = min(A[n], B[n]) B[n] -= b b2 = min(A[n + 1], B[n]) A[n + 1] -= b2 res += b + b2 print(res) ```
p03095 AtCoder Grand Contest 031 - Colorful Subsequence
You are given a string S of length N. Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings. Here, a subsequence of a string is a conca...
```python from collections import Counter n = int(input()) s = input() mod = 10**9+7 s_c = Counter(s) ans = 1 for c in s_c.values(): ans*=c+1 print((ans-1)%mod) ```
p03241 AtCoder Beginner Contest 112 - Partition
You are given integers N and M. Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N. Constraints * All values in input are integers. * 1 \leq N \leq 10^5 * N \leq M \leq 10^9 Input...
```python N ,M = map(int,input().split()) L = [] ans = 0 for i in range(1,int(M**(1/2)+1)): if M % i == 0: if i >= N: ans = max(ans,M//i) if M // i >= N: ans = max(ans,i) print(ans) ```
p03394 AtCoder Grand Contest 022 - GCD Sequence
Nagase is a top student in high school. One day, she's analyzing some properties of special sets of positive integers. She thinks that a set S = \\{a_{1}, a_{2}, ..., a_{N}\\} of distinct positive integers is called special if for all 1 \leq i \leq N, the gcd (greatest common divisor) of a_{i} and the sum of the remai...
```python N = int(input()) M = 30001 if N == 3: print(2, 5, 63) exit() L = [3, 9] N -= 2 if N % 2 == 1: L.append(6) N -= 1 if N != 0: for i in range(2, M, 2): if i % 6 == 0: continue L.append(i) N -= 1 if N == 0: break if N % 2 == 1: N += 1 L.pop() if N != 0: for i in ran...
p03558 AtCoder Beginner Contest 077 - Small Multiple
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K. Constraints * 2 \leq K \leq 10^5 * K is an integer. Input Input is given from Standard Input in the following format: K Output Print the smallest possible sum of the digits in the decimal notation of a positive mu...
```python from collections import deque k = int(input()) d = deque() mat = [] for i in range(k): mat.append([]) #mark = [False]*k dis = [10**18]*k dis[1] = 0 for i in range(k): mat[i].append(((i+1)%k,True)) if (10*i)%k != i: mat[i].append(((10*i)%k,False)) #bfs 1->0 d.append(1) res = 0 while d: ...
p03712 AtCoder Beginner Contest 062 - Picture Frame
You are given a image with a height of H pixels and a width of W pixels. Each pixel is represented by a lowercase English letter. The pixel at the i-th row from the top and j-th column from the left is a_{ij}. Put a box around this image and output the result. The box should consist of `#` and have a thickness of 1. ...
```python h,w=list(map(int,input().split())) print('#'*(w+2)) for i in range(h): print('#'+input()+'#') print('#'*(w+2)) ```
p04034 AtCoder Grand Contest 002 - Box and Ball
We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball. Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i. Find the number of boxes that may ...
```python n,m=map(int,input().split()) cnt=[1]*n res=[0]*n res[0]=1 for i in range(m): x,y=map(int,input().split()) if res[x-1]==1: res[y-1]=1 if cnt[x-1]==1: res[x-1]=0 cnt[x-1]-=1 cnt[y-1]+=1 print(sum(res)) ```
p00116 Rectangular Searching
There are a total of W x H squares, with H rows vertically and W columns horizontally. Some squares are marked. Create a program that reads the marked state of each square and outputs the maximum rectangular area consisting of only the unmarked squares. The input data consists of one line of W characters, given H line...
```python while True: h, w = map(int, input().split()) if h == 0: break mp = [] for _ in range(h): lst = list(input()) cum = [] acc = 0 for i in lst: acc = acc + 1 if i == "." else 0 cum.append(acc) mp.append(cum) mp.append([-1] * w) ans = 0 for i in range(w): s...
p00430 Square
There are n sheets of square paper of the same size. Align the bottom of these papers horizontally and arrange them in several rows. However, adjacent rows must be arranged so that the left side is not lower than the right side. For example, n When = 5, the following 7 ways of arranging are possible. <image> We wil...
```python def solve(): answers = [] def square(ans, rest, limit): if rest == 0: print(*ans) else: for i in range(rest, 0, -1): if i > limit: continue square(ans + [i], rest - i, i) import sys for n in map(in...
p00901 ASCII Expression
Mathematical expressions appearing in old papers and old technical articles are printed with typewriter in several lines, where a fixed-width or monospaced font is required to print characters (digits, symbols and spaces). Let us consider the following mathematical expression. <image> It is printed in the following f...
```python MOD = 2011 while 1: n = int(input()) if n == 0: break S = [input() for i in range(n)] w = len(S[0]) def parse(bcur, bright, top, bottom): #print("parse", bcur, bright, top, bottom) base = -1 for i in range(bcur, bright): for j in range(top, bott...
p01304 Heian-Kyo Walking
Heiankyo is known as a town with a grid of roads. Hokusai, a cat who lives in Heiankyo, has to go from his home to a secret place on the outskirts of town every day for patrol. However, I get tired of following the same path every day, and there is a risk of being followed, so Hokusai wants to use a different route ev...
```python L = int(input().strip()) for _ in range(0,L): gx,gy = map(int,input().strip().split(" ")) heiankyo = [[0 for j in range(0,gx+1)] for i in range(0,gy+1)] heiankyo[0][0] = 1 P = int(input()) matatabi = [] for p in range(P): x1,y1,x2,y2 = map(int,input().strip().split(" ")) ...
p01473 Palindromic Anagram
Problem statement Given the string $ S $. Find the number of all anagrams in $ S $ that are palindromic. An anagram of the string $ X $ is an anagram of $ Y $, which means that $ X $ is equal to $ Y $, or that the rearranged characters of $ X $ are equal to $ Y $. For example, for the string abcd, abcd and cbda are a...
```python import collections from math import * s=input() a=collections.Counter(s) o=0 for x in a: if a[x]&1: o+=1 if o>1:print(0);break a[x]-=1 else: b=factorial(len(s)//2) for x in a.values(): b//=factorial(x//2) print(b) ```
p02058 Tree
G: Tree problem Given a tree consisting of N vertices. Each vertex of the tree is numbered from 1 to N. Of the N-1 edges, the i \ (= 1, 2, ..., N-1) edge connects the vertex u_i and the vertex v_i. Write a program to find the number of K non-empty subgraph sets of this tree, each of which is concatenated and no two ...
```python import sys def getpar(Edge, p): N = len(Edge) par = [0]*N par[0] = -1 par[p] -1 stack = [p] visited = set([p]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf in visited: continue visited.add(vf) ...
p02200 Today's Random Number
Today's Random Number E869120 You ran a campaign called "Today's Random Numbers" for N days. This is a project to generate a random number once a day and post the value on Twitter. The "random numbers of the day" on day $ 1, 2, 3, \ dots, N $ were $ A_1, A_2, A_3, \ dots, A_N $, respectively. E869120 You would be ha...
```python N = int(input()) A = [int(i) for i in input().split()] ret = 0 for i in range(1, N) : if A[i] > A[i - 1] : ret += 1 print(ret) ```
p02354 The Smallest Window I
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $S$, find the smallest sub-array size (smallest window length) where the sum of the sub-array is greater than or equal to $S$. If there is not such sub-array, report 0. Constraints * $1 \leq N \leq 10^5$ * $1 \leq S \leq 10^9$ * $1 \leq a_i \...
```python #import pysnooper #import numpy #import os,re,sys,operator #from collections import Counter,deque #from operator import itemgetter #from itertools import accumulate,combinations,groupby,combinations_with_replacement,permutations from sys import stdin,setrecursionlimit from bisect import bisect_left #from copy...
1010_D. Mars rover
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex 1, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, whi...
```python import sys input=sys.stdin.readline n=int(input()) stack=[] children=[] for i in range(n): children.append([]) parent=[-1]*n nodes=[-1]*n inputs=[] functions=[-1]*n for i in range(n): a=list(map(str,input().split())) r=a[0] if r=='IN': stack.append((i,int(a[1]))) inputs.append(i) elif r=='NO...
1057_A. Bmail Computer Network
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values p_i — the index of the router to which the i-th router was connected...
```python n=int(input()) a=list(map(int,input().split())) if len(set(a))==n: a.append(n) print(*a) else: a.insert(0,0) b=[n] x=n while x!=1: b.append(a[x-1]) x=a[x-1] print(*b[::-1]) ```
109_D. Lucky Sorting
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya got an array consisting of n numbers, it is the gift for his birthday. Now he wants to sort it...
```python #!/usr/bin/env python3 def is_lucky(v): while v > 0: r = v % 10 if r != 4 and r != 7: return False v //= 10 return True n = int(input()) arr = list(map(int, input().split())) arr_with_pos = sorted([[a, i] for i, a in enumerate(arr)]) pos, tpos = None, None # po...
1169_B. Pairs
Toad Ivan has m pairs of integers, each integer is between 1 and n, inclusive. The pairs are (a_1, b_1), (a_2, b_2), …, (a_m, b_m). He asks you to check if there exist two integers x and y (1 ≤ x < y ≤ n) such that in each given pair at least one integer is equal to x or y. Input The first line contains two space-s...
```python bound, m = [int(x) for x in input().split()] if m == 1: print("YES") exit(0) pairs_uniq = set() for _ in range(m): x = [int(x) for x in input().split()] x.sort() pairs_uniq.add((x[0], x[1])) if len(pairs_uniq) == 1: print("YES") exit(0) pairs = [x for x in pairs_uniq] # Choose...
1187_D. Subarray Sorting
You are given an array a_1, a_2, ..., a_n and an array b_1, b_2, ..., b_n. For one operation you can sort in non-decreasing order any subarray a[l ... r] of the array a. For example, if a = [4, 2, 2, 1, 3, 1] and you choose subbarray a[2 ... 5], then the array turns into [4, 1, 2, 2, 3, 1]. You are asked to determi...
```python from sys import stdin, stdout from collections import defaultdict t = int(stdin.readline()) inf = 10**6 def merge_sort(order, a): if len(order) == 1: return order, a mid = (len(order) + 1) // 2 left_o, left_a = merge_sort(order[:mid], a[:mid]) right_o, right_a = merge_sort(order[mid:...
1206_C. Almost Equal
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th...
```python n=int(input()) if n%2==0: print('NO') else: print('YES') ans=1 c=3 for i in range(n): if i==0: print(ans,end=' ') else: print(ans+c,end=' ') ans=ans+c c=1 if c==3 else 3 ans=2 c=1 for i in range(n): if i==0...
1249_B2. Books Exchange (hard version)
The only difference between easy and hard versions is constraints. There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers ...
```python q = int(input()) for _ in range(q): n = int(input()) succ = list(map(lambda x: int(x) -1 ,input().split())) cycle_belong = [-1 for k in range(n)] cycle_size = [] for k in range(n): if cycle_belong[k] == -1 : # not visited yet start = k current = k ...
128_C. Games with Rectangle
In this task Anna and Maria play the following game. Initially they have a checkered piece of paper with a painted n × m rectangle (only the border, no filling). Anna and Maria move in turns and Anna starts. During each move one should paint inside the last-painted rectangle a new lesser rectangle (along the grid lines...
```python from math import factorial MOD = 1000000007 def c(n, k): if k > n: return 0 return factorial(n) //(factorial(k) * factorial(n - k)) n, m, k = map(int, input().split()) print ((c(n - 1, 2 * k) * c(m - 1, 2 * k)) % MOD) ```
1332_D. Walk on Matrix
Bob is playing a game named "Walk on Matrix". In this game, player is given an n × m matrix A=(a_{i,j}), i.e. the element in the i-th row in the j-th column is a_{i,j}. Initially, player is located at position (1,1) with score a_{1,1}. To reach the goal, position (n,m), player can move right or down, i.e. move from ...
```python k = int(input()) arr = [[0, k, 0], [0, 0, k]] length = 0 t = k while t > 0: t >>= 1 length += 1 # print(((1 << length) - 1) ^ k) arr[1][1] = (1 << length) + k arr[1][0] = (1 << length) + (((1 << length) - 1) ^ k) arr[0][0] = (1 << (length + 1)) - 1 print(2, 3) for i in arr: print(*i) ``...
1352_G. Special Permutation
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5. For a given number n (n ≥ 2), find a permutation p in which absolute difference (that is, the absolut...
```python """ Author: guiferviz Time: 2020-05-09 16:35:02 """ def solve(): n = int(input()) if n < 4: print(-1) elif n == 4: print("3 1 4 2") else: sol = [] i = 1 while i <= n: sol.append(i) i += 2 i = sol[-1] val = i - 3 ...
1372_E. Omkar and Last Floor
Omkar is building a house. He wants to decide how to make the floor plan for the last floor. Omkar's floor starts out as n rows of m zeros (1 ≤ n,m ≤ 100). Every row is divided into intervals such that every 0 in the row is in exactly 1 interval. For every interval for every row, Omkar can change exactly one of the 0s...
```python from bisect import * import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(r...
1395_D. Boboniu Chats with Du
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu ...
```python n, d, m = map(int, input().split()) a = list(map(int, input().split())) less = [] more = [] for i in a: if i>m: more.append(i) else: less.append(i) less.sort(reverse = True) more.sort(reverse = True) lessp = [] if len(less)>0: lessp = [less[0]] for i in less[1:]: lessp.append(lessp[-1]+i) m...
1419_F. Rain of Fire
There are n detachments on the surface, numbered from 1 to n, the i-th detachment is placed in a point with coordinates (x_i, y_i). All detachments are placed in different points. Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts. To move from one detachment to...
```python # import numpy as npy import functools import math n=int(input()) x=[0 for i in range(n+2)] y=[0 for i in range(n+2)] adj=[[] for i in range(n+2)] idx=[] idy=[] for i in range(n): x[i],y[i]=map(int,input().split()) idx.append(i) idy.append(i) def cmpx(a,b): if x[a]!=x[b]: if x[a]<x[b...
1462_E1. Close Tuples (easy version)
This is the easy version of this problem. The only difference between easy and hard versions is the constraints on k and m (in this version k=2 and m=3). Also, in this version of the problem, you DON'T NEED to output the answer by modulo. You are given a sequence a of length n consisting of integers from 1 to n. The s...
```python #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=200): """Initialize sorted list instance.""" values = so...
1487_F. Ones
You are given a positive (greater than zero) integer n. You have to represent n as the sum of integers (possibly negative) consisting only of ones (digits '1'). For example, 24 = 11 + 11 + 1 + 1 and 102 = 111 - 11 + 1 + 1. Among all possible representations, you have to find the one that uses the minimum number of o...
```python def ones(a): return (10 ** a - 1) // 9 def add_in_dict(dct, key, val): if key in dct: dct[key] = min(dct[key], val) else: dct[key] = val _s = input() _n = len(_s) _x = int(_s) cur_dict = {} cur_dict[_x] = 0 for i in range(_n + 1, 0, -1): ns = ones(i) new_dict = {} ...
1511_C. Yet Another Card Deck
You have a card deck of n cards, numbered from top to bottom, i. e. the top card has index 1 and bottom card — index n. Each card has its color: the i-th card has color a_i. You should process q queries. The j-th query is described by integer t_j. For each query you should: * find the highest card in the deck with...
```python N, Q = map(int, input().split()) A = list(map(int, input().split())) T = list(map(int, input().split())) inds = [0]*51 for i in range(N): if inds[A[i]]==0: inds[A[i]] = i+1 ans = [] for i in range(Q): ans.append(inds[T[i]]) for c in range(1,51): if inds[c]<inds[T[i]]: inds[c] += 1 inds[T...
1539_A. Contest Start
There are n people participating in some contest, they start participating in x minutes intervals. That means the first participant starts at time 0, the second participant starts at time x, the third — at time 2 ⋅ x, and so on. Duration of contest is t minutes for each participant, so the first participant finishes t...
```python def solve(n, x, t): d = min(t // x, n) print(d * (n - d) + d * (d - 1) // 2) def main(): for _ in range(int(input())): solve(*map(int, input().split())) if __name__ == '__main__': main() ```
165_C. Another Problem on Strings
A string is binary, if it consists only of characters "0" and "1". String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their po...
```python def main(): k, s = lie(), input() n = len(s) dp = [-1] for i in range(n): if s[i] == '1': dp.append(i) dp.append(n) if len(dp) - 2 < k: print(0) elif k == 0: ans = 0 for i in range(1, len(dp)): ans += (dp[i] - dp[i - 1] - 1) *...
186_D. 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 S = int(input()) v = [int(x) for x in input().strip().split()] zeroes = v.count(0) total = sum(v) ans = [] if zeroes == 0: ans = [S * v[i] / total for i in range(3)] elif zeroes == 1: for i in range(3): if v[i] == 0: total -= v[i] for i in range(3): if v[i] != 0: ...
258_D. Little Elephant and Broken Sorting
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n. This time the Little Elephant has permutation p1, p2, ..., pn. Its sort...
```python inp = input().split(' ') val=[]; totNums = int(inp[0]); totOpt = int(inp[1]); inp = input().split(' '); #assert(len(inp) == totNums); for it in inp: val.append(int(it)) dp = [[0.0 for _ in range(0,totNums)] for __ in range(0,totNums)] for i in range(0,totNums): for j in range(0,totNums): if val[...
281_D. 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 #https://codeforces.com/problemset/problem/281/D def empty(l): return len(l) == 0 def lucky_number(arr): st = [] l = 0 for d in arr: while not empty(st) and st[-1] < d: l = max(l, st.pop() ^ d) if not empty(st): l = max(l, st[-1] ^ d) st.appen...
304_C. 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 r = int(input()) if r % 2 == 0: print (-1) elif r == 1: print(0) print(0) print(0) else: for i in range(r): print(i,end=" ") print() i = r - 1 while i >= 0: print(i,end=" ") i -= 2 i = r - 2 while i >= 0: print(i,end=" ") i -= 2 ...
352_B. Jeff and Periods
One day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold: * x occurs in sequence a. * Consider all positions of numbers x in the sequence a (such i, that ai = x). These...
```python le = int(input()) integers = [int(i) for i in str(input()).split(" ")] d = {} for index, ele in enumerate(integers): # should already be sorted if ele in d: d[ele].append(index) else: d[ele] = [index] ans = [] for key, items in d.items(): if len(items) == 1: ans.append...
376_C. 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 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=(10000*modCnt)%7 print(str(mod[7-modCnt])+...
421_A. Pasha and Hamsters
Pasha has two hamsters: Arthur and Alexander. Pasha put n apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamste...
```python n, a, b = map(int, input().split()) x = set(map(int, input().split())) y = set(map(int, input().split())) y -= x s = "" for i in range(1, n + 1, 1): if i in x: s += str(1) + " " else: s += str(2) + " " print(s) ```
469_E. 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 m = int(input()) x,t=10**100-1,m-100*45*10**99%m print(t,t+x) ```
492_A. Vanya and Cubes
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ...
```python n=int(input()) i=1;x=0 while 1: x+=(i*(i+1)/2) if x==n: print(i) break elif x>n: print(i-1) break i+=1 ```
542_F. Quest
Polycarp is making a quest for his friends. He has already made n tasks, for each task the boy evaluated how interesting it is as an integer qi, and the time ti in minutes needed to complete the task. An interesting feature of his quest is: each participant should get the task that is best suited for him, depending o...
```python from collections import defaultdict if __name__ == '__main__': n, T = [int(_) for _ in input().split()] data = defaultdict(list) for i in range(n): t, q = [int(_) for _ in input().split()] data[T - t].append(q) prev_level = [] for level_id in range(1, T + 1): lev...
56_B. Spoilt Permutation
Vasya collects coins: he has exactly one coin for every year from 1 to n. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order...
```python n = int(input()) l = list(map(int,input().split())) v = l.copy() v.sort() i = 0 j = 0 l1 = [] l2 = [] ans = [] while i<n and j<n: if l[i] == v[j]: i+=1 j+=1 else: l1.append(v[j]) l2.append(l[i]) ans.append(j) j+=1 i+=1 l2.reverse() if l1 == l2...
612_D. The Union of k-Segments
You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others. Input The first line contains two integers n and ...
```python #### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools imp...
632_D. Longest Subsequence
You are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value l ≤ m. A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase z...
```python import bisect from itertools import accumulate import os import sys import math from decimal import * from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable =...
685_A. Robbers' watch
Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches. First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hour...
```python from sys import exit from itertools import permutations as prm def to_base(n, base): ans = [] while n // base > 0: ans.append(n % base) n //= base ans.append(n % base) ans.reverse() return ans def le(l, n, m): prev_eq = True for i in range(len(n)): if l[i...
750_C. New Year and Rating
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating ch...
```python I = lambda: list(map(int, input().split())) n = I()[0] c, d = [[0] * n for _ in range(2)] for i in range(n): _c, _d = I() c[i] = _c d[i] = _d lb, ub, change = -1e100, 1e100, 0 for i in range(n)[::-1]: change -= c[i] if d[i] == 1: lb = max(lb, 1900 - change) else: ub = ...
774_A. Amusement Park
Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once. Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible tha...
```python n, c1, c2 = [int(x) for x in input().split(' ')] s = input() cnt = s.count('1') def price(x): return c1 + c2 * (x - 1) ** 2 prices = [] for i in range(1, cnt + 1): bigGroupsPeople = n // i + 1 numBigGroups = n % i smallGroupsPeople = n // i numSmallGroups = i - n % i totalPrice = n...
799_A. Carrot Cakes
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui...
```python n,t,k,d=[int(i) for i in input().split()] a = (n+k-1)//k*t b=1000000000 for i in range(n//k+1): b=min(b,max(d+i*t,(n-i*k+k-1)//k*t)) if b<a: print('YES') else: print('NO') ```
819_A. Mister B and Boring Game
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens. All characters in this game are lowercase English letters. There are two players: Mister B and his competitor. Initially the players have a string s consisting of the...
```python def main(a, b, l, r): qL = (l - 1) // (2 * a + 2 * b) rL = (l - 1) % (2 * a + 2 * b) + 1 qR = (r - 1) // (2 * a + 2 * b) rR = (r - 1) % (2 * a + 2 * b) + 1 #print(qL, qR, rL, rR) if qL == qR: #In b segment if a < rL <= a + b and a < rR <= a + b: re...
844_D. 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) ...
865_A. Save the problem!
Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph. People don't use cash as often as they...
```python print(int(input())*2-1,2,1,2) ```
891_A. Pride
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). What is the minimum number of ope...
```python import math,sys,bisect,heapq,os from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 def input(): return sys.stdin.readline().rstrip('\r\n') #input = iter(sys.stdin.buffer.read()...
913_D. Too Easy Problems
You are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly ti milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either. Unfortunately, your teacher considers ...
```python # -*- coding: utf-8 -*- """ Created on Fri Jan 12 18:46:09 2018 @author: Sand Boa """ import itertools if __name__ == "__main__": n:int T:int n, T = list(map(int,input().split())) listi:list = [] tsum:int = 0 csum:int = 0 k:int k = 1 a:int b:int t:int ind:int ...
935_D. Fafa and Ancient Alphabet
Ancient Egyptians are known to have used a large set of symbols <image> to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S1 and S2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the word...
```python n, m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] mult = 1 mod = 10 ** 9 + 7 res = 0 m_inv = pow(m, mod - 2, mod) for x, y in zip(a, b): if x and y: if x > y: res += mult res %= mod break ...
961_C. Chessboard
Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being ...
```python import itertools n = int(input()) a = [] for i in range(4): a.append([input() for _ in range(n)]) if i < 3: assert input() == '' best = 4*n*n for p in itertools.permutations(a): for s in range(2): count = 0 for i in range(4): for r in range(n): ...
989_B. A Tide of Riverscape
Walking along a riverside, Mino silently takes a note of something. "Time," Mino thinks aloud. "What?" "Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this." "And what are you recording?" "You see it, tide. Everything has its own period, and I think I've figured...
```python n, p = [int(i) for i in input().split()] s = list(input()) k = 0 for index in range(n - p): if k != 0: break if s[index] == s[index + p] and s[index] == ".": s[index] = str(0) s[index + p] = str(1) k += 1 elif s[index] != s[index + p] and s[index] != "." and s[index...
p02600 M-SOLUTIONS Programming Contest 2020 - Kyu in AtCoder
M-kun is a competitor in AtCoder, whose highest rating is X. In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given: * From 400 through 599: 8-kyu * From 600 through 799: 7-kyu * From 800 through 999: 6-kyu * From 1000 thro...
```python X = int(input()) print(8-(X-400)//200) ```
p02731 AtCoder Beginner Contest 159 - Maximum Volume
Given is a positive integer L. Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L. Constraints * 1 ≤ L ≤ 1000 * L is an integer. Input Input is given from Standard Input in the following format: L Output Print the maximum possible volume of a re...
```python N=int(input()) print((N**3)/27) ```
p02864 AtCoder Beginner Contest 145 - Laminate
We will create an artwork by painting black some squares in a white square grid with 10^9 rows and N columns. The current plan is as follows: for the i-th column from the left, we will paint the H_i bottommost squares and will not paint the other squares in that column. Before starting to work, you can choose at most K...
```python N, K = map(int, input().split()) H = [0] + [int(a) for a in input().split()] X = [[1<<100] * (N-K+1) for _ in range(N+1)] X[0][0] = 0 for i in range(1, N+1): for j in range(1, min(i+1, N-K+1)): X[i][j] = min([X[ii][j-1] + max(H[i] - H[ii], 0) for ii in range(i)]) print(min([x[-1] for x in X])) `...
p02999 AtCoder Beginner Contest 130 - Rounding
X and A are integers between 0 and 9 (inclusive). If X is less than A, print 0; if X is not less than A, print 10. Constraints * 0 \leq X, A \leq 9 * All values in input are integers. Input Input is given from Standard Input in the following format: X A Output If X is less than A, print 0; if X is not less th...
```python a,b=map(int,input().split());print('100'[a<b::2]) ```
p03140 NIKKEI Programming Contest 2019 - Touitsu
You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters. Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation: * Operation: Choose one of the strings A, B and C, and specify an integer i betwe...
```python N=int(input()) A=input() B=input() C=input() ans=0 for i in range(N): if A[i]==B[i]==C[i]: ans+=0 elif A[i]==B[i] or B[i]==C[i] or C[i]==A[i]: ans+=1 else: ans+=2 print(ans) ```
p03284 AtCoder Beginner Contest 105 - AtCoder Crackers
Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible. When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user. Constraints * 1 \leq N,K \leq 100 * A...
```python N,M=map(int,input().split()) print(0 if N % M == 0 else 1) ```
p03440 AtCoder Petrozavodsk Contest 001 - Forest
You are given a forest with N vertices and M edges. The vertices are numbered 0 through N-1. The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge. Each vertex i has a value a_i. You want to add edges in the given forest so that the forest becomes connected. To add a...
```python # -*- coding: utf-8 -*- from collections import defaultdict from heapq import merge import sys sys.setrecursionlimit(10**7) def inpl(): return tuple(map(int, input().split())) N, M = inpl() A = inpl() tree = [[-1, 1] for _ in range(N)] # [next, rank] def find(i): if tree[i][0] == -1: group = ...
p03598 AtCoder Beginner Contest 074 - Collecting Balls (Easy Version)
There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i). Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N. In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B. Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th t...
```python n=int(input()) k=int(input()) x=list(map(int,input().split())) ans=0 for i in range(n): ans+=2*min(x[i],k-x[i]) print(ans) ```