name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p00869 Traveling Cube
On a small planet named Bandai, a landing party of the starship Tadamigawa discovered colorful cubes traveling on flat areas of the planet surface, which the landing party named beds. A cube appears at a certain position on a bed, travels on the bed for a while, and then disappears. After a longtime observation, a scie...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write D = [ (1, 5, 2, 3, 0, 4), # 'U' (3, 1, 0, 5, 4, 2), # 'R' (4, 0, 2, 3, 5, 1), # 'D' (2, 1, 5, 0, 4, 3), # 'L' ] p_dice = (0, 0, 0, 1, 1, 2, 2, 3)*3 def rotate_dice(L, k): return (L[e] for e in...
p01000 Independent Research
Problem I chose creature observation as the theme of my free study during the summer vacation and purchased a creature observation kit. This creature prefers to live in a three-dimensional grid-like space. Only one animal can be placed in each cell. It repeats birth and death every day according to the surrounding en...
```python class Simulator: def __init__(self, exist_mp, cnt_mp, birth_num, death_num, limit): self.exist_mp = exist_mp self.cnt_mp = cnt_mp self.birth_num = birth_num self.death_num = death_num self.birth_list = [] self.death_list = [] self.limit = limit ...
p01132 Make Purse Light
Mr. Bill is shopping at the store. There are some coins in his wallet (10-yen coins, 50-yen coins, 100-yen coins, 500-yen coins), but he is now trying to consume as much of this coin as possible. In other words, by paying for the goods with an appropriate number of coins, we are trying to minimize the total number of c...
```python coin=[10, 50, 100, 500, 500000] first = True while True: bill = int(input()) if bill == 0: break; if not first: print() else: first = False posses = list(map(int, input().split())) Sumcoin= sum(coin[i] * posses[i] for i in range(4)) change = Sumcoin - ...
p01271 Mirror Cave
Twin adventurers Rin and Len are searching for treasure in the Mirror Cave. The cave has two pairs of rooms, the Hall of Mirrors, and an expensive treasure lies behind the door of the room. For convenience, each of the two rooms is considered to have W × H cells arranged in a grid pattern. The outside of the room is s...
```python from collections import deque, defaultdict def main(): directs = ((-1, 0, 1, 0), (1, 0, -1, 0), (0, 1, 0, 1), (0, -1, 0, -1)) while True: w, h = map(int, input().split()) if w == 0: break mp_l = ["#" * (w + 2)] mp_r = ["#" * (w + 2)] for _ in range(h): l, r = input().sp...
p01747 Snake
Sunake is in the form of a polygonal line consisting of n vertices (without self-intersection). First, Sunake-kun's i-th vertex is at (xi, yi). You can move continuously by translating or rotating, but you cannot deform (change the length of the polygonal line or the angle between the two line segments). y = 0 is the w...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def dot3(p0, p1, p2): x0, y0 = p0; x1, y1 = p1; x2, y2 = p2 return (x1 - x0) * (x2 - x0) + (y1 - y0) * (y2 - y0) def cross3(p0, p1, p2): x0, y0 = p0; x1, y1 = p1; x2, y2 = p2 return (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0) ...
p01887 Pipe Fitter and the Fierce Dogs
Example Input 5 5 4 6 3 2 4 2 5 2 1 4 3 4 5 4 Output 6
```python from collections import defaultdict import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): W, H, K = map(int, readline().split()) N = int(readline()) mp = defaultdict(lambda:defaultdict(int)) for i in range(N): x, y = map(int, readline().split()) if y % ...
p02024 City
J: City Santa decides to deliver a present to a city. The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with one house delivering gifts to each parcel. The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $. Santa mov...
```python h, w, s, t = map(int, input().split()) if h * w % 2 == 1: if (s + t) % 2 == 1: print("No") else: print("Yes") else: print("Yes") ```
p02166 Cyclic Shift Sort
Problem Given a permutation of length $ N $ $ P = \\ {P_1, P_2, \ ldots, P_N \\} $ and the integer $ K $. Determine if the permutation $ P $ can be monotonically increased by repeating the following operation any number of times $ 0 $ or more. * Choose the integer $ x \ (0 \ le x \ le N-K) $. Patrol right shift aroun...
```python #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline(...
p02307 Circumscribed Circle of a Triangle
Write a program which prints the central coordinate ($cx$,$cy$) and the radius $r$ of a circumscribed circle of a triangle which is constructed by three points ($x_1$, $y_1$), ($x_2$, $y_2$) and ($x_3$, $y_3$) on the plane surface. Constraints * $-10000 \leq x_i, y_i \leq 10000$ * The three points are not on the same...
```python from decimal import Decimal x1, y1 = map(str, input().split()) x2, y2 = map(str, input().split()) x3, y3 = map(str, input().split()) x1, y1 = Decimal(x1), Decimal(y1) x2, y2 = Decimal(x2), Decimal(y2) x3, y3 = Decimal(x3), Decimal(y3) #3辺の長さ a = (((x1-x2)**Decimal('2'))+((y1-y2)**Decimal('2')))**Decimal('0....
p02455 Set: Search
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$ (0 or 1). Constraints * $1 \leq q \leq 200,000$ * $0 \leq ...
```python n = int(input()) s = set() for _ in range(n): a, b = map(int,input().split()) if a == 0: s.add(b) print(len(s)) else: if b in s: print(1) else: print(0) ```
1023_C. Bracket Subsequence
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
```python n, k = [int(x) for x in input().split()] s = input() pairs = k // 2 subs = '' count = 0 sum = 0 for i in range(len(s)): if s[i] == '(': sum += 1 count += 1 subs += '(' if count == pairs: subs += ')' * sum break else: if sum > 0: ...
1067_C. Knights
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the en...
```python print('\n'.join(str(2 * i // 3) + ' ' + str(2 * i % 3) for i in range(int(input())))) ```
108_A. Palindromic Times
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th...
```python s=input() if s[0]=="0": h=s[1] else: h=s[:2] if s[3]=="0": m=s[3] else: m=s[3:] def pallin(x,y): if len(x)==1: x="0"+x if len(y)==1: y="0"+y if x[0]==y[1] and x[1]==y[0]: return True else: return False while(1): if int(m)+1==60: h=str...
1108_F. MST Unification
You are given an undirected weighted connected graph with n vertices and m edges without loops and multiple edges. The i-th edge is e_i = (u_i, v_i, w_i); the distance between vertices u_i and v_i along the edge e_i is w_i (1 ≤ w_i). The graph is connected, i. e. for any pair of vertices, there is at least one path be...
```python import sys # 26 input = lambda: sys.stdin.readline().strip() ipnut = input def find(a): st = [] while a!=dsu[a]: st.append(a) a = dsu[a] for j in st: dsu[j]=a return a def union(a,b,f): a = find(a) b = find(b) if f: dsu[a]=b else: dsu[b]=...
1138_C. Skyscrapers
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monument...
```python # -*- coding: utf-8 -*- # @Time : 2019/3/8 17:32 # @Author : LunaFire # @Email : gilgemesh2012@gmail.com # @File : C. Skyscrapers.py import sys def main(): n, m = map(int, input().split()) a = [] disc_row = [] for i in range(n): a.append(list(map(int, input().split()))) ...
1156_E. Special Segments of Permutation
You are given a permutation p of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once). Let's call some subsegment p[l, r] of this permutation special if p_l + p_r = max _{i = l}^{r} p_i. Please calculate the number of special subsegments. Input The first line contain...
```python mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): s = 0 while i > 0: s += self.tree[i] ...
1197_A. DIY Wooden Ladder
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which * two planks of length at least k+1 — the base of the ladder; * k planks of length at least 1 — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example...
```python T = int(input()) for t in range(T): N = int(input()) Arr = list(map(int, input().split())) Arr.sort(reverse=True) M = min(Arr[0], Arr[1]) if (len(Arr) == 1 or M-1 == 0): print(0) else: print(min(len(Arr)-2, M-1)) ```
1214_B. Badges
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya ...
```python b = int(input()) g = int(input()) n = int(input()) j = n ma = max(b,g) mi = min(b,g) counter =0 if ma >= n : # for i in range(n+1): # if i <= mi: # counter += 1 # else: # break counter = min(mi,n) + 1 else: counter = mi - (n-ma) + 1 print(counter) ...
1237_D. Balanced Playlist
Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of n tracks numbered from 1 to n. The playlist is automatic and cyclic: whenever track i finishes playing, track i+1 starts playing automatically; after track n goes track 1. For each track i, you...
```python import sys input=sys.stdin.buffer.readline from collections import deque n=int(input()) l=list(map(int,input().split())) d=deque() ans=[] currmax=-1000000000000 j=0 for i in range(n): while(len(d) and d[0]<i): d.popleft() currmax=l[d[0]%n] if(len(d)) else l[i] while(j<3*n): currmax...
1255_D. Feeding Chicken
Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm. His farm is presented by a rectangle grid with r rows and c columns. Some of these cells contain rice, others are empty. k chickens are living on his farm. The number of chicken...
```python import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) t,=I() bl=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',...
1279_C. Stack of Presents
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct. Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send...
```python for _ in range(int(input())): n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) rec = {} for i in range(n): rec[a[i]] = i # print(rec) ans = 0 lim = 0 for i in range(m): if rec[b[i]] > lim: a...
129_A. Cookies
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan...
```python a=int(input()) l=list(map(int,input().split())) count=0 for i in l: if i%2!=0: count+=1 if count%2==0: print(a-count) else: print(count) ```
1322_D. Reality Show
A popular reality show is recruiting a new cast for the third season! n candidates numbered from 1 to n have been interviewed. The candidate i has aggressiveness level l_i, and recruiting this candidate will cost the show s_i roubles. The show host reviewes applications of all candidates from i=1 to i=n by increasing ...
```python import sys input = sys.stdin.readline n,m=map(int,input().split()) A=list(map(int,input().split())) C=list(map(int,input().split())) P=list(map(int,input().split())) DP=[[-1<<30]*(n+1) for i in range(5001)] # DP[k][cnt] = Aのmaxがkで, そういう人間がcnt人いるときのprofitの最大値 for i in range(5001): DP[i][0]=0 for i in r...
1341_C. Nastya and Strange Generator
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi...
```python for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) t=a[0] c=0 for i in range(1,n): if a[i]==a[i-1]+1: pass else: if a[i]<t: t=a[i] else: c=1 break if c==1: ...
1363_C. Game On Leaves
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: * Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree...
```python #CF 644 (DIV-3) '''test=int(input()) for i in range(test): a,b=[int(i) for i in input().split()] k=min(a,b) if 2*k>=max(a,b): print((2*k)**2) else: print((max(a,b))**2)''' '''test=int(input()) for i in range(test): n=int(input()) arr=[int(i) for i i...
1383_E. Strange Operation
Koa the Koala has a binary string s of length n. Koa can perform no more than n-1 (possibly zero) operations of the following form: In one operation Koa selects positions i and i+1 for some i with 1 ≤ i < |s| and sets s_i to max(s_i, s_{i+1}). Then Koa deletes position i+1 from s (after the removal, the remaining part...
```python import sys readline = sys.stdin.readline MOD = 10**9+7 S = readline().strip().split('1') if len(S) == 1: print(len(S[0])) else: S = [len(s)+1 for s in S] ans = S[0]*S[-1] S = S[1:-1] dp = [0]*(max(S)+2) dp[0] = 1 for ai in S: res = 0 rz = 0 for i in ra...
1426_B. Symmetric Matrix
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type. Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ...
```python def check(flst, size): if size <= 0: return "NO" elif size % 2 == 0: for each in flst: if each[1] == each[2]: return "YES" return "NO" else: return "NO" tsts = int(input()) for i in range(tsts): init = input().split(" ") types = ...
144_A. Arrival of the General
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
```python def findmax(arr): idx = 0 for i in range(len(arr)): if arr[i]> arr[idx]: idx = i return idx def findmin(arr): idx = len(arr)-1 for i in range(len(arr)-1,-1,-1): if arr[i] < arr[idx]: idx = i return idx x = int(input()) arr = list(map(int,input()....
1473_A. Replacing Elements
You have an array a_1, a_2, ..., a_n. All a_i are positive integers. In one step you can choose three distinct indices i, j, and k (i ≠ j; i ≠ k; j ≠ k) and assign the sum of a_j and a_k to a_i, i. e. make a_i = a_j + a_k. Can you make all a_i lower or equal to d using the operation above any number of times (possibl...
```python def solver(): tc=int(input()) for i in range(tc): n,d=[int(i) for i in input().split()] a=[int(i) for i in input().split()] a.sort() if max(a)<=d: print('YES') else: if (a[0]+a[1])<=d: print('YES') else: ...
1499_C. Minimum Grid Path
Let's say you are standing on the XY-plane at point (0, 0) and you want to reach point (n, n). You can move only in two directions: * to the right, i. e. horizontally and in the direction that increase your x coordinate, * or up, i. e. vertically and in the direction that increase your y coordinate. In othe...
```python for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) best = float("inf") mn = [float("inf")] * 2 sm = [0] * 2 for i in range(n): mn[i%2] = min(mn[i%2], arr[i]) sm[i%2] += arr[i] best = min(best, sm[0]+mn[0]*(n-i//2-1) + sm[1]+mn[1...
1521_A. Nastia and Nearly Good Numbers
Nastia has 2 positive integers A and B. She defines that: * The integer is good if it is divisible by A ⋅ B; * Otherwise, the integer is nearly good, if it is divisible by A. For example, if A = 6 and B = 4, the integers 24 and 72 are good, the integers 6, 660 and 12 are nearly good, the integers 16, 7 are ne...
```python for _ in range(int(input())) : a,b = list(map(int,input().split())) if b == 1 : print("NO") else : if b == 2 : b = 4 print( "YES" ) print( a, a*(b-1), a*b ) ```
1550_A. Find The Array
Let's call an array a consisting of n positive (greater than 0) integers beautiful if the following condition is held for every i from 1 to n: either a_i = 1, or at least one of the numbers a_i - 1 and a_i - 2 exists in the array as well. For example: * the array [5, 3, 1] is beautiful: for a_1, the number a_1 - 2...
```python t = int(input()) for _ in range(t): n = int(input()) cur = 0 ans = 0 for i in range(1, 1000000, 2): if cur+i > n: break ans += 1 cur += i if cur == n: print(ans) else: print(ans+1) ```
197_A. Plate Game
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the...
```python a,b,r=map(int,input().split()) (print("First")if (a>=2*r and b>=2*r) else print("Second")) ```
220_B. Little Elephant and Array
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query ...
```python # -*- coding:utf-8 -*- """ created by shuangquan.huang at 1/8/20 for each query l, r; how many x that count of x in range [l, r] equals x for each query ends with x, query (l, x) with Fenwick tree """ import collections import time import os import sys import bisect import heapq from typing import List ...
244_C. The Brand New Function
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an. Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar. Polycarpus took a piece of...
```python #CF Round 150. Div II Prob. C - The Brand New Function import sys In = sys.stdin n = int(In.readline().strip()) arr = [int(x) for x in In.readline().split()] res, m = set(), set() for i in range(n): s = set() s.add(arr[i]) s.update([x | arr[i] for x in m]) m = s res.update(s) print(...
26_A. Almost Prime
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive. Input Input contains one integer number n (1 ≤ n ≤ 3000). Output Output the amount ...
```python from math import sqrt n = int(input()) count = 0 primes = [] numbers = list(range(3000)) for i in numbers: if i != 0 and i != 1: non_prime_value = i + i while non_prime_value < len(numbers): numbers[non_prime_value] = 0 non_prime_value += i for i in numbers: ...
340_A. The Wall
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on. Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-...
```python def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return a * b / gcd(a, b) x, y, a, b = map(int, input().split(' ')) l = lcm(x, y) print(int(b // l - (a - 1) // l)) ```
363_C. Fixing Typos
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ...
```python s = input() n = len(s) l = [] i = 0 while i<n: j = i+1 while j<n and s[j]==s[i]: j+=1 if (j-i)==1: l.append(s[i]) i+=1 continue l.append(s[i]) l.append(s[i]) k = j+1 while k<n and s[k]==s[j]: k+=1 if j<n: l.append(s[j]) i = k ...
387_B. George and Round
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi. To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem...
```python n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) cnt = 0 j = 0 for i in range(n): while j < m: if a[i] <= b[j]: cnt += 1 j += 1 break else: j += 1 print(n - cnt) ```
435_A. Queue on Bus Stop
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has n groups of people. The i-th group from the beginning has ...
```python a,b = map(int, input().split()) ar = list(map(int, input().split())) count=1 sums=0 for i in range(a): sums += ar[i] if(sums > b): sums = ar[i] count+= 1 print(count) ```
47_A. Triangular numbers
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers...
```python n = int(input()) t = [] for i in range(1, 32): t.append(i * (i + 1) / 2) print('YES' if n in t else 'NO') ```
504_A. Misha and Forest
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the secon...
```python n = int(input()) deg2vs = {} ss = [0] * n degs = [0] * n for i in range(n): degs[i], ss[i] = list(map(int, input().split())) if degs[i] > 0: if degs[i] not in deg2vs: deg2vs[degs[i]] = set() deg2vs[degs[i]].add(i) edges = [] while len(deg2vs) != 0: leaves = deg2vs.pop(1...
527_D. Clique Problem
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? No...
```python def main(): from bisect import bisect_right as br n = int(input()) ab = [list(map(int, input().split())) for _ in [0]*n] ab.sort() ans = [-10**20] l = 1 for a, b in ab: c = br(ans, a-b) d = a+b if c == br(ans, d): if c == l: ans...
553_B. Kyoya and Permutation
Let's define the permutation of length n as an array p = [p1, p2, ..., pn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on. Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a...
```python n, k = list(map(int, input().split())) #n = int(input()) #k = int(input()) fib = [0] * (n + 1) fib[0] = 1 fib[1] = 1 res = [0] * n for i in range(2, n): fib[i] = fib[i - 1] + fib[i - 2] idx = 0 while idx < n: if k <= fib[n - idx - 1]: res[idx] = idx + 1 idx += 1 else: k -= ...
57_A. Square Earth?
Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thu...
```python n, x1, y1, x2, y2 = map(int, input().split()) first, secnd = 0, 0 if y1 == 0: first = 4 elif y1 == n: first = 2 if x1 == 0: first = 1 elif x1 == n: first = 3 if y2 == 0: secnd = 4 elif y2 == n: secnd = 2 if x2 == 0: secnd = 1 elif x2 == n: secnd = 3 if first == 4 and secnd...
645_B. Mischievous Mess Makers
It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has f...
```python def gh(w): return (w*(w+1))//2 a,b=map(int,input().split()) z=a-1 r=min(b,a//2) f=gh(z) k=max(0,z-2*r) l=gh(k) if b<=r:print(f-l) else:print(max(0,f-l-(r-(a//2))%2)) ```
697_B. Barnicle
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. <image> Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the ...
```python from functools import reduce import math from decimal import * def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) def sol(): a = Decimal(input()) if (int(a) == a): print(int(a)) else: print(a) sol() `...
717_I. Cowboy Beblop at his computer
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rot...
```python from math import gcd, sqrt from functools import reduce import sys input = sys.stdin.readline EPS = 0.0000000001 def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def GCD(args): return reduce(gcd, args) def plane_value(plane, point): A, B, C, D = plane ...
762_D. Maximum path
You are given a rectangular table 3 × n. Each cell contains an integer. You can move from one cell to another if they share a side. Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximu...
```python import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def output(*args): sys.stdout.buffer.write( ('\n'.join(map(str, args)) + '\n').encode('utf-8') ) def main(): n = int(input()) a =...
807_E. Prairie Partition
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2k. Let's call that representation prairie partition of x. For example, the prairie partitions of 12, 17, 7 and 1 are: 12 = 1 + 2 + 4 + 5, 17 = 1 + 2 + 4 + 8 + 2, ...
```python from collections import Counter from math import log2 powers = [2 ** p for p in range(64)] def can(): near = Counter() for num in set(nums): p = int(log2(num)) near[p] += nums[num] seq_cp = seqs - Counter() for num in set(near): cnt = near[num] while cnt != 0...
852_G. Bathroom terminal
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is conn...
```python import sys from itertools import product from collections import defaultdict r=sys.stdin.readline N,M=map(int,r().split()) words=defaultdict(int) tb=['a','b','c','d','e'] st=set() cnt=0 res="" def dfs(u): global res,cnt if u==l: if res in st: return if words[res]>0: cnt+=wo...
877_B. Nikita and string
One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b". Nikita wants to make...
```python s=input() n=len(s) prefa=[0]*(n) prefb=[0]*(n) prefa[0]=(s[0]=='a') prefb[0]=(s[0]=='b') c=0 for i in range(1,n): prefa[i]=prefa[i-1]+(s[i]=='a') prefb[i]=prefb[i-1]+(s[i]=='b') ans1,ans=0,0 prefa=[0]+prefa prefb=[0]+prefb for i in range(n+1): for j in range(i,n+1): ans1=(prefa[n]-prefa[j])+(pref...
900_C. Remove Extra One
You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible. We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai. Input The first line contains the onl...
```python a=int(input()) b=[] for i in range(a+1): b.append(0) fir=0 sec=0 for i in (input().split(' ')): j=int(i) if j>fir: sec=fir fir=j b[j]=1 elif j>sec: sec=j b[fir]-=1 ans=1 for i in range(1,a+1): if b[i]<b[ans]: ans=i print(ans) ...
923_A. Primal Sport
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and anno...
```python x = int(input()) lp = [0 for x in range(x+1)] for i in range(2, x+1): if(lp[i]==0): for j in range(i*2, x+1, i): lp[j] = i lp[i] = i - lp[i] + 1 p = x for i in range(lp[x], x+1): p = min(p, lp[i]) print(p) ```
950_C. Zebras
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences o...
```python s = input() arr, zero, one = [], [], [] for i in range(len(s)): if s[i] == '0': if one: idx = one.pop() arr[idx].append(i + 1) zero.append(idx) else: zero.append(len(arr)) arr.append([i + 1]) else: if not zero:break ...
978_F. Mentors
In BerSoft n programmers work, the programmer i is characterized by a skill r_i. A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel. You are given the skills of ea...
```python from bisect import * n, k = map(int, input().split()) r = list(map(int, input().split())) s = sorted(r) l = [0] * n for i in range(n): l[i] = bisect_left(s, r[i]) for i in range(k): x, y = map(int, input().split()) x -= 1 y -= 1 if r[x] < r[y]: l[y] -= 1 elif r[x] > r[y]: ...
p02662 AtCoder Beginner Contest 169 - Knapsack for All Subsets
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S. For a non-empty subset T of the set \\{1, 2, \ldots , N \\}, let us define f(T) as follows: * f(T) is the number of different non-empty subsets \\{x_1, x_2, \ldots , x_k \\} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k}...
```python N, S = map(int, input().split()) A = list(map(int, input().split())) mod = 998244353 L = [[0 for i in range(S+1)] for j in range(N+1)] L[0][0] = 1 for j, a in enumerate(A): for i in range(S+1): if i < a: L[j+1][i] = (2 * L[j][i]) % mod else: L[j+1][i] = (2 * L[j][i] + L[j][i-a]) % mod pr...
p02791 AtCoder Beginner Contest 152 - Low Elements
Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition: * For any integer j (1 \leq j \leq i), P_i \leq P_j. Constraints * 1 \leq N \leq 2 \times 10^5 * P_1, \ldots, P_N is a permutation of 1, \ldots, N. * All values in input are ...
```python N=int(input()) ans=0 champ=10**6 for p in list(map(int,input().split())): if p<champ: ans+=1 champ=p print(ans) ```
p02927 Japanese Student Championship 2019 Qualification - Takahashi Calendar
Today is August 24, one of the five Product Days in a year. A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day): * d_1 \geq 2 * d_{10} \geq 2 *...
```python m, d = map(int, input().split()) ans = 0 for i in range(22, d+1): d10 = i // 10 d1 = i - d10 * 10 if d10 > 1 and d1 > 1 and d10 * d1 <= m: ans += 1 print(ans) ```
p03062 AtCoder Beginner Contest 125 - Flipping Signs
There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order. You can perform the following operation on this integer sequence any number of times: Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1. Let B_1, B_2, ..., B_N be the integer sequence after your ...
```python N = int(input()) A = list(map(int, input().split())) B = sorted(map(abs, A)) if sum(x < 0 for x in A) % 2 == 0: print(sum(B)) else: print(sum(B[1:])-B[0]) ```
p03206 AtCoder Beginner Contest 115 - Christmas Eve Eve Eve
In some other world, today is December D-th. Write a program that prints `Christmas` if D = 25, `Christmas Eve` if D = 24, `Christmas Eve Eve` if D = 23 and `Christmas Eve Eve Eve` if D = 22. Constraints * 22 \leq D \leq 25 * D is an integer. Input Input is given from Standard Input in the following format: D ...
```python D = int(input()) a = "Christmas" print(a + " Eve"*(25-D)) ```
p03353 AtCoder Beginner Contest 097 - K-th Substring
You are given a string s. Among the different substrings of s, print the K-th lexicographically smallest one. A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = `ababc`, `a`, `bab` and `ababc` are substrings of s, while `ac`, `z` and an empty string are not. Also,...
```python s = input() K = int(input()) d = set() for l in range(1, K+1): for i in range(len(s)+1-l): d |= {s[i:i+l]} print(sorted(list(d))[K-1]) ```
p03675 AtCoder Regular Contest 077 - pushpush
You are given an integer sequence of length n, a_1, ..., a_n. Let us consider performing the following n operations on an empty sequence b. The i-th operation is as follows: 1. Append a_i to the end of b. 2. Reverse the order of the elements in b. Find the sequence b obtained after these n operations. Constraints...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from collections import deque N,*A = map(int,read().split()) B = deque() reverse = False for x in A: if reverse: B.appendleft(x) else: B.append(x) reverse = not re...
p03829 AtCoder Beginner Contest 052 - Walk and Teleport
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i. You are now at town 1, and you want to visit all the ...
```python N,A,B = map(int,input().split()) X = [int(x) for x in input().split()] ans = 0 for i in range(1,N): d = X[i]-X[i-1] ans += min(A*d, B) print(ans) ```
p03996 CODE FESTIVAL 2016 qual A - LRU Puzzle
There are N arrays. The length of each array is M and initially each array contains integers (1,2,...,M) in this order. Mr. Takahashi has decided to perform Q operations on those N arrays. For the i-th (1≤i≤Q) time, he performs the following operation. * Choose an arbitrary array from the N arrays and move the intege...
```python def reads(offset = 0): return [int(i) - offset for i in input().split(' ')] def Judge(vector): length = len(vector)-1 for i in range(length): if(vector[i] > vector[i+1]): return 0 return 1 (N, M) = reads() Q = int(input()) A = reads(1) pos = [-1] * M pat = [] freq = [0] * (M+1) freq[0] = N found = ...
p00084 Search Engine
Internet search engines, such as Google, automatically sort and categorize web pages around the world to create a huge database. It also parses the search keywords entered by the user and creates an inquiry statement for database search. In each case, complicated processing is performed to realize efficient search, bu...
```python print(' '.join([x for x in input().replace('.',' ').replace(',',' ').split() if 3 <= len(x) <= 6])) ```
p00216 Cutting Down Water Bills
Mr. Matsudaira is always careful about eco-friendliness in his life. Last month's water charge was 4280 yen, which exceeded the usual target of 4000 yen, so we have been trying to save water this month. How much have you saved on your water bill compared to last month? Enter this month's water usage w [m3] and create ...
```python while(True): n = int(input()) if n == -1: break p = 1150 if n < 10: print(4280-p) elif n < 20: p += 125*(n-10); print(4280-p) elif n < 30: p += 125*10; p += 140*(n-20); print(4280-p) else: p += 125*10; p += 140*10; p += 160*(n-30); print(4280-p) ```
p00376 Red Dragonfly
It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed. When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate ...
```python a,b =map(int,(input().split())) print(abs(a-b)) ```
p00594 What Color Is The Universe?
On a clear night, a boy, Campanella looked up at the sky, there were many stars which have different colors such as red, yellow, green, blue, purple, etc. He was watching the stars and just lost track of time. Presently, he wondered, | <image> ---|--- "There are many stars in the space. What color is the universe if...
```python while True: num=int(input()) if num==0: break stars=sorted(input().split()) if stars.count(stars[num//2]) > num/2 : print(stars[num//2]) else: print("NO COLOR") ```
p00730 Cut the Cake
Today is the birthday of Mr. Bon Vivant, who is known as one of the greatest patissiers in the world. Those who are invited to his birthday party are gourmets from around the world. They are eager to see and eat his extremely creative cakes. Now a large box-shaped cake is being carried into the party. It is not beautif...
```python while True: dic = {} n,w,d = map(int,input().split(" ")) if n == 0 and w == 0 and d == 0: break dic[1] = (w,d) for i in range(n): p,s = map(int,input().split(" ")) W,H = dic[p] for j in range(p,i+1): dic[j] = dic[j+1] cycle = 2*(H+W) s %= cycle if s < W or ((H+W) < s and s < (W+H+W)): ...
p00870 Search of Concatenated Strings
The amount of information on the World Wide Web is growing quite rapidly. In this information explosion age, we must survive by accessing only the Web pages containing information relevant to our own needs. One of the key technologies for this purpose is keyword search. By using well-known search engines, we can easily...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M = map(int, readline().split()) if N == M == 0: return False ca = ord('a') E = [list(map(lambda x: ord(x)-ca, readline().strip())) for i in range(N)] F = "".join(readli...
p01133 Dragon Fantasy
Peace, which was supposed to last forever, suddenly ended. The Demon King, who had been sealed long ago, has finally revived. But when the world was about to be covered in darkness, a brave man appeared. The hero then set out on a journey to collect legendary crystals scattered around the world. Legend has it that if y...
```python def solve(): from math import sqrt from sys import stdin f_i = stdin def dfs(point, remain, elapsed): if not remain: return True next_c = set() for c in remain: new_elapsed = elapsed + adj[point][c] if new_elapsed >= fro...
p01442 Mysterious Maze
A robot in a two-dimensional maze again. The maze has an entrance and an exit this time, though. Just as in the previous problem, the maze is made up of H × W grid cells, its upper side faces north, and each cell is either empty or wall. Unlike the previous, on the other hand, one of the empty cells is connected to th...
```python from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write dd = ((-1, 0), (0, -1), (1, 0), (0, 1)) def solve(): H, W, N = map(int, readline().split()) if H == 0: return False S = readline().strip() C = [[0]*W for i in range(H)] sx = sy =...
p02025 Angel Relief
K: Relief (Angel Relief) Tenma, an angel, decides to save a city. The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with houses in each parcel. The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $. The house in parc...
```python def f(): return map(int,input().split()) h,w=f();print(sum([sum([(x+1)*(w-x)*v for x,v in enumerate(f())])*(y+1)*(h-y)for y in range(h)])) ```
p02308 Cross Points of a Circle and a Line
For given a circle $c$ and a line $l$, print the coordinates of the cross points of them. Constraints * $p1$ and $p2$ are different * The circle and line have at least one cross point * $1 \leq q \leq 1,000$ * $-10,000 \leq cx, cy, x1, y1, x2, y2 \leq 10,000$ * $1 \leq r \leq 10,000$ Input The input is given in the...
```python def solve_eq(a,b,c): return (-b-(b**2-4*a*c)**0.5)/(2*a),(-b+(b**2-4*a*c)**0.5)/(2*a) def ret_line(x1,y1,x2,y2): k = (y1-y2)/(x1-x2) d = y1-k*x1 return k,d x,y,r = map(float,input().split()) q = int(input()) x1,y1,x2,y2 = [],[],[],[] for i in range(q): arr = list(map(float,input().sp...
p02456 Set: Delete
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$ (0 or 1). * delete($x$): Delete $x$ from $S$. Constraints ...
```python q = int(input()) s = set() for i in range(q): x, y = map(int, input().split()) if x == 0: s.add(y) print(len(s)) elif x == 1: print(1) if y in s else print(0) else: s.discard(y) ```
1011_F. 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 AND = "AND" OR = "OR" XOR = "XOR" NOT = "NOT" IN = "IN" OPS = { AND: AND, OR: OR, XOR: XOR, NOT: NOT, } class Node: def __init__(self, num): self.num = num self.op = None self.parent = None self.input_1 = None self.input_2 = None self.orig...
105_A. Transmigration
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes...
```python #!/usr/bin/env python3 ESP = 1e-7 n, m, k = input().rstrip().split() n, m, k = int(n), int(m), float(k) cur = {} for i in range(n): skill, exp = input().rstrip().split() exp = int(int(exp) * k + ESP) if exp >= 100: cur[skill] = exp for i in range(m): skill = input().rstrip() cur....
1081_B. Farewell Party
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced. Chouti remembered that n persons took part in that party. To make the party funnier, each person wore one hat among n kinds of ...
```python import math, sys from fractions import * def mp(): return list(map(int, input().split())) def main(): n = int(input()) a = mp() cnt = [0] * (n + 1) for i in a: cnt[i] += 1 k = 1 ans = [[] for i in range(n + 1)] for i in range(n + 1): if cnt[i] == 0: ...
1100_B. Build a Contest
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features n problems of distinct difficulty, the difficulties are numbered from 1 to n. To hold a round Arkady needs n new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems...
```python diff, prob = [int(x) for x in input().split()] probs = [int(x) for x in input().split()] counts = {} comp = {} num = 0 for i in range(diff): counts[i + 1] = 0 comp[i + 1] = False for p in probs: counts[p] += 1 if comp[p] == False: num += 1 comp[p] = True if (num == di...
1121_F. Compress String
Suppose you are given a string s of length n consisting of lowercase English letters. You need to compress it using the smallest possible number of coins. To compress the string, you have to represent s as a concatenation of several non-empty strings: s = t_{1} t_{2} … t_{k}. The i-th of these strings should be encode...
```python import sys sys.setrecursionlimit(10 ** 8) n, a, b = map(int,input().split()) s = input() def calc(j): if (j >= n): return 0 if (dp[j] != -1): return dp[j] dp[j] = a + calc(j + 1) lo = j hi = n farthest = -1 # finding best string to reach from a given j such that it eist before...
1207_F. Remainder Problem
You are given an array a consisting of 500000 integers (numbered from 1 to 500000). Initially all elements of a are zero. You have to process two types of queries to this array: * 1 x y — increase a_x by y; * 2 x y — compute ∑_{i ∈ R(x, y)} a_i, where R(x, y) is the set of all integers from 1 to 500000 which hav...
```python import sys n = 500001 sqrt = int(0.75 * n**0.5) data = [0]*(n) ans = [[]] # out = [] for i in range(1, sqrt): ans.append([0]*i) j = int(sys.stdin.readline()) qus = sys.stdin.readlines() for qu in qus: q = [int(i) for i in qu.split()] if q[0] == 1: x = q[1] y = q[2] data[x]...
124_B. Permutations
You are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers. Input The first line contains integers n and k — the number and digit capacity of numbers cor...
```python import sys data = sys.stdin.read().split() data_ptr = 0 def data_next(): global data_ptr, data data_ptr += 1 return data[data_ptr - 1] N = int(data_next()) K = int(data_next()) arr = [] for i in range(N): arr.append(list(data_next())); perm = [] for i in range(K): perm.append(str(i)) ...
1311_A. Add Odd or Subtract Even
You are given two positive integers a and b. In one move, you can change a in the following way: * Choose any positive odd integer x (x > 0) and replace a with a+x; * choose any positive even integer y (y > 0) and replace a with a-y. You can perform as many such operations as you want. You can choose the sam...
```python for i in range(int(input())): a,b=map(int,input().split()) if a==b: print(0) elif a<b: if (b-a)%2==0: print(2) else: print(1) elif a>b: if (a-b)%2==0: print(1) else: print(2) ```
1333_E. Road to 1600
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help! Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, i...
```python from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i...
1354_B. Ternary String
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once. A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character...
```python import math from sys import stdin,stdout def L(): return list(map(int,stdin.readline().split())) #For array input def Si(): return sorted(list(map(int,stdin.readline().split()))) #For sorted array def In(): return map(int,stdin.readline().split()) #For multiple input def I(): return stdin.read...
1373_G. Pawns
You are given a chessboard consisting of n rows and n columns. Rows are numbered from bottom to top from 1 to n. Columns are numbered from left to right from 1 to n. The cell at the intersection of the x-th column and the y-th row is denoted as (x, y). Furthermore, the k-th column is a special column. Initially, the ...
```python import collections import math n, k, m = [int(i) for i in input().split()] l = math.ceil((math.log(2*n) / math.log(2))) p = 2 ** l # print(p) memo = [0] * (2 * p) allres = [0] * (2 * p) exist = set() for _i in range(m): x, y = [int(i) for i in input().split()] l = abs(x - k) + y index = l + p ...
1397_A. Juggling Letters
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters. In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal? In...
```python for _ in range(int(input())): #n,k=map(int,input().split()) ll=[0]*26 n=int(input()) bool=True for _ in range(n): s=input() pp=set(s) for c in pp: cc=s.count(c) ll[ord(c)-97]+=cc # print(ll) for x in ll: if x%n!=0 : bool=False if bool == True : print...
1420_C1. Pokémon Army (easy version)
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R...
```python import sys from collections import defaultdict as dc import math from bisect import bisect, bisect_left,bisect_right input=sys.stdin.readline for _ in range(int(input())): n,x=map(int,input().split()) l=list(map(int,input().split())) f=0 a=0 b=0 i=0 while(i<n): if f==0: ...
1439_A2. Binary Table (Hard Version)
This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem. You are given a binary table of size n × m. This table consists of symbols 0 and 1. You can make such operat...
```python from sys import stdin input = stdin.readline mp = lambda : map(int,input().split()) it = lambda: int(input()) for _ in range(it()): a,b = mp() t = [list(map(int,list(input().strip()))) for i in range(a)] # print(t) saare =[] for i in range(a-2): for j in range(b): if t[i][j]==1: if j!=b-1: ...
1466_A. Bovine Dilemma
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io. There are n trees growing along the river, where Argus tends Io. For this problem, the river ca...
```python import sys input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return (int(input())) def inlt(): return (list(map(int, input().split()))) def insr(): s = input() return (list(s[:len(s) - 1])) def invr(): return (map(int, input().split()...
1490_B. Balanced Remainders
You are given a number n (divisible by 3) and an array a[1 ... n]. In one move, you can increase any of the array elements by one. Formally, you choose the index i (1 ≤ i ≤ n) and replace a_i with a_i + 1. You can choose the same index i multiple times for different moves. Let's denote by c_0, c_1 and c_2 the number o...
```python import math result = [] cases = int(input()) for i in range(cases): sum = 0 num = int(input()) ain = list(map(int,input().split(" "))) dt = {} dt[0]=0 dt[1]=0 dt[2]=0 for j in ain: dt[j%3]=dt[j%3]+1 for l in range(2): for m in range(3): if dt[m]...
1512_E. Permutation by Sum
A permutation is a sequence of n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] are permutations, and [2, 3, 2], [4, 3, 1], [0] are not. Polycarp was given four integers n, l, r (1 ≤ l ≤ r ≤ n) and s (1 ≤ s ≤ (n (n+1))/(2)) and asked to find a permutatio...
```python t = int(input()) for _ in range(t): n, l, r, s = map(int, input().split()) l -= 1 r -= 1 c = r - l + 1 if c * (c + 1) // 2 > s or c * (2 * n + 1 - c) // 2 < s: print(-1) continue sec = [i for i in range(1, c + 1)] sec.reverse() s -= c * (c + 1) // 2 cnt = 0 ...
167_A. Wizards and Trolleybuses
In some country live wizards. They love to ride trolleybuses. A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it lea...
```python # written with help of passed solutions from math import sqrt n, a, d = map(int, input().split()) a = float(a) ans = [0] * n tm = 0 for i in range(n): t, v = map(int, input().split()) acc_t = v / a add_t = 0 if acc_t ** 2 * a > 2 * d: add_t = sqrt(2 * d / a) else: add_t ...
234_C. Weather
Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet. Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a ther...
```python ''' Auther: ghoshashis545 Ashis Ghosh College: jalpaiguri Govt Enggineerin College Date:07/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,inso...
25_B. Phone numbers
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three d...
```python n = int(input()) s = input() while (len(s) > 4): print (s[0:2], end='-') s = s[2:] if (len(s) <=3): print (s) else: print (s[0:2], s[2:4], sep='-') ```
283_B. Cow Program
Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a1, a2, ..., an of positive integers: 1. Initially, x = 1 and y = 0. If, after any step, x ≤ 0 or x > n, the program immediately terminates. 2. The p...
```python INF = float('inf') n = int(input()) aaa = [0, 0] + list(map(int, input().split())) dp = [[0 for _ in range(n+1)] for i in range(2)] vis = [[0 for _ in range(n+1)] for i in range(2)] rs = [0] * (n-1) def di(d): return 0 if d == 1 else 1 def solve(x, d): if dp[di(d)][x]: return dp[di(d)][x] ...
306_A. Candies
Polycarpus has got n candies and m friends (n ≥ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such ai, where ai is the number of candies in the i-th friend's prese...
```python n,m=map(int,input().split()) print(*[n//m+1 if i<n%m else n//m for i in range(m)]) ```
331_C3. The Great Julya Calendar
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open ...
```python memoization_table = {} def compute_count(previous_max, rest): global memoization_table original_rest = rest if (previous_max, rest) in memoization_table: return memoization_table[(previous_max, rest)] num_digits = len(str(rest)) if num_digits == 1: memoization...
378_A. Playing with Dice
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways ...
```python import math n1,n2 = map(int ,input().split()) a,b,d = 0,0,0 for i in range(1,7): d1 = abs(i-n1) d2 = abs(i-n2) if d1<d2: a+=1 elif d1>d2: b+=1 else: d+=1 print(a,d,b) ```