name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1037_E. Trips
There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: * ...
```python from collections import deque def solve(adj, m, k, uv): n = len(adj) nn = [len(a) for a in adj] q = deque() for i in range(n): if nn[i] < k: q.append(i) while q: v = q.popleft() for u in adj[v]: nn[u] -= 1 if nn[u] == k-1: ...
1060_A. Phone Numbers
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit. For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not. You have n cards with digits, and you want to use them to make as many phone n...
```python n = int(input()) s = input() k = s.count("8") l = n - k if k <= l//10: print(k) else: while k > l//10: k -= 1 l += 1 print(min(k, l//10)) ```
1101_A. Minimum Integer
You are given q queries in the following form: Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i]. Can you answer all the queries? Recall that a number x belongs to segment [l, r] if l ≤ x ≤ r. Input The first l...
```python n = int(input()) A = [] for i in range(n): A = A+[input().split()] for a in A: if int(a[2]) < int(a[0]) or int(a[2]) > int(a[1]): print(a[2]) else: print(int(a[2])*(int(a[1])//int(a[2])+1)) ```
1189_D1. Add on a Tree
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al...
```python m = int(input()) l = [0 for _ in range(m + 1)] for _ in range(m - 1): a,b = map(int, input().split()) l[a] += 1 l[b] += 1 if 2 in l: print("NO") else: print("YES") ```
1208_D. Restore Permutation
An array of integers p_{1},p_{2}, …,p_{n} is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4]. There is a hidden permutation of length n. ...
```python from sys import stdin,stdout class Tree(object): def __init__(self,n): self.tree=[0]*(4*n+10) self.b=[0]*(n+10) self.a=list(map(int,stdin.readline().split())) self.n=n def update(self,L,C,l,r,rt): if l==r: self.tree[rt]+=C return ...
1227_D1. Optimal Subsequences (Easy Version)
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily...
```python # class SegmentTree(): # adapted from https://www.geeksforgeeks.org/segment-tree-efficient-implementation/ # def __init__(self,arr,func,initialRes=0): # self.f=func # self.N=len(arr) # self.tree=[0 for _ in range(2*self.N)] # self.initialRes=initialRes # for i in r...
1269_E. K Integers
You are given a permutation p_1, p_2, …, p_n. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k. ...
```python n = int(input()) a = [0] + list(map(int, input().split())) pos, pb, ps = [[0] * (n + 1) for x in range(3)] def add(bit, i, val): while i <= n: bit[i] += val i += i & -i def sum(bit, i): res = 0 while i > 0: res += bit[i] i -= i & -i return res def find(bi...
1291_E. Prefix Enlightenment
There are n lamps on a line, numbered from 1 to n. Each one has an initial state off (0) or on (1). You're given k subsets A_1, …, A_k of \{1, 2, ..., n\}, such that the intersection of any three subsets is empty. In other words, for all 1 ≤ i_1 < i_2 < i_3 ≤ k, A_{i_1} ∩ A_{i_2} ∩ A_{i_3} = ∅. In one operation, you ...
```python from sys import stdin input = stdin.readline n , k = [int(i) for i in input().split()] pairs = [i + k for i in range(k)] + [i for i in range(k)] initial_condition = list(map(lambda x: x == '1',input().strip())) data = [i for i in range(2*k)] constrain = [-1] * (2*k) h = [0] * (2*k) L = [1] * k + [0] * k dp1...
1311_F. Moving Points
There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points move with the constant speed, the coordinate of the i-th point at the moment t (t can be non-integer) is calculated as x_i + t ...
```python import bisect def getsum(tree , i): s = 0 i += 1 while i>0: s += tree[i] i -= i & (-i) return s def updatebit(tree , n , i , v): i+= 1 while i <= n: tree[i] += v i += i & (-i) n = int(input()) x = list(map(int , input().split())) v = list(map(int , in...
1334_D. Minimum Euler Cycle
You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of...
```python # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2020/7/1 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(n, l, r): # 1, 2, 1, 3, ..., 1, n # 2, 3, 2, 4, ..., 2, n # ... # n-1, n # 1 lo, hi = 1, n...
1354_F. Summoning Minions
Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other. Polycarp can summon n different minions. The initial power level of the i-th minion is a_i, and when it is summoned, all previously summoned minions' power levels are increased by b_i. The minions c...
```python from sys import stdin, gettrace from heapq import nlargest if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() INF = int(10E10) def main(): def solve(): n, k = map(int, input().split()) mm = [] for i in range(1...
1374_E1. Reading Books (easy version)
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ...
```python import sys input=sys.stdin.readline f=lambda :list(map(int, input().strip('\n').split())) n, k=f() _11=[] _01=[] _10=[] for _ in range(n): t, a, b=f() if a and b: _11.append(t) elif a: _10.append(t) elif b: _01.append(t) _01.sort(); _10.sort(); _11.sort() for i in range(1, len(_01)): _01[i]+=_01[i...
1398_A. Bad Triangle
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
```python t=int(input()) for z in range(t): n=int(input()) arr=list(map(int,input().split())) min= arr[0] + arr[1] pos=True for i in range(2,n): if(arr[i]>=min): pos=False posf=i break if(pos): print("-1") else: print("1 2", posf+1)...
1421_B. Putting Bricks in the Wall
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid. Roger Waters has a square grid of size n× n and he wants to traverse his grid f...
```python l=[] for _ in range(int(input())): n=int(input()) a=[] for i in range(n): a.append(list(input())) if a[0][1]==a[1][0]: if a[n-1][n-2]==a[n-2][n-1]: if a[n-1][n-2]==a[0][1]: l.append("2") l.append("1 2") l.append("2 1")...
143_A. Help Vasilisa the Wise 2
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha...
```python inn = list(map(int, input().split(" "))) r1 = inn[0] r2 = inn[1] inn = list(map(int, input().split(" "))) c1 = inn[0] c2 = inn[1] inn = list(map(int, input().split(" "))) d1 = inn[0] d2 = inn[1] x = int((d1+c1-r2)/2) y = int(((2*r1)-d1-c1+r2)/2) a = int(((2*c1)-d1-c1+r2)/2) b = int((r2-(2*c1)+d1+c1)/2) if x ...
1466_F. Euclid's nightmare
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare. In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words h...
```python import sys input = sys.stdin.buffer.readline def _find(s, u): p = [] while s[u] != u: p.append(u) u = s[u] for v in p: s[v] = u return u def _union(s, u, v): su, sv = _find(s, u), _find(s, v) if su != sv: s[su] = sv return su != sv n, m = map(int, input().split()...
1490_G. Old Floppy Drive
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it. Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm: * the drive takes one positive number x...
```python def findIndexGE(prefixSumsMax,startSum,query): n=len(prefixSumsMax) b=n i=-1 while b>0: while i+b<n and startSum+prefixSumsMax[i+b]<query: i+=b b//=2 i+=1 return i def main(): t=int(input()) allans=[] for _ in range(t): n,m=readInt...
1513_C. Add One
You are given an integer n. You have to apply m operations to it. In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once. You have to find the length of n after applying m operations. Since...
```python from os import path import sys,time from math import ceil, floor,gcd,log,log2 ,factorial from collections import defaultdict ,Counter , OrderedDict , deque from heapq import heapify , heappush , heappop from bisect import * # from functools import reduce from operator import mul from itertools import permutat...
1540_C1. Converging Array (Easy Version)
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved. There is a process that takes place on arrays a and b of length n and length n-1 respectively. The process is an infinite sequence of operations. Each operat...
```python def putin(): return map(int, input().split()) def sol(): n = int(input()) C = list(putin()) B = list(putin()) q = int(input()) x = int(input()) min_arr = [x] min_part_sums = [x] part_sums = [C[0]] for i in range(1, n): part_sums.append(part_sums[-1] + C[i]) ...
168_A. Wizards and Demonstration
Some country is populated by wizards. They want to organize a demonstration. There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr...
```python num,wiz,per = map(int,input().split()) k = 0 while (k+wiz)/num*100 < per: k += 1 print(k) ```
20_B. Equation
You are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order. Input The first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0. Output In case of infinite root cou...
```python a, b, c = map(float, input().split()) D = b ** 2 - (4 * a * c) if D < 0: print(0) elif a == 0 and b == 0 and c != 0: print(0) elif a == 0 and b == 0 and c == 0: print(-1) elif a == 0: x0 = c / -(b) print(1) print(x0) elif b == 0: print(1) print(0) elif D == 0 and (a > 0 or a < ...
260_B. Ancient Prophesy
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-". We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say tha...
```python s=input() n=len(s) l=list("0987654321") cnt={} for i in range(n-9): t=s[i:i+10] if t[0] in l and t[1] in l and t[2]=="-" and t[3] in l and t[4] in l and t[5]=="-" and t[6] in l and t[7] in l and t[8] in l and t[9] in l: if 2013<=int(t[6:11])<=2015 and 1<=int(t[3:5])<=12: if int(t[3:5]) in [1,3,...
284_B. Cows and Poker Game
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any bett...
```python #!/bin/python # -*- coding: utf-8 -*- n = int(input()) s = input() print(int(s.count('I') == 1) if 'I' in s else s.count('A')) ```
379_A. New Year Candles
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like...
```python a, b = map(int, input().split()) c, s = a, 0 while a >= b: s += a // b a = (a // b) + (a % b) print(s + c) ```
39_H. Multiplication Table
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn...
```python k=int(input()) for i in range(1,k): z,a=i,[] for j in range(k-1): p,s=z,"" while p: s=str(p%k)+s p//=k z+=i a.append(s) print(*a) ```
44_B. Cola
To celebrate the opening of the Winter Computer School the organizers decided to buy in n liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly a bottles 0.5 in volume, b one-liter bottles and c of two...
```python def nik(rudy,x,y,z,cot): for i in range(z+1): for j in range(y+1): t = rudy - i*2 -j if t>=0 and x*0.5 >= t: cot+=1 return cot rudy, x, y, z = list(map(int,input().split())) cot = 0 print(nik(rudy,x,y,z,cot)) ```
519_B. A and B and Compilation Errors
A and B are preparing themselves for programming contests. B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code. Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix s...
```python n = int(input()) a_sum = sum(map(int, input().split())) b_sum = sum(map(int, input().split())) c_sum = sum(map(int, input().split())) print(a_sum - b_sum) print(b_sum - c_sum) ```
545_C. Woodcutters
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
```python ll=lambda:map(int,input().split()) t=lambda:int(input()) ss=lambda:input() #from math import log10 ,log2,ceil,factorial as f,gcd #from itertools import combinations_with_replacement as cs #from functools import reduce #from bisect import bisect_right as br #from collections import Counter n=t() x,h=[],[] fo...
593_C. Beautiful Function
Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the i...
```python def f(x): if x == n: return "0" if x == 0: return "(" + str(X[0]) + "+" + f(1) + ")" ss = "(abs((t-" + str(x-1) + "))-abs((t-" + str(x) + ")))" tmp = (X[x] - X[x - 1]) // 2 re = (X[x] - X[x - 1]) - 2 * tmp X[x] -= re ...
615_A. Bulbs
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
```python import math nm = input().split() n = int(nm[0]) m = int(nm[1]) lis = [ 0 for i in range(m+1)] for _ in range(n) : inp = list(map(int, input().split())) inp.pop(0) for i in inp: lis[i]=1 prev = i if sum(lis)==m: print("YES") else: print("NO") ```
634_C. Factory Repairs
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but ...
```python from functools import reduce class SegmentTree(): def __init__(self, L, function = lambda x,y: x+y, initilizer = None): self.function = function self.initilizer = initilizer N = self.size = len(L) M = 1 << N.bit_length() self.margin = 2*M - N self.L = [None ...
663_A. Rebus
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds. Input The only line of the input contains a re...
```python s = input().split() plus = 1 minus = 0 for ch in s: if (ch == '+') : plus += 1 if (ch == '-') : minus += 1 n = int(s[len(s) - 1]) maxx = plus * n - 1 * minus minn = plus - n * minus now = n - (plus - minus) if (n>maxx or n<minn): print("Impossible") else: pre = '+' print("Possible") for ...
730_J. Bottles
Nick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda ai and bottle volume bi (ai ≤ bi). Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda...
```python f = lambda: list(map(int, input().split())) n = int(input()) a, b = f(), f() d = [[None] * 10001 for i in range(n)] def g(i, s): if s <= 0: return (0, s) if i == n: return (1e7, 0) if not d[i][s]: x, y = g(i + 1, s - b[i]) d[i][s] = min(g(i + 1, s), (x + 1, y + b[i] - a[i])) ...
776_A. A Serial Killer
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
```python def main(): l = input().split() print(*l) for _ in range(int(input())): a, b = input().split() l[a == l[1]] = b print(*l) if __name__ == '__main__': main() ```
7_B. Memory Manager
There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: ...
```python t, m = map(int, input().split()) disk = [False] * m req = 0 for i in range(t): inp = input().split() if inp[0][0] == "a": c = 0 inp[1] = int(inp[1]) for j in range(m): if disk[j]: c = 0 else: c += 1 if c == inp...
820_D. Mister B and PR Shifts
Some time ago Mister B detected a strange signal from the space, which he started to study. After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation whi...
```python from sys import stdin def main(): n = int(stdin.readline()) a = list(map(int, stdin.readline().split())) inf = [0] * (n + 1) curr = 0 d = 0 for i in range(n): curr += abs(i + 1 - a[i]) if a[i] > i + 1: d += 1 inf[a[i] - i - 1] += 1 elif a...
846_E. Chemistry in Berland
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment. Fortunately, chemical laws allow material transformations (yes, chemistry i...
```python import sys # @profile def main(): f = sys.stdin # f = open('input.txt', 'r') # fo = open('log.txt', 'w') n = int(f.readline()) # b = [] # for i in range(n): # b.append() b = list(map(int, f.readline().strip().split(' '))) a = list(map(int, f.readline().strip().split(' '...
868_A. Bark to Unlock
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's p...
```python one=input() num=int(input()) twos=[] for i in range(num): twos.append(input()) if (one in twos) or (one[::-1] in twos): print("YES") else: flag1,flag2=False,False for i in range(num): if twos[i][0]==one[1]: flag1=True if twos[i][1]==one[0]: flag2=True if(flag1 and flag2): p...
893_D. Credit Card
Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card. She starts with 0 money on her account. In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, ...
```python #Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue, bisect #sys.stdin = open("input.txt", "r") MOD = 10**9+7 sys.setrecursionlimit(1000000) n, d = map(int, input().split()) a = list(map(int, input().split())) p = [0 for i in range(n)] for i in range(n): p[i] = p[i-1]+a[i] mx = [-1 f...
915_A. Garden
Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the gro...
```python def is_prime(a): return all(a % i for i in range(2, a)) n, k = map(int, input().split()) l = [int(x) for x in input().split()] if is_prime(k): if k in l: print(1) else: print(k) else: ll = [] for i in range(len(l)): if k % l[i] == 0: ll.append(l[i]) ...
938_B. Run For Your Prize
You and your friend are participating in a TV show "Run For Your Prize". At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positi...
```python input() a=list(map(int,input().split())) ans=0 for x in a: z=min(x-1,1000000-x) ans=max(z,ans) print(ans) ```
963_B. Destruction of a Tree
You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or...
```python from collections import defaultdict,deque import sys import bisect import math input=sys.stdin.readline mod=1000000007 def bfs(root,count): q=deque([root]) vis.add(root) while q: vertex=q.popleft() for child in graph[vertex]: if ans[child]==0: ans[child...
990_E. Post Lamps
Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked an...
```python import sys from array import array n, m, k = map(int, input().split()) block = list(map(int, input().split())) a = [0] + list(map(int, input().split())) if block and block[0] == 0: print(-1) exit() prev = array('i', list(range(n))) for x in block: prev[x] = -1 for i in range(1, n): if prev...
p02613 AtCoder Beginner Contest 173 - Judge Status Summary
Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A. The problem has N test cases. For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is `AC`,...
```python n=int(input()) S = [] for i in range(n): S.append(input()) for t in ["AC","WA","TLE","RE"]: print(f"{t} x {S.count(t)}") ```
p02744 Panasonic Programming Contest 2020 - String Equivalence
In this problem, we only consider strings consisting of lowercase English letters. Strings s and t are said to be isomorphic when the following conditions are satisfied: * |s| = |t| holds. * For every pair i, j, one of the following holds: * s_i = s_j and t_i = t_j. * s_i \neq s_j and t_i \neq t_j. For example, `a...
```python a='a' exec('a=[s+chr(c)for s in a for c in range(97,ord(max(s))+2)];'*~-int(input())) print(*a) ```
p02879 AtCoder Beginner Contest 144 - 9x9
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation. Given are two integers A and B. If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead. Constraints * 1 \leq A \leq 20 * 1 \leq B ...
```python a,b = map(int,input().split()) print(a*b) if(a<=9 and b<=9) else print(-1) ```
p03013 AtCoder Beginner Contest 129 - Typical Stairs
There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time. However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps. How many are there to climb ...
```python n,m = map(int,input().split()) a_list = [int(input()) for _ in range(m)] dp = [1]*(n+1) for a in a_list: dp[a] = 0 for i in range(2,n+1): if dp[i] != 0: dp[i] = dp[i-1] + dp[i-2] print(dp[n]%(10**9+7)) ```
p03153 KEYENCE Programming Contest 2019 - Connecting Cities
There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}. Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads. Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from heapq import heappush, heappop, heapify from collections import defaultdict """ ・最小値のある場所を調べる。左右にまたがる辺は結ばない。 ・最小値の両隣は必ず最小値と結ぶ。 ・結んだあと1点に縮約していく。 """ N,D,*A = map(int,read().split()) A = ...
p03297 AtCoder Grand Contest 026 - rng_10s
Ringo Mart, a convenience store, sells apple juice. On the opening day of Ringo Mart, there were A cans of juice in stock in the morning. Snuke buys B cans of juice here every day in the daytime. Then, the manager checks the number of cans of juice remaining in stock every night. If there are C or less cans, D new can...
```python def main(): import math def gcd(a, b): while b: a, b = b, a % b return a N = int(input()) ABCD = [list(map(int, input().split())) for i in range(N)] for A,B,C,D in ABCD: # 在庫が買う本数以下 or 在庫追加が買う本数以下 if A < B or D < B: print("No") ...
p03455 AtCoder Beginner Contest 086 - Product
AtCoDeer the deer found two positive integers, a and b. Determine whether the product of a and b is even or odd. Constraints * 1 ≤ a,b ≤ 10000 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the product is odd, print `Odd`; if it is even, print `Even`. E...
```python print("Odd" if sum([int(i) % 2 for i in input().split()])==2 else "Even") ```
p03616 AtCoder Regular Contest 082 - Sandglass
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb. The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per...
```python X=int(input()) K=int(input()) r=list(map(int,input().split())) Q=int(input()) p=[tuple(map(int,input().split())) for i in range(Q)] N=Q L=0 R=Q-1 start=0 sign="-" # N: 処理する区間の長さ N0 = 2**(N-1).bit_length() data = [0]*(2*N0) INF = 0 # 区間[l, r+1)の値をvに書き換える # vは(t, value)という値にする (新しい値ほどtは大きくなる) def update(l, r...
p03774 AtCoder Beginner Contest 057 - Checkpoints
There are N students and M checkpoints on the xy-plane. The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j). When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance. T...
```python n,m=map(int,input().split()) p=[list(map(int, input().split())) for _ in range(n)] c=[list(map(int, input().split())) for _ in range(m)] for i in p: d=[abs(i[0]-c[j][0])+abs(i[1]-c[j][1]) for j in range(len(c))] print(d.index(min(d))+1) ```
p03943 AtCoder Beginner Contest 047 - Fighting over Candies
Two students of AtCoder Kindergarten are fighting over candy packs. There are three candy packs, each of which contains a, b, and c candies, respectively. Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible. Not...
```python l=sorted(list(map(int,input().split()))) print("Yes" if l[0]+l[1]==l[2] else "No") ```
p00035 Is it Convex?
4 different points on the plane Read the coordinates of $ A (x_a, y_a) $, $ B (x_b, y_b) $, $ C (x_c, y_c) $, $ D (x_d, y_d) $ and read those 4 points Create a program that outputs YES if there is no dent in the quadrangle $ ABCD $ with the coordinates as the vertices, and NO if there is a dent. A quadrangle with a de...
```python def gai(a,b,c,d): S = a*d - b*c return(S) while True: try: x1,y1,x2,y2,x3,y3,xp,yp = map(float,input().split(",")) A1,A2,B1,B2,C1,C2,D1,D2 = x1,y1,x2,y2,x3,y3,xp,yp if gai(x1 - x2,y1 - y2,x1 - xp,y1 - yp) < 0 and gai(x2 - x3,y2 - y3,x2 - xp,y2 - yp) < 0 and gai(x3...
p00167 Bubble Sort
Sorting algorithms for sorting data are basic algorithms indispensable in computer science. For example, as shown in the figure below, the operation of "sorting the elements of an array of integer values ​​in ascending order" is alignment. <image> Many alignment algorithms have been devised, but one of the basic alg...
```python def bubble_sort(n): arr = [int(input()) for _ in range(n)] cnt = 0 for i in range(n): for j in range(n-1, i, -1): if arr[j] < arr[j-1]: arr[j], arr[j-1] = arr[j-1], arr[j] cnt += 1 return cnt while True: n = int(input()) if n == 0: b...
p00323 Metal Recycling
PCK, which recycles Aizu's precious metal, Aizunium, has a network all over the country and collects Aizunium with many collection vehicles. This company standardizes the unit of weight and number of lumps for efficient processing. A unit called "bokko" is used for the weight of the lump. x Bocco's Aidunium weighs 2 x...
```python n = int(input()) size = 200100 total = [0 for _ in range(size)] for _ in range(n): s = sum(map(int, input().split())) total[s] += 1 for i in range(size - 1): if total[i] % 2: print(i, 0) total[i + 1] += total[i] // 2 ```
p00822 Weather Forecast
You are the God of Wind. By moving a big cloud around, you can decide the weather: it invariably rains under the cloud, and the sun shines everywhere else. But you are a benign God: your goal is to give enough rain to every field in the countryside, and sun to markets and festivals. Small humans, in their poor vocabu...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01086 Short Phrase
Short Phrase A Short Phrase (aka. Tanku) is a fixed verse, inspired by Japanese poetry Tanka and Haiku. It is a sequence of words, each consisting of lowercase letters 'a' to 'z', and must satisfy the following condition: > (The Condition for a Short Phrase) > The sequence of words can be divided into five sections ...
```python tanku = [5, 7, 5, 7, 7] while True: n = int(input()) if n==0: break w = [len(input()) for i in range(n)] ans = 0 for i in range(n): sum = 0 k = 0 for j in range(i, n): sum += w[j] if sum == tanku[k]: sum = 0 k += 1 if k==5: ans = i+1 ...
p01356 Nearest Station
I have n tickets for a train with a rabbit. Each ticket is numbered from 0 to n − 1, and you can use the k ticket to go to p⋅ak + q⋅bk station. Rabbit wants to go to the all-you-can-eat carrot shop at the station m station ahead of the current station, but wants to walk as short as possible. The stations are lined up ...
```python def solve(): n,m,a,b,p,q = map(int,input().split()) if a==1 and b==1: if (p+q)*n <= m: return m - (p+q)*n else: k = m//(p+q) return min(m-k*(p+q),(k+1)*(p+q)-m) else: ans = m for i in range(min(n-1,40),-1,-1): f = p*(a...
p01538 Kakezan
Taro is an elementary school student who has just learned multiplication. Somehow, he likes multiplication, so when he sees numbers, he wants to multiply. He seems to like to do the following for integers greater than or equal to 0. (Processing flow) * Procedure 1. If a certain integer n greater than or equal to 0 is ...
```python "かけざん" "最大のものを取得して、一桁になるまでに操作を行う回数を答える" def kakezan(n): ret = 0 str_n = str(n) digit_amount = len(str_n) for i in range(digit_amount-1): # print(str_n[:i+1]) # print(str_n[i+1:]) # print("") ret = max(ret, int(str_n[:i+1])*int(str_n[i+1:])) return ret Q...
p01694 Step Aerobics
Step up and down Kazuki, commonly known as Kerr, who attends JAG University, was invited by your friend this summer to participate in the ICPC (International Collegiate Potchari Contest). ICPC is a sports contest and requires a high degree of athletic ability. However, Mr. Kerr was always in front of the computer, and...
```python while True: N = int(input()) if N == 0: break a = input() b = a.split() x = 0 for i in range(N//2): if b[2 * i] == 'lu' and b[(2 * i)+1] == 'ru': x += 1 if b[2 * i] == 'ru' and b[(2 * i)+1] == 'lu': x += 1 if b[2 * i] == 'ld' a...
p01974 Pigeonhole principle
problem Given $ N $ different natural numbers $ a_i $. I decided to make a pair by choosing a different natural number from the given natural numbers. Output one pair that can be created with a value difference that is a multiple of $ N -1 $. It should be noted that such a pair always exists. Example Input 5 1...
```python N = int(input()) a = [int(x) for x in input().split()] x, y = -1, -1 for i in range(N) : for j in range(N) : if i != j and abs(a[i] - a[j]) % (N - 1) == 0 : x, y = i, j print(a[x], a[y]) ```
p02260 Selection Sort
Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: SelectionSort(A) 1 for i = 0 to A.length-1 2 mini = i 3 for j = i to A.length-1 4 if A[j] < A[mini] 5 mini = j 6 swap A[i] and A[mini]...
```python n = int(input()) s = list(map(int, input().split())) indexMin = 0 count = 0 for start in range(n): indexMin = s[start:].index(min(s[start:])) + start s[start], s[indexMin] = s[indexMin], s[start] if start != indexMin: count+=1 print(*s) print(count) ```
p02408 Finding Missing Cards
Taro is going to play a card game. However, now he has only n cards, even though there should be 52 cards (he has no Jokers). The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond. Note 解説 Input In the first line, the number of cards n (n ≤ 52) is given. In the following n line...
```python n=int(input()) cs = [ (s,k) for s in ['S','H','C','D'] for k in range(1,14) ] for _ in range(n): s,k=input().split() cs.remove((s,int(k))) for (s, k) in cs: print(s, k) ```
101_C. Vectors
At a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector А: * Turn the vector by 90 degrees clockwise. * Add to the vector a certain vector C. Operations could be performed in any order any number of times. ...
```python import math def ok(xa, ya): x, y = xb - xa, yb - ya d = math.gcd(abs(xc), abs(yc)) if xc == 0 and yc == 0: return x == 0 and y == 0 if xc == 0: return x % yc == 0 and y % yc == 0 if yc == 0: return x % xc == 0 and y % xc == 0 if (x % d != 0) or (y % d != 0): ...
1043_A. Elections
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t...
```python import math n = int(input()) l= list(map(int,input().split())) s = 2*sum(l) z= s/n p = max(l) an = int(z+1) print(max(p,an)) ```
1107_D. Compression
You are given a binary matrix A of size n × n. Let's denote an x-compression of the given matrix as a matrix B of size n/x × n/x such that for every i ∈ [1, n], j ∈ [1, n] the condition A[i][j] = B[⌈ i/x ⌉][⌈ j/x ⌉] is met. Obviously, x-compression is possible only if x divides n, but this condition is not enough. For...
```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------------------------...
1136_D. Nastya Is Buying Lunch
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to de...
```python import sys import math import bisect from math import sqrt def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def rinput(): return map(int, sys.stdin.readline().strip().split()) def get_list(): return list(map(int, sys.stdin.readline().strip().split())) mod = int(1e9)+...
1155_A. Reverse a Substring
You are given a string s consisting of n lowercase Latin letters. Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position 3 and ends in position 6), but "aa" or "d" aren't substrings of this string. So the substring of the string s from po...
```python ''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' def main(): n = input() s = input() for i in range(len(s)-1): if s[i]>s[i+1]: p...
1176_F. Destroy it!
You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game. The boss battle consists of n turns. During each turn, you will get several cards. Each card has two parameters: its cost c_i and damage d_i. You may play some of your cards during each turn i...
```python import sys import math import cProfile DEBUG = False def log(s): if DEBUG and False: print(s) def calc_dmg(num, arr): maximum = 0 if num - len(arr) < 0: maximum = max(arr) return sum(arr) + maximum if DEBUG: sys.stdin = open('input.txt') pr = cProfile.Profile...
1195_D2. Submarine in the Rybinsk Sea (hard edition)
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the st...
```python from collections import Counter n = int(input()) a = list(map(int, input().split())) l = [len(str(i)) for i in a] c = Counter(l) cl = [c[i] for i in range(1,11)] M = 998244353 pad = lambda a, d: a%d + (a - a%d) * 10 #print(a, l, c, cl) ans = 0 for i in a: il = len(str(i)) # let's calculate it again t...
1236_A. Stones
Alice is playing with some stones. Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones. Each time she can do one of two operations: 1. take one stone from the first heap and two stones from the second heap (...
```python t = int(input()) while t>0: x, y, z = [int(i) for i in input().split()] s = 0 f = -1 z = z//2 if y >= z: y = y - z s = z*2 + z else: s = y*2 + y f = 1 if f == -1: y = y//2 if x >= y: s = s + 2*y + y ...
1277_E. Two Fairs
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n. Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ...
```python import sys import threading from collections import deque def func(): lines = sys.stdin.readlines() nxt = 0 t = int(lines[nxt]) nxt += 1 ans = [] for _ in range(t): n,m,a,b = map(int, lines[nxt].split()) nxt += 1 g = [[] for _ in range(n)] for _ in rang...
1382_A. Common Subsequence
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
```python #!/usr/bin/env python3 import io import os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_str(): return input().decode().strip() def rint(): return map(int, input().split()) def oint(): return int(input()) t = oint() for _ in range(t): n, m = rint() a = set(rint(...
1497_D. Genius
Please note the non-standard memory limit. There are n problems numbered with integers from 1 to n. i-th problem has the complexity c_i = 2^i, tag tag_i and score s_i. After solving the problem i it's allowed to solve problem j if and only if IQ < |c_i - c_j| and tag_i ≠ tag_j. After solving it your IQ changes and be...
```python def nr():return int(input()) def nrs():return [int(i) for i in input().split()] def f(n,t,s): d=[0]*n for i in range(1,n): for j in range(i-1,-1,-1): if t[i]==t[j]:continue sc=abs(s[i]-s[j]) d[i],d[j]=max(d[i],d[j]+sc),max(d[j],d[i]+sc) return max(d) for _ in range(nr()): n=nr() t=nrs() s=nrs...
151_C. Win or Freeze
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circl...
```python import sys line = sys.stdin.readline() N = int(line) tmp = N factor = [] i = 2 while i**2 <= tmp: if tmp % i == 0: tmp //= i factor.append(i) else: i += 1 if tmp != 1: factor.append(i) if len(factor) == 2: print(2) else: print(1) if len(factor) <= 1: print(0) else: print(fa...
1547_C. Pair Programming
Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming. It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file. Ever...
```python # -*- coding: utf-8 -*- """ Created on Sat Jul 10 23:15:34 2021 @author: Kevin Chang Project: Codeforces Problem 1547C """ t = int(input()) for i in range(t): shit = input() k, n, m = list(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) ...
195_A. Let's Watch Football
Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the si...
```python from math import ceil a,b,c = map(int,input().split()) t = (a*c - c*b)/b print(ceil(t)) ```
219_A. k-String
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string s, ...
```python from collections import Counter import string import math import sys def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(number_of_variables): if number_of_variables==1: return int(sys.stdin.readline()) if number_of_variables>=2: return map(int,sys.stdin...
242_C. King's Path
The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the...
```python from collections import deque x0,y0,x1,y1=list(map(int, input().split())) n=int(input()) allowed={} for i in range(n): r,a,b=list(map(int,input().split())) for j in range(a,b+1): allowed[(r,j)]=True visited={} q=deque() q.append((x0,y0)) visited[(x0,y0)]=0 dire=[(-1,0),(1,0),(0,-1),(0,1),(-1,...
268_A. Games
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ...
```python n=int(input()) mat=[] for i in range(n): mat.append(list(map(int, input().rstrip().split()))) b=0 for i in range (n): for j in range (n): if mat[i][0]==mat[j][1]: b=b+1 print(b) ```
290_D. Orange
<image> Input The first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase. The second line of the input is an integer between 0 and 26, inclusive. Output Output the required string. Examples Input AprilFool 14...
```python text = input().lower() caps = int(input())+97 for letter in text: print(letter.upper(), end='')if letter < chr(caps) else print(letter, end='') print() ```
316_B2. EKG
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another. (Cultural note: standing in huge and disorganized queues for hours is a native ...
```python def f(x, p): q = [] while x: q.append(x) x = p[x] return q from collections import defaultdict n, k = map(int, input().split()) t = list(map(int, input().split())) p = [0] * (n + 1) for i, j in enumerate(t, 1): p[j] = i p = [f(i, p) for i, j in enumerate(t, 1) if j == 0] s = de...
339_A. Helpful Maths
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
```python x=input() x=x.replace("+","") x=sorted(x) for i in range(1,2*len(x)-1,2): x.insert(i,"+") x=''.join(x) print(x) ```
361_C. Levko and Array Recovery
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types: 1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j ...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if ...
385_A. Bear and Raspberry
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≤ i ≤ n) day, the price for one barrel of honey is going to is xi kilos of raspberry. Unfortunately, the b...
```python n, c = map(int, input().split()) l = list(map(int, input().split())) ans = 0 for i in range(n - 1): d = l[i] - l[i + 1] - c ans = max(ans, d) print(ans) ```
405_E. Graph Cutting
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partiti...
```python import sys input = sys.stdin.readline print = sys.stdout.write def get_input(): n, m = [int(x) for x in input().split(' ')] graph = [[] for _ in range(n + 1)] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] graph[c1].append(c2) graph[c2].append(c1) ...
433_A. Kitahara Haruki's Gift
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends. Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ...
```python n = int(input()) a = list(input().split(' ')) a = list(int(x) for x in a) one, two = 0, 0 for i in range(n): if a[i] == 100: one += 1 else: two += 1 flag = False if one%2 == 0 and two%2 == 0 or one > two and two % 2 == 1 and one % 2 == 0 and one >= 2 \ or one < two and two%2 == 1 an...
478_A. Initial Bet
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player. Your task is to write a program that...
```python l=list(map(int,input().split())) x=sum(l) if(x%5==0 and x!=0): print(int(x/5)) else: print(-1) ```
500_C. New Year Book Reading
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi. As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a...
```python n,m=map(int,input().split()) weight=[int(i) for i in input().split()] order=[int(i) for i in input().split()] stack=[] for i in order: if i-1 not in stack: stack.append(i-1) #print(stack) ans=0 for i in order: #i=i-1 currlift=sum(weight[i] for i in stack[0:stack.index(i-1)]) ans+=currl...
526_A. King of Thieves
In this problem you will meet the simplified model of game King of Thieves. In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. <image> An interesting feature of the game is that you can design your own levels...
```python #!/usr/bin/env python # jump.py - Codeforces <!!! NNNA !!!> quiz # # Copyright (C) 2015 Sergey # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/L...
551_B. ZgukistringZ
Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one. GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x...
```python from collections import defaultdict def find_max_possible_substring(a, a_char_counts, char_counts): max_count_of_sub = len(a) for char, count in char_counts.items(): max_count_of_sub = min(max_count_of_sub, a_char_counts[char] // char_counts[char]) return max_count_of_sub def get_opti...
578_C. Weakness and Poorness
You are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poor...
```python """ Python 3 compatibility tools. """ from __future__ import division, print_function import itertools import sys import os from io import BytesIO, IOBase if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip def is_it_...
5_A. Chat Server's Outgoing Traffic
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: * Include a perso...
```python import sys n=0 ans=0 while True: i=sys.stdin.readline().strip() if len(i)<=1: break if i[0]=="+": n+=1 elif i[0]=="-": n-=1 else: ans+=(len(i.split(':')[1]))*n print(ans) ```
621_D. Rat Kwesh and Cheese
Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point. Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to ...
```python from decimal import * getcontext().prec = 700 x, y, z = map(Decimal, input().split()) a = [] a.append((y**z * x.ln(), -1, 'x^y^z')) a.append((z**y * x.ln(), -2, 'x^z^y')) a.append((y *z * x.ln(), -3, '(x^y)^z')) a.append((x**z * y.ln(), -5, 'y^x^z')) a.append((z**x * y.ln(), -6, 'y^z^x')) a.append((x *z * ...
643_B. Bear and Two Paths
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities. Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting ea...
```python import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, k = map(int, input().split()) a, b, c, d = map(int, input().split()) if k < n + 1 or n == 4: print("-1") exit(0) l = [_ for _ in range(1, n + 1)] l.remove(a) l.remove(b) l.remove(c) l.remove(d) print(a, end = ' ') print(c, end...
670_B. Game of Robots
In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109. At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. Aft...
```python n, k = input().split(' ') n = int(n) k = int(k) d = input().split(' ') i = 0 while True: i += 1 p = int((i) * (i+1) / 2) if k <= p : print(d[k-(p-i)-1]) break ```
691_D. Swaps in Permutation
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj). At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get? Let p and q be two permutations of the numbers 1, 2, ..., n. p i...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def solve(n,p,path): se, x, fin = [1] * (n + 1), 1, [0] * n while x != len(se): se[x], jj, curr, inde, vals = 0, 0, [x], [x - 1], [p[x - 1]] while jj != len(curr): ...
716_D. Complete The Graph
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edg...
```python import heapq from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edg...
737_A. Road to Cinema
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s. ...
```python # Question B. Road to Cinema import sys def roadToCinema(V, S, T, stations): # O(M) """ V : volume of fuel tank S : total distance T : time limit stations: fuel stations' locations rtype : boolean, whether this aircraft can travel within the time limit """ ...