name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1428_A. Box is Pull
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will...
```python for i in range(int(input())): x1,y1,x2,y2=map(int,input().split()) q=abs(x1-x2)+abs(y1-y2) print(q if x1==x2 or y1==y2 else q+2) ```
1451_A. Subtract or Divide
Ridbit starts with an integer n. In one move, he can perform one of the following operations: * divide n by one of its proper divisors, or * subtract 1 from n if n is greater than 1. A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 2...
```python for _ in range(int(input())): k = 3 n = int(input()) if n == 1: print("0") elif n == 2: print("1") elif n == 3: print("2") elif n%2==0: print("2") else: print("3") ```
1475_A. Odd Divisor
You are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x > 1) that n is divisible by x and x is odd). For example, if n=6, then there is x=3. If n=4, then such a number does not exist. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of t...
```python test_cases = 1 test_cases = int(input()) for ttttt in range(test_cases): n = int(input()) while n%2==0: n/=2 if n==1: print("NO") else: print("YES") ```
14_D. Two Paths
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path ...
```python import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mo...
1525_A. Potion-making
You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly k\ \% magic essence and (100 - k)\ \% water. In one step, you can pour either one liter of magic essence or one liter of water i...
```python import math for i in range(int(input())): n=int(input()) a=100-n b=n if n==100: print(1) else: g=math.gcd(a,b) print(a//g+b//g) ```
156_C. Cipher
Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of somethin...
```python S, N = 2501, 101 m = 1000000007 k = 26 p = [[0] * (S + k) for i in range(N)] p[0][0] = 1 for n in range(1, N): for s in range(S): p[n][s] = (p[n][s - 1] + p[n - 1][s] - p[n - 1][s - k]) % m r = [] for j in range(int(input())): t = input() s = sum(ord(q) - 97 for q in t) print(p[len(t)]...
199_D. Jumping on Walls
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some...
```python from collections import deque l, j = [int(i) for i in input().split(' ')] wallA = list(input()) wallB = list(input()) g = {} for i in range(l): # Each 4-tuple represents: (Visited?, Current Height, Current Water Height, Drowned?) if wallA[i] == '-': g[(1,i+1)] = (-1, 0, 0, False) if wal...
222_E. Decoding Genome
Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most m different nucleotides, numbered from 1 to m. Special characteristics of the Martian DNA prevent some nucleotide pairs from followin...
```python import sys def pyes_no(condition) : if condition : print ("YES") else : print ("NO") def plist(a, s = ' ') : print (s.join(map(str, a))) def rint() : return int(sys.stdin.readline()) def rints() : return map(int, sys.stdin.readline().split()) def rfield(n, m = None) : if m == None : ...
246_C. Beauty Pageant
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants. All soldiers in the battalion have different beauty that is represented by a positive integer. The value...
```python n, k = map(int, input().split()) p = list(map(int, input().split())) p.sort() t = [[i] for i in p] for i in range(1, n): t += [t[-1] + i for i in t[: n - i]] print('\n'.join(str(len(i)) + ' ' + ' '.join(map(str, i)) for i in t[: k])) ```
271_D. Good Substrings
You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad. A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2...s|s| (where |s| is the length of string s) is string slsl + 1...sr. The substring s[l...r] is good, if among the letters sl, sl + 1, ..., sr t...
```python import collections as cc import sys input=sys.stdin.readline I=lambda:list(map(int,input().split())) S=lambda :list(input().strip()) s=S() t=S() k,=I() ans=0 prev='' ss=sorted([s[i:] for i in range(len(s))]) for j in ss: now=0 f=0 for i in range(len(j)): if i>=len(prev) or j[i]!=prev[i]: f=1 now+=t[...
295_A. Greg and Array
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di. Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, ...
```python import sys input=sys.stdin.readline n,m,k=map(int,input().split()) a=list(map(int,input().split())) query=[] times=[] x=[0]*(m+2) y=[0]*(n+2) for i in range(m): query.append(list(map(int,input().split()))) for i in range(k): times.append(list(map(int,input().split()))) for i in range(k): l,r=times...
366_A. Dima and Guards
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can b...
```python import itertools as it n = int(input()) res = None for i in range(4): a = list(map(int, input().split())) for v in list(it.product(a[:2], a[2:])): if sum(v) <= n: res = [i + 1, v[0], n - v[0]] break if res is not None: break print(-1 if res is None else '...
389_E. Fox and Card Game
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom o...
```python n = int(input()) lista = [] aux = [] somaA = 0 somaB = 0 for i in range(n): a = [int(i) for i in input().split()][1:] if len(a) > 1: somaA += sum(a[0:len(a)//2]) somaB += sum(a[-(len(a)//2):]) if len(a) % 2 == 1: aux.append(a[len(a)//2]) aux.sort(reverse=True) for i...
409_H. A + B Strikes Back
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? Input The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space. Output Output ...
```python import sys import os a,b=input().split() a=int(a) b=int(b) print(a+b) ```
437_C. The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The...
```python def mlt(): return map(int, input().split()) x, y = mlt() s = [0] + list(mlt()) res = 0 for n in range(y): a, b = mlt() res += min(s[a], s[b]) print(res) ```
506_D. Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. ...
```python #make a table n,m = map(int,input().split()) arr = [[] for i in range(n+1)] for i in range(1,m+1): l = list(map(int,input().split())) arr[l[0]].append((l[1],l[2])) arr[l[1]].append((l[0],l[2])) #dfs def dfs(a,b,k): if a == b: return True seen.append(a) for i in arr[a]: ...
52_C. Circular RMQ
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it: * inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v; * rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively). Assume segments to be c...
```python import math,sys,bisect,heapq,os from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 def input(): return sys.stdin.readline().rstrip('\r\n') #input = iter(sys.stdin.buffer.read()...
581_D. Three Logos
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no e...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output....
603_C. Lieges of Legendre
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the pow...
```python def grundy(n, k): if k % 2 == 0: if n <= 2: return n else: return n % 2 == 0 else: if n <= 4: return [0, 1, 0, 1, 2][n] elif n % 2 == 1: return 0 else: return 2 if grundy(n // 2, k) == 1 else 1 if __n...
626_A. Robot Sequence
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the sam...
```python import io import sys import time import random start = time.clock() #~ test = '''6 #~ URLLDR''' #~ test = '''7 #~ RLRLRLR''' #~ test = '''200 #~ ''' #~ for i in range(200): #~ test += random.choice("UDLR") #~ print(test) #~ test = '10 15' #~ test = '1 1000000' #28733372 #~ test = '1 11' #55 #~ test = '1...
675_B. Restoring Painting
Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 × 3, each cell contains a single integer from 1 to n, an...
```python n,a,b,c,d=map(int,input().split()) count=0 for x in range(1,n+1): y=x+b-c z=x+a-d w=y+a-d if (y>=1 and y<=n) and(z>=1 and z<=n) and (w>=1 and w<=n): count+=1 print(count*n) ```
699_C. Vacations
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
```python size = int(input()) days = [int(a) for a in input().split()] daysoff = 0 yesterday = 0 if days[0] == 0: daysoff += 1 yesterday = 0 elif days[0] == 3: yesterday = 0 else: yesterday = days[0] for i in range(1, size): if days[i] == 0: yesterday = 0 daysoff += 1 elif da...
71_E. Nuclear Fusion
There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a ...
```python numbersDict = { "1": "H", "2": "He", "3": "Li", "4": "Be", "5": "B", "6": "C", "7": "N", "8": "O", "9": "F", "10": "Ne", "11": "Na", "12": "Mg", "13": "Al", "14": "Si", "15": "P", "16": "S", "17": "Cl", "18": "Ar", "19": "K", "20": "Ca", "21": "Sc", "22": "Ti", "23": "V", "24": "Cr", "25": "Mn", "26": "Fe", "...
741_B. Arpa's weak amphitheater and Mehrdad's valuable Hoses
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if...
```python n, m, k = map(int, input().split()) a = map(int, input().split()) b = map(int, input().split()) ab = [(0, 0)] + list(zip(a, b)) l = list(range(n + 1)) def f(x): if x == l[x]: return x l[x] = f(l[x]) return l[x] for i in range(m): x, y = map(int, input().split()) x, y = f(...
765_A. Neverending competitions
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team ...
```python import sys,math from collections import deque #input = sys.stdin.buffer.readline def solve(): return; # for _ in range(int(input())): # solve() n = int(input()) h = input() cnt=0 for i in range(n): s = input() if h==s[:3] or h==s[-3:]: cnt+=1 if cnt%2==0: print("home") else: print("contest") ...
788_C. The Great Mixing
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should als...
```python ## ## ## import sys def line(): return sys.stdin.readline() def numbers(): return list(map(int, line().split())) def number(): return int(line()) adjlist = {} n, k = 0, 0 mark = [False]*2010 edges = [False]*1010 # bfs for "ssph" def bfs(s): i = 0 frontier = [s] while frontier:...
834_C. The Meaningless Game
<image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's s...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup------------------------...
855_A. Tom Riddle's Diary
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
```python l = [] for _ in range(int(input())): s = input() if s not in l: print('NO') l.append(s) else: print('YES') ```
879_D. Teams Formation
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai. Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in ...
```python def main(): _, k, m = [int(x) for x in input().split()] a = [] last = ("-1", 0) a.append(last) for ai in input().split(): if last[0] == ai: last = (ai, last[1]+1) a[-1] = last else: last = (ai, 1) a.append(last) if la...
903_A. Hungry Student Problem
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th...
```python t = int(input()) for i in range(0,t): flag = 0 x = int(input()) b = 0 temp = x while temp >= 0 : if(temp%3 == 0): flag = 1 break b = b+1 temp = x-7*b if flag == 1 : print("YES") else: print("NO") ```
925_B. Resource Distribution
One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units. In order for production to work, it is needed ...
```python def fin(c, x): return (x + c - 1) // c def ck(x, b): r = (n, n) for i in range(b, n): r = min(r, (i + fin(c[i][0], x), i)) return r def sol(r, l): if r[0] <= n and l[0] <= n and r[1] < n and l[1] < n : print("Yes") print(r[0] - r[1], l[0]- l[1]) print(' '...
954_C. Matrix Walk
There is a matrix A of size x × y filled with integers. For every <image>, <image> Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you st...
```python def main(): int(input()) a = list(map(int, input().split())) ds = [i - j for i, j in zip(a[1:], a)] dss = set(abs(x) for x in ds) if 0 in dss: return False try: dss.remove(1) except KeyError: pass if len(dss) > 1: return False if not dss: ...
980_B. Marlin
The city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon p...
```python EMPTY = "." HOTEL = "#" def main(): n, k = map(int, input().split()) print("YES") print(EMPTY * n) if k % 2 == 0: m = k // 2 s = EMPTY + HOTEL * m + EMPTY * (n - m - 1) print(s) print(s) elif k < n - 1: s = (HOTEL * k).center(n, EMPTY) p...
9_B. Running Student
And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x. Poor Student knows the following: * during one run the minibus makes n st...
```python # -*- coding: utf - 8 -*- """"""""""""""""""""""""""""""""""""""""""""" | author: mr.math - Hakimov Rahimjon | | e-mail: mr.math0777@gmail.com | | created: 27.01.2018 9:50 | """"""""""""""""""""""""""""""""""""""""""""" # inp = open("input.txt", "r"); input = inp.readline; ...
p02545 ACL Contest 1 - Center Rearranging
Given are integer sequences A and B of length 3N. Each of these two sequences contains three copies of each of 1, 2, \dots, N. In other words, A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N). Tak can perform the following operation to the sequence A arbitrarily many times: * Pick a value from 1, 2...
```python import sys readline = sys.stdin.buffer.readline class E: def __init__(self,to,nx): self.to=to self.nx=nx class Graph: def __init__(self,n): self.n=n self.head=[None]*n def ae(self,a,b): head=self.head head[a]=E(b,head[a]) #head[b]=E(a,head[b]) return head[a] def scc(g): n=g.n cur=g.h...
p02676 AtCoder Beginner Contest 168 - ... (Triple Dots)
We have a string S consisting of lowercase English letters. If the length of S is at most K, print S without change. If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result. Constraints * K is an integer between 1 and 100 (inclusive). * S is a string ...
```python K = int(input()) S = input() print(S[:K] + "...") if len(S) > K else print(S) ```
p02804 AtCoder Beginner Contest 151 - Max-Min Sums
For a finite set of integers X, let f(X)=\max X - \min X. Given are N integers A_1,...,A_N. We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) ove...
```python N,K = map(int,input().split()) A = list(map(int,input().split())) mod = 10**9+7 A = sorted(A) bikkuri = [1] for i in range(1,N+1): bikkuri.append((bikkuri[-1]*i)%mod) bikkuri2 = [1] for i in range(1,N+1): bikkuri2.append(pow(bikkuri[i],mod-2,mod)) def comb(n,r): if n<r: return 0 ...
p02940 AtCoder Grand Contest 037 - RGB Balls
We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls. Takahashi will distribute these 3N balls to N people so that each pe...
```python MOD = 998244353 N = int(input()) Ss = input() convs = {'R': 0, 'G': 1, 'B': 2} num0 = N num1s = [0] * 3 num2s = [0] * 3 ans = 1 for S in Ss: c = convs[S] if num2s[c]: ans *= num2s[c] num2s[c] -= 1 else: for i in range(3): if i == c: continue if num...
p03077 AtCoder Beginner Contest 123 - Five Transportations
In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)! There are five means of transport in this empire: * Train: travels from City 1 to 2 in one minute. A train can occupy at most A people. * Bus: travels from City 2 to 3 in one minute. A bus can occupy a...
```python n = int(input()) l = [int(input()) for _ in range(5)] print(-(-n//min(l))+4) ```
p03219 AtCoder Beginner Contest 113 - Discount Fare
There is a train going from Station A to Station B that costs X yen (the currency of Japan). Also, there is a bus going from Station B to Station C that costs Y yen. Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then trav...
```python L = list(map(int,input().split())) print(L[0]+L[1]//2) ```
p03691 AtCoder Grand Contest 016 - Poor Turkeys
There are N turkeys. We number them from 1 through N. M men will visit here one by one. The i-th man to visit will take the following action: * If both turkeys x_i and y_i are alive: selects one of them with equal probability, then eats it. * If either turkey x_i or y_i is alive (but not both): eats the alive one. * ...
```python import sys from itertools import combinations def solve(n, pairs): survivors = {v: {v} for v in range(1, n + 1)} for x, y in reversed(pairs): for v, srv in survivors.copy().items(): if x in srv: if y in srv: del survivors[v] el...
p03844 AtCoder Beginner Contest 050 - Addition and Subtraction Easy
Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either `+` or `-`. Your task is to evaluate the formula instead of her. Constraints * 1≦A,B≦10^9 * op is either `+` or `-`. Input The input is given from Standard Input in the following format: A op B Outpu...
```python a,b,c=input().split();print(int(a)+int(c)if b=='+'else int(a)-int(c)) ```
p04011 AtCoder Beginner Contest 044 - Tak and Hotels (ABC Edit)
There is a hotel with the following accommodation fee: * X yen (the currency of Japan) per night, for the first K nights * Y yen per night, for the (K+1)-th and subsequent nights Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee. Constraints * 1 \leq N, K \leq 10000 * 1 \leq ...
```python a,b,c,d=[int(input()) for i in range(4)] if a<=b: print(a*c) else: print(b*c+(a-b)*d) ```
p00097 Sum of Integers II
Write a program that extracts n different numbers from the numbers 0 to 100 and outputs the number of combinations that add up to s. Each n number is from 0 to 100, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is 1 + 2 + 3 = ...
```python dp = [[0 for _ in range(1001)] for _ in range(10)] dp[1][0] = dp[0][0] = 1 for now in range(1, 101): for used in range(9, 0, -1): dpu = dp[used] dpu_1 = dp[used - 1] for s in range(now, 1001): dpu[s] = dpu_1[s - now] + dpu[s] while True: n, s = map(int, input().split()) if not n: ...
p00229 Big Hit !
Ataru Oafoot of Aizu Gakuen University High School decided to play with a slot machine. When you insert a medal on this machine, three reels will start spinning and each reel will stop automatically. In a normal game (normal game), 3 medals are inserted, and when the symbols are aligned, the following medals are obtai...
```python while 1: b, r, g, c, s, t = map(int, input().split()) if t == 0: break ans = 100 ans += (15 - 2) * (5*b) + (15 - 3) * b t -= 6*b ans += (15 - 2) * (3*r) + (15 - 3) * r t -= 4*r ans += (7 - 3) * g t -= g ans += (2 - 3) * c t -= c t -= s ans += (...
p00391 Treasure Map
Mr. Kobou found a bundle of old paper when he was cleaning his family home. On each paper, two series of numbers are written. Strange as it appeared to him, Mr. Kobou further went through the storehouse and found out a note his ancestor left. According to it, the bundle of paper is a treasure map, in which the two sequ...
```python import sys,heapq _,a,q=[[-int(e) for e in sys.stdin.readline().split() if e!='0'] for _ in[0]*3] heapq.heapify(q) for e in a: t=[] for _ in [0]*-e: if not q:print(0);exit() if q[0]!=-1:heapq.heappush(t,q[0]+1) heapq.heappop(q) while t:heapq.heappush(q,t[0]);heapq.heappop(t) print(int(not q)) ```
p00607 Emacs-like Editor
Emacs is a text editor which is widely used by many programmers. The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed witho...
```python class Editer: def __init__(self, text): # カーソルの位置 self.row = 0 #行 self.col = 0 #列 # 編集中のテキスト self.text = [list(t) + ['\n'] for t in text] # バッファー self.buffer = [] def row_head(self): return 0 def row_tail(self): return len(...
p00744 Cards
There are many blue cards and red cards on the table. For each card, an integer number greater than 1 is printed on its face. The same number may be printed on several cards. A blue card and a red card can be paired when both of the numbers printed on them have a common divisor greater than 1. There may be more than o...
```python import collections import math class Dinic: """Dinic Algorithm: find max-flow complexity: O(EV^2) used in GRL6A(AOJ) """ class edge: def __init__(self, to, cap, rev): self.to, self.cap, self.rev = to, cap, rev def __init__(self, V, E, source, sink): ...
p00883 Infected Land
The earth is under an attack of a deadly virus. Luckily, prompt actions of the Ministry of Health against this emergency successfully confined the spread of the infection within a square grid of areas. Recently, public health specialists found an interesting pattern with regard to the transition of infected areas. At e...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write dd0 = ((-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)) DD = [] for k in range(6): ddk = [] for y in range(k): for x in range(k): v = 0 for dx, dy in dd...
p01285 Find the Point
We understand that reading English is a great pain to many of you. So we’ll keep this problem statememt simple. Write a program that reports the point equally distant from a set of lines given as the input. In case of no solutions or multiple solutions, your program should report as such. Input The input consists o...
```python import sys readline = sys.stdin.readline write = sys.stdout.write EPS = 1e-9 def line_cross_point(P1, P2, Q1, Q2): x0, y0 = P1; x1, y1 = P2 x2, y2 = Q1; x3, y3 = Q2 dx0 = x1 - x0; dy0 = y1 - y0 dx1 = x3 - x2; dy1 = y3 - y2 s = (y0-y2)*dx1 - (x0-x2)*dy1 sm = dx0*dy1 - dy0*dx1 if ...
p01767 RUPC
Problem statement A programming contest will be held in the Russian Federation. The contest has N questions and has M participants. Question i has a score a_i, and it is known that participant j's ability is b_j. For problem i and participant j, participant j can always solve problem i if a_i ≤ b_j and only then. The ...
```python import bisect n=int(input()) a=sorted(list(map(int,input().split()))) d=[0]*(n+1) for i in range(1,n+1):d[i]=d[i-1]+a[i-1] m=int(input()) b,c=[list(map(int,input().split())) for _ in [0,0]] for i in range(m): p=bisect.bisect_right(a,b[i]) print(['Yes','No'][d[p]<c[i]]) ```
p01901 Suntan
D: Sunburn-Suntan- story Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. Cute like an angel. Aizu Nyan is planning to participate in this summer festival, so I made a schedule for the band to go to listen to. I'm worried abou...
```python # AOJ 2801: Suntan # Python3 2018.7.11 bal4u from bisect import bisect_left T, N = int(input()), int(input()) a, s, t = [0], [0], [0] for i in range(N): _s, _t = map(int, input().split()) s.append(_s) t.append(_t) a.append(a[-1]+_t-_s) s.append(1<<62) t.append(1<<62) ans = 0 k = bisect_left(t, T, 0)-1 f...
p02038 Tanuki and Fox
problem There is a mysterious device $ M $, and if you put Tanuki and Fox in this device, one animal will come out from the device (hereinafter, Tanuki will be $ T $ and Fox will be $ F $). $ M (x, y) $ represents an animal that came out by putting animals in the device $ M $ in the order of $ x, y $. As a result of...
```python from functools import reduce def M(x, y): if x == 'T' and y == 'T': return 'T' elif x == 'T' and y == 'F': return 'F' elif x == 'F' and y == 'T': return 'T' else: return 'T' _ = input() P = input().split() print(reduce(M, P)) ```
p02182 Spot The Difference
A: Find the difference problem Given rectangular boards A and B with N squares vertically and M squares horizontally. For each board, each square is painted white or black. The color of the square in the i-th row and j-th column of the board X is written as C (i, j, X). Count how many pairs of integers (i, j) meet ...
```python N, M = map(int, input().split()) table1 = '' table2 = '' for i in range(2 * N): if i < N: table1 += input() else: table2 += input() count = 0 for i, j in zip(table1, table2): if i != j: count+=1 print(count) ```
p02324 Chinese Postman Problem
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * T...
```python import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) # adjacency matrix no_edge = float("inf") adj = [[no_edge] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 # acceptance of input for l_i in f_i: s, t, d = map(int, l_i.spl...
p02469 Least Common Multiple
Find the least common multiple (LCM) of given n integers. Constraints * 2 ≤ n ≤ 10 * 1 ≤ ai ≤ 1000 * Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1 Input n a1 a2 ... an n is given in the first line. Then, n integers are given in the second line. Output Print the least common multiple of th...
```python from functools import reduce import math n = int(input()) def lcm_base(x, y): return (x * y) // math.gcd(x, y) def lcm_list(numbers): return reduce(lcm_base, numbers, 1) numlis = [int(a) for a in input().split()] print(lcm_list(numlis)) ```
1033_C. Permutation Game
After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of mo...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self...
1056_A. Determine Line
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in. During his ride, Arkady woke up several time...
```python n = int(input()) def intersect(a, b): x = [] for i in a: if i in b: x.append(i) return x things = [input().split()[1:] for i in range(n)] ans = things[0] for i in range(1, n): ans = intersect(ans, things[i]) print(" ".join(ans)) ```
1078_B. The Unbearable Lightness of Weights
You have a set of n weights. You know that their masses are a_1, a_2, ..., a_n grams, but you don't know which of them has which mass. You can't distinguish the weights. However, your friend does know the mass of each weight. You can ask your friend to give you exactly k weights with the total mass m (both parameters ...
```python from collections import defaultdict def calcBinomials(N): global binom N += 1 binom = [[0]*N for _ in range(N)] for n in range(N): binom[n][0] = binom[n][n] = 1 for k in range(1, n): binom[n][k] = binom[n-1][k] + binom[n-1][k-1] n = int(input()) a = list(map(int, ...
1099_B. Squares and Segments
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with ve...
```python # cook your dish here t=int(input()) l=int(t**(0.5)) if l==(t**(0.5)): print(2*l) else: if abs((l**2)-t) < ((l+1)**2)-t: print(2*l+1) else: print(2*(l+1)) ```
111_A. Petya and Inequiations
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: * a12 + a22 + ... + an2 ≥ x * a1 + a2 + ... + an ≤ y Input The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please d...
```python from math import sqrt, ceil n, x, y = map(int, input().split()) t = 1 if x < n else ceil(sqrt(x - n + 1)) if t + n - 1 > y: print(-1) else: print(str(t), '\n1' * (n - 1)) ```
1167_F. Scalar Queries
You are given an array a_1, a_2, ..., a_n. All a_i are pairwise distinct. Let's define function f(l, r) as follows: * let's define array b_1, b_2, ..., b_{r - l + 1}, where b_i = a_{l - 1 + i}; * sort array b in increasing order; * result of the function f(l, r) is ∑_{i = 1}^{r - l + 1}{b_i ⋅ i}. Calcula...
```python import sys MOD = (int)(1e9+7) def add(a, b): a += b if a >= MOD: a -= MOD return a def mul(a, b): return (a * b) % MOD class fenwickTree: def __init__(self, max_val): self.max_val = max_val + 5 self.tree = [0] * self.max_val def update(self, idx, value): idx += 1 while idx < self.max_val:...
1186_A. Vus the Cossack and a Contest
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
```python def solve(n, m, k): if min(m,k) >= n: return "Yes" else: return "No" def main(): n, m, k = list(map(int, input().split())) print(solve(n, m, k)) if __name__ == '__main__': main() ```
1205_A. Almost Equal
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th...
```python n = int(input()) if n%2 == 0: print("NO") exit(0) arr = [] for i in range(1, n+1): if i%2 == 1: arr.append(2*i-1) else: arr.append(2*i) for i in range(n): if arr[i] % 2 == 1: arr.append(arr[i]+1) else: arr.append(arr[i]-1) print("YES") print(*arr) ```
1221_E. Game With String
Alice and Bob play a game. Initially they have a string s_1, s_2, ..., s_n, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select...
```python q = int(input()) for i in range(q): a, b = [int(item) for item in input().split()] s = input().rstrip() + "#" cnt = 0 bob_world = 0 alice_world = 0 length = 0 bob_winning = False for ch in s: if ch == ".": cnt += 1 else: if cnt < b: ...
1248_B. Grow The Tree
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting o...
```python a=int(input());b=sorted(list(map(int,input().split())),reverse=True);from math import ceil as c;print(sum(b[:c(len(b)/2)])**2+sum(b[c(len(b)/2):])**2) ```
1288_A. Deadline
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
```python import math for _ in range(int(input())): n,d = map(int,input().split()) if ((1-n)**2) - (4*(d-n)) >= 0: print('YES') else: print('NO') ```
1331_D. Again?
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
```python value = input() print(int(value, 16)%2) ```
1351_B. Square?
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
```python for t in range(int(input())): a, b = map(int, input().split()) c, d = map(int, input().split()) a, b = min(a, b), max(a, b) c, d = min(c, d), max(c, d) if a + c == b == d: print("YES") else: print("NO") ```
1371_D. Grid-00100
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the gr...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.wri...
1394_A. Boboniu Chats with Du
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu ...
```python #! /usr/bin/python3 n, d, m = [int(inp) for inp in input().split()] aArr = sorted([int(inp) for inp in input().split()], reverse = True) i = sum([j > m for j in aArr]) aU = aArr[:i] aL = aArr[i:] aUS = aU for i in range(1, len(aU)): aUS[i] += aUS[i - 1] aUS = [0] + aUS aLS = aL for i in range(1, len(aL)...
1436_E. Complicated Computations
In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty...
```python class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.range = [(-1,n)] * 2 * self.num # 配列の値を葉...
1461_C. Random Events
Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n,m = map(int,input().split()) a = list(map(int,input().split())) j = n-1 while j != -1 and a[j] == j+1: j -= 1 ...
1486_D. Max Median
You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2,...
```python import collections def solveTestCase(): n, k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] r = n + 1 l = 1 while r - l > 1: m = (r+l)//2 b = [1 if i >= m else -1 for i in a] for i in range(1, len(b)): b[i] += b[i - 1] ans = False if b[k-1] > 0: ans = True m...
1510_D. Digits
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with he...
```python import math;n, d = map(int, input().split());a = [int(_) for _ in input().split()];dp = [[-1e10] * 10 for _ in range(n + 1)] come = [[(0, 0, 0) for i in range(10)] for j in range(n + 1)];dp[0][1] = 0 for i in range(n): for j in range(10): val = dp[i][j] + math.log(a[i]) if dp[i + 1][(j * a...
1536_F. Omkar and Akmar
Omkar and Akmar are playing a game on a circular board with n (2 ≤ n ≤ 10^6) cells. The cells are numbered from 1 to n so that for each i (1 ≤ i ≤ n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty. Omkar and Akmar take turns placing either an A or a B on the board, wit...
```python import sys input = sys.stdin.readline n = int(input()) mod = 10 ** 9 + 7 F = [0] * (n + 1) F[0] = 1 for i in range(1, n + 1): F[i] = i * F[i - 1] % mod iF = [0] * (n + 1) iF[-1] = pow(F[-1], mod - 2, mod) for i in range(n - 1, -1, -1): iF[i] = iF[i + 1] * (i + 1) % mod def C(n, k): if k > n: ret...
185_A. Plant
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
```python n=int(input()) e=10**9+7 print(1if n==0else(pow(2,n-1,e)+pow(2,n*2-1,e))%e) # Made By Mostafa_Khaled ```
231_B. Magic, Wizardry and Wonders
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into...
```python n, d, L = map(int, input().split()) sp = [] for _ in range(n - 1): if d <= 0: sp.append(1) d = 1 - d else: sp.append(L) d = L - d if 1 <= d <= L: sp.append(d) print(*sp) else: print(-1) ```
257_A. Sockets
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets. Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filt...
```python n,m,k=map(int,input().split(" ")) li=list(map(int,input().split(" ",n)[:n])) li.sort(reverse=True) fl=0 a,s=0,0 if m<=k: print(0) else: while fl==0 and a<n: s+=li[a] a+=1 if a!=1: s-=1 if s+k-1>=m and a!=0: fl=1 break if fl!=1: ...
280_A. Rectangle Puzzle
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side tha...
```python from math import radians, cos, sin, atan2 def rotate(point, alpha): x = point[0] y = point[1] return (x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha)) def crs(a, b): return a[0] * b[1] - a[1] * b[0] def m(end, start): return (end[0] - start[0], end[1] - start[1]) def a...
32_A. Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ...
```python n, d = [int(i) for i in input().split()] S = sorted([int(i) for i in input().split()]) k = 0 for i in range(n): for j in range(i+1, n): if(S[j]-S[i]<=d): k += 1 else: break print(k*2) ```
397_B. On Corruption and Numbers
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to w...
```python t = int(input()) for _ in range(t): n, l, r = map(int, input().split()) print("No" if n // l * r < n else "Yes") ```
41_C. Email address
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address (vasya@gmail.com). It is known that a proper email address contains only such symbols a...
```python a = input() b = '' if a[0] + a[1] + a[2] == 'dot': b += 'dot' i = 3 elif a[0] + a[1] == 'at': b += 'at' i = 2 else: i = 0 at = 0 while i < len(a) - 3: if a[i] == 'd' and a[i + 1] == 'o' and a[i + 2] == 't': b += '.' i += 3 elif a[i] == 'a' and a[i + 1] == 't' and at...
446_A. DZY Loves Sequences
DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one numb...
```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()) n=ii() a=li() pre,suf = [1]*n,[1]*n for i in range(1,n): if a[i]>a[i-1]: pre[i]+=pre[i-1] for i in range(n-2,-1,-1): ...
468_B. Two Sets
Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Hel...
```python import sys import queue sys.setrecursionlimit(100000) # global constant INF = int(1e7+1) MAX = 100005 # For testing #sys.stdin = open("INP.txt", 'r') #sys.stdout = open("OUT.txt", 'w') # global variables parents = [] ranks = [] size = [] n = 0 # classes class Pair: def __init__(self, a, b): ...
490_B. Queue
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working. Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of...
```python import math from collections import deque class Empty(Exception): pass class _DoublyLinkedBase: """A base class providing a doubly linked list representation.""" #-------------------------- nested _Node class -------------------------- # nested _Node class class _Node: """Lightweight, nonpub...
514_B. Han Solo and Lazer Gun
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can ...
```python n, x0, y0 = map(int, input().split()) slopes = {} # key: (num, den), val: count for i in range(n): x, y = map(int, input().split()) num = y - y0 den = x - x0 # print(num, den) if den == 0 and "inf" in slopes: slopes["inf"] += 1 elif den == 0: slopes["inf"] = 1 else...
540_C. Ice Cave
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice. The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists e...
```python import queue MAX = 500 dr = [0,0,1,-1] dc = [1,-1,0,0] def isValid(r, c): return r in range(m) and c in range(n) def BFS(sr, sc, fr, fc): q = [0] * (MAX * MAX) left = right = 0 q[0] = (sr, sc) while left <= right: ur, uc = q[left] left += 1 for i in range(4): vr = ur + dr[i] ...
58_B. Coins
In Berland a money reform is being prepared. New coins are being introduced. After long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. Also the following restriction has been introduced for comfort: the denomination of each coin should be div...
```python def O(x): l=[] if x==1: return 1 for i in range(1,x//2+1): if x%i==0: l.append(i) print(x) return O(l[len(l)-1]) x=int(input()) O(x) print(1) ```
631_A. Interview
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ...
```python read = lambda: map(int, input().split()) n = int(input()) a = list(read()) b = list(read()) f1 = f2 = 0 for i in a: f1 |= i for i in b: f2 |= i print(f1 + f2) ```
706_B. Interesting drink
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink fo...
```python def binary(t,s): fir=0 last=len(t)-1 mid=0 while(fir<=last): mid=(fir+last)//2 if t[mid]>s: last=mid-1 else: fir=mid+1 return last+1 n=int(input()) t=list(map(int,input().split())) m=int(input()) p=0 t.sort() for i in range(m): ...
729_D. Sea Battle
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot ...
```python n,a,b,k = map(int, input().split()) open = 0 must = 0 must_arr = [] for i,c in enumerate(input()): if c == '1': open = 0 else: open += 1 if open == b: open = 0 must += 1 if must >= a: must_arr.append(i+1) must -= a - 1 pr...
749_E. Inversions After Shuffle
You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable. 2. Let k = r - l + 1, i.e. the le...
```python # Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Tr...
797_D. Broken BST
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: 1. Set ...
```python from collections import deque nodes = [] parents = [] values = [] broken = [] upperBound = [] lowerBound = [] n = int(input()) for _ in range(n): v, l, r = map(int, input().split()) nodes.append((v, l - 1, r - 1)) parents.append(-1) values.append(v) broken.append(False) upperBound.a...
843_A. Sorting by Subsequences
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is...
```python n = int(input()) d = list(map(int, input().split())) temp = d[:] d.sort() from bisect import bisect_left A = [bisect_left(d,i) for i in temp] del d,temp f = [False]*len(A) result = [] for i in range(n): if not f[i]: L = [i+1] f[i] = True j = A[i] while j != i: L.append(j+1) ...
863_F. Almost Permutation
Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less...
```python import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) while AUX and min(AUX) < x: AUX.remove(min(AUX)) for quantity in range(cnt[x]): if AUX: AUX.remov...
912_A. Tricky Alchemy
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ...
```python y,b=input().split(' ') ay,ag,ab=input().split(' ') y=int(y) b=int(b) ay=int(ay) ag=int(ag) ab=int(ab) b=b-(ab*3) y=y-(ay*2) b=b-ag y=y-ag br=0 if(y<0): br=br-y if(b<0): br=br-b print(br) ```
934_A. A Compatible Pair
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has n lanterns and Big Ban...
```python n, m = [int(x) for x in input().split()] lstT = [int(x) for x in input().split()] lstB = [int(x) for x in input().split()] z=-9999999999999999999999999999 T=0 B=0 for i in range(n): for j in range(m): if z<lstT[i]*lstB[j]: T=i B=j ...
960_C. Subsequence Counting
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence...
```python X, d = map(int, input().split()) x = X ans = list() ln = 0 last = 1 while x > 0: if last >= 10 ** 18: print(-1) exit() i = 0 while 2 ** (i + 1) - 1 <= x: i += 1 t = 2 ** i - 1 x -= t if ln + i > 10000: print(-1) exit() for _ in range(i):...
p02592 AtCoder Grand Contest 047 - Product Simulation
This is an output-only problem. You shouldn't read anything from the input. In short, your task is to simulate multiplication by using only comparison (x < y) and addition (x + y). There is no input in this problem, you just print a sequence of operations. Imagine that there is a big array a[0], a[1], ..., a[N-1] of ...
```python n=97 p=print r=range def a(i,j,k,l=0):p(chr(43+l*17),i,j,k) def b(i):a(i,i,i+1) def d(x,i,j): for t in r(30): b(j+t-1);a(j+t,n,j+t) for s in r(j+t,j+29):b(s) a(j+29,x,i+t,1);b(j+t-1);a(j+t,i+t,j+t) p(3933) a(0,1,n) a(2,n,n,1) a(0,n,3) a(1,n,4) d(3,5,36) d(4,36,67) for t in r(59): a(2,2,2) for s in r(...