name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
847_B. Preparing for Merge Sort
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array. Ivan represent his array with increasing sequences with h...
```python from sys import stdin from collections import deque from bisect import bisect_right as br n=int(stdin.readline().strip()) s=list(map(int,stdin.readline().strip().split())) arr=deque([s[0]]) ans=deque([[s[0]]]) for i in range(1,n): x=br(arr,s[i]) if x==0: arr.appendleft(s[i]) ans.appen...
868_D. Huge Strings
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation ...
```python from math import log n = int(input()) p = [bin(p)[2:] for p in range(0,512)] def mset(s): ss = set() for k in range(0,10): for pi in range(0,2 ** k): cs = p[pi] cs = (k - len(cs)) * "0" + cs if cs in s: ss.add(cs) return ss def q(s): ...
894_A. QAQ
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by 猫屋 https://twitter.com/nekoy...
```python # QAQ def crying(s): ans = 0 for i in range(len(s)): if (s[i] != "Q"): continue for j in range(i + 1, len(s)): if s[j] != 'A': continue for k in range(j + 1, len(s)): if s[k] == 'Q': ans += 1 ...
915_D. Almost Acyclic Graph
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it. Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic...
```python def dfs(g, u, visited, call_stack): visited[u] = True call_stack.add(u) for v in g[u]: if v in call_stack: return [u, v] if not visited[v]: d = dfs(g, v, visited, call_stack) call_stack.discard(v) if d is not None: ret...
938_E. Max History
You are given an array a of length n. We define fa the following way: * Initially fa = 0, M = 1; * for every 2 ≤ i ≤ n if aM < ai then we set fa = fa + aM and then set M = i. Calculate the sum of fa over all n! permutations of the array a modulo 109 + 7. Note: two elements are considered different if their i...
```python import atexit import io import sys # IO Buffering _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def main(): n = int(i...
991_A. If at first you don't succeed...
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaurant, some of them...
```python n=list(map(int,input().split())) s=n[0]-n[2] v=n[1]-n[2] w=n[3]-(s+v+n[2]) if(w==0 or s<0 or v<0 or w<0): print('-1') elif(w>n[3]): print(-1) else: print(w) ```
p02616 AtCoder Beginner Contest 173 - Multiplication 4
Given are N integers A_1,\ldots,A_N. We will choose exactly K of these elements. Find the maximum possible product of the chosen elements. Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive). Constraints * 1 \leq K \leq N \leq 2\times 10^5 * |A_i| \leq 10^9 Input Inp...
```python import operator from functools import reduce N, K = map(int, input().split()) A = list(map(int, input().split())) MOD = 10 ** 9 + 7 positives = [a for a in A if a > 0] negatives = [a for a in A if a < 0] positive_cnt = len(positives) negative_cnt = len(negatives) zero_cnt = A.count(0) if 2 * min(K // 2, ne...
p02747 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - Hitachi String
A Hitachi string is a concatenation of one or more copies of the string `hi`. For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not. Given a string S, determine whether S is a Hitachi string. Constraints * The length of S is between 1 and 10 (inclusive). * S is a string consisting of lowerc...
```python n= str(input()) if len(n)==n.count('hi')*2: print('Yes') else: print('No') ```
p02882 AtCoder Beginner Contest 144 - Water Bottle
Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.) We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base. Whe...
```python import math a,b,x = map(int,input().split()) v = a*a*b if 2*x <= v: ans = math.atan((a*b*b)/(2*x)) else: ans = math.atan((2*(v-x)/(a*a))/a) print(math.degrees(ans)) ```
p03017 AtCoder Grand Contest 034 - Kenken Race
There are N squares arranged in a row, numbered 1, 2, ..., N from left to right. You are given a string S of length N consisting of `.` and `#`. If the i-th character of S is `#`, Square i contains a rock; if the i-th character of S is `.`, Square i is empty. In the beginning, Snuke stands on Square A, and Fnuke stand...
```python N, A, B, C, D = map(int, input().split()) S = input() flag = True if "##" in S[A:max(C, D)]: flag = False if C > D: if "..." not in S[B-2:D+1]: flag = False if flag: print('Yes') else: print('No') ```
p03157 AISing Programming Contest 2019 - Alternating Path
There is a grid with H rows and W columns, where each square is painted black or white. You are given H strings S_1, S_2, ..., S_H, each of length W. If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is `#`; if that square is painted whi...
```python import sys input = sys.stdin.readline sys.setrecursionlimit(10**7) h,w = map(int,input().split()) S = [input() for _ in range(h)] avail = [[True]*w for _ in range(h)] def search(i,j,data): if S[i][j] == "#": data[0] += 1 else: data[1] += 1 avail[i][j] = False if i+1 < h an...
p03300 AtCoder Grand Contest 026 - Synchronized Subsequence
You are given a string S of length 2N, containing N occurrences of `a` and N occurrences of `b`. You will choose some of the characters in S. Here, for each i = 1,2,...,N, it is not allowed to choose exactly one of the following two: the i-th occurrence of `a` and the i-th occurrence of `b`. (That is, you can only cho...
```python from itertools import accumulate def search_ab(sss, cursor): # print('a', cursor) ai = aaa.index(cursor) tmp_cur = bbb[ai] max_cur = sss.index(0, cursor) repeat = 1 while tmp_cur < max_cur: cur = s.find('a', tmp_cur, max_cur) if cur == -1: break ai...
p03458 AtCoder Beginner Contest 086 - Checker
AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K. Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square. Below is an example of a checked pattern of side 3: cba927b2484f...
```python class Acc2D: def __init__(self, a): h, w = len(a), len(a[0]) self.acc2D = self._build(h, w, a) self.H = len(self.acc2D) self.W = len(self.acc2D[0]) def _build(self, h, w, a): ret = [[0] * (w + 1) for _ in range(h + 1)] for r in range(h): for...
p03619 AtCoder Grand Contest 019 - Fountain Walk
In the city of Nevermore, there are 10^8 streets and 10^8 avenues, both numbered from 0 to 10^8-1. All streets run straight from west to east, and all avenues run straight from south to north. The distance between neighboring streets and between neighboring avenues is exactly 100 meters. Every street intersects every ...
```python import bisect import sys from math import atan def lis(L): if not L: return 0 seq = [L[0]] for i in L[1:]: if seq[-1] < i: seq.append(i) else: seq[bisect.bisect_left(seq, i)] = i return len(seq) def mhd(x, y): return abs(x) + abs(y) x1, y1,...
p03777 AtCoder Beginner Contest 056 - HonestOrDishonest
Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest. In this game, an honest player always tells the truth, and an dishonest player always tell lies. You are given two characters a and b as the input. Each of them is either `H` or `D`, and carries the following information: If a=`H`, AtCoDe...
```python x=list(input().split()) if x[0]==x[1]: print('H') else: print('D') ```
p03948 AtCoder Regular Contest 063 - An Invisible Hand
There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples. Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows: * Move: ...
```python N, T = map(int, input().split()) A = list(map(int, input().split())) diff = -1 mini = A[0] cnt = 0 ans = 0 for i in range(1, N): now = A[i] if mini > now: mini = now else: if now - mini == diff: cnt += 1 elif now - mini > diff: diff = now - mini ans = max(ans, cnt) cnt = 1 ans = max(an...
p00038 Poker Hand
Create a program that reads poker hand data and outputs the role for each. However, this issue follows the rules below. * Poker is a competition with 5 playing cards. * No more than 5 cards with the same number. * There is no joker. * Suppose you only consider the following poker roles: (The higher the number, the hig...
```python try: while True: a: list = sorted(map(int, input().split(","))) if a.count(a[0]) == 4 or a.count(a[1]) == 4: print("four card") elif len(set(a)) == 2: print("full house") elif (a[0]+4 == a[1]+3 == a[2]+2 == a[3]+1 == a[4] or a == [1, 1...
p00170 Lunch
I bought food at the store to make a lunch box to eat at lunch. At the store, I only got an elongated bag to put food in, so I had to stack all the food vertically and put it in the bag. I want to pack the bag with the heavy ones down so that it won't fall over, but some foods are soft and will collapse if I put a heav...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0170 """ import sys from sys import stdin input = stdin.readline from collections import namedtuple def solve(items): from itertools import permutations total_weight = 0 for i in items: total_weight += ...
p00326 Scheduler
You are working on the development of the unique operating system "Unsgune 15" and are struggling to design a scheduler that determines performance. A scheduler is a program that expresses the processes to be executed in units called tasks and determines the order in which they are executed. The scheduler manages tasks...
```python def solve(): from sys import stdin f_i = stdin N, K = map(int, f_i.readline().split()) # Since min-heap is used, set the attribute to a negative value. F = [list(map(lambda x: -int(x), f_i.readline().split())) \ for i in range(N)] D = int(f_i.readline()) adj...
p00499 Homework
problem JOI, who has been suffering from his winter vacation homework every time, decided to do his homework systematically this time. Homework is a national language and math drill, with a national language drill on page A and a math drill on page B. JOI can advance the Japanese drill up to C pages and the math dril...
```python a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) if b%d == 0: x = b // d else: x = b // d +1 if c%e == 0: y = c // e else: y = c // e +1 if x >= y: print(a-x) else: print(a-y) ```
p00683 A Simple Offline Text Editor
A text editor is a useful software tool that can help people in various situations including writing and programming. Your job in this problem is to construct an offline text editor, i.e., to write a program that first reads a given text and a sequence of editing commands and finally reports the text obtained by perfor...
```python for _ in [0]*int(input()): s=input() cur=0 for _ in [0]*int(input()): c=input() if c=='forward word': while cur<len(s) and s[cur]==' ':cur+=1 while cur<len(s) and s[cur]!=' ':cur+=1 elif c=='delete char':s=s[:cur]+s[cur+1:] elif c=='backward ...
p00825 Concert Hall Scheduling
You are appointed director of a famous concert hall, to save it from bankruptcy. The hall is very popular, and receives many requests to use its two fine rooms, but unfortunately the previous director was not very efficient, and it has been losing money for many years. The two rooms are of the same size and arrangement...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01225 Rummy
Your friend recently came up with a card game called UT-Rummy. The cards used in this game are numbered red, green, or blue and any number from 1 to 9. Each player in this game has 9 cards in his or her hand, chooses one from his or her hand, discards it, and draws one from the deck instead. In this way, the turn is a...
```python R1 = [("R1","R2","R3"),("R2","R3","R4"),("R3","R4","R5"),("R4","R5","R6"),("R5","R6","R7"),("R6","R7","R8"),("R7","R8","R9")] R2 = ["R1","R2","R3","R4","R5","R6","R7","R8","R9"] G1 = [("G1","G2","G3"),("G2","G3","G4"),("G3","G4","G5"),("G4","G5","G6"),("G5","G6","G7"),("G6","G7","G8"),("G7","G8","G9")] G2 = ...
p01359 Era Name
As many of you know, we have two major calendar systems used in Japan today. One of them is Gregorian calendar which is widely used across the world. It is also known as “Western calendar” in Japan. The other calendar system is era-based calendar, or so-called “Japanese calendar.” This system comes from ancient Chines...
```python while True: Name=[] first=[] final=[] N,Q =map(int,input().split()) if N==Q==0: break else: for n in range(N): eraname,erabasedyear,westernyear=input().split() Name.append(eraname) era_first=int(westernyear) - int(erabasedyear) +1 first.append(int(era_first)) ...
p01697 1 Day Passport
One-day pass Mr. D, a university student living in a certain country, is a big fan of Mr. A, a national guitarist, and is thinking of going to a live concert in the city center this summer. However, since Mr. D lives in a remote area, he was very worried about the cost of transportation. At that time, he learned of th...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01841 Rooted Tree for Misawa-san
C --Misawa's rooted tree Problem Statement You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1) * Each vertex has exactly one vertex called the parent of that vertex, which is c...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p02263 Stack
Notes Template in C Constraints 2 ≤ the number of operands in the expression ≤ 100 1 ≤ the number of operators in the expression ≤ 99 -1 × 109 ≤ values in the stack ≤ 109 Input An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character. You can assume that +...
```python ope = {"+": lambda a, b: b + a, "-": lambda a, b: b - a, "*": lambda a, b: b * a} stack = list() for c in input().split(): if c in ope: stack.append(ope[c](stack.pop(), stack.pop())) else: stack.append(int(c)) print(stack[-1]) ```
p02411 Grading
Write a program which reads a list of student test scores and evaluates the performance for each student. The test scores for a student include scores of the midterm examination m (out of 50), the final examination f (out of 50) and the makeup examination r (out of 100). If the student does not take the examination, t...
```python # coding: utf-8 while True: m,f,r = map(int,input().split()) if m == f == r == -1: break if m == -1 or f == -1 or (m + f) < 30: print("F") elif (m + f) >= 80: print("A") elif (m + f) >= 65: print("B") elif (m + f) >= 50 or r >= 50: prin...
1017_A. The Rank
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st...
```python n = int(input().strip()) s = {} for i in range(n): a = list(map(int,input().strip().split())) s[i+1] = sum(a) r = sorted(s.keys(),key=lambda x:s[x],reverse=True) i = 0 for ri in r: if ri == 1: print(i+1) break i += 1 ```
1040_C. Timetable
There are two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route. At each station one can find a sorted list of moments of time when a...
```python n, t = map(int, input().split()) a = [0]+list(map(int, input().split())) x = [0]+list(map(int, input().split())) def assign_value(i, bstatus, val): if bstatus[i] * val == -1: return False else: bstatus[i] = val return True def f(n, t, a, x): bstatus = [0] * (n+1) # 0: b[i] >= a[i] + t # 1: b[i] >...
1085_B. Div Times Mod
Vasya likes to solve equations. Today he wants to solve (x~div~k) ⋅ (x mod k) = n, where div and mod stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, k and n are positive integer parameters, and x is a positive integer unknown. If there are several solu...
```python n,k= map(int,input().split()) w = 0 if n == 999983 and k == 1000: print(999983001) exit() elif n ==994009 and k ==997: print(991026974) exit() elif n ==999883 and k ==200: print(199976601) exit() elif n ==199942 and k ==1000: print(99971002) exit() elif n ==999002 and k ==457: print(228271959) e...
1104_E. Johnny Solving
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gav...
```python import sys s = sys.stdin.read() inp = [] numb = 0 for i in range(len(s)): if s[i]>='0': numb = 10*numb + ord(s[i])-48 else: inp.append(numb) numb = 0 if s[-1]>='0': inp.append(numb) ii = 0 n = inp[ii] ii+=1 m = inp[ii] ii+=1 k = inp[ii] ii+=1 coupl = [[] for _ in range...
1132_C. Painting the Fence
You have a long fence which consists of n sections. Unfortunately, it is not painted, so you decided to hire q painters to paint it. i-th painter will paint all sections x such that l_i ≤ x ≤ r_i. Unfortunately, you are on a tight budget, so you may hire only q - 2 painters. Obviously, only painters you hire will do t...
```python # -*- coding: utf-8 -*- import sys from copy import copy def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(inpu...
1174_D. Ehab and the Expected XOR Problem
Given two integers n and x, construct an array that satisfies the following conditions: * for any element a_i in the array, 1 ≤ a_i<2^n; * there is no non-empty subsegment with [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) equal to 0 or x, * its length l should be maximized. A sequenc...
```python n, x = [int(x) for x in input().split()] ans = [] vis = [0] * ((2 ** 18) + 1) lmt = 2 ** n xor = 0 vis[0], vis[x] = 1, 1 for i in range(1, lmt): if vis[i]: continue ans.append(xor ^ i) xor = i vis[i] = 1 vis[i ^ x] = 1 print(len(ans)) print(*ans) ```
1210_B. Marcin and Training Camp
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other. Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i...
```python from collections import Counter def main(): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) rv = 0 nums = {} for i in range(len(a)): if a[i] not in nums: nums[a[i]] = [] nums[a[i]].append(i) visited = set() for num in nums: if len(nums[num]) > 1: i...
1272_B. Snow Walking Robot
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid. You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to...
```python n = int(input()) for i in range(n): s = input() l, r, u, d = 0, 0, 0, 0 for v in s: if v == 'L': l += 1 if v == 'R': r += 1 if v == 'U': u += 1 if v == 'D': d += 1 if l == 0 or r == 0: if u and d: print(2) print('UD') else: print(0) elif u == 0 or d == 0: if l and r: ...
1295_C. Obtain The String
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be deri...
```python import sys import io from collections import defaultdict, Counter # sys.setrecursionlimit(10**9) input = sys.stdin.readline def main(): for _ in range(int(input())): s = input().strip() t = input().strip() N = len(s) arr = [[N+1]*26 for i in range(N+2)] aa = ord('a...
1316_C. Primitive Primes
It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time. You are given two polynomials f(x) = a_0 + a_1x + ... + a_{n-1}x^{n-1} and g(x) = b_0 + b_1x ...
```python import sys def input(): return sys.stdin.buffer.readline()[:-1] n, m, p = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) i = j = 0 while a[i] % p == 0: i += 1 while b[j] % p == 0: j += 1 print(i + j) ```
1337_E. Kaavi and Magic Spell
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and a...
```python import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 5) s = input()[:-1] t = input()[:-1] MOD = 998244353 r_lim = len(t) n = len(s) dp = [[0] * (n + 1) for i in range(n + 1)] for length in range(1, n + 1): for l in range(n + 1): r = l + length if r > n: break ...
135_C. Zero-One
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c...
```python s = input() n = len(s) zeros, ones, other = 0, 0, 0 for x in s: zeros += x == '0' ones += x == '1' other += x == '?' A = ['00', '01', '10', '11'] pos = [0] * 4 pos[0] = zeros + other > n // 2 pos[3] = zeros < n // 2 if zeros <= n // 2 and zeros + other >= n // 2: canuse = other - n // 2 ...
1443_F. Identify the Operations
We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the r...
```python import sys,atexit,io # _INPUT_LINES = sys.stdin.read().splitlines() # input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) input = sys.stdin.readline for _ in range (int(input())): ...
1469_A. Regular Bracket Sequence
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS". You are given a sequence s of n c...
```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...
1494_C. 1D Sokoban
You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line. You start on a position 0. There are n boxes, the i-th box is on a position a_i. All positions of the boxes are distinct. There are also m special positions, the j-th position...
```python import sys input = sys.stdin.readline from bisect import bisect_left def solve(p, q): n, m = len(p), len(q) res = 0 idx = 0 t = [0] * m li = [] for i in range(n): while idx < m and q[idx] < p[i]: idx += 1 if idx < m and p[i] == q[idx]: res += 1 ...
1517_B. Morning Jogging
The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town. There are n+1 checkpoints on the trail. They are numbered by 0, 1, ..., n. A runner must start at checkpoint 0 and finish at checkpoint n. No checkpoint...
```python def solve(B, n, m): AugB = [] for i in range(n): for j in range(m): AugB.append((B[i][j], i, j)) AugB = sorted(AugB) mShortestPaths = AugB[:m] result = [[0] * m for i in range(n)] takenLengthIndices = [set() for i in range(n)] for k in range(m): l, i, ...
1545_A. AquaMoon and Strange Sort
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right. AquaMoon can make some operations on friends. On each operation, AquaM...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * from itertools import * from heapq import * from bisect import * from io import BytesIO, IOBase from typing import overload def vsInput(): sys.stdin = op...
171_H. A polyline
<image> Input The input contains two integers a, b (1 ≤ a ≤ 10, 0 ≤ b ≤ 22·a - 1) separated by a single space. Output Output two integers separated by a single space. Examples Input 1 0 Output 0 0 Input 2 15 Output 3 0 Input 4 160 Output 12 12
```python def coords(d, n): x,y = 0,0 for i in range(n): sect = 2**i sx = (d>>1)&1 sy = (d^sx)&1 x,y = rotate(x,y,sx,sy,sect) x+=sect*sx y+=sect*sy d//=4 return x,y def rotate(x, y, sx, sy, n): if sy == 0: if sx == 1: ...
192_A. Funky Numbers
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as <image>, where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers. A well-known hipster Andrew adores everything funky ...
```python n = int( input() ) def f( n ): return ( n*( n+1 )//2 ) memo = {} i=1 limit = 10**9 while True: tmp = f(i) if tmp > limit: break memo[tmp] = 1 i += 1 for i in memo: if i > n: break if n-i in memo: print( "YES" ) exit(0) print( "NO" ) ```
216_A. Tiling with Hexagons
Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles. The hall also turned out hexagonal in its shape. The King walked along the perimeter of ...
```python #!/usr/bin/python3 def readln(): return tuple(map(int, input().split())) abc = sorted(readln()) print((abc[1] + abc[0] - 1) * (abc[2] + abc[0] - 1) - (abc[0] - 1) * abc[0]) ```
23_A. You're Given a String...
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2). Input The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-...
```python s = input() k = [] for i in range(len(s)): for j in range(i+1,len(s)+2): x = s[i:j] for t in range(i+1,len(s)): if x == s[t:t+j-i]: k += [j-i] print(max(k) if k != [] else 0) ```
313_D. Ilya and Roads
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right. Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single Zoo...
```python """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlin...
336_A. Vasily the Bear and Triangle
Vasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you t...
```python x,y=map(int,input().split()) w = abs(x)+abs(y) if x<0: if y<0: print(-w,0,0,-w) else: print(-w,0,0,w) else: if y<0: print(0,-w,w,0) else: print(0,w,w,0) ```
359_B. Permutation
A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n...
```python n,k = list(map(int, input().split())) A = [i for i in range(0, (2*n)+1)] for i in range(1,k+1): A[2*i], A[2*i-1] = A[2*i-1], A[2*i] print(" ".join(map(str, A[1:]))) ```
382_A. Ksenia and Pan Scales
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium. The scales is in equilibrium ...
```python nm = list(map(str, input().split("|"))) s = list(input()) n = nm[0] m = nm[1] while s: if len(n)<=len(m): n = n + s.pop(0) else: m = m + s.pop(0) if len(n) == len(m): print(n + "|" + m) else: print("Impossible") ```
430_A. Points and Segments (easy)
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct points and m segme...
```python n, m = map(int, input().split()) t = list(enumerate(list(map(int, input().split())))) t.sort(key = lambda x: x[1]) p = ['0'] * n for i, x in t[:: 2]: p[i] = '1' print(' '.join(p)) ```
452_D. Washer, Dryer, Folder
You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before i...
```python k, na, nb, nc, ta, tb, tc = list(map(int, input().split())) from collections import deque a = deque() b = deque() c = deque() for i in range(na): a.append(0) for i in range(nb): b.append(0) for i in range(nc): c.append(0) t = 0 for i in range(k): vr = max(a[0], b[0] - ta, c[...
475_B. Strongly Connected City
Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traff...
```python import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 #def input(): return sys.stdin.readline().strip() input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ ilele = l...
499_B. Lecture
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
```python l = [int(x) for x in input().split()] n = l[0] m = l[1] dic = {} for i in range(0, m): lis = [x for x in input().split()] if len(lis[1]) < len(lis[0]): dic[lis[0]] = lis[1] dic[lis[1]] = lis[1] else: dic[lis[0]] = lis[0] dic[lis[1]] = lis[0] lis1 = [x for x in input...
522_C. Chicken or Fish?
Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food. The flight menu has k dishes in t...
```python t = int(input()) for j in range(t): e = input() m, k = map(int, input().split()) arr = [int(i) for i in input().split()] sum, bfail = [0] * k, [0] * k ffail, undef = -1, 0 used = [False] * k ubfail = 0 for i in range(m - 1): c, ns = map(int, input().split()) if ...
549_E. Sasha Circle
Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has n points, Sasha — m. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that ...
```python nm = input() nOm = nm.split() n = int(nOm[0]) m = int(nOm[1]) a = b = [] for i in range(0, n): a.append(input()) for i in range(0, m): b.append(input()) if(n == 2 and m == 2 and a[0] == '-1 0') or (n == 2 and m == 3 and a[0] == '-1 0') or (n == 3 and m == 3 and a[0] == '-3 -4') or ( n == 1000 and m == 10...
598_B. Queries on a String
You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given. One operation of a cyclic shift (rota...
```python s = input() for i in range(int(input())): l, r, k = map(int, input().split()) k %= r - l + 1 s = s[:l-1] + s[r-k:r] + s[l-1:r-k] + s[r:] print(s) ```
667_B. Coat of Anticubism
<image> As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to tran...
```python n, l = int(input()), list(map(int, input().split())) print(2 * max(l) - sum(l) + 1) ```
734_B. Anton and Digits
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
```python k2,k3,k5,k6=input().split() k2,k3,k5,k6=int(k2),int(k3),int(k5),int(k6) x=min(k2,k5,k6) #print(x) k2=k2-x k5=k5-x k6=k6-x y=min(k3,k2) print(256*x+32*y) ```
758_B. Blown Garland
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland. Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is workin...
```python #in the name of god #Mr_Rubick and sepanta s=input() mp=[0,0,0,0] for i in range(len(s)): m=i%4 if s[i]=='R':r=m if s[i]=='B':b=m if s[i]=='Y':y=m if s[i]=='G':g=m if s[i]=='!':mp[m]=mp[m]+1 print (mp[r],mp[b],mp[y],mp[g]) ```
802_N. April Fools' Problem (medium)
The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed. The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has...
```python from collections import deque from heapq import heappop, heappush class Edge(object): __slots__ = ('x', 'y', 'cap', 'cost', 'inv') def __repr__(self): return '{e.x}-->{e.y} ({e.cap} , {e.cost})'.format(e=self) class MCFP(list): def add(G, x, y, cap, cost): n = max(x, y) + 1 ...
849_C. From Y to Y
From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t...
```python from math import sqrt def readln(): return map(int, input().rstrip().split()) def possible(n): return n * (n + 1) // 2 charset = 'abcdefghijklmnopqrstuvwxyz' ci = 0 n = int(input()) rs = [] while n > 0: for i in range(int(sqrt(n) + 1), 0, -1): if n >= possible(i): n -= possible(i...
919_A. Supermarket
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that a yuan for b kilos (You don't need to care about what "yuan" is), the same as a/b yuan for a kilo. Now imagine you'd like ...
```python pointer = 0 lst = [0, 0] n, m = list(map(int, input().split())) for i in range(n): a, b = list(map(int, input().split())) if (pointer == 0): lst[0], lst[1] = a, b pointer+=1 if ((m*lst[0])/lst[1]) > ((m*a)/b): lst[0], lst[1] = a, b print((m*lst[0])/lst[1]) ```
96_C. Hockey
Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin ...
```python n= int(input())#how many word b = [] for i in range(n): b.append(input())# put the word in a list w = input()#what we whant to change let = input()#which we change in to bad=[] for i in range(len(w)): bad.append(True) for i in range(len(w)): mx = 0 for j in range(n): if w[i:].lower()...
994_C. Two Squares
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ...
```python mp=[[0 for i in range(205)]for j in range(205)] ax1,ay1,ax2,ay2,ax3,ay3,ax4,ay4=map(int,input().split()) bx1,by1,bx2,by2,bx3,by3,bx4,by4=map(int,input().split()) ax1+=100;ay1+=100;ax2+=100;ay2+=100;ax3+=100;ay3+=100;ax4+=100;ay4+=100 bx1+=100;by1+=100;bx2+=100;by2+=100;bx3+=100;by3+=100;bx4+=100;by4+=100 x1=m...
p02635 AtCoder Grand Contest 046 - Shift
Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S between 0 and K times (inclusive): * Choose a pair of integers i, j (1\leq i < j\leq |S|) such that the i-th and j-th characters of S are `0` and `1`, respectively. Re...
```python s,k = input().split() mod = 998244353 k = int(k) k = min(300,k) raw = [0] l = len(s) for i in range(l): if s[i] == '0': raw.append(0) else: raw[-1] += 1 #print(raw) now = [[0 for _ in range(k+1)] for _ in range(k+1)] l = len(raw) raw.reverse() #print(raw) now[0][0] = 1 for x in raw: last = now[:...
p02766 AtCoder Beginner Contest 156 - Digits
Given is an integer N. Find the number of digits that N has in base K. Constraints * All values in input are integers. * 1 \leq N \leq 10^9 * 2 \leq K \leq 10 Input Input is given from Standard Input in the following format: N K Output Print the number of digits that N has in base K. Examples Input 11 2 O...
```python N,K=map(int,input().split()) x=0 while K**x<=N: x=x+1 print(x) ```
p02901 AtCoder Beginner Contest 142 - Get Everything
We have N locked treasure boxes, numbered 1 to N. A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times. Find the minimum cost required to unlock all the treasure boxes....
```python N,M=map(int,input().split()) A=[0]*M keys=[0]*M for i in range(M): a,b=map(int,input().split()) A[i]=a c=list(map(int,input().split())) for j in range(len(c)): keys[i]|=1<<(c[j]-1) INF=10**9+1 dp=[INF]*(2**N) dp[0]=0 for i in range(len(keys)): for j in range(len(dp)-1,-1,-1): if dp[j]!=...
p03036 AtCoder Beginner Contest 127 - Algae
The development of algae in a pond is as follows. Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds: * x_{i+1} = rx_i - D You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order. Constraints * 2 ≤ r ≤ 5 * 1 ≤ D...
```python a,b,c=(int(i) for i in input().split()) for i in range(10): c=a*c-b print(c) ```
p03177 Educational DP Contest - Walk
There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N. For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j. If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not. Find ...
```python mod = 10**9+7 n, K = map(int, input().split()) a = [[int(x) for x in input().split()] for _ in range(n)] A = [a] i = 1 while 2**i <= K: mtrix = [] for j in range(n): raw = [] for l in range(n): tmp = 0 for k in range(n): tmp += A[-1][j][k] * A[...
p03325 AtCoder Beginner Contest 100 - *3 or /2
As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}. Snuke, an employee, would like to play with this sequence. Specifically, he would like to repeat the following operation as many times as possible: For every i satisfy...
```python _=input();print(sum(map(lambda x:(bin(int(x))[:2:-1]+"1").index("1"),input().split()))) ```
p03479 AtCoder Beginner Contest 083 - Multiple Gift
As a token of his gratitude, Takahashi has decided to give his mother an integer sequence. The sequence A needs to satisfy the conditions below: * A consists of integers between X and Y (inclusive). * For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i. Find the maximum possible ...
```python X, Y = map(int,input().split()) n = 1 while 2*X <= Y: X *= 2 n += 1 print(n) ```
p03644 AtCoder Beginner Contest 068 - Break Number
Takahashi loves numbers divisible by 2. You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique. Here, the number of times an integer can be divisible by 2, is how many times the integer can...
```python N=int(input()) print(1<<N.bit_length()-1) ```
p03802 AtCoder Regular Contest 069 - Flags
Snuke loves flags. Snuke is placing N flags on a line. The i-th flag can be placed at either coordinate x_i or coordinate y_i. Snuke thinks that the flags look nicer when the smallest distance between two of them, d, is larger. Find the maximum possible value of d. Constraints * 2 ≤ N ≤ 10^{4} * 1 ≤ x_i, y_i ≤ 10^...
```python import sys INF = 1 << 60 MOD = 10**9 + 7 # 998244353 sys.setrecursionlimit(2147483647) input = lambda:sys.stdin.readline().rstrip() def SCC(E): n = len(E) rev = [[] for _ in range(n)] for v in range(n): for nv in E[v]: rev[nv].append(v) used = [0] * n order = [] f...
p03970 CODE FESTIVAL 2016 qual B - Signboard
CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard. He intended to write `CODEFESTIVAL2016` on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length. So Mr. Takahashi decided to perform an operation that replaces a ce...
```python s = input() t = 'CODEFESTIVAL2016' ans = 0 for i, j in zip(s, t): if i != j: ans += 1 print(ans) ```
p00059 Intersection of Rectangles
There are two rectangles whose bases are parallel to the x-axis. Read the lower left coordinates (xa1, ya1) and upper right coordinates (xa2, ya2) of rectangle A, the lower left coordinates (xb1, yb1) and upper right coordinates (xb2, yb2) of rectangle B, and rectangle A and B Create a program that outputs YES if there...
```python import sys for x in sys.stdin: a,b,c,d,e,f,g,h=map(float,x.split()) print(['YES','NO'][c<e or g<a or d<f or h<b]) ```
p00190 Eleven Puzzle
Taro is very good at 8 puzzles and always has his friends sort them out during breaks. At that time, my friend asked me, "Can you solve more complicated puzzles?", But I have never done other puzzles. Apparently the friend made 11 puzzles by himself. The puzzle has the following shape. <image> 11 The puzzle is done ...
```python from heapq import heappush, heappop comp = [(1, 1), (2, 1), (3, 1), (0, 2), (1, 2), (2, 2), (3, 2), (4, 2), (1, 3), (2, 3), (3, 3)] numbers = range(11) zeros = (11, 12) def manhattan(v1, v2): x1, y1 = v1 x2, y2 = v2 return abs(x2 - x1) + abs(y2 - y1) def heuristic(state): return sum...
p00345 Irreducible Fractionalization
Of the real numbers, those with a circular decimal part and those with a finite number of digits can be expressed as fractions. Given a real number that can be represented by a fraction, write a program that outputs an irreducible fraction equal to that real number (a fraction that cannot be reduced any further). ...
```python def gcd(x, y): return gcd(y, x%y) if y else x def printV(x, y): g = gcd(x, y) print(str(x//g) + "/" + str(y//g)) S = input() all = "" sub = "" p = -1 for i in range(len(S)): if S[i] == '.': o = i elif S[i] == '(': p = i sub = all elif S[i] != ')': al...
p00705 When Can We Meet?
The ICPC committee would like to have its meeting as soon as possible to address every little issue of the next contest. However, members of the committee are so busy maniacally developing (possibly useless) programs that it is very difficult to arrange their schedules for the meeting. So, in order to settle the meetin...
```python from collections import defaultdict def main(n, m): d = defaultdict(int) for _ in range(n): M = list(map(int, input().split())) for num, i in enumerate(M): if num == 0: continue d[i] += 1 ans = 10**20 for key, value in d.items(): if value > m: ...
p01561 A Two Floors Dungeon
It was the last day of the summer camp you strayed into the labyrinth on the way to Komaba Campus, the University of Tokyo. The contest has just begun. Your teammates must impatiently wait for you. So you have to escape from this labyrinth as soon as possible. The labyrinth is represented by a grid map. Initially, each...
```python from collections import deque import sys def main(): readline = sys.stdin.readline write = sys.stdout.write W, H = map(int, readline().split()) MP = [readline() for i in range(H)] A = [[-1]*W for i in range(H)] B = [[-1]*W for i in range(H)] C = [[0]*W for i in range(H)] SW0 = ...
p01723 Ordering
There are N towers in the town where Ikta lives. Each tower is given a different number from 0 to N-1, and the tower with number i is called tower i. Curious Ikta was interested in the height of the N towers and decided to make a table T showing the magnitude relationship between them. T has N × N elements, and each el...
```python import sys readline = sys.stdin.readline write = sys.stdout.write from collections import deque def solve(): MOD = 10**9 + 7 N = int(readline()) dp0 = [[[0]*(N+1) for i in range(N+1)] for j in range(N+1)] dp0[0][0][0] = 1 for c in range(1, N+1): for a in range(N+1): ...
p01996 Test
problem $ M $ students will be tested in a classroom with $ N $ seats in a straight line. Seats are numbered $ 1 \ dots N $ from the front, and $ 1 $ per seat can seat $ 1 $ students. Now each student is sitting in the $ A_1, \ dots, A_M $ seats. To start the test, the following conditions must be met: * $ 1 \ dots...
```python n,m = map(int, input().split()) a = list(map(int, input().split())) num = m for i in range(m): if a[i] <= m: num -= 1 print(num) ```
p02283 Binary Search Tree I
Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to sat...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 8 insert 30 insert 88 insert 12 insert 1 insert 20 insert 17 insert 25 print output: in_order + pre_order 1 12 17 20 25 30 88 30 12 1 20 17 25 88 def pre_order(node): if node is not None: print('', node.data, end='') pre_order(nod...
p02430 Enumeration of Combinations
Print all combinations which can be made by $k$ different elements from $0, 1, ..., n-1$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a combination is calculated by bitwise OR of the selected elements. Constraints *...
```python from itertools import combinations n, k = map(int, input().split()) a = [i for i in range(n)] rs = [] for c in combinations(a, k): tmp = sum(1 << i for i in c) rs.append([tmp, *c]) for ans in sorted(rs): print(str(ans[0]) + ":", *ans[1:]) ```
101_B. Buses
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they f...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from bisect import bisect_left as bt def main(): mod = 10**9+7 n,m = map(int,input().split()) jump,x = [],[] for i in range(m): s,e = map(int,input().split()) jump.append...
1065_E. Side Transmutations
Consider some set of distinct characters A and some string S, consisting of exactly n characters, where each character is present in A. You are given an array of m integers b (b_1 < b_2 < ... < b_m). You are allowed to perform the following move on the string S: 1. Choose some valid i and set k = b_i; 2. Take ...
```python n,m,a=map(int,input().split()) b=list(map(int,input().split())) for i in range(m): if i==0: diffs=[b[0]] else: diffs.append(b[i]-b[i-1]) powers=[a%998244353] for i in range(30): powers.append(powers[-1]**2%998244353) def power(x,y,binpowers): prod=1 bits=bin(y)[2:] bits...
1088_C. Ehab and a 2-operation task
You're given an array a of length n. You can perform the following operations on it: * choose an index i (1 ≤ i ≤ n), an integer x (0 ≤ x ≤ 10^6), and replace a_j with a_j+x for all (1 ≤ j ≤ i), which means add x to all the elements in the prefix ending at i. * choose an index i (1 ≤ i ≤ n), an integer x (1 ≤ x ≤...
```python prime = [] def SieveOfEratosthenes(): n = 6000 global prime prime = [True for q in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 SieveOfEratosthenes() I = input n=int(I()) ...
1107_C. Brutality
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons ...
```python # cook your dish here #import sys #sys.setrecursionlimit(10**9) ll=lambda:map(int,input().split()) t=lambda:int(input()) ss=lambda:input() lx=lambda x:map(int,input().split(x)) yy=lambda:print("YES") nn=lambda:print("NO") from math import log10 ,log2,ceil,factorial as fac,gcd,inf,sqrt,log #from itertools im...
1136_C. Nastya Is Transposing Matrices
Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task. Two matrices A and B are given, each of them has size n × m. Nastya can perform the following operation to matrix A unlimited number of times: * take any square square submatrix of A and...
```python import os from io import BytesIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline from collections import defaultdict def main(): n, m = map(int, input().split()) s1 = [defaultdict(int) for _ in range(n + m)] s2 = [defaultdict(int) for _ in range(n + m)] for s in (s1, s2): ...
1154_G. Minimum Possible LCM
You are given an array a consisting of n integers a_1, a_2, ..., a_n. Your problem is to find such pair of indices i, j (1 ≤ i < j ≤ n) that lcm(a_i, a_j) is minimum possible. lcm(x, y) is the least common multiple of x and y (minimum positive number such that both x and y are divisors of this number). Input The fi...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from array import array def main(): INF = 10**18 n = int(input()) a = list(map(int,input().split())) lim = max(a)+1 counter = array('i',[0]*lim) for i in a: counter[i] +=...
1176_E. Cover it!
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at l...
```python n, m = map(int, input().split()) g = [] for i in range(n): g.append([]) for i in range(m): u, v = map(int, input().split()) u-=1 v-=1 g[u]+=[v] g[v]+=[u] start = max(range(n), key=lambda i: len(g[i])) edges = [] vis = [False] * n q = [start] vis[start] = True while q: u = q.pop(0)...
1195_D1. Submarine in the Rybinsk Sea (easy edition)
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too. A team of SIS students is going to make a trip on a submarine....
```python n = int(input().strip()) arr = input().strip().split() digs = [] l = len(str(arr[0])) ans = 0 m = 1 for i in range(l-1, -1, -1): total = 0 for j in range(n): total += int(arr[j][i]) ans += total*n*m + total*n*(m*10) m *= 100 print(ans%998244353) ```
1253_E. Antenna Coverage
The mayor of the Central Town wants to modernize Central Street, represented in this problem by the (Ox) axis. On this street, there are n antennas, numbered from 1 to n. The i-th antenna lies on the position x_i and has an initial scope of s_i: it covers all integer positions inside the interval [x_i - s_i; x_i + s_i...
```python #!/usr/bin/python3 import os import sys def main(): N, M = read_ints() A = [tuple(read_ints()) for _ in range(N)] print(solve(N, M, A)) def solve(N, M, A): A.sort() D = {0: 0} for x, s in A: #dprint(x, s) #dprint(D) d = D.copy() for x0, c in d.item...
1277_D. Let's Play the Words?
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100". Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the ...
```python t = int(input()) for _ in range(t): n = int(input()) words = [] for i in range(n): words.append(input()) same_1 = [] same_0 = [] zero_1 = [] one_0 = [] index_zero_1 = [] index_one_0 = [] for index, w in enumerate(words): if w[0] == w[-1]: if ...
133_C. Turing Tape
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one ...
```python def obin(a): a = ord(a) text = bin(a)[bin(a).find('1'):] ntext = '0'*(8-len(text))+text return ntext def rev(a): return a[-1::-1] def revascii(char): return int(rev(obin(char)),base=2) text = input() for i in range(len(text)): if i == 0: lastele = 0 else: las...
1401_F. Reverse and Swap
You are given an array a of length 2^n. You should process q queries on it. Each query has one of the following 4 types: 1. Replace(x, k) — change a_x to k; 2. Reverse(k) — reverse each subarray [(i-1) ⋅ 2^k+1, i ⋅ 2^k] for all i (i ≥ 1); 3. Swap(k) — swap subarrays [(2i-2) ⋅ 2^k+1, (2i-1) ⋅ 2^k] and [(2i-1) ...
```python from sys import stdin REPLACE_ID = 1 REVERSE_ID = 2 SWAP_ID = 3 SUM_ID = 4 def main(): n, q = _read_ints() a = tuple(_read_ints()) requests = tuple(_read_ints() for _ in range(q)) for result in compute_requests_results(a, requests): print(result) def _read_ints(): return map(...
1424_M. Ancient Language
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book. After taking a deeper look into the contents of these pages, linguists t...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self....