name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
338_A. Quiz
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly,...
```python def chk(x): d = (m - x) // (k - 1) * k if (m - x) % (k - 1): d += 1 + (m - x) % (k - 1) if d <= n - x: return True else: return False def calc(e): if e == 1: return 2 if e & 1: d = 2 else: d = 1 f = calc(e >> 1) d = d * f % D...
384_A. Coder
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1). Iahub wants to know how many ...
```python """ ██╗ ██████╗ ██╗ ██████╗ ██████╗ ██╗ █████╗ ██║██╔═══██╗██║ ╚════██╗██╔═████╗███║██╔══██╗ ██║██║ ██║██║ █████╔╝██║██╔██║╚██║╚██████║ ██║██║ ██║██║ ██╔═══╝ ████╔╝██║ ██║ ╚═══██║ ██║╚██████╔╝██║ ███████╗╚██████╔╝ ██║ █████╔╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚════╝ """ ...
432_A. Choosing Teams
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
```python n, k = [int(x) for x in input().split()] pros = [int(x) for x in input().split()] teams=0 for i in range(n): z = pros[i]+k if z <= 5: teams+=1 print(int(teams/3)) ```
454_C. Little Pony and Expected Maximum
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game. The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, ...
```python n,m = map(int, input().split()) s=0 for i in range(n): s+=(i+1)*(pow((i+1)/n,m)-pow(i/n,m)) print(s) ```
477_A. Dreamoon and Sums
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a]. By <image> we denote the quotient of integer division of...
```python import sys import math MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 MODMAX = 1000000007 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().r...
4_B. Before an Exam
Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, th...
```python def print_arr(arr): for a in arr: print(a, end=' ') def solution(): d, hr = input().split() d, hr = int(d), int(hr) intervals = [] first = [] for _ in range(d): vmin, vmax = input().split() vmin, vmax = int(vmin), int(vmax) intervals.append((vmin, vm...
525_A. Vitaliy and Pie
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ro...
```python n = int(input()) knowledge = input() count = 0 keyHash = {} for i in range((2*n) -2): if i%2 == 0: key = knowledge[i] if key in keyHash: keyHash[key]+=1 else: keyHash[key] = 1 else: door = knowledge[i] reqKey = chr(ord(door)+ 32) if reqKey i...
550_B. Preparing Olympiad
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made. A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must b...
```python vet = [] aux = [] cont = 0 def fa(i, f): global aux, cont if i<=f: aux.append(vet[i]) #print(aux, menor, sum(aux), maior, max(aux), min(aux), diff) if len(aux) >=2 and menor<=sum(aux)<=maior and max(aux) - min(aux)>=diff: #print('Entrei', aux) cont+=1 ...
577_C. Vasya and Petya's Game
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number. Petya can ask questions like: "Is the unknown number divisible by number y?". The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no ...
```python def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes n = int(input()) l = get_primes(n+1) ans = [] for x in l: p = x while(p<=n): ...
59_A. Word
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
```python n = input() a=0 b=0 for i in n: if(i.isupper()): a+=1 else: b+=1 if(a>b): print(n.upper()) else: print(n.lower()) ```
641_D. Little Artem and Random Variable
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them. Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and dif...
```python n = int(input()) M = list(map(float, input().split())) m = list(map(float, input().split())) a = [] sa = [0] b = [] sb = [0] for i in range(0, n): p = sa[i] - sb[i] - M[i] - m[i] q = M[i] - sa[i]*(M[i] + m[i]) d = p*p - 4*q if d < 0: d = -d a.append((-p + (d ** 0.5))/2) b.appe...
66_B. Petya and Countryside
Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed h...
```python num = input() sec = list(map(int, input().split(' '))) ans = 0 def check(index): total = 1 #print(sec[index]) for i in range(len(sec)): #print(i) if index-i-1 < 0: break if sec[index-i-1] <= sec[index-i]: #print(i) total = total +1 ...
715_D. Create a Maze
ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of n × m rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is den...
```python corr = lambda x, y: 1 <= x <= n and 1 <= y <= m T = int(input()) a = [] while T: a.append(T % 6) T //= 6 L = len(a) n = m = L * 2 + 2 ans = [(1, 2, 2, 2), (2, 1, 2, 2)] f = [[1] * 9 for i in range(7)] f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0 f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0 p = [0...
736_A. Tennis Championship
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately. Organizers are stil...
```python n = int(input()) an = 0 a = 1 b = 0 c = 2 while(n >= c): b = a a = c c = a + b an+=1 print(an) ```
760_A. Petr and a calendar
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: <image> Petr ...
```python def read_input(): line = input().strip().split() m = int(line[0]) week = int(line[1]) days31 = {1,3,5,7,8,10,12} if m == 2: days = 28 elif m in days31: days = 31 else: days = 30 z = (days + week - 1) return z//7 if z % 7 == 0 else z//7 + 1 if __name...
804_B. Minimum number of steps
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7...
```python MOD = 10**9 + 7 s = input() bcount, count = 0, 0 for c in reversed(s): if c == 'b': bcount += 1 else: count += bcount bcount *= 2 if bcount > 2**62: bcount %= MOD print(count % MOD) ```
82_A. Double Cola
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
```python n=int(input()) #L=["Sheldon","Leonard","Penny","Rajesh","Howard"] i=1 val=5 while n>val: if i%2==0 or i==1: n=n-5*i val=2*val i=2*i if 1<=n<=i: print("Sheldon") elif i<=n<=2*i: print("Leonard") elif 2*i<=n<=3*i: print("Penny") elif 3*i<=n<=4*i: print("Rajesh") elif 4*i<=n<=5*i: print("Howard") ...
850_C. Arpa and a game with Mojtaba
Mojtaba and Arpa are playing a game. They have a list of n numbers in the game. In a player's turn, he chooses a number pk (where p is a prime number and k is a positive integer) such that pk divides at least one number in the list. For each number in the list divisible by pk, call it x, the player will delete x and a...
```python import sys input = sys.stdin.buffer.readline from collections import Counter games = Counter() # prime : bitmask of if that power of the prime exists def add_primes(a): i = 2 while i*i <= a: cnt = 0 while a % i == 0: a //= i cnt += 1 if cnt: ...
899_D. Shovel Sale
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs. Visitors are more likely to buy a pair of shovels if their total cost ends with severa...
```python n = int(input()) if n < 5: print((n*(n-1))//2) else: x = n+n-1 if str(x).count('9') == len(str(x)): print(1) else: ans = 0 x = len(str(x)) x = x-1 z = 10**x y = int('9'*x) while y <= (n+(n-1)): if n >= y: ans +...
948_C. Producing Snow
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden. Each day, every pile w...
```python import heapq heap = [] n = int(input()) V = list(map(int, input().split())) T = list(map(int, input().split())) tmp = 0 for i in range(n): ans = 0 heapq.heappush(heap, tmp+V[i]) while len(heap) and heap[0]<=tmp+T[i]: ans += heapq.heappop(heap)-tmp tmp += T[i] ans += T[i]*len(heap) ...
976_C. Nested Segments
You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj. Segment [l1, r1] lies within segment [l2, r2] iff l1 ≥ l2 and r1 ≤ r2. Print indices i and j. If there are multiple answers, print a...
```python n = int(input()) otr = [tuple(map(int, input().split())) for i in range(n)] left = sorted(otr, key=lambda x: (x[0], x[1])) for i, el in enumerate(left[1:]): one, two = left[i], el if one[0] == two[0]: print(f'{otr.index(one) + 1} {n - otr[::-1].index(two)}') exit() elif one[1] ...
996_A. Hit the Lottery
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
```python money=int(input()) number=0 alist=[100,20,10,5,1] for i in alist: number+=money//i money=money%i print(int(number)) ```
p02647 Tokio Marine & Nichido Fire Insurance Programming Contest 2020 - Lamps
We have N bulbs arranged on a number line, numbered 1 to N from left to right. Bulb i is at coordinate i. Each bulb has a non-negative integer parameter called intensity. When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5. Initially, the intensity o...
```python n, k = map(int, input().split()) A = list(map(int, input().split())) for i in range(min(50, k)): DP = [0] * (n+1) for j in range(n): light = A[j] DP[max(0, j-light)] += 1 DP[min(n, j+light+1)] -= 1 for j in range(1, n): DP[j] += DP[j-1] A = DP[:-1] print(*A)...
p02776 AtCoder Beginner Contest 155 - Perils in Parallel
After being invaded by the Kingdom of AlDebaran, bombs are planted throughout our country, AtCoder Kingdom. Fortunately, our military team called ABC has managed to obtain a device that is a part of the system controlling the bombs. There are N bombs, numbered 1 to N, planted in our country. Bomb i is planted at the ...
```python from bisect import bisect_left, bisect_right from sys import setrecursionlimit setrecursionlimit(10 ** 6) class UnionFind: def __init__(self, size): self.data = [-1] * size def find(self, x): if self.data[x] < 0: return x else: self.data[x] = self.find...
p02911 AtCoder Beginner Contest 141 - Attack Survival
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows. A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K poi...
```python N, K, Q = list(map(int, input().split())) P = [K-Q]*N for _ in range(Q): P[int(input())-1]+=1 for p in P: print('Yes' if p>0 else 'No') ```
p03047 diverta 2019 Programming Contest - Consecutive Integers
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi. How many ways are there to choose K consecutive integers? Constraints * All values in input are integers. * 1 \leq K \leq N \leq 50 Input Input is given from Standard Input in the following format: N K Output Print the a...
```python n, m = list(map(int, input().split())) print(n-m+1) ```
p03188 AtCoder Grand Contest 030 - Coloring Torus
For an n \times n grid, let (r, c) denote the square at the (r+1)-th row from the top and the (c+1)-th column from the left. A good coloring of this grid using K colors is a coloring that satisfies the following: * Each square is painted in one of the K colors. * Each of the K colors is used for some squares. * Let us...
```python def solve(k): if k == 1: print(1) print(1) return n = ((k - 1) // 4 + 1) * 2 ans = [[0] * n for _ in [0] * n] dub = 2 * (k - n) for m in range(n * 2): l = m + 1 if m < dub else dub + (m - dub) // 2 + 1 i = m % 2 j = (m // 2 + m % 2) % n ...
p03496 AtCoder Beginner Contest 081 - Non-decreasing
Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}. He can perform the following operation any number of times: * Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y. He would like to perform this operation between 0 and 2N times (inclusive) so ...
```python N = int(input()) A = list(map(int, input().split())) mina = min(A) mini = A.index(mina) maxa = max(A) maxi = A.index(maxa) if mina >= 0: print(N-1) for i in range(N-1): print("{} {}".format(i+1, i+2)) elif maxa < 0: print(N-1) for i in range(N-1): print("{} {}".format(N-i, N-i-1)) else: if...
p03812 AtCoder Grand Contest 010 - Tree Game
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree. First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they wi...
```python import sys input = sys.stdin.readline from collections import deque n = int(input()) stone = [0]+list(map(int,input().split())) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0]*(n+1) for a,b in ab: if stone[a] < stone[b]: graph[a].append(b) deg[b] ...
p00069 Drawing Lots II
There are n vertical lines in the Amidakuji. This Amidakuji meets the following conditions. * Draw a horizontal line right next to it. Do not pull diagonally. * Horizontal lines always connect adjacent vertical lines. In other words, the horizontal line does not cross the vertical line. * For any vertical line, horizo...
```python # AOJ 0069: Drawing Lots II # Python3 2018.6.28 bal4u while True: n = int(input()) if n == 0: break m, p, d = [int(input()) for i in range(3)] m -= 1 p -= 1 a = [[] for i in range(d+1)] for i in range(d): a[i] = list(map(int, input())) s = [[0 for j in range(n)] for i in range(d+1)] s[d] = [i for i ...
p00201 Wrought Gold Master
You finally got a magic pot, an alchemy pot. You can create a new item by putting multiple items in the alchemy pot. Newly created items can also be placed in alchemy pots to make other items. A list of items needed to make an item will be called an alchemy recipe. The following three are examples of alchemy recipes. ...
```python # from pprint import pprint as pprint import copy def findrecipe(rec,ite,obj): # pprint(rec) # print("obj: ",obj) # print("=-") try: mat = rec[obj] rec2 = copy.copy(rec) del rec2[obj] price = min(ite[obj],sum([findrecipe(rec2,ite,m) for m in mat])) # pr...
p00356 Wire
I am a craftsman specialized in interior works. A customer asked me to perform wiring work on a wall whose entire rectangular surface is tightly pasted with pieces of panels. The panels are all of the same size (2 m in width, 1 m in height) and the wall is filled with an x (horizontal) by y (vertical) array of the pane...
```python a, b = map(int, input().split()) cnt = 0 for x in range(0, a*2+1, 2): if((b*x) % (2*a) == 0): cnt += 1 print(a + b - cnt + 2) ```
p00715 Name the Crossing
The city of Kyoto is well-known for its Chinese plan: streets are either North-South or East-West. Some streets are numbered, but most of them have real names. Crossings are named after the two streets crossing there, e.g. Kawaramachi-Sanjo is the crossing of Kawaramachi street and Sanjo street. But there is a problem:...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False L = 0 n_map = {} def get(s): nonlocal L if s in n_map: return n_map[s] n_map[s] = L ...
p00855 Prime Gap
The sequence of n - 1 consecutive composite numbers (positive integers that are not prime and not equal to 1) lying between two successive prime numbers p and p + n is called a prime gap of length n. For example, (24, 25, 26, 27, 28) between 23 and 29 is a prime gap of length 6. Your mission is to write a program to 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 = 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...
p01118 On-Screen Keyboard
<!-- Problem B --> On-Screen Keyboard You are to input a string with an OSK (on-screen keyboard). A remote control with five buttons, four arrows and an OK (Fig. B-1), is used for the OSK. Find the minimum number of button presses required to input a given string with the given OSK. <image> Fig. B-1 Remote control...
```python # coding=utf-8 ### ### for python program ### import sys import math # math class class mymath: ### pi pi = 3.14159265358979323846264338 ### Prime Number def pnum_eratosthenes(self, n): ptable = [0 for i in range(n+1)] plist = [] for i in range(2, n+1): ...
p01417 Calender Colors
Taro is a member of a programming contest circle. In this circle, the members manage their schedules in the system called Great Web Calender. Taro has just added some of his friends to his calendar so that he can browse their schedule on his calendar. Then he noticed that the system currently displays all the schedule...
```python import itertools N,M = map(int,input().split()) src = [tuple(map(float,input().split())) for i in range(N)] if M <= 1: print(0) exit() dists = [[None for j in range(N)] for i in range(N)] for i in range(N-1): for j in range(i+1,N): l1,a1,b1 = src[i] l2,a2,b2 = src[j] dist =...
p01733 Fox Observation
Ievan Ritola is a researcher of behavioral ecology. Her group visited a forest to analyze an ecological system of some kinds of foxes. The forest can be expressed as a two-dimensional plane. With her previous research, foxes in the forest are known to live at lattice points. Here, lattice points are the points whose x...
```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 = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in ...
p01872 My Number
A: My Number-My Number- problem I'm sorry! Late late! Ah! I'm starting to work for this company I've been longing for today! Even so, I've been oversleeping since the first day ...! ?? Today is an important day when I have to tell my number to the company ...! I think everyone knows, but I'll explain my number fo...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- import array def is_valid_number(sequence): q = lambda n: (n + 1) if 1 <= n <= 6 else (n - 5) sum_pq = 0 for index in range(1, 12): sum_pq += sequence[index] * q(index) rem_pq = sum_pq % 11 check_digit = 0 if rem_pq <= 1 else (11 - ...
p02293 Parallel/Orthogonal
For given two lines s1 and s2, print "2" if they are parallel, "1" if they are orthogonal, or "0" otherwise. s1 crosses points p0 and p1, and s2 crosses points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st...
```python import math EPS = 1e-10 class Point(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, point): # + 演算子での挙動を指定 return Point(self.x+point.x, self.y+point.y) def __sub__(self, point): # - 演算子での挙動を指定 return Point(self.x-point.x, sel...
p02440 Min-Max Element
Write a program which manipulates a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ by the following operations: * min($b, e$): report the minimum element in $a_b, a_{b+1}, ..., a_{e-1}$ * max($b, e$): report the maximum element in $a_b, a_{b+1}, ..., a_{e-1}$ Constraints * $1 \leq n \leq 1,000$ * $-1,000,000,000 \leq a...
```python N = int(input()) A = list(map(int,input().split())) Q = int(input()) for _ in range(Q): q = list(map(int,input().split())) if q[0] == 0: print(min(A[q[1]:q[2]])) else: print(max(A[q[1]:q[2]])) ```
1025_G. Company Acquisitions
There are n startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup. The following steps happen ...
```python m = 1000000007 n = int(input()) a = list(map(int, input().split())) print((pow(2,n-1,m)-1 - sum(pow(2,a.count(x),m)-1 for x in set(a) if x != -1)) % m) ```
1045_I. Palindrome Pairs
After learning a lot about space exploration, a little girl named Ana wants to change the subject. Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so s...
```python # Fast IO (only use in integer input) import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline MOD1 = 100000007 MOD2 = 1000000007 evenStrDict = {} oddStrDict = {} cnt = 0 N = int(input()) for _ in range(N): p = input() countList = [0] * 26 for elem in p: if elem < 97: ...
106_C. Buns
Lavrenty, a baker, is going to make several buns with stuffings and sell them. Lavrenty has n grams of dough as well as m different stuffing types. The stuffing types are numerated from 1 to m. Lavrenty knows that he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough ...
```python from sys import stdin, setrecursionlimit def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return list(stdin.readline()[:-1]) def dp(i, rem): if rem == 0: retur...
1091_B. New Year and the Treasure Geolocation
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out. Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at hom...
```python n = int(input().strip()) xm,ym = (0,0) for i in range(2*n): x,y = list(map(int,input().strip().split())) xm+=x ym+=y print(xm//(n), ym//(n)) ```
110_E. Lucky Tree
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of...
```python from sys import stdin, stdout import re from random import randrange from pprint import PrettyPrinter pprint = PrettyPrinter(width=55).pprint def is_lucky(num): return re.fullmatch("[47]+", num) is not None gr = None def topo_order(u): res = [(u, None, None)] i = 0 while i < len(res): ...
113_B. Petr#
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings...
```python from functools import cmp_to_key def calc_lcp(s, sa): rank = [0 for _ in range(len(s))] for i in range(len(s)): rank[sa[i]] = i lcp = [0 for _ in range(len(s) - 1)] h = 0 for i in range(len(s)): if rank[i] < len(s) - 1: while max(i, sa[rank[i] + 1]) + h < len(...
1158_A. The Party and Sweets
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≤ i ≤ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i an...
```python n, m = map(int, input().split()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] a.sort() b.sort() if a[-1] > b[0]: print(-1) exit() if a[-1] == b[0]: print(sum(b) + sum(a[:-1]) * m) else: print(sum(b) + a[-1] + sum(a[:-1]) * m - a[-2]) ```
1198_F. GCD Groups 2
You are given an array of n integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one. The GCD of a group of integers is the largest non-negative integer that divides all the integers in th...
```python import sys def gcd(l): if len(l)==0: return 0 if len(l)==1: return l[0] if len(l)==2: if l[1]==0: return l[0] return gcd([l[1],l[0]%l[1]]) return gcd([gcd(l[:-1]),l[-1]]) def brute_force(l1,l2,l,sol): if len(l)==0: g1=gcd(l1) g2=g...
1215_E. Marbles
Monocarp has arranged n colored marbles in a row. The color of the i-th marble is a_i. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color). In other words, Monocarp wants to rearra...
```python import sys n = int(sys.stdin.readline().strip()) a = list(map(int, sys.stdin.readline().strip().split())) M = [[0 for i in range (0, 21)] for j in range (0, 21)] F = [0 for i in range (0, 21)] for i in range (0, n): x = int(a[i]) for j in range (0, 21): if j != x: M[j][x] = M[j][x...
1257_B. Magic Stick
Recently Petya walked in the forest and found a magic stick. Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer: 1. If the chosen number a is even, then the spell will turn it into 3a/2; 2. If t...
```python t=int(input()) s=[] a=[1,2,3] for jngg in range(0,t): x=input() xx=x.split( ) x=int(xx[0]) y=int(xx[1]) if x==y: s.append('yes') elif x in a and y in a and x!=1: s.append('yes') elif x in a and y not in a: s.append('no') elif x==1: s.append('no')...
1280_C. Jeremy Bearimy
Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign ea...
```python import sys input = sys.stdin.buffer.readline for T in range(int(input())): k = int(input()) counts = [0] * (2 * k + 1) adjacencies = [list() for i in range(2 * k + 1)] for _ in range(2 * k - 1): a, b, weight = map(int, input().split()) counts[a] += 1; counts[b] += 1 ad...
1300_B. Assigning to Classes
Reminder: the [median](https://en.wikipedia.org/wiki/Median) of the array [a_1, a_2, ..., a_{2k+1}] of odd number of elements is defined as follows: let [b_1, b_2, ..., b_{2k+1}] be the elements of the array in the sorted order. Then median of this array is equal to b_{k+1}. There are 2n students, the i-th student has...
```python import sys T = int(sys.stdin.readline().strip()) for t in range (0, T): n = int(sys.stdin.readline().strip()) a = list(map(int, sys.stdin.readline().strip().split())) a.sort() print(a[n]-a[n-1]) ```
1324_C. Frog Jumps
There is a frog staying to the left of the string s = s_1 s_2 … s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. ...
```python for i in range(int(input())): print(max(map(len,input().split("R")))+1) ```
1343_B. Balanced Array
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2). You want to construct the array a of length n such that: * The first n/2 elements of a are even (divisible by 2); * the second n/2 elements of a are odd (not divisible by 2); * all elements of a are distinct and positi...
```python if __name__ == '__main__': test_case = int(input()) for _ in range(test_case): n = int(input()) if n%4!=0: print("NO") else: print("YES") res = [] for i in range(0,n//2): res.append((i+1)*2) for i in ra...
1365_C. Rotation Matching
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
```python n=int(input()) arr1=[int(c) for c in input().split()] arr2=[int(c) for c in input().split()] dic1={} dic2={} for i in range(n): dic1[arr1[i]] = i dic2[arr2[i]] = i lshift=[0 for i in range(n)] rshift=[0 for i in range(n)] lcount={} rcount={} for i in range(n): dig=arr1[i] ind=dic2[dig] ...
1385_C. Make It Good
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k...
```python t = int(input()) for _ in range(t): n = int(input()) a = list(int(x) for x in input().split()) start = 0 end = n-1 while end>0 and a[end]<=a[end-1]: end-=1 start=end while start>0 and a[start]>=a[start-1]: start-=1 print(start) ```
1407_A. Ahahahahahahahaha
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n — length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s...
```python ##while True: ## N = int(input()) ## a = [i+1 for i in range(N)] #### a = [2, 7, 12, 3, 8] ## ## ans = 0 ## ## for i in a: ## ans ^= i ## ## print(a) ## ## x = int(input()) ## ## r = [] ## ## for i in range(len(a)): ## r.append(a[i]^x) ## ## print(r) ## ## res = ...
1474_E. What Is It?
Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation p of length n. Scientists found out, that to overcome an obstacle, the robot should make p an identity permutation (make p_i = i for all i). Unfortunately, scientists can't control the robot. Thus the only way to make p ...
```python def main(): n=int(*input().split()) L=[x for x in range(n+1)];ans=[] def swp(x,y): L[x],L[y]=L[y],L[x] swp(1,n);ans.append((1,n)) for i in range(2,(n+1)//2+1): swp(i,n);ans.append((i,n)) if not n-i+1==i: swp(n-i+1,1);ans.append((n-i+1,1)) val=sum((i-j)*(i-j) for i,j in ans) print(val) for x...
14_B. Young Photographer
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at tha...
```python #***************14B - Young Photographer***************# #author - @Divyesh Chhabra from math import * import os import random import re import sys from itertools import * n,a = map(int,input().split()) sp = [] xp = [] yp = [] f = 1 while n != 0: x,y = map(int,input().split()) if x>y: x,y = ...
156_A. Message
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string s and cut out som...
```python from sys import stdin, stdout first, second = stdin.readline().strip(), stdin.readline().strip() n, m = len(first), len(second) first = '#' * m + first + '#' * m ans = float('inf') for i in range(n + m): cnt = 0 for j in range(m): if first[i + j] != second[j]: cnt += 1 ...
177_E2. Space Voyage
The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet. The Smart Beaver is going to bring som...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def check(a,b,tar,x): ans = 0 for i in range(len(a)): ans += (a[i]*x)//b[i] if ans == tar: return 0 elif ans > tar: return 1 else: return -1 def main()...
199_B. Special Olympics
A renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine. Let us remind you that a ring is a region located between two...
```python import os import sys from io import BytesIO, IOBase from collections import Counter 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 ...
222_C. Reducing Fractions
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that t...
```python from collections import defaultdict import bisect from itertools import accumulate import os import sys import math from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() se...
246_A. Buggy Sorting
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of ...
```python def s(a): k = len(a) for i in range(k-1): for j in range(i,k-1): if a[j] > a[j+1]: a[j],a[j+1] = a[j+1],a[j] return a def main(): n = int(input()) if n <= 2: v = [-1] else: v = [int(i) for i in range(n,0,-1)] print(*v,sep = ' ') i...
271_B. Prime Matrix
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a...
```python # coding: utf-8 matrix_params = input() params = matrix_params.split(" ") rows = int(params[0]) cols = int(params[1]) initial_matrix = [] count_r = [] count_c = [] curr_row = [] def is_prime(n): if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if...
318_B. Strings of Power
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style. Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of cons...
```python from functools import reduce from operator import * from math import * from sys import * from string import * from collections import * setrecursionlimit(10**7) dX= [-1, 1, 0, 0,-1, 1,-1, 1] dY= [ 0, 0,-1, 1, 1,-1,-1, 1] RI=lambda: list(map(int,input().split())) RS=lambda: input().rstrip().split() ###########...
342_B. Xenia and Spies
Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the ...
```python R = lambda: map(int, input().split()) n, m, s, f = R() if s < f: d = 1 c = 'R' else: d = -1 c = 'L' res = "" i = 1 j = s t, l, r = R() k = 1 while j != f: if i > t and k < m: t, l, r = R() k += 1 if i == t and (l <= j <= r or l <= j + d <= r): res += 'X' else...
389_C. Fox and Box Accumulation
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For exampl...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt'...
409_F. 000001
Input The input contains a single integer a (1 ≤ a ≤ 64). Output Output a single integer. Examples Input 2 Output 1 Input 4 Output 2 Input 27 Output 5 Input 42 Output 6
```python print([0,1,1,1,2,1,2,1,5,2,2,1,5,1,2,1,14,1,5,1,5,2,2,1,15,2,2,5,4,1,4,1,51,1,2,1,14,1,2,2,14,1,6,1,4,2,2,1,52,2,5,1,5,1,15,2,13,2,2,1,13,1,2,4,267,1,4,1,5,1,4,1,50,1,2,3,4,1,6,1,52,15,2,1,15,1][int(input())]) ```
437_A. The Child and Homework
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct. Fortunately the child knows how to solve such complicated test. The chi...
```python a = input()[2:] b = input()[2:] c = input()[2:] d = input()[2:] zc = 0 z = -100 if (len(a)*2 <= len(b) and len(a)*2 <= len(c) and len(a)*2 <= len(d)) or (len(a) >= len(b)*2 and len(a) >= len(c)*2 and len(a) >= len(d)*2): zc += 1 z = 'A' if (len(b)*2 <= len(a) and len(b)*2 <= len(c) and len(b)*2 <= ...
45_C. Dancing Lessons
There are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, havi...
```python from heapq import heapify,heappush,heappop n = int(input()) sex = input() a = [int(i) for i in input().split()] cp = [] r = [] b = sex.count('B') N = min(n-b,b) for i in range(1,len(a)): if sex[i] != sex[i-1]: cp.append((abs(a[i]-a[i-1]),i-1,i)) heapify(cp) prev = [i for i in range(-1,len(sex))] ...
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that su...
```python import sys input = sys.stdin.readline n, m = map(int, input().split()) a = [] for _ in range(m): l, r, q = map(int, input().split()) l -= 1 r -= 1 a.append((l, r, q)) res = [0] * n bad = False for i in range(30): events = [0] * (n + 1) for l, r, q in a: if q & (1 << i): ...
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, tha...
```python def main(): n, m = map(int, input().split()) n += 1 cluster, dest, avail, ab = list(range(n)), [0] * n, [True] * n, [[] for _ in range(n)] def getroot(x): while x != cluster[x]: x = cluster[x] return x def setroot(x, r): if r < x != cluster[x]: ...
52_A. 123-sequence
There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other. Input The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence o...
```python from collections import deque from math import ceil,floor,sqrt,gcd def ii(): return int(input()) def mi(): return map(int,input().split()) def li(): return list(mi()) def si():return input() n=ii() a=li() m={} for i in a: if i not in m: m[i]=1 else: m[i]+=1 b=[] for i in m.keys(): ...
555_C. Case of Chocolate
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom. A bar of chocolate can be presented as an n × n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are ...
```python import sys from bisect import bisect def input(): return sys.stdin.readline().strip() def solve(): n, q = map(int, input().split()) was = set() Q = [None]*q all = [0]*(2*q) for i in range(q): x, y, t = input().split() x, y = int(x), int(y) Q[i] = (x, y, t) all[2*i] = x all[2*i+1] = y all.so...
581_B. Luxurious Houses
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row. Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all...
```python n = int(input()) hs = list(map(int, input().split())) maxx = 0 ans = [] for h in reversed(hs): if h > maxx: ans.append(0) else: ans.append(maxx-h+1) maxx = max(maxx, h) print(' '.join(map(str, reversed(ans)))) ```
603_A. Alternative Thinking
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise. However, all is not...
```python input() a = input() s = [] for c in a: if not s or s[-1][0] != c: s.append([c, 1]) else: s[-1][1] += 1 s2 = sorted(s, key=lambda x: x[1]) delta = 0 if s2[-1][1] >= 3 or len(s2) > 1 and s2[-2][1] >= 2: delta = 2 elif s2[-1][1] >= 2: delta = 1 print(len(s) + delta) ```
625_D. Finals in arithmetic
Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder. Let's denote a flip operation of an integer as follows: number is considered...
```python def digits(n): rd = [] while n: n, d = divmod(n, 10) rd.append(d) return list(reversed(rd)) def _ifs(dn, i, j, ci, cj, al, ar): while i < j: di = dn[i] + 10*ci dj = dn[j] - cj for (ci, cj) in ((0, 0), (0, 1), (1, 0), (1, 1)): d = di - ci ...
699_A. Launch of Collider
There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dista...
```python import sys def main(arr): curr = None m = float("inf") for d, pos in arr: if d == 'L': if curr is not None: m = min(m, pos - curr) elif d == 'R': curr = pos print(m // 2 if m != float("inf") else -1) if __name__ == "__main__": arr =...
71_C. Round Table Knights
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood. Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights ...
```python def gen_prime(n): prime = [] prime.append(2) prime.append(3) prime.append(4) for i in range(5, n+1): div = False for j in prime: if not i%j: div = True break if not div: prime.append(i) return prime n = int(input()) prime = gen_prime(n) prime = prime[1:] prime.append(n) a = [int(...
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different...
```python '''plan noticed that if both upperle ''' from sys import stdin, stdout # n = int(stdin.readline().rstrip()) # n = int(input()) all_lines = stdin.read().split('\n') stdout.write('YES\n') for line in all_lines[1:-1]: x1, y1, x2, y2 = (int(x) % 2 for x in line.split()) num = 2 * x2 + y2 + 1 # st...
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as...
```python n=int(input()) l=list(map(int,input().split())) ma=0 p1=0 p2=0 for i in range(n-1) : if (i+1)%2!=0 : p1=p1+abs(l[i]-l[i+1]) p2=p2-abs(l[i]-l[i+1]) if p2<0 : p2=0 ma=max(p1,ma) else : p2=p2+abs(l[i]-l[i+1]) p1=p1-abs(l[i]-l[i+1]) if p1...
809_C. Find a car
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help. Form...
```python mod = 1000000007 def sum(x,y,k,add) : if k<add:return 0 up=x+add if up>k:up=k add=add+1 return y*(((add+up)*(up-add+1)//2)%mod)%mod def solve(x,y,k,add=0) : if x==0 or y==0:return 0 if x>y:x,y=y,x pw = 1 while (pw<<1)<=y:pw<<=1 if pw<=x:return (sum(pw,pw,k,add)+sum(pw,x...
834_A. The Useless Toy
<image> Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of carame...
```python a, b = input().split() t = int(input()) d = dict() d["^"] = 0 d[">"] = 1 d["v"] = 2 d["<"] = 3 a, b = d[a], d[b] t = t % 4 if t == 2 or t == 0: print("undefined") else: if t == 1: if (b-1) % 4 == a: print("CW".lower()) else: print("CCW".lower()) elif t ==...
854_D. Jury Meeting
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for...
```python R=lambda :map(int,input().split()) n,m,k=R() F,T=[],[] ans=int(1e12) for i in range(m): d,f,t,c=R() if f:F.append((d,f,c)) else:T.append((-d,t,c)) for p in [F,T]: cost=[ans]*(n+1) s=n*ans q=[] p.sort() for d,t,c in p: #print(p) if c<cost[t]: #print(c...
879_B. Table Tennis
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner. For each of the p...
```python n,k=[int(i) for i in input().split()] a=[int(i) for i in input().split()] d=a[0] t=0 h=0 for i in range(1,n): if d>a[i]: t+=1 if t>=k: print(d) h=1 break else: t=1 d=a[i] if h==0: print(max(a)) ```
902_D. GCD of Polynomials
Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way: <image> This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder o...
```python class polynomial: def __init__(self, data): self.data = data def __lshift__(self, x): return polynomial([0] * x + self.data) def __len__(self): return len(self.data) def __sub__(self, other): newData = [y - x for y, x in zip(self.data, other.data ...
954_A. Diagonal Walking
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible. In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an...
```python n = int(input()) s = str(input()) l = len(s) prev = ''; for i in s: if prev=='': prev = i continue if (i=='U' and prev =='R') or (i=='R' and prev =='U'): l=l-1 prev = '' else: prev = i print(l) ```
p02543 ACL Contest 1 - Keep Distances
There are N points on a number line, i-th of which is placed on coordinate X_i. These points are numbered in the increasing order of coordinates. In other words, for all i (1 \leq i \leq N-1), X_i < X_{i+1} holds. In addition to that, an integer K is given. Process Q queries. In the i-th query, two integers L_i and R...
```python import sys readline = sys.stdin.buffer.readline n,k = map(int,readline().split()) vs = list(map(int,readline().split())) L=18 xid=[0]*(n*L) xsum=[0]*(n*L) yid=[0]*(n*L) ysum=[0]*(n*L) j=n for i in reversed(range(n)): while i<j and vs[i]+k<=vs[j-1]: j-=1 xid[i*L+0]=j xsum[i*L+0]=j for lv in range(1,L)...
p02674 AtCoder Grand Contest 044 - Name-Preserving Clubs
There are N people (with different names) and K clubs. For each club you know the list of members (so you have K unordered lists). Each person can be a member of many clubs (and also 0 clubs) and two different clubs might have exactly the same members. The value of the number K is the minimum possible such that the fol...
```python # # File : F.py # Author : Kazune Takahashi # Created : 5/24/2020, 3:07:25 AM # Powered by Visual Studio Code # dic = { 1: 1, 2: 1, 3: 1, 4: 7, 5: 4, 6: 1, 7: 336, 8: 384, 9: 334, 10: 220, 11: 108, 12: 36, 13: 6, 27: 976, 28: 108, 29: 4, ...
p02802 AtCoder Beginner Contest 151 - Welcome to AtCoder
Takahashi participated in a contest on AtCoder. The contest had N problems. Takahashi made M submissions during the contest. The i-th submission was made for the p_i-th problem and received the verdict S_i (`AC` or `WA`). The number of Takahashi's correct answers is the number of problems on which he received an `A...
```python N,M=map(int,input().split()) PS=[input().split() for i in range(M)] wa,ac=[0]*N,[0]*N for p,s in PS: p=int(p)-1 if s=='WA' and ac[p]==0: wa[p]+=1 elif s=='AC': ac[p]=1 for i in range(N): if ac[i]==0: wa[i]=0 print(sum(ac),sum(wa)) ```
p02938 AtCoder Beginner Contest 138 - Coincidence
Given are integers L and R. Find the number, modulo 10^9 + 7, of pairs of integers (x, y) (L \leq x \leq y \leq R) such that the remainder when y is divided by x is equal to y \mbox{ XOR } x. What is \mbox{ XOR }? The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows: * When A \mbox{ XOR } B is writte...
```python def i1(): return int(input()) def i2(): return [int(i) for i in input().split()] [l,r]=i2() z=10**9+7 dp=[[[[0 for l in range(2)]for k in range(2)]for j in range(2)]for i in range(61)] dp[60][0][0][0]=1 for n in range(60)[::-1]: lb=l>>n&1 rb=r>>n&1 for x in range(2): for y in range(2): for i in rang...
p03075 AtCoder Beginner Contest 123 - Five Antennas
In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively. Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k. ...
```python a,*_,e,k=[int(input())for x in' '*6];print([':(','Yay!'][e-a<=k]) ```
p03217 Dwango Programming Contest V - Square Rotation
Niwango-kun, an employee of Dwango Co., Ltd., likes Niconico TV-chan, so he collected a lot of soft toys of her and spread them on the floor. Niwango-kun has N black rare soft toys of Niconico TV-chan and they are spread together with ordinary ones. He wanted these black rare soft toys to be close together, so he deci...
```python n,d = map(int,input().split()) num = [[0]*d for i in range(d)] a = 0 for i in range(n): x,y = map(int,input().split()) x %=d y%=d num[x][y] += 1 a = max(a,num[x][y]) x=1 while x*x<a: x += 1 r = (x-1)*d a = x-1 dai = d-1 syo = 0 anum = [[[0]*d for i in range(d)]for i in range(3)] rui = [[[0]*(2*d+1...
p03366 AtCoder Grand Contest 023 - Go Home
There are N apartments along a number line, numbered 1 through N. Apartment i is located at coordinate X_i. Also, the office of AtCoder Inc. is located at coordinate S. Every employee of AtCoder lives in one of the N apartments. There are P_i employees who are living in Apartment i. All employees of AtCoder are now le...
```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**15 mod = 10**9+7 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()...
p03526 CODE FESTIVAL 2017 Final - Zabuton
In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of zabuton. Init...
```python N = int(input()) men = [] for _ in range(N): H,P = map(int,input().split()) men.append((H,P,H+P)) men.sort(key=lambda x: x[2]) maxH = max(men)[0] inf = maxH+1 #dp[i][j] -> i人目までみたとき、j人が座布団を積む場合の最小枚数 dp = [[-1]*(N+1) for _ in range(N+1)] dp[0][0] = 0 for i in range(1,N+1): h,p,a = men[i-1] for...
p03689 AtCoder Grand Contest 016 - +/- Rectangle
You are given four integers: H, W, h and w (1 ≤ h ≤ H, 1 ≤ w ≤ W). Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive: * The matrix has H rows and W columns. * Each element of the matrix is an integer between -10^9 and 10^...
```python #設定 import sys input = sys.stdin.buffer.readline #ライブラリインポート from collections import defaultdict #入力受け取り def getlist(): return list(map(int, input().split())) #処理内容 def main(): H, W, h, w = getlist() L = [[1] * W for i in range(H)] if h * w != 1: x = (10 ** 9 - 1) // (h * w - 1) for i in range(H): ...
p00095 Surf Smelt Fishing Contest
A smelt fishing tournament was held at Lake Hibara. The winner is the one who wins the most smelt. Create a program that reads the list of participant numbers and the number of fish caught and outputs the number of winners and the number of fish caught. If there are multiple winners, output the one with the lowest par...
```python d={} for _ in[0]*int(input()): a,v=map(int,input().split()) d.setdefault(v,[]) d[v]+=[a] m=max(d) print(min(d[m]),m) ```
p00227 Thanksgiving
As bad weather continues and vegetable prices soar, Seven-Eleven is offering customers bulk purchase sales of vegetables. The store is very busy, as you can get vegetables that are hard to find in stores at reasonable prices. One day, a group of three good friends living in the Matsunaga housing complex bloomed with a...
```python # -*- coding: utf-8 -*- """ Thanksgiving http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0227 """ import sys def solve(n, m, prices): ans = 0 for i in range(0, n, m): t = prices[i:i+m] if len(t) == m: t[-1] = 0 ans += sum(t) return ans def main(arg...
p00389 Pilling Blocks
We make a tower by stacking up blocks. The tower consists of several stages and each stage is constructed by connecting blocks horizontally. Each block is of the same weight and is tough enough to withstand the weight equivalent to up to $K$ blocks without crushing. We have to build the tower abiding by the following ...
```python n,k = map(int, input().split()) res = 0 row = 1 w = 0 while n >= row : if row*k >= w : res += 1 w += row n -= row elif n >= row+1 : row += 1 else : break print(res) ```