name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p02362 Single Source Shortest Path (Negative Edges)
Constraints * 1 ≤ |V| ≤ 1000 * 0 ≤ |E| ≤ 2000 * -10000 ≤ di ≤ 10000 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E) and the source r. |V| |E| r s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph verti...
```python import collections import sys sys.setrecursionlimit(100000) # ---- belmann-ford ----- V_num, E_num, r = [int(ele) for ele in input().split()] adjc_list = [] edges = [] for _ in range(V_num): adjc_list.append([]) for _ in range(E_num): src, dst, w = [int(ele) for ele in input().split()] adjc_list...
1023_D. Array Restoration
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n. Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of t...
```python n,q=map(int,input().split()) arr=list(map(int,input().split())) count_zero=arr.count(0) count_q=arr.count(q) if count_q ==0 and count_zero ==0: print("NO") exit() if count_q ==0: for i in range(n): if arr[i] ==0: arr[i] =q break for i in range(n): r=arr[i] i...
108_B. Datatypes
Tattah's youngest brother, Tuftuf, is new to programming. Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava. Today, Tuftuf was introduced to Gava's unsigned integer datatypes. G...
```python n=int(input())-1 a=sorted(map(int,input().split())) ans='NO' for i in range(n): if a[i]<a[i+1]and a[i]*2>a[i+1]: ans='YES' print(ans) ```
1109_A. Sasha and a Bit of Relax
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
```python def main(): n = int(input()) arr = list(map(int,input().split())) pref = [None]*(n+1) pref[0] = 0 pref[1] = arr[0] funny = 0 for i in range(1,n): pref[i+1] = pref[i]^arr[i] even = dict() odd = dict() even[0] = 1 for i in range(1,n+1): if i&1: ...
1138_D. Camp Schedule
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symb...
```python def kmp(s): p = [0] * len(s) idx = 0 for i in range(1, len(s)): while idx > 0 and s[idx] != s[i]: idx = p[idx - 1] if s[idx] == s[i]: idx += 1 p[i] = idx return idx def solve(s, t, pref): f = [0, 0] f[0] = s.count('0') f[1] = s.cou...
1197_B. Pillars
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: ...
```python n=int(input()) ar=list(map(int,input().split())) m=max(ar) ind=-1 for i in range(n): if(ar[i]==m): ind=i ans="YES" a1=[] a2=[] for i in range(ind): a1.append(ar[i]) a2.append(ar[i]) a2.sort() for i in range(ind): if(a1[i]!=a2[i]): ans="NO" a3=[] a4=[] for i in range(ind+1,n):...
1214_C. Bad Sequence
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from i...
```python def main(): n = int(input()) s = input() tab = [] inc = 0 if s.count("(") != s.count(")"): print("No") return for x in range(n): if s[x] == ")": inc -= 1 else: inc += 1 tab.append(inc) if min(tab) >= -1: print("Yes") else: print("No") main() ```
1237_E. Balanced Binary Search Trees
Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree. The depth of a vertex is the number o...
```python # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code def main(): k = int(input()) s = [1,2,4,5] i = 2 while True: if s[-1] > int...
1255_E1. Send Boxes to Alice (Easy Version)
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o...
```python x=int(input()) from math import ceil s=list(map(int,input().split())) id=[] for n in range(x): if s[n]: id.append(n) if len(id)==1: print(-1) exit(0) sm=len(id) res=1e9 divs=set() for n in range(2,int(sm**.5)+1): if sm%n==0: divs.add(n) divs.add(sm//n) divs.add(sm) ...
1279_D. Santa's Bot
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids. Santa is really busy, so he wants the ...
```python import sys from collections import Counter from itertools import chain def input(): return sys.stdin.readline().rstrip() def input_ints(): return [int(_) for _ in input().split()] INV = {} def inv(x): if x not in INV: INV[x] = pow(x, M - 2, M) return INV[x] M = 998244353 n = int(...
129_B. Students and Shoelaces
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the f...
```python from collections import defaultdict n, m = [int(y) for y in input().split()] d=defaultdict(list) for i in range(m): a, b = [int(y) for y in input().split()] d[a].append(b) d[b].append(a) cnt=0 while True: f=0 vis=[False]*n for k, v in d.items(): if len(v)==1 and not vis[k-1]: ...
1341_D. Nastya and Scoreboard
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He w...
```python import sys input = sys.stdin.readline def main(): N, K = [int(x) for x in input().split()] S = [int(input().strip(), 2) for _ in range(N)] A = [119, 18, 93, 91, 58, 107, 111, 82, 127, 123] B = [[-1] * 10 for j in range(N)] for i, s in enumerate(S): for j in range(10): ...
1405_A. Permutation Forgery
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 4 in the array). Let p be any permutation of length ...
```python # Om Namh Shivai # Jai Shree Ram # Jai Hanuman # Jai Shree Krishna # Radhe-Krishna # Jai Maa Kali # Jai Maa Durga # Jai Maa Burithakran for i in range(int(input())): n = int(input()) arr = list(map(int, input().split())) if(n%2 == 0): arr_res = list(reversed(arr)) else: arr_re...
1426_C. Increase and Copy
Initially, you have the array a consisting of one element 1 (a = [1]). In one move, you can do one of the following things: * Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); * Append the copy of some (single) element of a to the end of the array...
```python from math import ceil for _ in range(int(input())): n = int(input()) b = ceil(pow(n, 0.5)) a = ceil(n / b) ans = a + b - 2 print(ans) ```
144_B. Meeting
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at...
```python xa, ya, xb, yb = map(int, input().split()) blankets, radiators = 0, [tuple(map(int, input().split())) for i in range(int(input()))] if xa > xb: xa, xb = xb, xa if ya > yb: ya, yb = yb, ya def distance(x1, y1, x2, y2): return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 for y in [ya, yb]: p = ...
1473_B. String LCM
Let's define a multiplication operation between a string a and a positive integer x: a ⋅ x is the string that is a result of writing x copies of a one after another. For example, "abc" ⋅~2~= "abcabc", "a" ⋅~5~= "aaaaa". A string a is divisible by another string b if there exists an integer x such that b ⋅ x = a. For e...
```python def gcd(a,b): if a == 0: return b return gcd(b % a, a) # Function to return LCM of two numbers def compute_lcm(a,b): return (a / gcd(a,b))* b def main(): T = int(input()) for c in range(T): s1 = input().rstrip() s2 = input().rstrip() s = s1 if le...
1521_B. Nastia and a Good Array
Nastia has received an array of n positive integers as a gift. She calls such an array a good that for all i (2 ≤ i ≤ n) takes place gcd(a_{i - 1}, a_{i}) = 1, where gcd(u, v) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers u and v. You can perform the op...
```python from sys import stdin """ n=int(stdin.readline().strip()) n,m=map(int,stdin.readline().strip().split()) s=list(map(int,stdin.readline().strip().split())) """ T=int(stdin.readline().strip()) for caso in range(T): n=int(stdin.readline().strip()) s=list(map(int,stdin.readline().strip().split())) mn=1...
1550_B. Maximum Cost Deletion
You are given a string s of length n consisting only of the characters 0 and 1. You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For...
```python for iii in range(int(input())): n,a,b=map(int,input().split()) q=input() if b>=0: x=n*(a+b) print(x) else: cout=1 x=q[0] for i in range(1,n): if x!=q[i]: cout+=1 x=q[i] print((n*a)+(((cout//2)+1)*b)) `...
197_B. Limit
You are given two polynomials: * P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and * Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm. Calculate limit <image>. Input The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The seco...
```python from math import gcd def polynomials(): n, m = map(int, input().strip().split()[:2]) if n > 100 or m > 100 or n < 0 or m < 0: print() else: ap1 = list(map(int, input("").split()[:n+1])) aq1 = list(map(int, input("").split()[:m+1])) if ap1[0] == 0 or aq1[0] == 0: ...
26_B. Regular Bracket Sequence
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. One day Johnny got bracket sequence. He decided to remove some...
```python # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): l=list(input()) # print(l) ans=0 stack=0 for item in l: if item=='(': stack+=1 else: if stack:...
340_B. Maximal Area Quadrilateral
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one...
```python def convex(p): p.sort(key = lambda x:(x.real, x.imag)) p = p[0:1] + sorted(p[1:], key = lambda x:(x-p[0]).imag / abs(x-p[0])) j = 1 for i in range(2, len(p)): while j > 1 and ((p[j] - p[j-1]) * (p[i] - p[j]).conjugate()).imag > -(1e-8): j -= 1 else: j +=...
363_D. Renting Bikes
A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them. The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles. In total, the boys' shared budget is a rubles. Besides, each of them has his own pe...
```python def readn(): return map(int, input().split()) n,m,a=readn()#map(int,input().split()) b,p=sorted(map(int,input().split()))[-min(n,m):],sorted(map(int,input().split())) r=min(n,m) mm=r l=0 while l<=r: mid=l+(r-l)//2 pri=sum([max(0,p[i]-b[mm-mid+i]) for i in range(mid)]) if pri<=a: l=mid+1 ...
387_C. George and Number
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence...
```python s = input() r = len(s) c = 1 for i in range(len(s)-1, 0, -1): if s[i] != '0': if i > r-i: c += 1 r = i elif i == r-i: if s[:i] >= s[i:r]: c += 1 r = i else: break print(c) ```
408_A. Line to Cashier
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p...
```python num_cashiers = int(input()) queue_sizes = list(map(lambda x: int(x) * 15, input().split())) items = [] for i in range(num_cashiers): items_list = sum(map(lambda x: int(x) * 5, input().split())) items.append(items_list) min_time = min(change + groceries for change, groceries in zip(queue_sizes, item...
435_B. Pasha Maximizes
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer. Help Pasha count the maximum number he can get if he has the time to make at most k sw...
```python a,k=input().split() l=list(a) k=int(k) n=len(l) for i in range(n): t=l[i] i1=0 for j in range(i+1,min(i+k+1,n)): if l[j]>t: t=l[j] i1=j while i1>i: k-=1 l[i1],l[i1-1]=l[i1-1],l[i1] i1-=1 print(''.join(l)) ```
47_B. Coins
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul...
```python def R(): return map(int, input().split()) def I(): return int(input()) def S(): return str(input()) def L(): return list(R()) from collections import Counter import math import sys from itertools import permutations a=['A','B','C'] s=set() for _ in range(3): s.add(S()) l= list(permutations(a)) fo...
504_B. Misha and Permutations Summation
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation <image>, where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order. For example, Perm(0) = (0, 1, ..., n...
```python import sys class SegmTree(): def __init__(self, array=None): size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) for i in range(size): self.tree[i+self.N] = array[i] self.build() def...
553_C. Love Triangles
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (the...
```python from sys import stdin, stdout import sys class Node(object): def __init__(self, label): self.label = label self.par = self self.rank = 0 class DisjointSet(object): def __init__(self, n): self.n = n self.nodes = [Node(i) for i in range(self.n)] def find(...
601_A. The Two Routes
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
```python #created by Кама Пуля n,m=map(int,input().split()) L=[[] for i in range(n+1)] for i in range(m) : a,b=map(int,input().split()) L[a].append(b) L[b].append(a) if n not in L[1] : l=[1] D=[-1 for i in range(n+1)] D[1]=0 while len(l)>=1 : t=l[0] del(l[0]) for x i...
623_D. Birthday
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. n friends came by, and after a typical party they decided to play blind man's buff. The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several ro...
```python import random N = int(input()) prob = [float(x)/100 for x in input().strip().split()] prob_sum = [] cur = 0 for i in range(N): cur += prob[i] prob_sum.append(cur) def experiment(): cur_prob = [1.] * N cur_exp = 0 for i in range(200000): bp = [prob[i] * cur_prob[i] / (1-cur_prob[...
645_C. Enduring Exodus
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied. ...
```python import sys input = sys.stdin.readline def judge(i, x): return acc[min(n, i+x+1)]-acc[max(0, i-x)]>=k+1 def binary_search(i): l, r = 0, n while l<=r: mid = (l+r)//2 if judge(i, mid): r = mid-1 else: l = mid+1 return l n, k = ...
672_A. Summer Camp
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to...
```python n = int(input()) cur = 0 s = '' for i in range(1, n + 1): s += str(i) if len(s) >= n: print(s[n - 1]) exit(0) ```
697_C. Lorenzo Von Matterhorn
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two...
```python def main(): d = {} for _ in range(int(input())): c, *l = input().split() if c == "1": v, u, w = map(int, l) while u != v: if u < v: d[v] = d.get(v, 0) + w u, v = v // 2, u else: ...
718_A. Efim and Strange Grade
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after th...
```python n, t = map(int, input().split()) tmp = input() s = [] for i in range(n): s.append(tmp[i]) ind = n perenos = 0 for i in range(n): if (s[i] == '.'): nach = i + 1 for i in range(nach, n): if (int(s[i]) > 4): ind = i break if (ind == n): print(*s, sep="") exit() while (...
73_A. The Elder Trolls IV: Oblivon
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so ...
```python I=lambda: map(int,input().split()) x,y,z,k=I() a1,a2,a3,q=0,0,0,0 while q<3: q=0 if a1+a2+a3==k: break if a1<x-1: a1+=1 if a1+a2+a3==k: break else: q+=1 if a2<y-1: a2+=1 if a1+a2+a3==k: break else: q+=1 if a3<z-1: a3+=1 ...
786_A. Berzerk
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the oth...
```python f = lambda: list(map(int, input().split()))[1:] n = int(input()) s, p, q = [], [], [] for x in [0, 1]: r = f() s.append(r) t = [len(r)] * n t[0] = 0 p.append(t) q.append((x, 0)) while q: x, i = q.pop() y = 1 - x for d in s[y]: j = (i - d) % n if p[y][j] < 1:...
832_A. Sasha and Sticks
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak...
```python n,k=map(int,input().split()) if (n//k)%2!=0: print('YES') else: print('NO') ```
877_C. Slava and tanks
Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map. Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies ...
```python n = int(input()) if n == 2: print(3) print(2, 1, 2) else: shoots = [i for i in range(2, n + 1, 2)] + [i for i in range(1, n + 1, 2)] + [i for i in range(2, n + 1, 2)] print(len(shoots)) print(" ".join(map(str, shoots))) ```
900_D. Unusual Sequences
Count the number of distinct sequences a1, a2, ..., an (1 ≤ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and <image>. As this number could be large, print the answer modulo 109 + 7. gcd here means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Input Th...
```python M=10**9+7 a,b=map(int,input().split()) if b%a:print(0) else: b//=a d=set() for i in range(1,int(pow(b,0.5)+1)): if b%i==0: d.add(i) d.add(b//i) d=sorted(list(d)) f=d[::] for i in range(len(f)): f[i]=pow(2,d[i]-1,M) for j in range(i): ...
923_B. Producing Snow
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden. Each day, every pile w...
```python n=int(input()) v=list(map(int,input().split())) t=list(map(int,input().split())) sumv=list() sumv.append(0) for i in range(n): sumv.append(sumv[i]+v[i]) sumt=list() sumt.append(0) for i in range(n): sumt.append(sumt[i]+t[i]) ans=[0]*(n) add=[0]*(n+1) for i in range(n): if(v[i]<=t[i]): an...
950_D. A Leapfrog in the Array
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that i...
```python from collections import defaultdict, deque, Counter from sys import stdin, stdout from heapq import heappush, heappop import math import io import os import math import bisect input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # python3 15.py<in>op\ n, m = map(int, input().split()) for i in range(...
978_G. Petya's Exams
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n. There are three values about each exam: * s_i — the day, when questions for the i-th exam will be published, * d_i — t...
```python n, m = map(int, input().split()) x = [] ans = [0] * n for i in range(m): s, d, c = map(int, input().split()) x.append([d - 1, s - 1, c, i + 1]) ans[d - 1] = m + 1 x.sort() for d, s, c, i in x: cnt = 0 while cnt < c: if s == d: print(-1) exit() if ans...
999_A. Mishka and Contest
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic...
```python n, k =map(int, input().split()) a=list(map(int, input().split())) i=s=0 while i<n: if a[i]<=k: s+=1 i+=1 else: if a[n-1]<=k: s+=1 n-=1 else: break print(s) ```
p02663 NOMURA Programming Competition 2020 - Study Scheduling
In this problem, we use the 24-hour clock. Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying? Constraint...
```python a,b,c,d,e=map(int,input().split()) ans=(c-a)*60+d-b-e print(ans) ```
p02792 AtCoder Beginner Contest 152 - Handstand 2
Given is a positive integer N. Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition: * When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B. Con...
```python N = int(input()) l = [[0 for j in range(10)] for i in range(10)] for n in range(1, N+1): s = str(n) i = int(s[0]) j = int(s[-1]) l[i][j] += 1 ans = sum([l[i][j]*l[j][i] for i in range(10) for j in range(10)]) print(ans) ```
p02928 Japanese Student Championship 2019 Qualification - Kleene Inversion
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}. Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2. Find the inversion number of B, modulo 10^9 + 7. Here the inversion number of B is defined as the number of o...
```python N,K=list(map(int,input().split())) A=list(map(int,input().split())) mod=10**9+7 p=0 p_=0 for i,j in enumerate(A): p+=len(list(filter(lambda x:x>j,A))) p_+=len(list(filter(lambda x:x<j,A[i:]))) ans=p_*K+p*K*(K-1)//2 print(ans%mod) ```
p03064 Tenka1 Programmer Contest 2019 - Three Colors
You are given N integers. The i-th integer is a_i. Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied: * Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area...
```python M=998244353 N,*A=open(0) d=[0]*90001 d[0]=1 e=[0]*90001 e[0]=1 z=1 s=0 for a in A: i=s;a=int(a);s+=a;z*=3 while~i:d[i+a]+=d[i]%M;d[i]*=2;e[i+a]+=e[i]%M;i-=1 i=s while i*2>=s:z=(z-d[i]*3)%M;i-=1 print([(z+e[s//2]*3)%M,z][s%2]) ```
p03207 AtCoder Beginner Contest 115 - Christmas Eve Eve
In some other world, today is the day before Christmas Eve. Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan). He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 i...
```python ps = [ int(input()) for _ in range(int(input()))] print(sum(ps)-max(ps)//2) ```
p03354 AtCoder Beginner Contest 097 - Equals
We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N. We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M). AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N)...
```python n,m = list(map(int, input().split())) p = list(map(int, input().split())) # parentsには根の要素番号(自身が根の場合は、要素数(マイナスの値))が入る parents = [-1] * (n + 1) def find(x): if parents[x] < 0: return x else: parents[x] = find(parents[x]) return parents[x] def union(x, y): x = find(x) y ...
p03677 AtCoder Regular Contest 077 - guruguru
Snuke is buying a lamp. The light of the lamp can be adjusted to m levels of brightness, represented by integers from 1 through m, by the two buttons on the remote control. The first button is a "forward" button. When this button is pressed, the brightness level is increased by 1, except when the brightness level is m...
```python n,m=map(int,input().split()) arr=list(map(int,input().split())) imos1=[0]*(m*2+2) imos2=[0]*(m*2+2) imos3=[0]*(m*2+2) for i in range(n-1): cost=(m+arr[i+1]-arr[i])%m if arr[i]<arr[i+1]: imos1[arr[i]]+=cost imos1[arr[i]+m]-=cost imos2[arr[i]+2]+=-1 imos2[arr[i+1]+1]+=1 imos3[arr[i+1]+1]...
p03832 AtCoder Regular Contest 067 - Grouping
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions: * Every group contains between A and B people, inclusive. * Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds. ...
```python N, A, B, C, D = map(int, input().split()) mod = 7 + 10 ** 9 fact = [1] * (N+1) frev = [1] * (N+1) for i in range(1, N+1): temp = fact[i] = (fact[i-1] * i) % mod frev[i] = pow(temp, mod-2, mod) def P(n, r): return (fact[n] * frev[n-r]) % mod DP = [[0 for j in range(N+1)] for i in range(N+1)] for...
p03997 AtCoder Beginner Contest 045 - Trapezoids
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively. <image> An example of a trapezoid Find the area of this trapezoid. Constraints * 1≦a≦100 * 1≦b≦100 * 1≦h≦100 * All input values are integers. * h is even. Input The input is given from Standard Input i...
```python a,b,h=[int(input()) for i in range(3)];print(int((a+b)*h/2)) ```
p00085 Joseph's Potato
<image> There used to be a game called Joseph's potatoes. Let's say n people are participating. Participants form a circle facing the center and are numbered starting from 1. One hot potato is given to participant n (the large number 30 inside the figure on the left). Participants who are given the potatoes will give...
```python while 1: n,m=map(int,input().split()) if n==0:break a=m-1 while a<(m-1)*n: a=m*a//(m-1)+1 a=n*m-a print(a) ```
p00217 Walking in the Hospital
At Aizu Riverside Hospital, inpatients walk twice a day for rehabilitation and health promotion. As the number of people trying to recover their physical strength by walking is increasing day by day in order to leave the hospital energetically, the director plans to give a present to the person who walked the longest d...
```python while True: n = int(input()) if n == 0: break ls = [] for i in range(n): v = list(map(int,input().split())) ls.append((sum(v[1:]),v[0])) ls.sort() ls.reverse() print(ls[0][1],ls[0][0]) ```
p00377 Cake Party
I’m planning to have a party on my birthday. Many of my friends will come to the party. Some of them will come with one or more pieces of cakes, but it is not certain if the number of the cakes is a multiple of the number of people coming. I wish to enjoy the cakes equally among the partiers. So, I decided to apply th...
```python #標準入力 a,b = map(int,input().split()) num = list(map(int,input().split())) #リストの値を全て合計する num = sum(num) #出力 if num % (a + 1) == 0:print(num // (a + 1)) else:print(num // (a + 1) + 1) ```
p00595 Greatest Common Divisor
Please find the greatest common divisor of two natural numbers. A clue is: The Euclid's algorithm is a way to resolve this task. Input The input file consists of several lines with pairs of two natural numbers in each line. The numbers do not exceed 100000. The number of pairs (datasets) is less than 50. Output ...
```python import sys def gcd(a,b): if(b): return gcd(b,(a%b)) else: return a List = [] for i in sys.stdin: List.append(i) for data in List: print(gcd(int(data.split()[0]),int(data.split()[1]))) ```
p00731 Cliff Climbing
At 17:00, special agent Jack starts to escape from the enemy camp. There is a cliff in between the camp and the nearest safety zone. Jack has to climb the almost vertical cliff by stepping his feet on the blocks that cover the cliff. The cliff has slippery blocks where Jack has to spend time to take each step. He also ...
```python import sys import math import bisect import heapq import copy sys.setrecursionlimit(1000000) from collections import deque from itertools import permutations def main(): dy = [-2,-1,0,1,2,-1,0,1,0] rx = [1,1,1,1,1,2,2,2,3] lx = [-1,-1,-1,-1,-1,-2,-2,-2,-3] inf = 1000000007 while True: ...
p01134 Area Separation
Mr. Yamada Springfield Tanaka was appointed as Deputy Deputy Director of the National Land Readjustment Business Bureau. Currently, his country is in the midst of a major land readjustment, and if this land readjustment can be completed smoothly, his promotion is certain. However, there are many people who are not hap...
```python import math EPS = 1e-10 def eq(a, b): return (abs(a-b) < EPS) def eqv(a, b): return (eq(a.real, b.real) and eq(a.imag, b.imag)) def cross(a, b): return a.real * b.imag - a.imag * b.real def is_intersected_ls(a1, a2, b1, b2): return (cross(a2-a1, b1-a1) * cross(a2-a1, b2-a1) < EPS) and \ ...
p01273 Infected Computer
Adam Ivan is working as a system administrator at Soy Group, Inc. He is now facing at a big trouble: a number of computers under his management have been infected by a computer virus. Unfortunately, anti-virus system in his company failed to detect this virus because it was very new. Adam has identified the first comp...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split...
p02168 Double or Increment
Problem One day, mo3tthi and tubuann decided to play a game with magic pockets and biscuits. Now there are $ K $ pockets, numbered $ 1,2, \ ldots, K $. The capacity of the $ i $ th pocket is $ M_i $, which initially contains $ N_i $ biscuits. mo3tthi and tubuann start with mo3tthi and perform the following series of o...
```python K = int(input()) ans = 0 for _ in range(K): N, M = map(int, input().split()) grundy0 = {0} grundy1 = {1} m = M while m // 2 >= N: if (m+1)//2%2: grundy_l = grundy0 else: grundy_l = grundy1 m, r = divmod(m, 2) if r==0: gr0 ...
p02309 Cross Points of Circles
For given two circles $c1$ and $c2$, print the coordinates of the cross points of them. Constraints * The given circle have at least one cross point and have different center coordinates. * $-10,000 \leq c1x, c1y, c2x, c2y \leq 10,000$ * $1 \leq c1r, c2r \leq 10,000$ Input The input is given in the following format...
```python # coding: utf-8 # Your code here! import math EPS = 0.0000000001 COUNTER_CLOCKWISE = 1 CLOCKWISE = -1 ONLINE_BACK = 2 ONLINE_FRONT = -2 ON_SEGMENT = 0 class Point: global EPS def __init__(self, x = 0, y = 0): se...
p02457 Set: Range Search
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$ (0 or 1). * delete($x$): Delete $x$ from $S$. * dump($L$, $R...
```python from bisect import bisect_left, bisect_right, insort_left q = int(input()) S = [] D = {} a = [] c = 0 for i in range(q): a.append(list(map(int,input().split()))) for i in range(q): if a[i][0] == 0: if not a[i][1] in D: insort_left(S,a[i][1]) D[a[i][1]] = 1 ...
1017_B. The Bits
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise...
```python n = int(input()) a = input() b = input() index = [] zeros = 0 ones = 0 for i in range(n): if b[i]=='0': index.append(i) if a[i]=='0': zeros += 1 else: ones += 1 ans = 0 interchange = 0 for i in index: if a[i]=='0': ans += ones zeros -= 1 else: ...
1040_D. Subway Pursuit
This is an interactive problem. In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontr...
```python import sys import random random.seed() n, k = [int(x) for x in input().split()] sson = 8*k + 1 ssoff = 4*k + 1 l = 1 r = n ss = True if r-l > sson else False while True: if ss: al = l ar = (l + r) // 2 print(al, ar) sys.stdout.flush() ans = input() if ...
1085_C. Connect Three
The Squareland national forest is divided into equal 1 × 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C i...
```python koor = dict() a = input() xa = int(a.split()[0]) ya = int(a.split()[1]) b = input() xb = int(b.split()[0]) yb = int(b.split()[1]) c = input() xc = int(c.split()[0]) yc = int(c.split()[1]) koor[ya] = xa koor[yb] = xb koor[yc] = xc print(max(xa, xb, xc) + max(ya, yb, yc) - min(xa, xb, xc) - min(ya, yb, yc) +...
1105_A. Salem and Sticks
Salem gave you n sticks with integer positive lengths a_1, a_2, …, a_n. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x. A stick length a_i is...
```python n = int(input()) a = [int(t) for t in input().split(' ')] mincost = 1000 * 100 + 1 best_t = None for t in range(1, 101): cost = 0 for x in a: cost += max(0, abs(x - t) - 1) if cost < mincost: mincost = cost best_t = t print(best_t, mincost) ```
1132_D. Stressful Training
Berland SU holds yet another training contest for its students today. n students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers! Let students be numbered from 1 to n. Laptop of the i-th student has charge a_i at the beginning of the contest and it uses b_i of char...
```python import sys import os from math import trunc s = os.read(0,os.fstat(0).st_size) inp = [] sign = 1.0 numb = 0.0 for i in range(len(s)): if s[i]>=48: numb = 10.0*numb + s[i]-48.0 else: if s[i]==45: sign = -1.0 elif s[i]!=13: inp.append(sign*numb) ...
1174_E. Ehab and the Expected GCD Problem
Let's define a function f(p) on a permutation p as follows. Let g_i be the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of elements p_1, p_2, ..., p_i (in other words, it is the GCD of the prefix of length i). Then f(p) is the number of distinct elements among g_1, g_2, ..., g_...
```python p=10**9+7 import math def r(l): x=1 for m in l: x=x*m%p return x n=int(input()) a,k,x,t=[],int(math.log2(n)),n,0 while x>0: a.append(x-x//2) x//=2 b=[n//(3*2**i)-n//(6*2**i) for i in range(k+1)] d=[n//2**i-n//(3*2**i) for i in range(k+1)] y=r([i for i in range(2,n+1)]) s=k if n<3*2...
1210_C. Kamil and Making a Stream
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him? You're given a tree — a connected undirected graph consisting of n vertices conne...
```python from math import gcd from collections import deque from bisect import bisect_left from sys import setrecursionlimit MOD = 1000000007 def modInt(mod): class ModInt: def __init__(self, value): self.value = value % mod def __int__(self): return self.value ...
1231_A. Dawid and Bags of Candies
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
```python a1, a2, a3, a4 = map(int, input().split()) n = sum([a1, a2, a3, a4]) if n % 2 != 0: print('NO') else: if (a1 + a3 == a2 + a4 or a1 + a4 == a2 + a3 or a1 + a2 == a3 + a4): print('YES') elif (a1 - (n - a1) == 0 or a2 - (n - a2) == 0 or a3 - (n - a3) == 0 ...
1272_C. Yet Another Broken Keyboard
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them! A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≤ a ≤ b ≤ n). For e...
```python n, k = [int(i) for i in input().split()] s = input() arr = input().split() subs = [0] for x in s: if(x in arr): subs[-1] += 1 else: subs.append(0) count = 0 for x in subs: count += x*(x+1)/2 print(int(count)) ```
1295_D. Same GCDs
You are given two integers a and m. Calculate the number of integers x such that 0 ≤ x < m and \gcd(a, m) = \gcd(a + x, m). Note: \gcd(a, b) is the greatest common divisor of a and b. Input The first line contains the single integer T (1 ≤ T ≤ 50) — the number of test cases. Next T lines contain test cases — one pe...
```python import sys, math for ii in range(int(input())): a,m = map(int,input().split()) g = math.gcd(a,m) m=int(m/g) ans = m for i in range(2,int(math.sqrt(m))+1): if m%i==0: ans-=(ans/i) while m%i==0: m=int(m/i) if m>1: ans-=ans/m print(int(...
1316_D. Nash Matrix
Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n× n board. Rows and columns of this board are numbered from 1 to n. The cell on the intersection of the r-th row and c-th...
```python from collections import deque import sys def input(): return sys.stdin.buffer.readline()[:-1] def main(): n = int(input()) res = [[''] * n for _ in range(n)] data = [[None] * n for _ in range(n)] q = deque() for i in range(n): row = [int(x) - 1 for x in input().split()] ...
137_E. Last Chance
Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Inn...
```python s=[(0,0)] c=0 for i,x in enumerate(input()) : c+=-1 if x.lower() in 'aeiou' else 2 s.append((c,i+1)) #print(s) lis = sorted(s) #print(lis) u = 10**9 d = {} answer = 0 for i in lis : if u < i[1] : if i[1]-u >= answer : answer = i[1]-u d[answer] = d.get(answer , 0) + 1 ...
1444_A. Division
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division. To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that: * p_i is divisible by x_i; * x_i is not divisible by q_i. ...
```python from sys import stdin, stdout from math import sqrt #stdin = open('Q3.txt', 'r') def II(): return int(stdin.readline()) def MI(): return map(int, stdin.readline().split()) bigp=10**18+7 primes=[] def SieveOfEratosthenes(n,primes): prime = [True for i in range(n+1)] p = 2 while (p * p <= n): ...
1469_B. Red and Blue
Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue. After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence ...
```python for _ in range(int(input())): n=int(input()) r=list(map(int,input().split())) m=int(input()) b=list(map(int,input().split())) c,t,prev,prevv=0,0,0,0 for i in r: t+=i prev=max(t,prev) t=0 for i in b: t+=i prevv=max(t,prevv) if prev <...
1494_D. Dogeforces
The Dogeforces company has k employees. Each employee, except for lower-level employees, has at least 2 subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employ...
```python import heapq class UF: def __init__(self, N): self.par = list(range(N)) self.sz = [1] * N def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y)...
1517_C. Fillomino 2
Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it: Consider an n by n chessboard. Its rows are numbered from 1 to n from the top to the bottom. Its columns are numbered from 1 t...
```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...
1545_B. AquaMoon and Chess
Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if po...
```python from sys import stdin, stdout import heapq from collections import defaultdict import math import bisect import io, os # for interactive problem # n = int(stdin.readline()) # print(x, flush=True) #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def ncr(n, r, p): # initialize numerator ...
172_A. Phone Code
Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest comm...
```python n = int(input()) phone = [] for i in range(n): s = input().strip() phone.append(s) c = 0 k = 0 flag = True while True: for p in phone: if p[k] != phone[0][k]: flag = False break k += 1 if flag: c += 1 else: print(c) break ```
192_B. Walking in the Rain
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from ...
```python n=int(input()) l=list(map(int,input().split())) c=9999 for i in range(n-1): if(l[i]<=l[i+1] and l[i+1]<c): c=l[i+1] elif(l[i]>l[i+1] and l[i]<c): c=l[i] print(min(l[0],l[n-1],c)) ```
216_B. Forming Teams
One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people. We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B ...
```python def arr_inp(): return [int(x) for x in stdin.readline().split()] class graph: # initialize graph def __init__(self, gdict=None): if gdict is None: gdict = defaultdict(list) self.gdict = gdict # get edges def edges(self): return self.find_edges() ...
23_B. Party
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount of pe...
```python for i in range(int(input())): x = int(input()) print(max(0,x-2)) ```
336_B. Vasily the Bear and Fly
One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), r...
```python m, r = map(int, input().split()) def calc(k): if k < 1: return 0 else: return (1 + 2 * (k - 1)) * 2**0.5 + k * 2 + (k - 1) * (k - 2) avg = 0 div = m ** 2 for i in range(0, m): avg += r * (2 + calc(i) + calc(m - 1 - i)) / div print(avg) ```
359_C. Prime Number
Simon has a prime number x and an array of non-negative integers a1, a2, ..., an. Simon loves fractions very much. Today he wrote out number <image> on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: <image>, where number t equals xa1 + a2 + ... + an. Now ...
```python import sys import heapq input = sys.stdin.readline MOD = int(1e9+7) n, x = list(map(int, input().split())) a = list(map(int, input().split())) s, h = sum(a), [] for i in a: heapq.heappush(h, s-i) p, cnt = 0, 0 while h: z = heapq.heappop(h) if p == z: cnt += 1 if cnt == x: ...
382_B. Number Busters
Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers a, b, w, x (0 ≤ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number...
```python a, b, w, x, c = map(int, input().split()) def result(a, b, w, x, c, s): na = a - (s * x - b) / w nc = c - s return (na, nc) def solve(a, b, w, x, c): left = 0 right = 10e15 if (c <= a): return 0 while (left < right): half = (left+right) // 2 ret = result(a, b, w, x, c, half) if (ret[1] <= re...
403_A. Searching for Graph
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A sub...
```python t = int(input()) while t > 0: [n, p] = map(int, input().split(' ')) count = int(0) for i in range(n): j = i+2 while j <= n: count = count+1 print(str(i+1)+' '+str(j)) if count == 2*n+p: break j = j + 1 if j <=...
430_B. Balls Game
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any p...
```python def destroy_balls(_a, _b, _x): if len(_a) == 0 or len(_b) == 0: return 0 lenb = len(_b) a_cur_index = len(_a) - 1 b_cur_index = 0 if _a[a_cur_index] == _b[b_cur_index]: to_be_destroyed = 2 a_cur_index -= 1 b_cur_index += 1 while a_cur_index >= 0: ...
499_C. Crazy Town
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the po...
```python x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) n = int(input()) arr = [] for _ in range(n): a, b, c = map(int, input().split()) arr.append((a,b,c)) res = 0 for i in arr: a, b, c = i if(b != 0): y00 = -c/b y01 = -(a+c)/b s1 = x1*(y01-y00)-(y1-y00) s2 = x2*(y01-y00)-(y2-y00) ...
522_D. Closest Equals
You are given sequence a1, a2, ..., an and m queries lj, rj (1 ≤ lj ≤ rj ≤ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x ≠ y), that: * both indexes of the elements lie within range [lj, rj], that is, lj ≤ x, y ≤ rj; * the values of the elements are equal, tha...
```python import sys class Fenwick(object): def __init__(self, n): self.n = n self.a = [10**9 for i in range(n)] self.w= 10**9 def zag(self, i, zn): self.w= min(self.w, zn) while i < self.n: self.a[i] = min(self.a[i], zn) i = (i | (i + 1)) def pol(self, r): ans= 10**9 wh...
575_H. Bots
Sasha and Ira are two best friends. But they aren’t just friends, they are software engineers and experts in artificial intelligence. They are developing an algorithm for two bots playing a two-player game. The game is cooperative and turn based. In each turn, one of the players makes a move (it doesn’t matter which pl...
```python # https://codeforces.com/problemset/problem/575/H import sys import math MOD = 1000000007 def inv(a, b): if(a > 1): return b-inv(b % a, a)*b//a else: return 1 def main(): # sys.stdin = open('E:\\Sublime\\in.txt', 'r') # sys.stdout = open('E:\\Sublime\\out.txt', 'w') #...
598_C. Nearest vectors
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them. Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 ...
```python from functools import cmp_to_key n = int(input()) def dot(p1,p2): x1,y1 = p1 x2,y2 = p2 return x1 * x2 + y1 * y2 def cross(p1,p2): x1,y1 = p1 x2,y2 = p2 return x1 * y2 - x2 * y1 def top(p): x,y = p return y > 0 or (y == 0 and x > 0) def polarCmp(p1,p2): res = False...
61_A. Ultra-Fast Mathematician
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
```python a = input() b = input() res = [] for i in range(len(a)): if(a[i] != b[i]): res.append('1') else: res.append('0') print(''.join(res)) ```
667_C. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know l...
```python s = input()[5:][::-1] n = len(s) mu = set() can2 = [0]*(n+1) can3 = [0]*(n+1) if n >= 2: mu.add(s[0:2][::-1]) can2[2] = 1 if n >= 3: mu.add(s[0:3][::-1]) can3[3] = 1 if n >= 4 and s[0:2] != s[2:4]: mu.add(s[2:4][::-1]) can2[4] = 1 if n >= 5: mu.add(s[2:5][::-1]) mu.add(s[3:5]...
690_C1. Brain Network (easy)
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite!...
```python import sys sys.setrecursionlimit(1000000) def dfs(v, pr): global used global p global f if not f: return None if used[v]: f = False used[v] = True for i in range(len(p[v])): if p[v][i] != pr: dfs(p[v][i], v) n, m = map(int, input().split()) p = [...
734_C. Anton and Making Potions
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions. Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. 1. Spells of...
```python """ ref: http://codeforces.com/blog/entry/48397 At first, observe that if we'll take the i-th potion of the first type and the j-th potion of the second type, then we can prepare all the potions in ai*(n-cj) seconds. So, we have to minimize this number. Let's iterate over what potion of the first type we'll ...
758_C. Unfair Poll
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others. Seating in the class looks like a rectangle, where n rows with m pupils in each. The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of t...
```python import math import sys def printf(*a): if len(sys.argv) > 1: print(a) n, m, k, x, y = map(int, input().split()) mi = 0 ma = 0 serg = 0 filed_lines = k//m partial_line = k%m printf(filed_lines, partial_line) if n==1: mi = filed_lines ma = filed_lines if partial_line > 0: ma += 1 if y <= ...
77_A. Heroes
The year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us...
```python from itertools import product, permutations, combinations n = int(input()) names = {} nex = 0 mama = 128 liking = [0]*mama likes = [[0]*7 for _ in range(7)] def getName(name): global nex if name in names: return names[name] names[name] = nex nex += 1 return names[name] for _ in...
849_D. Rooter's Song
Wherever the destination is, whoever we meet, let's render this song together. On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage. On the sides of t...
```python import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n,w,h=map(int,input().split()) dic={} ansx=[0]*n ansy=[0]*n for i in range(n): g,x,t=map(int,input().split()) if x-t in dic: dic[x-t][g-1].append([x,i]) else: dic[x-t]=[] dic[x-t].append([]) dic[x-t].append([]) di...
871_A. Maximum splitting
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prime, i.e. if...
```python t = int(input()) for i in range(t): n = int(input()) if n in [1, 2, 3, 5, 7, 11]: print(-1) else: print((n // 4) - (n % 2)) ```