contestId
int64
0
1.01k
name
stringlengths
2
54
prompt
stringlengths
297
7.35k
response
stringlengths
32
43.6k
120
Luck is in Numbers
Title: Luck is in Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a luck...
```python import sys sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') s = input() n = len(s) // 2 lines = ["1111110", "0110000", "1101101", "1111001", "0110011", "1011011", "1011111", "1110000", "1111111", "1111011"] common = [[0] * 10 for _ in range(10)] for i in range(10): for...
837
Prefix Sums
Title: Prefix Sums Time Limit: None seconds Memory Limit: None megabytes Problem Description: Consider the function *p*(*x*), where *x* is an array of *m* integers, which returns an array *y* consisting of *m*<=+<=1 integers such that *y**i* is equal to the sum of first *i* elements of array *x* (0<=≤<=*i*<=≤<=*m*)....
```python import sys from collections import deque input = sys.stdin.readline def fgh(): return [int(xx) for xx in input().split()] def fg(): return int(input()) n, ok = fgh() a = fgh() if max(a) >= ok: print(0) quit() if n == 2: print((ok - a[1] + a[0] - 1) // a[0]) quit() fac = ...
961
Partitions
Title: Partitions Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a set of *n* elements indexed from 1 to *n*. The weight of *i*-th element is *w**i*. The weight of some subset of a given set is denoted as . The weight of some partition *R* of a given set into *k* subsets is ...
```python def read_data(): n, m = map(int, list(input().strip().split())) a = list(map(int, list(input().strip().split()))) return n, m, a def get_modinv(m): modinv = [-1 for _ in range(m+1)] modinv[1] = 1 for i in range(2,m+1): modinv[i] = (-(div//i) * modinv[div%i]) % div ...
630
Challenge Pennants
Title: Challenge Pennants Time Limit: None seconds Memory Limit: None megabytes Problem Description: Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed ...
```python n=int(input()) print(((n+4)*(n+3)*(n+2)*(n+1)*n*(n+2)*(n+1)*n)//720) ```
690
Collective Mindsets (medium)
Title: Collective Mindsets (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the small...
```python n = int(input()) if n & 1: print(n//2) else: k = 1 while k <= n: k *= 2 print((n - k//2)//2) ```
609
Minimum spanning tree for each edge
Title: Minimum spanning tree for each edge Time Limit: None seconds Memory Limit: None megabytes Problem Description: Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains *n* vertices and *m* edges. For each edge (*u*,<=*v*) find the minimal possible weight of the spann...
```python from sys import stdin, stdout def main(): n, m = map(int, stdin.readline().split()) d = [] ev = [set() for _ in range(n + 1)] ans = [0] * m for i in range(m): u, v, w = map(int, stdin.readline().split()) d.append((w, u, v)) ev[u].add(i) ev[v].add(...
628
Bear and Fair Set
Title: Bear and Fair Set Time Limit: None seconds Memory Limit: None megabytes Problem Description: Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skil...
```python from sys import stdin input=lambda :stdin.readline()[:-1] n,b,q=map(int,input().split()) t=[(b,n)] for _ in range(q): x,y=map(int,input().split()) t.append((x,y)) t.sort(key=lambda x:x[0]) task=[] tmp=1 now=0 ng=False for x,y in t: if x+1==tmp: if y==now: pass else: ...
762
Maximum path
Title: Maximum path Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a rectangular table 3<=×<=*n*. Each cell contains an integer. You can move from one cell to another if they share a side. Find such path from the upper left cell to the bottom right cell of the table that do...
```python import sys input = sys.stdin.readline n = int(input()) a1 = list(map(int, input().split())) a2 = list(map(int, input().split())) a3 = list(map(int, input().split())) inf = pow(10, 15) for _ in range(2): a1.append(-inf) a2.append(-inf) a3.append(0) dp1 = [-inf] * (n + 2) dp2 = [-inf] ...
1,003
Tree Constructing
Title: Tree Constructing Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given three integers $n$, $d$ and $k$. Your task is to construct an undirected tree on $n$ vertices with diameter $d$ and degree of each vertex at most $k$, or say that it is impossible. An undirected tree i...
```python n,d,k=map(int,input().strip().split()) ans=[] if (d>n-1): print ("NO") exit(0) if (k<2 and n>2): print ("NO") exit(0) l1=[0 for i in range(d+2)] count=d cnt=d+2 def insert(par,v,r,e): global count global cnt if count==n-1: print ("YES") for o in ans: print (o[0],o[1]) exit(0)...
690
Recover Polygon (easy)
Title: Recover Polygon (easy) Time Limit: None seconds Memory Limit: None megabytes Problem Description: The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel ...
```python import os, sys from io import BytesIO, IOBase 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 self.writ...
180
Cubes
Title: Cubes Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's imagine that you're playing the following simple computer game. The screen displays *n* lined-up cubes. Each cube is painted one of *m* colors. You are allowed to delete not more than *k* cubes (that do not necessarily go o...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m, k = map(int, input().split()) a = list(map(int, input().split())) x = [[] for _ in range(m + 1)] for i in range(n): x[a[i]].append(i) ans = 0 for y in x: if not y: continue r = 0 for l i...
818
Card Game Again
Title: Card Game Again Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vova again tries to play some computer card game. The rules of deck creation in this game are simple. Vova is given an existing deck of *n* cards and a magic number *k*. The order of the cards in the deck is fixed. Eac...
```python R,G=lambda:map(int,input().split()),range n,k=R();a=[0]+[*R()];z,l,p=0,1,1 for r in G(1,n+1): p=p*a[r]%k if p==0: p=1;i=r while p*a[i]%k:p=p*a[i]%k;i-=1 z+=(n-r+1)*(i-l+1);l=i+1 print(z) ```
120
Three Sons
Title: Three Sons Time Limit: None seconds Memory Limit: None megabytes Problem Description: Three sons inherited from their father a rectangular corn fiend divided into *n*<=×<=*m* squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, whic...
```python import sys input = sys.stdin.readline from itertools import permutations f = open('input.txt', 'r') n, m = map(int, f.readline().split()) g = [list(map(int, f.readline().split())) for _ in range(n)] w = list(zip(*g)) g = [sum(i) for i in g] w = [sum(i) for i in w] s = set(permutations(map(int, f.re...
988
Divisibility by 25
Title: Divisibility by 25 Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes. In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes...
```python n = int(input()) s = list(str(n)) s = [int(i) for i in s] l = len(s) if l == 1: print(-1) exit() import copy INF = 10**18 ans = INF for i in range(l): for j in range(l): t = copy.copy(s) if i == j: continue temp = 0 for k in range(i, ...
915
Imbalance Value of a Tree
Title: Imbalance Value of a Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a tree *T* consisting of *n* vertices. A number is written on each vertex; the number written on vertex *i* is *a**i*. Let's denote the function *I*(*x*,<=*y*) as the difference between maximum a...
```python import sys RI = lambda: map(int, sys.stdin.buffer.readline().split()) RILST = lambda: list(RI()) def find(x): # 不会被卡爆栈的并查集find函数 省空间 t = x while fa[x] != x: x = fa[x] while t != x: fa[t], t = x, fa[t] return x n, = RI() a = RILST() mns = [[] for _ in rang...
837
Round Subset
Title: Round Subset Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's call the roundness of the number the number of zeros to which it ends. You have an array of *n* numbers. You need to choose a subset of exactly *k* numbers so that the roundness of the product of the selected number...
```python import sys input = sys.stdin.readline n, k = map(int, input().split()) m = 30 * n a = list(map(int, input().split())) inf = 114514 dp = [[-inf] * (m + 1) for _ in range(n + 1)] dp[0][0] = 0 dp0 = [0] * (n + 1) for i in range(n): ai = a[i] x, y = 0, 0 while not ai % 2: y += 1...
903
Swapping Characters
Title: Swapping Characters Time Limit: None seconds Memory Limit: None megabytes Problem Description: We had a string *s* consisting of *n* lowercase Latin letters. We made *k* copies of this string, thus obtaining *k* identical strings *s*1,<=*s*2,<=...,<=*s**k*. After that, in each of these strings we swapped exac...
```python import sys k, n = map(int, input().split()) s = [list(word.rstrip()) for word in sys.stdin] double = True if max(s[0].count(chr(i+97)) for i in range(26)) > 1 else False diff = [set() for _ in range(k)] diff_cnt = [0]*k for i in range(1, k): for j in range(n): if s[0][j] != s[i][j]: ...
1,000
We Need More Bosses
Title: We Need More Bosses Time Limit: None seconds Memory Limit: None megabytes Problem Description: Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $n$ locations connected by $m$ two-way passages. The passages are designed in such a way t...
```python from sys import stdin input=lambda :stdin.readline()[:-1] def lowlink(links): n = len(links) order = [-1] * n low = [n] * n parent = [-1] * n child = [[] for _ in range(n)] roots = set() x = 0 for root in range(n): if order[root] != -1: conti...
630
A rectangle
Title: A rectangle Time Limit: None seconds Memory Limit: None megabytes Problem Description: Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem. A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wa...
```python x1,y1,x2,y2 = map(int,input().split()) print((x2-x1)//2*(y2-y1+1)+(y2-x1)//2-(y1-x1)//2+1) ```
797
Array Queries
Title: Array Queries Time Limit: None seconds Memory Limit: None megabytes Problem Description: *a* is an array of *n* positive integers, all of which are not greater than *n*. You have to process *q* queries to this array. Each query is represented by two numbers *p* and *k*. Several operations are performed in ea...
```python from heapq import heappush, heappop, heapify from collections import defaultdict, Counter, deque from functools import lru_cache import threading import sys import bisect input = sys.stdin.readline def ri(): return int(input()) def rs(): return input() def rl(): return list(map(int, input().split()))...
691
Couple Cover
Title: Couple Cover Time Limit: None seconds Memory Limit: None megabytes Problem Description: Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with *n* balls, each with an integer written on it, is placed on the table. The first player...
```python import sys input = sys.stdin.buffer.readline n = int(input()) l = 3 * pow(10, 6) + 5 cnt = [0] * l for i in list(map(int, input().split())): cnt[i] += 1 c1, c2 = [0] * l, [0] * l m0 = pow(10, 8) for i in range(1, l): ci = cnt[i] if i * i < l: j = i * i c1[j] += ci * ...
802
Fake News (medium)
Title: Fake News (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Thanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post i...
```python from sys import stdin inp = stdin.readline n = int(inp()) arr = [0 for i in range(47)] s = "aaa" for i in range(46, -1, -1): while n >= (i+1)*(i+2)*(i+3)*(i+4)/24: arr[i] += 1 n -= (i+1)*(i+2)*(i+3)*(i+4)/24 for i in range(47): s += "a" for j in range(arr[i]): ...
938
Buy a Ticket
Title: Buy a Ticket Time Limit: None seconds Memory Limit: None megabytes Problem Description: Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well. There are *n* cities in Berland. People can travel between cities...
```python from sys import stdin, stdout from heapq import heapify,heappop,heappush,heappushpop n, m = map(int, stdin.readline().split()) ady = [[] for i in range(n)] for i in range(m): u,v,w = map(int,stdin.readline().split()) ady[u-1].append((v-1,2*w)) ady[v-1].append((u-1,2*w)) c_xcity...
628
Zbazi in Zeydabad
Title: Zbazi in Zeydabad Time Limit: None seconds Memory Limit: None megabytes Problem Description: A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad). The country Zeydabad is a rectangular table consisting of *n* rows and *m* columns. Each cell on the country is either 'z' or '.'. The ...
```python import sys ni = lambda :int(input()) na = lambda :list(map(int,input().split())) yes = lambda :print("yes");Yes = lambda :print("Yes");YES = lambda : print("YES") no = lambda :print("no");No = lambda :print("No");NO = lambda : print("NO") ##################################################################...
818
Four Melodies
Title: Four Melodies Time Limit: None seconds Memory Limit: None megabytes Problem Description: Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two trac...
```python import heapq import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def add_edge(u, v, cost, f): G[u].append([v, cost, f, len(R[v])]) R[v].append([u, -cost, 0, len(G[u]) - 1]) def dijkstra(s): inf = pow(10, 9) + 1 dist = [inf] * l dist[s] = 0 pare...
920
List Of Integers
Title: List Of Integers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's denote as *L*(*x*,<=*p*) an infinite sequence of integers *y* such that *gcd*(*p*,<=*y*)<==<=1 and *y*<=&gt;<=*x* (where *gcd* is the greatest common divisor of two integer numbers), sorted in ascending order. Th...
```python from sys import stdin input=lambda :stdin.readline()[:-1] m=10**6+10 divs=[[1] for i in range(m)] p=list(range(m)) p2=[1]*m mebius=[0]*m mebius[1]=1 for i in range(2,m): if p[i]==i: for j in range(i,m,i): p2[j]=i for j in range(i*i,m,i): p[j]=i for j in range(i*i,m,...
797
Broken BST
Title: Broken BST Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let *T* be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an i...
```python from sys import stdin input=lambda :stdin.readline()[:-1] n=int(input()) par=[-1]*n left=[-1]*n right=[-1]*n a=[0]*n for i in range(n): v,l,r=map(int,input().split()) a[i]=v l-=1 r-=1 if l!=-2: par[l]=i left[i]=l if r!=-2: par[r]=i right[i]=r root=-1 for i in...
847
Dog Show
Title: Dog Show Time Limit: None seconds Memory Limit: None megabytes Problem Description: A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants an...
```python # using the min-heap from heapq import heappush,heappop bowels,Time = map(int,input().split()) myLine = [-int(b) for b in input().split()] gulp = []; eat = 0 for i in range(1,min(bowels+1,Time)): while gulp and -gulp[0] >= Time - i: # remove the bowel with the highest time penalty ...
938
Erasing Substrings
Title: Erasing Substrings Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *s*, initially consisting of *n* lowercase Latin letters. After that, you perform *k* operations with it, where . During *i*-th operation you must erase some substring of length exactly 2*i*<=-...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) n = len(s) pow2 = [1] for _ in range(14): pow2.append(2 * pow2[-1]) k = 0 while pow2[k + 1] <= n: k += 1 m = pow2[k] pow2 = pow2[:k] l = n - m + 1 x = [[] for _ in range(26)] for ...
632
Magic Matrix
Title: Magic Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: You're given a matrix *A* of size *n*<=×<=*n*. Let's call the matrix with nonnegative elements magic if it is symmetric (so *a**ij*<==<=*a**ji*), *a**ii*<==<=0 and *a**ij*<=≤<=*max*(*a**ik*,<=*a**jk*) for all triples *i*,...
```python from collections import defaultdict, deque import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, r...
817
Choosing The Commander
Title: Choosing The Commander Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires. Vova managed to build a large army, but forgot about the main person in the army - the commande...
```python import sys from collections import defaultdict class Node: def __init__(self, val): self.val = val self.left = None self.right = None q = int(sys.stdin.readline()) root = Node(0) # def search(node, bit, ) for _ in range(q): l = list(map(int, sys.stdin.readline().split())) if l[0] ==...
245
Game with Coins
Title: Game with Coins Time Limit: None seconds Memory Limit: None megabytes Problem Description: Two pirates Polycarpus and Vasily play a very interesting game. They have *n* chests with coins, the chests are numbered with integers from 1 to *n*. Chest number *i* has *a**i* coins. Polycarpus and Vasily move in tu...
```python n = int(input()) if n == 1 or n & 1 == 0: print(-1) else: t = list(map(int, input().split())) s, k = 0, n // 2 - 1 for i in range(n - 1, 1, -2): p = max(t[i], t[i - 1]) t[k] = max(0, t[k] - p) s += p k -= 1 print(s + t[0]) ```
961
k-substrings
Title: k-substrings Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *s* consisting of *n* lowercase Latin letters. Let's denote *k*-substring of *s* as a string *subs**k*<==<=*s**k**s**k*<=+<=1..*s**n*<=+<=1<=-<=*k*. Obviously, *subs*1<==<=*s*, and there are exactly...
```python import random import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def is_Prime(n): if n == 1: return False for i in range(2, min(int(n ** (1 / 2)) + 2, n)): if n % i == 0: return False return True def random_mod(): mod = ra...
774
Composing Of String
Title: Composing Of String Time Limit: None seconds Memory Limit: None megabytes Problem Description: Stepan has a set of *n* strings. Also, he has a favorite string *s*. Stepan wants to do the following. He will take some strings of his set and write them down one after another. It is possible that he will take s...
```python import sys import math MAXN = 55 INF = 1e9 MOD = 1e9+7 L_INF = 4e18 EPS = 1e-10 n = int(input()) s = [] for i in range(n): s.append(input()) t = input() l = len(t) dp = [INF] * (l + 1) dp[0] = 0 for i in range(l): for j in range(n): _l, _r = i, 0 while _r < le...
598
Cut Length
Title: Cut Length Time Limit: None seconds Memory Limit: None megabytes Problem Description: Given simple (without self-intersections) *n*-gon. It is not necessary convex. Also you are given *m* lines. For each line find the length of common part of the line and the *n*-gon. The boundary of *n*-gon belongs to polyg...
```python I = lambda: [float(x) for x in input().split()] n, m = [int(i) for i in input().split()] V = [I() for _ in range(n)] cmp = lambda x: (x >= 0) - (x <= 0) for _ in range(m): x0, y0, x1, y1 = I() p0, p1 = x1 - x0, y1 - y0 V3 = [((x - x0)*p0 + (y - y0)*p1, (y - y0)*p0 - (x - x0)*p1) for x, y ...
690
The Wall (hard)
Title: The Wall (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: So many wall designs to choose from! Even modulo 106<=+<=3, it's an enormous number. Given that recently Heidi acquired an unlimited supply of bricks, her choices are endless! She really needs to do something to narrow ...
```python mod = 10 ** 6 + 3 def prod(a, b): return [[sum([a[i][k] * b[k][j] for k in range(len(b))]) % mod for j in range(len(b[0]))] for i in range(len(a))] c, w, h = map(int, input().split()) a = [[0] * (w + 1) for _ in range(w + 1)] for i in range(w): a[i][i + 1] = 1 for cnt in range(0, w ...
884
Anti-Palindromize
Title: Anti-Palindromize Time Limit: None seconds Memory Limit: None megabytes Problem Description: A string *a* of length *m* is called antipalindromic iff *m* is even, and for each *i* (1<=≤<=*i*<=≤<=*m*) *a**i*<=≠<=*a**m*<=-<=*i*<=+<=1. Ivan has a string *s* consisting of *n* lowercase Latin letters; *n* is even...
```python import sys from heapq import heappop, heappush class Edge: def __init__(self, u, v, cap, cost, rev): self.u = u self.v = v self.cap = cap self.flow = 0 self.cost = cost self.rev = rev def add_edge(adj, u, v, capv, costv): adj[u].append(Edg...
802
Heidi and Library (hard)
Title: Heidi and Library (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: The good times at Heidi's library are over. Marmots finally got their internet connections and stopped coming to the library altogether. Not only that, but the bookstore has begun charging extortionate prices f...
```python import sys from heapq import heappop, heappush class Edge: def __init__(self, u, v, cap, cost, rev): self.u = u self.v = v self.cap = cap self.flow = 0 self.cost = cost self.rev = rev def add_edge(adj, u, v, capv, costv): adj[u].append(Ed...
883
Automatic Door
Title: Automatic Door Time Limit: None seconds Memory Limit: None megabytes Problem Description: There is an automatic door at the entrance of a factory. The door works in the following way: - when one or several people come to the door and it is closed, the door immediately opens automatically and all people imme...
```python n1,m,a,d=list(map(int,input().split())) t=list(map(int,input().split())) from bisect import * from math import * insort(t,a*n1) pred=0 k=0 kpred=0 n=0 step=d//a+1 sol=0 fl=0 for i in t: if (i > pred): if fl == 0: n=(i-pred+(pred%a))//a if n!=0: ...
845
Guards In The Storehouse
Title: Guards In The Storehouse Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop. The store...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) mod = pow(10, 9) + 7 if n >= m: s = [list(input().rstrip()) for _ in range(n)] else: s = [[] for _ in range(m)] for _ in range(n): s0 = list(input().rstrip()) ...
938
Shortest Path Queries
Title: Shortest Path Queries Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than ...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): return u << 20 ^ v def unite(s, t, w): while s ^ root[s]: w ^= d[s] s = root[s] while t ^ root[t]: w ^= d[t] t = root[t] if s == t: return 0 ...
76
Tourist
Title: Tourist Time Limit: 0 seconds Memory Limit: 256 megabytes Problem Description: Tourist walks along the *X* axis. He can choose either of two directions and any speed not exceeding *V*. He can also stand without moving anywhere. He knows from newspapers that at time *t*1 in the point with coordinate *x*1 an in...
```python from sys import stdin input = stdin.buffer.readline from bisect import bisect from itertools import zip_longest def main(): n = int(input()) events = [tuple(map(int,input().split())) for _ in range(n)] v = int(input()) tot, zero = [], [] for i, e in enumerate(events): pos, time = ...
1,005
Berland and the Shortest Paths
Title: Berland and the Shortest Paths Time Limit: None seconds Memory Limit: None megabytes Problem Description: There are $n$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The ...
```python from collections import deque n,r,k=map(int,input().split()) edges=[[] for _ in range(n)] edge=[] for i in range(r): temp=list(map(int,input().split())) edge.append([temp[0]-1,temp[1]-1]) edges[temp[0]-1].append(temp[1]-1) edges[temp[1]-1].append(temp[0]-1) d=[float('inf')]*n d[0]=0 ...
717
Dexterina’s Lab
Title: Dexterina’s Lab Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After go...
```python import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,x=map(int,input().split()) def mult(a,b): # compute a*b c=[0]*128 for i in range(128): for j in range(128): c[i^j]+=a[i]*b[j] return c def quickpow(a,b): # compute a**b if b==1: ...
632
Thief in a Shop
Title: Thief in a Shop Time Limit: None seconds Memory Limit: None megabytes Problem Description: A thief made his way to a shop. As usual he has his lucky knapsack with him. The knapsack can contain *k* objects. There are *n* kinds of products in the shop and an infinite number of products of each kind. The cost o...
```python from sys import stdin input=lambda :stdin.readline()[:-1] MOD = 998244353 IMAG = 911660635 IIMAG = 86583718 rate2 = (0, 911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 5108154...
409
Feed the Golorp
Title: Feed the Golorp Time Limit: None seconds Memory Limit: None megabytes Problem Description: Golorps are mysterious creatures who feed on variables. Golorp's name is a program in some programming language. Some scientists believe that this language is Befunge; golorps are tantalizingly silent. Variables consum...
```python import re line=input() line = line.rstrip('.') a, b, c = line.partition("):-") rels = c.split(',') relations = set() for rel in rels: if "<" in rel: x, _, y = rel.partition("<") relations.add((len(x), len(y))) else: x, _, y = rel.partition(">") relatio...
813
Army Creation
Title: Army Creation Time Limit: None seconds Memory Limit: None megabytes Problem Description: As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires. In the game Vova can hire *n* different warriors; *i*th warrior has the type *...
```python class segtree(): def __init__(self,init,func,ide): self.n=len(init) self.func=func self.ide=ide self.size=1<<(self.n-1).bit_length() self.tree=[self.ide for i in range(2*self.size)] for i in range(self.n): self.tree[self.size+i]=init[i] for i in range(self.size-1,0...
652
Pursuit For Artifacts
Title: Pursuit For Artifacts Time Limit: None seconds Memory Limit: None megabytes Problem Description: Johnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience. In that country there are *n* islands and *m* bridges between th...
```python if True: from io import BytesIO, IOBase import math import random import sys import os import bisect import typing from collections import Counter, defaultdict, deque from copy import deepcopy from functools import cmp_to_key, lru_cache, reduce from h...
802
Marmots (easy)
Title: Marmots (easy) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Heidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of *V* (1<=≤<=*V*<=≤<=100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in th...
```python for i in range(int(input())): t = list(map(int, input().split())) d = 212 * sum(q ** 2 for q in t) > sum(t) ** 2 print(['poisson', 'uniform'][d]) ```
946
Largest Beautiful Number
Title: Largest Beautiful Number Time Limit: None seconds Memory Limit: None megabytes Problem Description: Yes, that's another problem with definition of "beautiful" numbers. Let's call a positive integer *x* beautiful if its decimal representation without leading zeroes contains even number of digits, and there ex...
```python import sys t = int(sys.stdin.buffer.readline().decode('utf-8')) ans = ['']*t for _ in range(t): a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').rstrip())) n = len(a) parity = [0]*10 for x in a: parity[x] ^= 1 psum = sum(parity) for i, free in zip(r...
774
Amusement Park
Title: Amusement Park Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pupils decided to go to amusement park. Some of them were with parents. In total, *n* people came to the park and they all want to get to the most extreme attraction and roll on it exactly once. Tickets for group of *x*...
```python n, c1, c2 = [int(x) for x in input().split(' ')] s = input() cnt = s.count('1') def price(x): return c1 + c2 * (x - 1) ** 2 prices = [] for i in range(1, cnt + 1): bigGroupsPeople = n // i + 1 numBigGroups = n % i smallGroupsPeople = n // i numSmallGroups = i - n % i ...
730
Toda 2
Title: Toda 2 Time Limit: None seconds Memory Limit: None megabytes Problem Description: A group of *n* friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the *i*-th friend is *r**i*. The friends decided to take part in the champ...
```python # https://codeforces.com/problemset/problem/730/A # import heapq def solve_for_0(d, max_, ans): pos_M = list(d[max_])[0] pos_m = list(d[0])[0] for _ in range(max_): ans.append([pos_M, pos_m]) def solve_one_seg(d, max_, min_, ans): seg = list(d[max_]) n = ...
954
Runner's Problem
Title: Runner's Problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are running through a rectangular field. This field can be represented as a matrix with 3 rows and *m* columns. (*i*,<=*j*) denotes a cell belonging to *i*-th row and *j*-th column. You start in (2,<=1) and have t...
```python L = 3 M = 10**9 + 7 iden = [[0] * L for _ in range(L)] for i in range(L): iden[i][i] = 1 def mat_multiply(a, b): n = len(a) ret = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for k in range(n): ret[i][j] = (ret[i][j] + a[i][k]...
630
Pyramids
Title: Pyramids Time Limit: None seconds Memory Limit: None megabytes Problem Description: IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that it...
```python from sys import stdin, stdout def solve(): l3, l4, l5 = (int(s) for s in stdin.readline().split()) v1 = l3*l3*l3*(2**0.5)*2 v2 = l4*l4*l4*(2**0.5)*4 v3 = l5*l5*l5*(2**0.5)*((15+5*(5**0.5))**0.5) ans = (v1+v2+v3)/24 print(ans) if __name__ == '__main__': solve() ``...
852
Property
Title: Property Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punis...
```python n = int(input()) a = input().split() for i in range(n): a[i] = int(a[i]) b = [] for i in range(0, n-1): b.append((a[i]-(n-a[i+1]), i)) b.append((a[n-1]-(n-a[0]), n-1)) b = sorted(b) ans = n*[0] for i in range(n): # the line segment at index b[i][1] ans[b[i][1]] = i for i in range(...
774
Significant Cups
Title: Significant Cups Time Limit: None seconds Memory Limit: None megabytes Problem Description: Stepan is a very experienced olympiad participant. He has *n* cups for Physics olympiads and *m* cups for Informatics olympiads. Each cup is characterized by two parameters — its significance *c**i* and width *w**i*. ...
```python from functools import cmp_to_key def comparator(a, b) : if a[0] > b[0] : return -1 if a[0] < b[0] : return 1 if a[1] < b[1] : return -1 if a[1] > b[1] : return 1 return 0 n, m, d = list(map(int, input().split())) a = [] b = [] for i in rang...
620
New Year Tree
Title: New Year Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree. The New Year tree is an undirected tree wit...
```python from sys import stdin input=lambda :stdin.readline()[:-1] def popcount(n): c=(n&0x5555555555555555)+((n>>1)&0x5555555555555555) c=(c&0x3333333333333333)+((c>>2)&0x3333333333333333) c=(c&0x0f0f0f0f0f0f0f0f)+((c>>4)&0x0f0f0f0f0f0f0f0f) c=(c&0x00ff00ff00ff00ff)+((c>>8)&0x00ff00ff00ff00ff) c=(c...
234
Champions' League
Title: Champions' League Time Limit: None seconds Memory Limit: None megabytes Problem Description: In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world — the UEFA Champions League. Now, these teams have already started to play in the ...
```python import sys sys.stdin = open("input.txt") sys.stdout = open("output.txt",'w') n = int(input()) m = n//4 x, a, b, c = map(int, input().split()) g = sorted([(int(j), i) for i, j in [input().split() for _ in range(n)]], reverse=1) w1, w2, w3, w4 = g[:m].copy(), g[m:2*m].copy(), g[2*m:3*m].copy(), g[3*m:]...
802
Heidi and Library (medium)
Title: Heidi and Library (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences. Input Specification: Same as...
```python # https://codeforces.com/problemset/problem/802/B import heapq n, k = map(int, input().split()) a = list(map(int, input().split())) d = {} pos = {} Q = [] cnt = 0 for i, x in enumerate(a): if x not in pos: pos[x] = [] pos[x].append(i) for i, x in enumerat...
903
Clear The Matrix
Title: Clear The Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a matrix *f* with 4 rows and *n* columns. Each element of the matrix is either an asterisk (*) or a dot (.). You may perform the following operation arbitrary number of times: choose a square submatrix o...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) a = list(map(int, input().split())) b = [0] * (4 * n) for i in range(4): f = list(input().rstrip()) for j in range(n): b[i + 4 * j] = (46 - f[j]) // 4 for _ in range(4): b.append(0)...
245
Log Stream Analysis
Title: Log Stream Analysis Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got a list of program warning logs. Each record of a log stream is a string in this format: String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". St...
```python # import atexit # import io # import sys # # _INPUT_LINES = sys.stdin.read().splitlines() # input = iter(_INPUT_LINES).__next__ # _OUTPUT_BUFFER = io.StringIO() # sys.stdout = _OUTPUT_BUFFER # # # @atexit.register # def write(): # sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisec...
888
Xor-MST
Title: Xor-MST Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a complete undirected graph with *n* vertices. A number *a**i* is assigned to each vertex, and the weight of an edge between vertices *i* and *j* is equal to *a**i*<=*xor*<=*a**j*. Calculate the weight of the min...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def insert(x, la): j = 0 for i in p: if x & i: if not G[j] >> 25: la += 1 G[j] ^= la << 25 j = la else: j = G[j] ...
665
Four Divisors
Title: Four Divisors Time Limit: None seconds Memory Limit: None megabytes Problem Description: If an integer *a* is divisible by another integer *b*, then *b* is called the divisor of *a*. For example: 12 has positive 6 divisors. They are 1, 2, 3, 4, 6 and 12. Let’s define a function *D*(*n*) — number of integers...
```python def prime_pi(n): if n <= 1: return 0 elif n <= 3: return 2 v = int(n ** 0.5) - 1 while v ** 2 <= n: v += 1 v -= 1 smalls = [(i + 1) // 2 for i in range(v + 1)] s = (v + 1) // 2 roughs = [2 * i + 1 for i in range(s)] larges = [(n // (2 * i...
702
Analysis of Pathes in Functional Graph
Title: Analysis of Pathes in Functional Graph Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to *n*<=-<=1. Graph is given as the array *f*0,<=*f*1,<...
```python import sys input = sys.stdin.readline n,k = map(int, input().split()) a = list(map(int, input().split())) w = list(map(int, input().split())) pow_pos = a[:] pow_mi = w[:] pow_s = w[:] pos = list(range(n)) mi = [10 ** 18] * n s = [0] * n for i in range(35): if k & (1 << i): s = [s[po...
883
Road Widening
Title: Road Widening Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy! The Mayor thinks that one of the main city streets could be considerably widened on account of lawn ...
```python n = int(input()) s = [0]*n g = [0]*n for i in range(n): a,b = map(int,input().split()) s[i] = a g[i] = a+b for i in range(1,n): g[i] = min(g[i],g[i-1]+1) for i in range(n-2,-1,-1): g[i] = min(g[i],g[i+1]+1) ans = 0 for i in range(n): if s[i] <= g[i]: ans += g[...
852
Neural Network country
Title: Neural Network country Time Limit: None seconds Memory Limit: None megabytes Problem Description: Due to the recent popularity of the Deep learning new countries are starting to look like Neural Networks. That is, the countries are being built deep with many layers, each layer possibly having many cities. The...
```python import sys from array import array class Matrix: def __init__(self, r, c, mat=None, id=None): self.r, self.c = r, c if mat != None: self.mat = [[mat[i][j] for j in range(c)] for i in range(r)] else: self.mat = [[0 for i in range(c)] for j in ra...
946
Almost Increasing Array
Title: Almost Increasing Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: We call an array almost increasing if we can erase not more than one element from it so that the array becomes strictly increasing (that is, every element is striclty greater than every element before it). You ...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def segment_tree(n): tree = [0] * pow(2, n.bit_length() + 1) return tree def update(i, x, tree): i += len(tree) // 2 tree[i] = x i //= 2 while True: if i == 0: break ...
609
Gadgets for dollars and pounds
Title: Gadgets for dollars and pounds Time Limit: None seconds Memory Limit: None megabytes Problem Description: Nura wants to buy *k* gadgets. She has only *s* burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the c...
```python ''' Auther: ghoshashis545 Ashis Ghosh College: Jalpaiguri Govt Enggineering College ''' from os import path from io import BytesIO, IOBase import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,Counter,defaultdict as dd from bis...
600
Area of Two Circles' Intersection
Title: Area of Two Circles' Intersection Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given two circles. Find the area of their intersection. Input Specification: The first line contains three integers *x*1,<=*y*1,<=*r*1 (<=-<=109<=≤<=*x*1,<=*y*1<=≤<=109,<=1<=≤<=*r*1<=≤<=109) —...
```python from math import pi, sqrt from decimal import * getcontext().prec = 100 def cos(x): getcontext().prec += 2 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 while s != lasts: lasts = s i += 2 fact *= i * (i-1) num *= x * x sign *= -1 s +=...
690
Brain Network (hard)
Title: Brain Network (hard) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zo...
```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....
665
Beautiful Subarrays
Title: Beautiful Subarrays Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day, ZS the Coder wrote down an array of integers *a*<=with elements *a*1,<=<=*a*2,<=<=...,<=<=*a**n*. A subarray of the array *a* is a sequence *a**l*,<=<=*a**l*<=<=+<=<=1,<=<=...,<=<=*a**r* for some integers ...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def insert(x, la): j = 0 for i in p: if x & i: if not G[j] >> 25: la += 1 G[j] ^= la << 25 j = la else: j = G[j] ...
802
Marmots (medium)
Title: Marmots (medium) Time Limit: None seconds Memory Limit: None megabytes Problem Description: Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations. Can you help Heidi estimate each village's population? Input ...
```python def sampleVariance(V): X = sum(V) / len(V) S = 0.0 for x in V: S += (X-x)**2 S /= (len(V)) return (X, S) #That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester for i in range(int(input())): V = list(map(int, ...
873
Forbidden Indices
Title: Forbidden Indices Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *s* consisting of *n* lowercase Latin letters. Some indices in this string are marked as forbidden. You want to find a string *a* such that the value of |*a*|·*f*(*a*) is maximum possible, wher...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def suffix_array(s): l = len(s) x = [[] for _ in range(222)] for i in range(l): x[s[i]].append(i) y = [] z = [0] for x0 in x: for i in x0: y.append(i) z.app...
620
Xors on Segments
Title: Xors on Segments Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array with *n* integers *a**i* and *m* queries. Each query is described by two integers (*l**j*,<=*r**j*). Let's define the function . The function is defined for only *u*<=≤<=*v*. For each query pri...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v, w): return (u * z + v) * z + w def update1(x, c): i = x ^ l1 tree1[i], color1[i] = x, c i >>= 1 for _ in range(w): j, k = i << 1, i << 1 ^ 1 if color1[j] ^ c: ...
883
Orientation of Edges
Title: Orientation of Edges Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex *s* from the graph. Now Vasya wants to c...
```python import sys input = sys.stdin.readline def put(): return map(int, input().split()) def dfs0(x): s = [x] vis = [0] * n ans = ['+'] * m vis[x] = 1 while s: i = s.pop() for j, k in graph[i]: if (vis[j] == 0): if (k < 0): ans[-k - 1] = '-' elif (k > 0): ...
808
Anthem of Berland
Title: Anthem of Berland Time Limit: None seconds Memory Limit: None megabytes Problem Description: Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem. Though there are lots and lots of victories in history of Berland, there i...
```python import sys input = sys.stdin.readline def z_algorithm(w): m = len(w) z = [0] * m z[0] = m i, j = 1, 0 while i < m: while i + j < m and w[j] == w[i + j]: j += 1 z[i] = j if not j: i += 1 continue l = 1 ...
509
Sums of Digits
Title: Sums of Digits Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya had a strictly increasing sequence of positive integers *a*1, ..., *a**n*. Vasya used it to build a new sequence *b*1, ..., *b**n*, where *b**i* is the sum of digits of *a**i*'s decimal representation. Then sequenc...
```python import sys def get_max(su, le): div, mod = divmod(su, 9) ret = ['9'] * div if mod: ret = [str(mod)] + ret if le - len(ret) > 0: x = str(int(ret.pop(0)) - 1) ret = ['1', x] + ret if le - len(ret) > 0: ret = [ret[0]] + ['0'] * (le - l...
691
Xor-sequences
Title: Xor-sequences Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given *n* integers *a*1,<=<=*a*2,<=<=...,<=<=*a**n*. A sequence of integers *x*1,<=<=*x*2,<=<=...,<=<=*x**k* is called a "xor-sequence" if for every 1<=<=≤<=<=*i*<=<=≤<=<=*k*<=-<=1 the number of ones in the binar...
```python mod=10**9+7 def popcount(n): c=(n&0x5555555555555555)+((n>>1)&0x5555555555555555) c=(c&0x3333333333333333)+((c>>2)&0x3333333333333333) c=(c&0x0f0f0f0f0f0f0f0f)+((c>>4)&0x0f0f0f0f0f0f0f0f) c=(c&0x00ff00ff00ff00ff)+((c>>8)&0x00ff00ff00ff00ff) c=(c&0x0000ffff0000ffff)+((c>>16)&0x0000ffff0000fff...
630
Area of a Star
Title: Area of a Star Time Limit: None seconds Memory Limit: None megabytes Problem Description: It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area ...
```python from math import * n,r = map(int,input().split()) print(n*r*r/(1/tan(pi/(2*n))+1/tan(pi/n))) ```
245
Queries for Number of Palindromes
Title: Queries for Number of Palindromes Time Limit: None seconds Memory Limit: None megabytes Problem Description: You've got a string *s*<==<=*s*1*s*2... *s*|*s*| of length |*s*|, consisting of lowercase English letters. There also are *q* queries, each query is described by two integers *l**i*,<=*r**i* (1<=≤<=*l*...
```python import sys from array import array input = lambda: sys.stdin.buffer.readline().decode().strip() s, out = input(), array('i') n = len(s) dp = [array('i', [1] * n) for _ in range(n)] pre = array('i', [1] * n) for i in range(2, n + 1): for j in range(n - i + 1): l, r = j, i + j - 1 ...
954
Path Counting
Title: Path Counting Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a rooted tree. Let's denote *d*(*x*) as depth of node *x*: depth of the root is 1, depth of any other node *x* is *d*(*y*)<=+<=1, where *y* is a parent of *x*. The tree has the following property: every nod...
```python mod=10**9+7 n=int(input()) a=[1]+list(map(int,input().split()))+[1] ans=[0]*(2*n) cnt=[1] for i in a[1:]: cnt.append(cnt[-1]*i%mod) dp=[0]*2*n for i in range(n): for j in range(1,2*n): ans[j]+=cnt[i]*dp[j] ans[j]%=mod ndp=[0]*2*n for j in range(2*n-1): ndp[j+1]=dp[j] r...
241
Challenging Balloons
Title: Challenging Balloons Time Limit: None seconds Memory Limit: None megabytes Problem Description: Martha — as a professional problemsetter — proposed a problem for a world-class contest. This is the problem statement: Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready...
```python n = 402 print (n) print (0, 1000000) for i in range(1, n-1): print (i * 1000, n-i) print (1000000, 1000000) ```
730
Award Ceremony
Title: Award Ceremony Time Limit: None seconds Memory Limit: None megabytes Problem Description: All-Berland programming contest comes to an end. In total, *n* teams participated in it. Like in ACM-ICPC, current results stopped refreshing one hour before the contest ends. So at the Award Ceremony, results are partia...
```python n = int(input()) a = [] d = [] p = [] for i in range(n): ai, di = map(int, input().split()) a.append(ai) d.append(di) p.append((ai, -i)) p.append((ai + di, -i)) p.sort() s = [] for i in range(n): s.append((p.index((a[i], -i)), p.index((a[i] + d[i], -i)))) ans = 0 for i ...
845
Shortest Path Problem?
Title: Shortest Path Problem? Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, the...
```python from sys import stdin input=lambda :stdin.readline()[:-1] from collections import defaultdict class UnionFind(): def __init__(self,n): self.n=n self.parents=[-1]*n def find(self,x): if self.parents[x]<0: return x else: self.parents[x]=self.find(self.parents[x])...
774
Pens And Days Of Week
Title: Pens And Days Of Week Time Limit: None seconds Memory Limit: None megabytes Problem Description: Stepan has *n* pens. Every day he uses them, and on the *i*-th day he uses the pen number *i*. On the (*n*<=+<=1)-th day again he uses the pen number 1, on the (*n*<=+<=2)-th — he uses the pen number 2 and so on. ...
```python import sys def Min(x, y): if x > y: return y else: return x def Gcd(x, y): if x == 0: return y else: return Gcd(y % x, x) def Lcm(x, y): return x * y // Gcd(x, y) n = int(input()) a = [int(i) for i in input().split()] d = [int(0) f...
954
Castle Defense
Title: Castle Defense Time Limit: None seconds Memory Limit: None megabytes Problem Description: Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a...
```python import sys from array import array from collections import deque input = lambda: sys.stdin.buffer.readline().decode().strip() n, dist, k = map(int, input().split()) a = array('i', [int(x) for x in input().split()]) cum = [0] * (n + 1) for i in range(n): cum[i + 1] = cum[i] + a[i] be, en = 0...
290
HQ
Title: HQ Time Limit: None seconds Memory Limit: None megabytes Problem Description: The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ... Input Specification: The only line of the input is a string between 1 and 106 characters long. Out...
```python a = input() b = [] h = '' c = 0 for i in a: if i == 'Q': c += 1 if c == 0: print('Yes') exit(0) r = -1 for i in range(1001): if i*i == c: r = i break if r == -1: print('No') exit(0) h = [a.split('Q')[0], a.split('Q')[-1]] c = [len(h[0]), len(h[1])] if c[0] % 2 != 0 or c[1] % 2 ...
903
Yet Another Maxflow Problem
Title: Yet Another Maxflow Problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: In this problem you will have to deal with a very special network. The network consists of two parts: part *A* and part *B*. Each part consists of *n* vertices; *i*-th vertex of part *A* is denoted as *A**i...
```python import heapq import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def make_graph(n, m): x, y, s = [0] * (2 * m), [0] * m, [0] * (n + 3) for i in range(0, 2 * m, 2): u, v, w = map(int, input().split()) s[u + 2] += 1 x[i], x[i + 1] = u, v ...
985
Isomorphic Strings
Title: Isomorphic Strings Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a string *s* of length *n* consisting of lowercase English letters. For two given strings *s* and *t*, say *S* is the set of distinct characters of *s* and *T* is the set of distinct characters of *t*....
```python from sys import stdin input=lambda :stdin.readline()[:-1] mod=10**9+7 n,q=map(int,input().split()) base=103 s=[ord(i)-97 for i in input()] a=[] for i in range(26): b=[0] tmp=0 res=1 for j in range(n): res*=base res%=mod if s[j]==i: tmp+=res tmp%=mod b.app...
792
Mages and Monsters
Title: Mages and Monsters Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is...
```python #!/usr/bin/env python3 # solution after hint # (instead of best hit/mana spell store convex hull of spells) # O(n^2) instead of O(n log n) [q, m] = map(int, input().strip().split()) qis = [tuple(map(int, input().strip().split())) for _ in range(q)] mod = 10**6 j = 0 spell_chull = [(0, 0)] # lower hull _...
920
Tanks
Title: Tanks Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly *V* ml of water. Petya has got *N* tanks, *i*-th of them initially containing *a**i* ml of water. The tanks are really large, any of the...
```python n,k,v=map(int,input().split()) a=list(map(int,input().split())) s=sum(a) if s<v: print('NO') exit() def ceil(a,b): return (a+b-1)//b if (s-v)%k==0: print('YES') ans=[] for i in range(1,n): ans.append((ceil(a[i],k),i,0)) ans.append((ceil(s-v,k),0,1)) for x,y,z in ans: ...
813
Bipartite Checking
Title: Bipartite Checking Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an undirected graph consisting of *n* vertices. Initially there are no edges in the graph. Also you are given *q* queries, each query either adds one undirected edge to the graph or removes it. After ea...
```python from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v, w): return (u * n2 + v) * n2 + w def g(u, v): return u * n2 + v def get_root(s): while s ^ root[s]: s = root[s] return s def unite(s, t, i)...
1,009
Allowed Letters
Title: Allowed Letters Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline s = list(input().rstrip()) pow2 = [1] for _ in range(6): pow2.append(2 * pow2[-1]) p = pow2[6] cnt = [0] * p for i in s: cnt[pow2[i - 97]] += 1 sp = set(pow2) u = [[pow2[i]] for i in range(6)] for i in range(...
813
Two Melodies
Title: Two Melodies Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with *n* notes written on it. She wants to take two such non-empty ...
```python import sys def solve(): n = int(sys.stdin.readline()) a = [0] + [int(i) for i in sys.stdin.readline().split()] dp = [[0]*(n + 1) for i in range(n + 1)] ans = 0 maxnum = [0] * (10**5 + 2) maxmod = [0] * 7 for y in range(n + 1): maxmod = [0] * 7 ...
946
Fibonacci String Subsequences
Title: Fibonacci String Subsequences Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a binary string *s* (each character of this string is either 0 or 1). Let's denote the cost of string *t* as the number of occurences of *s* in *t*. For example, if *s* is 11 and *t* is 1110...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def f(u, v): return u * n + v n, x = map(int, input().split()) mod = pow(10, 9) + 7 s = list(input().rstrip()) m = 105 inv2 = pow(2, mod - 2, mod) fib = [1, 1] p = [2, 2] ip = [inv2, inv2] for _ in range(m): ...
837
Functions On The Segments
Title: Functions On The Segments Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have an array *f* of *n* functions.The function *f**i*(*x*) (1<=≤<=*i*<=≤<=*n*) is characterized by parameters: *x*1,<=*x*2,<=*y*1,<=*a*,<=*b*,<=*y*2 and take values: - *y*1, if *x*<=≤<=*x*1. - *a*·*x*...
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_segment(s, t): s, t = s + l1, t + l1 ans = [] while s <= t: if s & 1: ans.append(s) s += 1 s >>= 1 if not t & 1: ans.append(t) ...