name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
774_J. Stepan's Series
Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum num...
```python def process(S, k): n = len(S) if k > n: return 'NO' current = 0 for i in range(n): if S[i]=='N': current+=1 if current > k: return 'NO' else: current = 0 start_work = True for i in range(k): if S[i]=='Y...
79_C. Beaver
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly. However, Ciel fee...
```python s, n = input(), int(input()) t = [input() for i in range(n)] def f(i): global t for j in range(n): if i < j: if len(t[j]) < len(t[i]) and t[j] in t[i]: return False elif j < i and t[j] in t[i]: return False return True t = [t[i] for i in range(n) if f(i)] n = len(s) r...
846_A. Curriculum Vitae
Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job. During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero)...
```python def main(): n = int(input()) games = list(map(int, input().split(' '))) result = max([games[:i].count(0) + games[i:].count(1) for i in range(n+1)]) print(result) if __name__ == "__main__": main() ```
867_C. Ordering Pizza
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices. It is known that the i-th contestant will eat si slices of pizza, and gain ai ...
```python def cns(ts,s): if ts/s==int(ts/s): return ts else: return (int(ts/s)+1)*s n,spp=[int(i) for i in input().split()] tsr=0 da=[[] for i in range(100005)] db=[[] for i in range(100005)] sl=[] for i in range(n): sl.append([int(j) for j in input().split()]) tsr+=sl[i][0] if sl[i]...
914_E. Palindromes in a Tree
You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t. A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome. For each vertex, output the number of pa...
```python import sys, os def centroid_decomp(coupl): n = len(coupl) bfs = [n - 1] for node in bfs: bfs += coupl[node] for nei in coupl[node]: coupl[nei].remove(node) size = [0] * n for node in reversed(bfs): size[node] = 1 + sum(size[child] for child in...
937_C. Save Energy!
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s...
```python k,d,t = map(int, input().split()) if k % d == 0: print(t) exit() r = k % d ot = (d-r) /2 ot += k ct = k + (d-r) cn = int(t // ot) ans = cn*ct rt = t - cn*ot if rt < k: ans += rt else: ans += k rt -= k ans += rt*2 ans = "%.10f" % float(ans) print(ans) ```
962_E. Byteland, Berland and Disputed Cities
The cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities: * the cities of Byteland, * the cities of Berland, * disputed cities. Recent...
```python def solve(length, cities): result = 0 lastP = None lastB = None lastR = None maxB = 0 maxR = 0 for idx, city in enumerate(cities): i, code = city if(code == 'B'): if(lastB != None): result += abs(i - lastB) maxB = max(maxB, abs(i - lastB)) lastB = i if(cod...
990_A. Commentary Boxes
Berland Football Cup starts really soon! Commentators from all over the world come to the event. Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be...
```python n, m, a, b = list(map(int, input().split())) k = n%m print(min(k*b, (m - k)*a)) ```
p02609 AIsing Programming Contest 2020 - Anything Goes to Zero
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0. Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n...
```python from sys import stdin import sys import itertools import array import textwrap import math N = int(input()) X = input() temp = X.count("1") t = [0, 0, 0] t[0] = int(X, 2) % (temp-1) if temp != 1 else 0 t[2] = int(X, 2) % (temp+1) cnt = 0 for i in range(N): if X[i] == "1" and temp == 1: print(0) ...
p02875 AtCoder Grand Contest 040 - Neither AB nor BA
Given is a positive even number N. Find the number of strings s of length N consisting of `A`, `B`, and `C` that satisfy the following condition: * s can be converted to the empty string by repeating the following operation: * Choose two consecutive characters in s and erase them. However, choosing `AB` or `BA` is no...
```python N = int(input()) nn = N + 10 P = 998244353 fa = [1] * (nn+1) fainv = [1] * (nn+1) for i in range(nn): fa[i+1] = fa[i] * (i+1) % P fainv[-1] = pow(fa[-1], P-2, P) for i in range(nn)[::-1]: fainv[i] = fainv[i+1] * (i+1) % P C = lambda a, b: fa[a] * fainv[b] % P * fainv[a-b] % P if 0 <= b <= a else 0 ...
p03009 diverta 2019 Programming Contest 2 - Balanced Piles
There are N squares arranged in a row, numbered 1 to N from left to right. Takahashi will stack building blocks on these squares, on which there are no blocks yet. He wants to stack blocks on the squares evenly, so he will repeat the following operation until there are H blocks on every square: * Let M and m be the m...
```python n, h, d = map(int, input().split()) MOD = 10 ** 9 + 7 fact, fact_acc = 1, 1 for i in range(2, n + 1): fact = fact * i % MOD fact_acc = (fact_acc + fact) % MOD dp = [0] * (h + 1) dp[0] = base = fact for i in range(1, h): dp[i] = base * fact_acc % MOD base = (base + dp[i]) % MOD if i >= d:...
p03149 KEYENCE Programming Contest 2019 - Beginning
You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974". Constraints * 0 \leq N_1, N_2, N_3, N_4 \leq 9 * N_1, N_2, N_3 and N_4 are integers. Input Input is given from Standard Input in the following format: N_1 N_2 N_3 N_4 Output If N_1, N_2, N_3 ...
```python n = input().split() n.sort() print("YES" if "".join(n) == "1479" else "NO") ```
p03293 AtCoder Beginner Contest 103 - String Rotation
You are given string S and T consisting of lowercase English letters. Determine if S equals T after rotation. That is, determine if S equals T after the following operation is performed some number of times: Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}. Here, |X| denotes the len...
```python s=input()*100 t=input() if t in s: print("Yes") else: print("No") ```
p03449 AtCoder Beginner Contest 087 - Candies
We have a 2 \times N grid. We will denote the square at the i-th row and j-th column (1 \leq i \leq 2, 1 \leq j \leq N) as (i, j). You are initially in the top-left square, (1, 1). You will travel to the bottom-right square, (2, N), by repeatedly moving right or down. The square (i, j) contains A_{i, j} candies. You ...
```python N=int(input()) L1=list(map(int,input().split())) L2=list(map(int,input().split())) C=[] for n in range(N): C.append(sum(L1[:n+1])+sum(L2[n:])) print(max(C)) ```
p03609 AtCoder Beginner Contest 072 - Sandglass2
We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand. How many grams of sand will the upper bulb contains after t seconds? Constraints * 1≤X≤10^9 * 1≤t≤10^9 * X and t are integers. Input The input ...
```python X,t = map(int, input().split()) print(X - t if X > t else 0) ```
p03770 AtCoder Grand Contest 012 - Colorful Balls
Snuke arranged N colorful balls in a row. The i-th ball from the left has color c_i and weight w_i. He can rearrange the balls by performing the following two operations any number of times, in any order: * Operation 1: Select two balls with the same color. If the total weight of these balls is at most X, swap the po...
```python class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) return self._parent[x] def unite(self,...
p03939 AtCoder Grand Contest 007 - Pushing Balls
There are N balls and N+1 holes in a line. Balls are numbered 1 through N from left to right. Holes are numbered 1 through N+1 from left to right. The i-th ball is located between the i-th hole and (i+1)-th hole. We denote the distance between neighboring items (one ball and one hole) from left to right as d_i (1 \leq ...
```python def solve(n, d, x): ans = 0 while n: ans += d + (2 * n - 1) * x / 2 d = ((n + 1) * d + 5 * x / 2) / n x *= (n + 2) / n n -= 1 return ans print('{:.10f}'.format(solve(*map(float, input().split())))) ```
p00031 Weight
<image> My grandmother uses a balance. The balance will balance if you place the same size on both of the two dishes, otherwise it will tilt to the heavier side. The weights of the 10 weights are 1g, 2g, 4g, 8g, 16g, 32g, 64g, 128g, 256g, 512g in order of lightness. My grandmother says, "Weigh up to about 1 kg in gr...
```python import sys l = [2 ** i for i in range(10)] for line in sys.stdin: blist = list(bin(int(line))[2:]) blist.reverse() #print(blist) anslist = [] for i in range(len(blist)): if blist[i] == "1": anslist.append(str(l[i])) print(' '.join(anslist)) ```
p00162 Hamming Numbers
The number obtained by multiplying 1 by 2, 3, 5 several times (0 or more times) is called the Hamming numbers. For example * 1 * 1 x 2 x 2 = 4 * 1 x 2 x 2 x 3 x 5 x 5 = 300 Etc. are humming numbers, but 11, 13, 14 etc. are not humming numbers. All humming numbers are divisible by a power of 60 (for example, 54 is ...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0162 """ import sys from sys import stdin from bisect import bisect_right, bisect_left from math import ceil, log input = stdin.readline def main(args): hammings = [] temp = set() for i in range(ceil(log(1e6, ...
p00489 Soccer
problem Soccer is popular in JOI, and a league match called the JOI League is held every week. There are N teams in the JOI league, numbered from 1 to N. All combinations of matches are played exactly once. In other words, N × (N -1) / 2 games are played. The outcome of each match is determined by the score of each t...
```python n = int(input()) score = [list(map(lambda x: int(x) - 1 , input().split())) for _ in range(int(n*(n-1)/2))] points = [0 for _ in range(n)] for a,b,c,d in score: if c > d: points[a] += 3 elif c < d: points[b] += 3 else: points[a] += 1 points[b] += 1 rank = sorted...
p00949 Hidden Anagrams
Example Input anagram grandmother Output 4
```python s1 = input() s2 = input() cA = ord('a') s1 = [ord(e) - cA for e in s1] l1 = len(s1) s2 = [ord(e) - cA for e in s2] l2 = len(s2) ans = 0 for l in range(1, min(l1, l2)+1): s = set() use = [0]*26 for i in range(l-1): use[s1[i]] += 1 for i in range(l-1, l1): use[s1[i]] += 1 ...
p01352 Graph Construction
There are n rabbits, one in each of the huts numbered 0 through n − 1. At one point, information came to the rabbits that a secret organization would be constructing an underground passage. The underground passage would allow the rabbits to visit other rabbits' huts. I'm happy. The passages can go in both directions,...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, K = map(int, readline().split()) ES = [list(map(int, readline().split())) for i in range(K)] emp = {} sq = int(K**.5) + 1 def root(x): if x == p[x]: return x ...
p01534 Anipero 2012
D: Anipero 2012 Anipero Summer Live, commonly known as Anipero, is the largest anime song live event in Japan where various anime song artists gather. 2D, who loves anime songs, decided to go to Anipero this year as well as last year. He has already purchased m of psyllium to enjoy Anipero. Psyllium is a stick that g...
```python INF = 10 ** 20 n, m = map(int, input().split()) dp = [[[-INF] * 9 for _ in range(m + 1)] for _ in range(n + 1)] dp[0][m][0] = 0 for i in range(n): a, b, c = map(int, input().split()) for rest in range(m + 1): for l1 in range(9): for l2 in range(min(9, rest + 1)): if l1 == 0 and l2 == 0:a...
p02116 nCm
Problem Given the integer n, output the smallest m such that nCm (the number of combinations that choose m out of n different ones) is even. Constraints The input satisfies the following conditions. * 1 ≤ n ≤ 1018 Input The input is given in the following format. n Output Output the minimum m such that nCm i...
```python n = int(input()) print((n+1) &- (n+1)) ```
p02256 Greatest Common Divisor
Write a program which finds the greatest common divisor of two natural numbers a and b Hint You can use the following observation: For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y) Constrants 1 ≤ a, b ≤ 109 Input a and b are given in a line sparated by a single space. Output Output the greatest comm...
```python import math x,y = [int(x) for x in input().split()] print(math.gcd(x,y)) ```
p02404 Print a Frame
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm. ........# ........# ........# ........# Constraints * 3 ≤ H ≤ 300 * 3 ≤ W ≤ 300 Input The input consists of multiple datasets. Each dataset consists of t...
```python while True: h, w = [int(i) for i in input().split()] if w == h == 0: break print("#" * w, end="") print(("\n#" + "." * (w - 2) + "#") * (h - 2)) print("#" * w, end="\n\n") ```
1043_C. Smallest Word
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting. Today, when IA looked at the fridge, she noticed that...
```python s = input() arr_ans = [0] * len(s) for i in range(1, len(s)): if s[i] == 'a': arr_ans[i - 1] = (arr_ans[i - 1] + 1) % 2 arr_ans[i] += 1 print(*arr_ans) ```
1066_A. Vova and Train
Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on). There are lanterns on the...
```python if __name__ == '__main__': t = input() t = int(t) while t: e, v, l, r = input().split() e = int(e) v = int(v) l = int(l) r = int(r) res = e//v if l % v != 0: st = l//v + 1 else: st = l//v en = r//v ...
1107_F. Vasya and Endless Credits
Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles. However, the local bank has n credit offers. Each offer can be described with three numbers a_i, b_i and k_i. Offers are numbered from 1 to n. If Vasya takes the i-th offer, then the bank gives him a_i bur...
```python n = int(input()) a = [tuple(map(int, input().split())) for i in range(n)] a = [(y, x, k) for x, y, k in a] a.sort(reverse=True) dp = [[-1] * (n + 1) for i in range(n)] def f(i, j): if i < 0 or j < -1: return 0 if dp[i][j] == -1: y, x, k = a[i] dp[i][j] = f(i - 1, j) + max(0, x - k * ...
1137_A. 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 import sys input=sys.stdin.buffer.readline from bisect import bisect_left n,m=map(int,input().split()) arr=[] for i in range(n): arr.append(list(map(int,input().split()))) arr_maxi=[[0 for i in range(m)] for j in range(n)] arr_mini=[[0 for i in range(m)] for j in range(n)] for i in range(n): s=sorted(...
1155_C. Alarm Clocks Everywhere
Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awak...
```python def gcd(a,b): if b==0: return a else: return gcd(b,a%b) n, m = map(int, input().split(' ')) x = list(map(int, input().split(' '))) p = list(map(int, input().split(' '))) dx = [x[i+1]-x[i] for i in range(n-1)] d = dx[0] for i in dx: d = gcd(i, d) for i in range(m): if d % p[i]...
1177_B. Digits Sequence (Hard Edition)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
```python #import sys #digit = int(sys.argv[1]) digit = int(input()) if int(digit) <= 9: print(digit) exit() start_range = 1 end_range = 9 power = 1 digit_count = 2 while not (start_range <= digit and digit <= end_range): start_range = end_range + 1 end_range = 9 * 10**power * digit_count + start_ran...
1213_B. Bad Prices
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i. Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ...
```python for _ in range(int(input())): n = int(input()) lst = list(map(int, input().split())) cnt = 0 x = lst[-1] for i in lst[:-1][::-1]: x = min((x, i)) if x < i: cnt += 1 print(cnt) ```
1236_C. Labs
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, …, the lab with the number n^2 is at the highest place. To transpor...
```python n = int(input()) a = [[] for i in range(n)] j = 0 k = 1 cnt = 0 for i in range(n): for j in range(n): cnt += 1 if (i % 2 == 0): a[j].append(cnt) else: a[-j-1].append(cnt) for i in range(n): print(*a[i]) ```
1254_B1. Send Boxes to Alice (Easy Version)
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o...
```python from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per from heapq import heapify,heappush,heappop,heappushpop input=stdin.readline R=lambda:map(int,i...
1278_A. Shuffle Hashing
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems. Polycarp decided to store the hash of the password, generated by the following algorithm: 1. take the password p, consisting of lowercase Latin letters, and shuffle the l...
```python t = int(input()) for _ in range(t): s = input() t = input() ok = False s = ''.join(sorted(s)) for i in range(len(t) - len(s) + 1): temp = ''.join(sorted(t[i:i+len(s)])) if temp == s: ok = True break if ok: print("YES") else: print("NO") ```
1321_B. Journey Planning
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som...
```python from sys import stdin, gettrace if not gettrace(): def input(): return next(stdin)[:-1] def main(): n = int(input()) bb = [int(a) for a in input().split()] seq = {} for i, b in enumerate(bb): if b - i in seq: seq[b-i] += b else: seq[b-i] =...
1340_A. 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 t=int(input()) for pp in range(0,t): n=int(input()) arr=list(map(int,input().split())) arr.append(-1) pt1=0 pt2=0 while(pt1!=n): ele=arr[pt1] if(ele==-1): break for i in range(pt1+1,n+1): if(arr[i]-ele==1): pt2=i ...
1362_A. Johnny and Ancient Computer
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
```python # from debug import debug import math t = int(input()) for ii in range(t): a, b = map(int, input().split()) if a == b: print(0) else: b, a = min(a,b), max(a,b) if a%b: print(-1) else: aa = int(math.log2(a//b)) if pow(2, aa) == a//b: c = 0 c += aa//3 aa = aa%3 c += aa//2 ...
1382_C1. Prefix Flip (Easy Version)
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
```python from collections import defaultdict as dd import sys input=sys.stdin.readline t=int(input()) while t: n=int(input()) #d=dd(int) #n,m=map(int,input().split()) #l=list(map(int,input().split())) a=list(map(int,input().strip())) b=list(map(int,input().strip())) j=n-1 ans=[] whi...
1471_A. Strange Partition
You are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their ...
```python from math import ceil t = int(input()) for _ in range(t): n,x = map(int,input().split()) a = list(map(int,input().split())) mx = 0 mn = 0 for y in a: mx += ceil(y/x) mn += y mn = ceil(mn/x) print(mn,mx) ```
1498_A. GCD Sum
The \text{gcdSum} of a positive integer is the gcd of that integer with its sum of digits. Formally, \text{gcdSum}(x) = gcd(x, sum of digits of x) for a positive integer x. gcd(a, b) denotes the greatest common divisor of a and b — the largest integer d such that both integers a and b are divisible by d. For example...
```python def gcd(a,b): # Everything divides 0 if (b == 0): return a return gcd(b, a%b) for i in range(int(input())): n=int(input()) while(True): l=list(str(n)) sum1=0 for i in l: sum1+=int(i) if(gcd(n,sum1)>1): print(n) ...
1547_E. Air Conditioners
On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 ≤ a_i ≤ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct). Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to ...
```python def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().split()) def msi(): return map(str,input().split()) def li(): return list(mi()) t=ii() for _ in range(t): s=si() n,k=mi() a=li() temp=li() ac=[] for i in range(k): ac.append([a[i],temp[i]])...
175_B. Plane of Tanks: Pro
Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He ha...
```python from collections import defaultdict from bisect import bisect_left p, n = defaultdict(int), int(input()) for i in range(n): a, b = input().split() p[a] = max(p[a], int(b)) p, n = sorted((b, a) for a, b in p.items()), len(p) t = [0] + [bisect_left(p, (p[n - 1 - n // k][0], '')) for k in [2, 5, 10, 100]...
195_C. Try and Catch
Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that. The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: 1. The try op...
```python import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printO...
219_C. Color Stripe
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells. Input The first input line contains two integ...
```python n,k=map(int,input().split()) s=input() if(k==2): #A sol1=[s[i] for i in range(n)] ans1=0 for i in range(n): if(i%2==0 and sol1[i]=="B"): ans1+=1 sol1[i]="A" elif(i%2!=0 and sol1[i]=="A"): ans1+=1 sol1[i]="B" #B so...
268_C. Beautiful Sets of Points
Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions: 1. The coordinates of each point in the set are integers. 2. For any two points from the set, the distance between them is a non-integer. Consider all poi...
```python if __name__ == '__main__': nums = input().split() n = int(nums[0]) m = int(nums[1]) k = min(m, n) + 1 print(k) for i in range(k): print(str(i) + " " + str(k-1-i)) ```
339_C. Xenia and Weights
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes ...
```python __author__ = 'ratnesh.mishra' weights = map(int, input()) weights = [cnt for cnt, x in enumerate(weights, 1) if x] m = int(input()) state = [(0, 0, 0, [])] res = "NO" while state: w, b, k, l = state.pop() if k == m: res = 'YES\n' + ' '.join(map(str, l)) break for wt in weigh...
385_C. Bear and Prime Numbers
Recently, the bear started studying data structures and faced the following problem. You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answe...
```python import math, sys input = sys.stdin.buffer.readline def ints(): return map(int, input().split()) n = int(input()) x = list(ints()) MAX = max(x) + 1 freq = [0] * MAX for i in x: freq[i] += 1 sieve = [False] * MAX f = [0] * MAX for i in range(2, MAX): if sieve[i]: continue for j in ra...
406_B. Toy Sum
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them bac...
```python import sys INF = 10**20 MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) from math import gcd from math import ceil from collections import defaultdict as dd, Counter from bisect import bisect_left as bl, bisect_right as br """ Facts and Data representation Constructive? Top bottom up down """ n, =...
433_C. Ryouko's Memory Note
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
```python def median(a): if len(a) == 0: return 0 if len(a) % 2 == 1: return a[len(a) // 2] else: return (a[len(a) // 2] + a[(len(a) // 2) - 1]) // 2 def profit(a, old_val): a.sort() med = median(a) sum_old = 0 sum_new = 0 for i in a: sum_old += abs(i - ...
478_C. Table Decorations
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color? Your task is to write a program tha...
```python a = sorted(list(map(int, input().split()))) a[2] = min(a[2], 2 * (a[0] + a[1])) print(sum(a) // 3) ```
500_E. New Year Domino
Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos User ainta, who lives in a 2D world, is going to post a video as well. There are n dominoes on a 2D Cartesian plane. i-th domino (1 ≤ i ≤ n) can be represented a...
```python ''' from bisect import bisect,bisect_left from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import *''' #------------------------------------------------------------------------ ...
526_C. Om Nom and Candies
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? <image> One day, when he came to his friend Evan, Om Nom didn't find him at h...
```python C, Hr, Hb, Wr, Wb = map(int, input().split()) ans = 0 for i in range(10 ** 5): if Wr * i <= C: ans = max(ans, Hr * i + (C - Wr * i) // Wb * Hb) for i in range(10 ** 5): if Wb * i <= C: ans = max(ans, Hb * i + (C - Wb * i) // Wr * Hr) print(ans) ```
551_D. GukiZ and Binary Operations
We all know that GukiZ often plays with arrays. Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: <image>? Here operation <image> means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equival...
```python # -*- coding: utf-8 -*- from collections import deque def calc(n, m): if n == 1: return [[1, 0], [0, 1]] a = calc(n // 2, m) if n % 2 == 0: res00 = (a[0][0] * a[0][0]) % m res00 = (res00 + a[0][0] * a[1][0]) % m res00 = (res00 + a[0][1] * a[0][0]) % m res01...
5_C. Longest Regular Bracket Sequence
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not....
```python string = input() n = len(string) stack = [] mapping = [0]*n # First we create an array where the array called mapping where the index of array # gives the index of start of opening bracket in string and the value at that index # gives the index of closing bracket for corresponding opening bracket. for idx...
622_A. Infinite Sequence
Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not d...
```python n = int(input()) from math import sqrt # Find max m such that m(m+1)/2 <= n m = int((-1 + sqrt(1 + 8*n))/2) # l is the previous range l = m * (m + 1) // 2 print(m if n == l else n - l) ```
670_D1. Magic Powder - 1
This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only. Waking up in the ...
```python n, k = input().split(" ") n, k = [int(n), int(k)] list1 = list(map(int, input().split(" "))) list2 = list(map(int, input().split(" "))) low = 0 high = 2*(10**9) while low < high: if high - low % 2 != 0: mid = low + (high - low) // 2 + 1 else: mid = low + (high - low)//2 d = k ...
737_C. Subordinates
There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate ...
```python f = lambda: map(int, input().split()) n, s = f() c = [0] * n t = list(f()) for i in t: c[i] += 1 k = t[s - 1] c[k] -= 1 d = c[0] c += [d] d += k > 0 i, j = 1, n while i < j: if c[i]: i += 1 elif c[j]: c[j] -= 1 i += 1 d += j < n else: j -= 1 print(d) ```
761_B. Dasha and friends
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation: The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you...
```python n,l = map(int,input().split()) kefa = list(map(int,input().split())) sasha = list(map(int,input().split())) diff1 = [kefa[i+1] - kefa[i] if i != n - 1 else l - kefa[-1] + kefa[0] for i in range(n) ] diff2 = [sasha[i+1] - sasha[i] if i != n - 1 else l - sasha[-1] + sasha[0] for i in range(n) ] def rot...
784_D. Touchy-Feely Palindromes
Input The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive. Output Output "Yes" or "No". Examples Input 373 Output Yes Input 121 Output No Input 436 Output Yes
```python # ⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚ # 1234567890 R = [ ("1", "' "), ("2", ": "), ("3", "''"), ("4", "':"), ("5", "'."), ("6", ":'"), ("7", "::"), ("8", ":."), ("9", ".'"), ("0", ".:"), ] s = input() for a,b in R: s = s.replace(a,b) print("Yes" if s==s[::-1] else "No") ```
805_C. Find Amir
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co...
```python print(max((int(input()) + 1) // 2 - 1, 0)) ```
830_C. Bamboo Partition
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of...
```python import itertools unfold = itertools.chain.from_iterable def jumps(a): d = speedup while d < a - 1: c = (a + d - 1) // d d = (a + c - 2) // (c - 1) yield d def calc(d): return sum(d - 1 - (i - 1) % d for i in a) def ans(): for d, pd in zip(D, D[1:]): d -= 1 ...
89_E. Fire and Ice
The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment n in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom. <image> The n-long segment is located at a distance equal exactly to...
```python n = int(input()) a = [0] * 1010 b = [0] * 2010 S = 1000000007 W=0 b = list(map(int,input().strip().split()))[:n] for i in range(0,n): a.insert(i,b[i]) while(not a[n-1]): n-=1 for w in range(0,n+1): for i in range(0,n): b[i]=a[i] for i in range(w,n): if(b[i]): b[i]-=...
977_D. Divide by three, multiply by two
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: * divide the number x by 3 (x must be divisible by 3); * multiply the number x by 2. After each operation, Polycarp writes down the result on the boar...
```python n = int(input()) li = list(map(int, input().split())) g = {} def dfs(e, v, order): if e not in v: v[e] = 1 if e % 3 == 0: if (e // 3) in g: order.append(e // 3) dfs(e // 3, v, order) if e * 2 in g: order.append(e * 2) ...
997_B. Roman Digits
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as...
```python def solve(n): s = set() for i in range(0, n + 1): for v in range(0, n - i + 1): for x in range(0, n - i - v + 1): l = n - i - v - x s.add(i + v * 5 + x * 10 + l * 50) return len(s) n = int(input()) if n < 11: print(solve(n)) else: print...
p02654 AtCoder Grand Contest 045 - Lamps and Buttons
We have N lamps numbered 1 to N, and N buttons numbered 1 to N. Initially, Lamp 1, 2, \cdots, A are on, and the other lamps are off. Snuke and Ringo will play the following game. * First, Ringo generates a permutation (p_1,p_2,\cdots,p_N) of (1,2,\cdots,N). The permutation is chosen from all N! possible permutations ...
```python def prepare(n, MOD): factorials = [1] * (n + 1) for i in range(2, n + 1): factorials[i] = factorials[i - 1] * i % MOD finvs = [1] * (n + 1) finvs[n] = pow(factorials[n], MOD - 2, MOD) for i in range(n, 1, -1): finvs[i - 1] = finvs[i] * i % MOD return factorials, finvs ...
p02783 AtCoder Beginner Contest 153 - Serval vs Monster
Serval is fighting with a monster. The health of the monster is H. In one attack, Serval can decrease the monster's health by A. There is no other way to decrease the monster's health. Serval wins when the monster's health becomes 0 or below. Find the number of attacks Serval needs to make before winning. Constrai...
```python import math A,B=map(int,input().split()) print(math.ceil(A/B)) ```
p02918 AtCoder Beginner Contest 140 - Face Produces Unhappiness
There are N people standing in a queue from west to east. Given is a string S of length N representing the directions of the people. The i-th person from the west is facing west if the i-th character of S is `L`, and east if that character of S is `R`. A person is happy if the person in front of him/her is facing the...
```python n, k = map(int, input().split()) s = input() h = sum(1 for i in range(n-1) if s[i] == s[i+1]) print(min(n-1, h+k*2)) ```
p03054 AtCoder Grand Contest 033 - LRUD Game
We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. On this grid, there is a piece, which is initially placed at square (s_r,s_c). Takahashi and Aoki will play a game, where each player has a st...
```python H, W, N = map(int, input().split()) sr, sc = map(int, input().split()) S = input() T = input() B = [1, W, 1, H] for i in range(N - 1, -1, -1): if T[i] == 'L': B[1] = min(B[1] + 1, W) if T[i] == 'R': B[0] = max(B[0] - 1, 1) if T[i] == 'U': B[3] = min(B[3] + 1, H) if T[i] == 'D': B[2] = max(B[2] - 1, 1)...
p03198 CADDi 2018 - Negative Doubling
There are N positive integers A_1, A_2, ..., A_N. Takahashi can perform the following operation on these integers any number of times: * Choose 1 \leq i \leq N and multiply the value of A_i by -2. Notice that he multiplies it by minus two. He would like to make A_1 \leq A_2 \leq ... \leq A_N holds. Find the minimu...
```python n = int(input()) a = list(map(int,input().split())) def d4(x,y): ret = 0 while x > y: y *= 4 ret += 1 return ret def cost(ls): l = len(ls) ret = [0]*l stack = [(l-1,10**18)] for i in range(l-1)[::-1]: ret[i] = ret[i+1] if ls[i] <= ls[i+1]: d = d4(ls[i+1],ls[i])-1 if d...
p03345 AtCoder Grand Contest 024 - Fairness
Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively. After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get: * Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own inte...
```python a, b, c, k = list(map(int, input().split())) ans = b-a if k%2 else a-b print(ans) ```
p03505 Code Festival Team Relay (Parallel) - Kaiden
ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is 0, and a user whose rating reaches K or higher is called Ka...
```python from decimal import * import math K,A,B=map(int,input().split()) if A>=K: print(1) elif A-B>0: print(1+math.ceil(Decimal(K-A)/Decimal(A-B))*2) else: print(-1) ```
p03666 AtCoder Grand Contest 017 - Moderate Differences
There are N squares in a row. The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty. Aohashi would like to fill the empty squares with integers so that the following condition is satisfied: * For any two adjacent squares, the (absolute) difference of the two...
```python def ascending_range(i): return (a+c*i, a+d*i) def descendable_range(i, m, M): j = n-1-i floor = b+c*j ceil = b+d*j return not (m > ceil or M < floor) def solve_local(i): return descendable_range(i, *ascending_range(i)) n, a, b, c, d = map(int, input().split()) print("YES" if any(so...
p03821 AtCoder Grand Contest 009 - Multiple Array
There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons. When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1. There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so th...
```python N = int(input()) AB = [[int(i) for i in input().split()] for _ in range(N)] s = 0 for A, B in AB[::-1] : x = (A + s + B - 1) // B s += x * B - (A + s) print(s) ```
p03988 AtCoder Grand Contest 005 - Tree Restoring
Aoki loves numerical sequences and trees. One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree. Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vert...
```python from collections import defaultdict def getlist(): return list(map(int, input().split())) #処理内容 def main(): N = int(input()) D = defaultdict(int) a = sorted(getlist()) if N == 2: if a[0] != 1 or a[1] != 1: print("Impossible") else: print("Possible") else: for i in range(N): D[a[i]] += 1...
p00076 Treasure Hunt II
As I was cleaning up the warehouse, I found an old document that describes how to get to the treasures of my ancestors. The following was written in this ancient document. 1. First, stand 1m east of the well on the outskirts of the town and turn straight toward the well. 2. Turn clockwise 90 degrees, go straight for ...
```python # AOJ 0076 Treasure Hunt II # Python3 2018.6.15 bal4u import math MAX = 1005 r, d = [0.0]*MAX, [0.0]*MAX r[1] = 1.0 for i in range(2, MAX): d[i] = d[i-1] + math.atan(1 / r[i-1]) r[i] = math.sqrt(r[i-1]**2 + 1) while True: i = int(input()) if i < 0: break print(r[i]*math.cos(d[i]), r[i]*math.sin(d[i]),...
p00208 Room Numbers of a Hospital
An architect, Devunky, who lives in Water Deven, has been asked to renovate an old large hospital. In some countries, people don't want to use numbers that are disliked as numerophobia (4 and 9 are famous in Japan). However, the room numbers in this hospital were numbered from 1 regardless of the number of numerophobi...
```python from sys import stdin l=stdin.readlines() for i in l[:-1]:print(oct(int(i))[2:].translate(str.maketrans("4567","5789"))) ```
p00368 Checkered Pattern
You have a cross-section paper with W x H squares, and each of them is painted either in white or black. You want to re-arrange the squares into a neat checkered pattern, in which black and white squares are arranged alternately both in horizontal and vertical directions (the figure shown below is a checkered patter wi...
```python is_ok = True W, H = [int(i) for i in input().split()] matrix = list() for _ in range(H): matrix.append([i for i in input().split()]) up = matrix[0] not_up = [str(int(not int(i))) for i in up] if abs(up.count("0") * 2 - W) >= 2: is_ok = False same = 1 for line in matrix[1:]: if up[0] == line[...
p00575 Social Game
Problem statement JOI decided to start a new social game from tomorrow. In this social game, you can log in up to once a day, and you will get A coins each time you log in. Also, if you log in for 7 consecutive days from Monday to Sunday, you will get an additional B coins each time. No other coins will be given. ...
```python n = [0 for i in range(3)] n = input().split() coin = int(n[2]) total = 0 count = 0 day = 0 while(total < coin): total += int(n[0]) count += 1 if(count == 7): total += int(n[1]) count = 0 day += 1 print(day) ```
p00722 Dirichlet's Theorem on Arithmetic Progressions
Good evening, contestants. If a and d are relatively prime positive integers, the arithmetic sequence beginning with a and increasing by d, i.e., a, a + d, a + 2d, a + 3d, a + 4d, ..., contains infinitely many prime numbers. This fact is known as Dirichlet's Theorem on Arithmetic Progressions, which had been conjectur...
```python MAXN = 10**6 sieve = [0]*2 + [1]*MAXN n = 2 while n*n <= MAXN: if sieve[n]: for i in range(2*n,MAXN+1,n): sieve[i] = 0 n += 1 while True: a,d,n = map(int,input().split()) if n == 0: break cnt = 0 for i in range(a,MAXN+1,d): if sieve[i]: cnt += 1...
p00993 Numbers
Given n, find n consecutive positive integers. However, all numbers must have divisors other than 1 and the number itself. Hint In Sample Output 2, 8, 9 and 10 are selected as three consecutive integers. The second and third lines output 3, as a divisor of 9, and the fourth line outputs 5, as a divisor of 10. Inpu...
```python # AOJ 1503: Numbers # Python3 2018.7.13 bal4u import sys n = int(input()) if n == 1: print(4, 2, sep='\n'); sys.exit(0) ans = 1 for i in range(2, n+2): ans *= i print(ans+2) for i in range(2, n+2): print(i) ```
p01125 Misterious Gems
From 1603 to 1867, people call that era the EDO era. EDO stands for Enhanced Driving Operation, the most advanced space navigation technology at the time, and was developed by Dr. Izy in 1603. You are a space adventurer, flying around the universe and adventuring on various planets. During that adventure, you discover...
```python #coding: utf-8 if __name__ == '__main__': while True: n = int(input()) if n == 0: break flag = [] for i in range(21): flag.append([0 for j in range(21)]) for i in range(n): x,y = map(int,input().split()) flag[x][y] = ...
p01880 Best Matched Pair
Example Input 2 1 2 Output 2
```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 = 998244353 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split...
p02017 Pray
C: Prayer (Pray) Some twins are famous for praying before the contest. There are four integers $ H, W, X, Y $, and it seems unlucky if $ H \ times W $ and $ x + y $ are both odd numbers. input Four integers $ H, W, X, Y $ are given, separated by spaces. output Output "No" if you are unlucky, or "Yes" if not. But ...
```python a,b,c,d=map(int,input().split()) print("No" if ((a*b)%2)*((c+d)%2)==1 else "Yes") ```
p02300 Convex Hull
Find the convex hull of a given set of points P. In other words, find the smallest convex polygon containing all the points of P. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees. Please note that you should find all the points of P on both corner and boundary of the convex polygon....
```python import math EPS = 1e-10 class Vector2(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, v): return Vector2(self.x+v.x, self.y+v.y) def __sub__(self, v): return Vector2(self.x-v.x, self.y-v.y) def __mul__(self, v): return Vector2(...
p02447 Sorting Pairs
Write a program which print coordinates $(x_i, y_i)$ of given $n$ points on the plane by the following criteria. 1. first by $x$-coordinate 2. in case of a tie, by $y$-coordinate Constraints * $1 \leq n \leq 100,000$ * $-1,000,000,000 \leq x_i, y_i \leq 1,000,000,000$ Input The input is given in the following form...
```python from sys import stdin n = int(stdin.readline()) l = [] for i in range(n): a,b = map(int,stdin.readline().split()) l.append([a,b]) l.sort() for i in range(n): print(f'{l[i][0]} {l[i][1]}') ```
1056_D. Decorate Apple Tree
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from 1 to n, the junction 1 is called the root. A subtree of a junction v is a set of junc...
```python n=int(input()) p=[0,0]+list(map(int,input().split()))#tomamos la entrada d=[0]*(n+1)#aki vamos a contar la cantidad d colores q necesita cada union for i in range(n,1,-1):#empezamos x las hojas hasta llegar a la raiz if d[i]==0:#si no estas visitado eres una hoja => solo necesitas un color d[i]=1 ...
1078_E. Negative Time Summation
Everyone knows that computers become faster and faster. Recently Berland scientists have built a machine that can move itself back in time! More specifically, it works as follows. It has an infinite grid and a robot which stands on one of the cells. Each cell of the grid can either be empty or contain 0 or 1. The mach...
```python def C(x, y): return x + '10' + y + 't' + y def CBF(x, y): return x + '01' + y + 't' + y Cr = C('r', 'l') Cl = C('l', 'r') Cu = C('u', 'd') Cd = C('d', 'u') CBFr = CBF('r', 'l') CBFl = CBF('l', 'r') CBFu = CBF('u', 'd') CBFd = CBF('d', 'u') def CE(x, y): return x+x+'0'+x+'1'+y+y+'10...
111_D. Petya and Coloring
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n × m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number...
```python n, m, k = [int(x) for x in input().split()] mod = int(10**9 + 7) if m == 1: print(pow(k, n, mod)) exit() ans = 0 fac = [1] ifac = [1] tav = [0] for i in range(1, max(k + 1, n + 1)): fac.append((fac[i - 1] * i) % mod) for i in range(1, min(k + 1, n + 1)): ifac.append((ifac[i - 1] * pow(i, mo...
1147_A. Hide and Seek
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order....
```python from collections import Counter nums, num_questions = map(int, input().split()) questions = list(map(int, input().split())) exist = set() things = dict(Counter(questions)) nums = nums * 3 - 2 - len(things) for i in questions: if i not in exist: exist.add(i) if things.get(i - 1): ...
1168_B. Good Triple
Toad Rash has a binary string s. A binary string consists only of zeros and ones. Let n be the length of s. Rash needs to find the number of such pairs of integers l, r that 1 ≤ l ≤ r ≤ n and there is at least one pair of integers x, k such that 1 ≤ x, k ≤ n, l ≤ x < x + 2k ≤ r, and s_x = s_{x+k} = s_{x+2k}. Find th...
```python def func(st,en): for i in range(st,en+1): for j in range(i+1,en+1 ): if (j-i+1)%2==1: if s[(i+j)//2]==s[i]==s[j]: return False #print(st, en) return True s=input().strip() c=0 n=len(s) for i in range(2,9): for j in range(len(s)): ...
1186_E. Vus the Cossack and a Field
Vus the Cossack has a field with dimensions n × m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way: 1. He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field...
```python from sys import stdin,stdout n,m,q = map(int, stdin.readline().split()) mat = [[0]*m for i in range(n)] for i in range(n): row = stdin.readline().strip() for j,c in enumerate(row): mat[i][j] = 1 if c == '1' else -1 #print(mat) def get(a,b): if a < 0 or b < 0: return 0 x = a...
1205_D. Almost All
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from ...
```python import math n = int(input()) if n == 1: print() else: edge = [list(map(int, input().split())) for i in range(1, n) ] g = {} for x, y in edge: if x not in g: g[x] = [] if y not in g: g[y] = [] g[x].append(y) g[y].appe...
1223_A. CME
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
```python # import numpy as np import array def solution(): req = int(input()) for i in range(req): count = int(input()) result = 0 if count==2: print(2) continue while count % 2 != 0 : result+=1 count+=1 print(result) ...
1248_D2. The World Is Just a Programming Task (Hard Version)
This is a harder version of the problem. In this version, n ≤ 300 000. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya beli...
```python n = int(input()) s = input() r = 0 l = n-1 root = [] buf = [] to_the_right = True for count in range(n): if to_the_right: i = r r += 1 else: i = l l -= 1 b = s[i] if b == '(': if len(buf) == 0 or buf[-1][0] != -1: buf.append([-1,-1,[]]) ...
1267_B. Balls of Buma
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls). When the ball is inserted the following happens repeatedly: if so...
```python # -*- coding: utf-8 -*- """ Created on Sat Jul 18 16:25:32 2020 @author: MridulSachdeva """ s = input() n = len(s) condensed = [] temp = s[0] count = 1 for i in range(1, n): if s[i] == temp: count += 1 else: condensed.append((temp, count)) temp = s[i] count = 1 co...
1288_D. Minimax Problem
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}. You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict #threading.stack_size...
1331_G. Lingua Romana
per nextum in unam tum XI conscribementis fac sic vestibulo perlegementum da varo. morde varo. seqis cumula varum. cis per nextum in unam tum XI conscribementis fac sic seqis decumulamenta da varo. varum privamentum fodementum da aresulto. ...
```python l = [0 for i in range(11)] for i in range(11): l[i] = int(input()) l.reverse() for i in l: a = (i ** 3) * 5 + (abs(i) ** 0.5) if a > 400: print('f(' + str(i) + ') = MAGNA NIMIS!') continue print('f(' + str(i) + ') =', format(a, '.2f')) ```
1352_B. Same Parity Summands
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
```python T = int(input()) for test in range(T): n, k = map(int, input().split()) if n % 2 != 0 and k % 2 == 0: print("NO") else: if n % 2 != 0: # Ak is odd if (n - (k-1)) > 0 and (n - (k-1)) % 2 == 1: print("YES") temp = [1 for _ in range(k-1)]+[(...