src_uid
stringlengths
32
32
prob_desc_description
stringlengths
63
2.99k
tags
stringlengths
6
159
source_code
stringlengths
29
58.4k
lang_cluster
stringclasses
1 value
categories
listlengths
1
5
desc_length
int64
63
3.13k
code_length
int64
29
58.4k
games
int64
0
1
geometry
int64
0
1
graphs
int64
0
1
math
int64
0
1
number theory
int64
0
1
probabilities
int64
0
1
strings
int64
0
1
trees
int64
0
1
labels_dict
dict
__index_level_0__
int64
0
4.98k
94d98a05741019f648693085d2f08872
You are given two circles. Find the area of their intersection.
['geometry']
import math from decimal import * def sqrt(v): a = Decimal(0) b = v while a != b: a = b b = (a+v/a)/TWO return a def taylor_acos(v): return PI/2 - taylor_asin(v) def taylor_asin(v): curr = v vsq = v**2 ans = v coef = Decimal(1.) for i in xrange(3, 101, 2): ...
Python
[ "geometry" ]
63
1,286
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,767
3b5b8c54dc9956e7060c7f154eebd063
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.You can perform the following operation: choose some subsegment [l, r] (1\le l \le r \le n), and redistribute water in tanks l, l+1, \dots, r evenly. In other words, replace each of a_l, a_...
['data structures', 'geometry', 'greedy']
from __future__ import division import sys def main(): n, A = sys.stdin.readlines() n = int(n) A = list(map(int, A.split())) stack = [] for i in range(n): cur = [A[i], 1] while stack and stack[-1][0] * cur[1] > cur[0] * stack[-1][1]: cur[0] += stack[-1][0] cu...
Python
[ "geometry" ]
1,008
571
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,983
a628b6606c977059dca6d8dd05de99d4
A non-empty string s is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string s from 1 to the string's length and let's denote the i-th character in string s as si.Binary string s with length n is periodical, if there is an integer 1 ≤ k < n such that: k is a divi...
['dp', 'combinatorics', 'number theory']
import math def tree_search(l, u, x, a, b): if u == l: if check_upper(u, a, b, x): return u else: return u-1 if u - l <= 1: if check_upper(u, a, b, x): return u elif check_upper(l, a, b, x): return l else: retu...
Python
[ "math", "number theory" ]
719
2,911
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
3,140
a81ce25d1ac0b8f85543798dba514b24
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in ...
['greedy', 'graphs', 'data structures', 'dfs and similar', 'trees']
from sys import stdin from collections import defaultdict import heapq n = int(stdin.readline()) a = [[] for _ in range(n)] for _ in range(n-1): e = stdin.readline().split(' ') u, v = int(e[0]), int(e[1]) a[u-1].append(v-1) a[v-1].append(u-1) leaves = [i for i in range(n) if len(a[i]) == 1] def dfs...
Python
[ "graphs", "trees" ]
813
1,879
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,410
db8855495d22c26296351fe310281df2
This is the hard version of the problem. The only difference is maximum value of a_i.Once in Kostomuksha Divan found an array a consisting of positive integers. Now he wants to reorder the elements of a to maximize the value of the following function: \sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i), wher...
['dp', 'number theory']
''' D2. Divan and Kostomuksha (hard version) https://codeforces.com/contest/1614/problem/D2 ''' import io, os, sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str output = sys.stdout.write INF = float('inf') def sieve(N): '''return all primes in [2..N] in O(N)''' pri...
Python
[ "number theory" ]
769
2,576
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
527
6b75105015e5bf753ee93f6e0639a816
Andi and Budi were given an assignment to tidy up their bookshelf of n books. Each book is represented by the book title — a string s_i numbered from 1 to n, each with length m. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending.Settling their fight,...
['data structures', 'sortings', 'strings']
import functools import sys input = lambda: sys.stdin.readline().rstrip() def compare(a, b): for i in range(m): if a[0][i] != b[0][i]: if i % 2 == 0: if a[0][i] < b[0][i]: return -1 else: return 1 ...
Python
[ "strings" ]
982
656
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,145
7123c270fe618f44e419eabafdfe6c31
One university has just found out about a sport programming contest called ACM ICPC v2.0. This contest doesn't differ much from the well-known ACM ICPC, for example, the participants are not allowed to take part in the finals more than two times. However, there is one notable difference: the teams in the contest should...
['binary search', 'shortest paths', 'graphs', 'math']
def main(): n=input() x=raw_input().split() ps=[float(s) for s in x] ret=0.0 for a in xrange(n): for b in xrange(a+1,n+1): if 2*a>n or 2*b<n:continue ca=( (0.5*n)-b ) / (a-b) cb=( (0.5*n)-a ) / (b-a) ret=max(ret, ca*ps[a]+cb*ps[b]) print "%.9f"%ret main()
Python
[ "graphs", "math" ]
2,093
299
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,225
a4b170cc058c485a50bf18982fd96851
A sequence (b_1, b_2, \ldots, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 \le i&lt;j \le k, we have |a_i-a_j|\geq MAX, where MAX is the largest element...
['greedy', 'math', 'sortings']
tcs = int(input()) for _ in range(tcs): n = int(input()) a = list(map(int, input().split())) a.sort() if a[n-1] <= 0: print(n) else: flag = 0 pi = 0 while(a[pi] <= 0): pi += 1 for i in range(pi): ...
Python
[ "math" ]
920
468
0
0
0
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,289
69edc72ec29d4dd56751b281085c3591
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's...
['implementation', 'trees']
# cook your dish here from sys import stdin,stdout from collections import Counter from itertools import permutations import bisect import math I=lambda: map(int,stdin.readline().split()) I1=lambda: stdin.readline() #(a/b)%m =((a%m)*pow(b,m-2)%m)%m n=int(I1()) l=[] for _ in range(n-1): x=int(I1()) l.append(x) ...
Python
[ "trees" ]
515
556
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,834
6c7858731c57e1b24c7a299a8eeab373
The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings ar...
['implementation', '*special', 'strings']
s = raw_input().strip() lexemes = [] quoting = False chars = [] for pos, ch in enumerate(s): if ch == '"': if not quoting: quoting = True continue lexemes.append('<' + ''.join(chars) + '>') chars = [] quoting = False continue if ch == ' ': if quoting: chars.append(ch) e...
Python
[ "strings" ]
2,081
523
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
765
32077a3111c3f28ad56eab0c085a882d
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1, 2, ..., n. p is le...
['dsu', 'dfs and similar', 'math']
n, m = map(int, raw_input().split()) val = [_ for _ in map(int, raw_input().split())] adj = [[] for _ in range(n)] for i in range(m): a, b = map(int, raw_input().split()) adj[a - 1].append(b - 1) adj[b - 1].append(a - 1) vis = [False for _ in range(n)] for v in range(n): if vis[v] or len(adj[v]) == 0...
Python
[ "graphs", "math" ]
428
726
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,077
fe01ddb5bd5ef534a6a568adaf738151
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree o...
['data structures', 'dsu', 'dfs and similar', 'trees']
def main(): import sys from collections import deque input = sys.stdin.readline N = int(input()) color = list(map(int, input().split())) color.insert(0, 0) adj = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) adj[a].append(b) adj[b...
Python
[ "graphs", "trees" ]
529
1,787
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,856
c08933fdaceb220f4ef3ba8c5f09fe12
You are given some text t and a set of n strings s_1, s_2, \dots, s_n. In one step, you can choose any occurrence of any string s_i in the text t and color the corresponding characters of the text in red. For example, if t=\texttt{bababa} and s_1=\texttt{ba}, s_2=\texttt{aba}, you can get t=\color{red}{\texttt{ba}}\tex...
['brute force', 'data structures', 'dp', 'greedy', 'strings']
import sys input=lambda: sys.stdin.readline().strip() for _ in range(int(input())): t = input() n = int(input()) l = list() for i in range(n): inp = input() l.append((inp,len(inp),i+1)) l.sort(key=lambda p: p[1],reverse=True) ans = list() # (id, pos) mai = 0 i = 0 while i <= mai < len(t): ...
Python
[ "strings" ]
1,295
644
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,175
1ff25abd9d49de5e5ce3f7338ddef18c
You are given n - 1 integers a_2, \dots, a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root. Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root v...
['dfs and similar', 'dp', 'greedy', 'trees']
import sys I=lambda:[*map(int,sys.stdin.readline().split())] t, = I() for _ in range(t): n, = I() par = [0,0]+I() a = [0,0]+I() children = [[] for _ in range(n+1)] for i in range(2, n+1): children[par[i]].append(i) layers = [[1]] while 1: nextlayer = [] for v in layers[-1]: for u in children[v]: ne...
Python
[ "graphs", "trees" ]
1,400
740
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,850
cbd550be6982ef259de500194c33eff2
Nastia has an unweighted tree with n vertices and wants to play with it!The girl will perform the following operation with her tree, as long as she needs: Remove any existing edge. Add an edge between any pair of vertices. What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a ...
['constructive algorithms', 'data structures', 'dfs and similar', 'dp', 'dsu', 'greedy', 'implementation', 'trees']
from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) ...
Python
[ "graphs", "trees" ]
384
2,293
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,201
39dbd405be19c5a56c2b97b28e0edf06
Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.
['dp', 'greedy', 'implementation', 'expression parsing', 'brute force', 'strings']
n = raw_input() ans = 0 a = [-1] for i in xrange(len(n)): if n[i]=='*':a.append(i) a.append(len(n)) for i in a: for j in a: if j>i: ans = max(ans,eval(n[:i+1]+'('+n[i+1:j]+')'+n[j:])) ans = max(ans,eval(n)) print ans
Python
[ "strings" ]
300
244
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,053
5e5dbd70c7fcedf0f965aed5bafeb06c
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
['implementation', 'sortings', 'strings']
n = int(input()) w = input() w.upper() a=0 b=0 for i in range(n): if w[i]=='n': a=a+1 elif w[i]=='z': b=b+1 print("1 "*a+"0 "*b)
Python
[ "strings" ]
427
152
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
2,197
d8136eb72931851f501c5ce9042ce4eb
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two dis...
['constructive algorithms', 'dfs and similar']
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) v=[0]*n v[0]=1 d={} k=[] k.append(1) if len(set(l))==1: print("NO") else: print("YES") d[1]=[] for j in range(1,n): if l[j] != l[0]: d[1].append(j...
Python
[ "graphs" ]
822
576
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,145
d69e10bb05d119ec2ad4b5c0e4304336
You have a string s and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is i, you move it to the position i + 1. Of course, moving the ...
['brute force', 'dp', 'hashing', 'implementation', 'strings']
t = int(input()) res = [] for _ in range(t): a = list(input()) isAnswered = False a1 = list(input()) isConversely = False for j in range(len(a)): if(a1[0] == a[j]): if(len(a1) == 1): res.append("YES") isAnswered = True b...
Python
[ "strings" ]
1,234
1,777
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
2,032
22a43ccaa9e5579dd193bc941855b47d
You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence a is a subsequence of an array b if a can be obtained from b by deletion of ...
['graphs', 'number theory', 'shortest paths', 'dfs and similar', 'brute force']
from sys import stdin from collections import deque, Counter, defaultdict N = int(input()) arr = list(map(int, stdin.readline().split())) MAX = 1_000_005 lp = [0] * MAX pr = [] pid = {1: 0} for i in range(2, MAX): if not lp[i]: lp[i] = i pr.append(i) pid[i] = len(pr) for p in pr: if p > lp[i] or i * p >= M...
Python
[ "graphs", "number theory" ]
397
1,983
0
0
1
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,367
43336ae43d65a11c80337d0b6ea6b934
After many unsuccessful tries, Mashtali decided to copy modify an AtCoder problem. So here is his copied new problem:There is a tree with n vertices and some non-empty set of the vertices are pinned to the ground.Two players play a game against each other on the tree. They alternately perform the following action: Remo...
['games', 'trees']
import sys input = sys.stdin.buffer.readline N = int(input()) T = [[] for i in range(N)] for i in range(1, N): u, v = map(int, input().split()) u -= 1 v -= 1 T[u].append(v) T[v].append(u) stk = [(1, 0)] par = [-1] * N dp = [0] * N while stk: t, u = stk.pop() if t == 1: stk.append((2, u)) ...
Python
[ "games", "trees" ]
710
733
1
0
0
0
0
0
0
1
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
238
3cd56870a96baf8860e9b7e89008d895
You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Dete...
['implementation', 'strings']
number = int(input()) cases = [] for i in range(number): cases.append(input()) def yesno(c): if c in "YesYes"*(len(c)//6+2): return "Yes" else: return "NO" for c in cases: print(yesno(c))
Python
[ "strings" ]
436
217
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
775
0639fbeb3a5be67a4c0beeffe8f5d43b
You are given a tree of n vertices numbered from 1 to n, with edges numbered from 1 to n-1. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting o...
['constructive algorithms', 'dfs and similar', 'number theory', 'trees']
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) # 2.DFS from a vertex def DFS(self,vertex): path=[] stack...
Python
[ "graphs", "number theory", "trees" ]
1,049
1,700
0
0
1
0
1
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 1 }
678
fd63aeefba89bef7d16212a0d9e756cd
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge siz...
['implementation', 'strings']
def main(): a = input() b = input() boolean = False index_to_start_a = 0 index_to_start_b = 0 while index_to_start_a < len(a) and a[index_to_start_a] == "0": index_to_start_a += 1 while index_to_start_b < len(b) and b[index_to_start_b] == "0": index_to_start_b += 1 a ...
Python
[ "strings" ]
607
839
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
252
e93981ba508fec99c8ae3e8aa480dd52
This is the hard version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version."Interplanetary Software, Inc." together with "Robots of Cydonia, Ltd." has developed and released robot cats. These electronic pets can meow, catch mice and...
['binary search', 'data structures', 'dfs and similar', 'graphs', 'trees']
''' E2. Cats on the Upgrade (hard version) https://codeforces.com/contest/1625/problem/E2 ''' import io, os, sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # decode().strip() if str output = sys.stdout.write DEBUG = os.environ.get('debug') not in [None, '0'] if DEBUG: from inspect import curre...
Python
[ "graphs", "trees" ]
2,586
5,186
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,064
22c0489eec3d8e290fcbcf1aeb3bb66c
During the hypnosis session, Nicholas suddenly remembered a positive integer n, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal ...
['brute force', 'constructive algorithms', 'implementation', 'math', 'number theory']
from math import sqrt """ def IsPrime(n): if n==1: return False elif n==2: return True elif n%2 ==0: return False else: for i in range(3,int(sqrt(n))+1,2): if n%i ==0: return False return True """ composite_number=("1",...
Python
[ "math", "number theory" ]
875
1,829
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,744
584f7008e27dde53037396d2459efd84
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals . The operation x mod y means that we take the r...
['combinatorics', 'number theory', 'math']
leng, repeat=list(map(int,input().split())) Lis = list(map(int,input().split())) mod = 10**9 + 7 cum = [1] ans = [0]*leng for i in range(1, 2001): cum.append((cum[-1] * (repeat + i - 1) * pow(i, mod-2, mod)) % mod) for i in range(leng): for j in range(i + 1): ans[i] = (ans[i] + cum[i-j] * Lis[j]) % mod...
Python
[ "math", "number theory" ]
602
334
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,776
fefec879efd4f524de00684adee7cd19
Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of 2 rows and n columns. Monocarp controls a character, which starts in cell (1, 1) — at the intersection of the 1-st row and the 1-st column.Monocarp's character can move from one cell to another in...
['brute force', 'dfs and similar', 'dp', 'implementation']
def call(a,b): return "YES" if not a&b else "NO" if __name__ == '__main__': t=int(input()) while t >0: n=int(input()) first=int(input(),2) second=int(input(),2) print(call(first,second)) t-=1
Python
[ "graphs" ]
918
258
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
408
f4779e16e0857e6507fdde55e6d4f982
You are given one integer n (n &gt; 1).Recall that 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 of length 5, but [1, 2, 2] is not a permutation (2 appears twice in the array) and [1, 3, 4] is also not a permutation ...
['constructive algorithms', 'probabilities']
n = int(input()) list1 = [] a = 1 for i in range(0,n): list1.append(int(input())) for j in list1: if j%2==0: for num in range(j,0,-1): print(num,end=" ") else: print('2 3 1',end=" ") print(* [x for x in range(j,3,-1)]) if a in range(1,n): print("") a+=1
Python
[ "probabilities" ]
831
317
0
0
0
0
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
3,960
9d46ae53e6dc8dc54f732ec93a82ded3
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m ...
['constructive algorithms', 'greedy', 'math', 'strings']
temp = list(input()) m = int(input()) trans = [int(x) for x in input().split()] trans.sort() n = len(temp) k = 0 for i in range(n//2): while k < m and trans[k] - 1 <= i: k += 1 if k % 2 == 1: temp[i], temp[n-i-1] = temp[n-i-1], temp[i] print(''.join(temp)) ''' for i in trans: for j in range(...
Python
[ "math", "strings" ]
617
551
0
0
0
1
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
9
2d96a753ae2df1f1084a2cda65839a86
Fishingprince loves trees. A tree is a connected undirected graph without cycles.Fishingprince has a tree of n vertices. The vertices are numbered 1 through n. Let d(x,y) denote the shortest distance on the tree from vertex x to vertex y, assuming that the length of each edge is 1.However, the tree was lost in an accid...
['brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'trees']
def edge(x, y, n): return min(x, y) * n + max(x, y) def solve(): n = int(input()) eqlist, neqlist = [], [] m = n * n edge_adj = [[] for _ in range(m)] for i in range(n-1): for j, s in enumerate(input().split()): for k, c in enumerate(s): if c == ...
Python
[ "graphs", "trees" ]
696
2,432
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,978
1fe6daf718b88cabb2e956e81add3719
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some spe...
['dp', 'hashing', 'strings']
modulo = 10**9 + 7 def get_order(inp): n = len(inp) gt = [[-1] * i for i in range(n)] for j in range(i)[::-1]: if inp[n-1] > inp[j]: gt[n-1][j] = 0 for i in range(n-1)[::-1]: for j in range(i)[::-1]: if inp[i] > inp[j]: gt[i][j] = 0 el...
Python
[ "strings" ]
911
1,196
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,417
f82685f41f4ba1146fea8e1eb0c260dc
In the snake exhibition, there are n rooms (numbered 0 to n - 1) arranged in a circle, with a snake in each room. The rooms are connected by n conveyor belts, and the i-th conveyor belt connects the rooms i and (i+1) \bmod n. In the other words, rooms 0 and 1, 1 and 2, \ldots, n-2 and n-1, n-1 and 0 are connected with ...
['implementation', 'graphs']
ans = [] for i in range(int(input())): n = int(input()) s = list(input()) if '>' in s and '<' in s: a = 0 for i in range(n): if s[i] == '-' or s[i - 1] == '-': a += 1 ans.append(a) else: ans.append(n) print('\n'.join(map(str, ans)))
Python
[ "graphs" ]
1,058
309
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,807
38375efafa4861f3443126f20cacf3ae
You are given a binary string of length n. You have exactly k moves. In one move, you must select a single bit. The state of all bits except that bit will get flipped (0 becomes 1, 1 becomes 0). You need to output the lexicographically largest string that you can get after using all k moves. Also, output the number of ...
['bitmasks', 'constructive algorithms', 'greedy', 'strings']
I=input for _ in[0]*int(I()): n,k=map(int,I().split());a=[int(x)^k&1for x in I()];b=[0]*n;i=0 while(n-i)*k:b[i]=a[i]^1;a[i]=1;k-=b[i];i+=1 a[-1]^=k&1;b[-1]+=k;print(*a,sep='');print(*b)
Python
[ "strings" ]
737
188
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
2,765
3ea3f5b548b82449e4ce86e11b1afc48
Two T-shirt sizes are given: a and b. The T-shirt size is either a string M or a string consisting of several (possibly zero) characters X and one of the characters S or L.For example, strings M, XXL, S, XXXXXXXS could be the size of some T-shirts. And the strings XM, LL, SX are not sizes.The letter M stands for medium...
['implementation', 'implementation', 'strings']
x = int(input()) list1 = [] if x in range(1, 10 ** 4+1): z = 0 while z < x: a, b = map(str, input().split()) a = a.upper() b = b.upper() if len(a) <= 50 and len(b) <= 50: if a == b: list1.append("=") else: if len(a) == 1 and len(b) == 1 and a != b: if a == "L" and (b == "M" or ...
Python
[ "strings" ]
1,008
1,597
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,486
a9473e6ec81c10c4f88973ac2d60ad04
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!You are given n nonnegative integers a_1, a_2, \dots, a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 \leq i \leq n, the elements a_{i - 1} ...
['dp', 'greedy', 'games', 'brute force']
## necessary imports import sys input = sys.stdin.readline # from math import ceil, floor, factorial; def ceil(x): if x != int(x): x = int(x) + 1; return x; # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if...
Python
[ "games" ]
830
4,592
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
361
3afa68fbe090683ffe16c3141aafe76e
Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0).Split the artists into two performances ...
['brute force', 'greedy', 'math', 'strings']
#!/usr/bin/env python2 """ This file is part of https://github.com/cheran-senthil/PyRival Copyright 2019 Cheran Senthilkumar <hello@cheran.io> """ from __future__ import division, print_function import itertools import os import sys from atexit import register from io import BytesIO class dict(dict): """dict() ...
Python
[ "math", "strings" ]
683
3,376
0
0
0
1
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,612
38388446f5c265f77124132caa3ce4d2
New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as tot...
['combinatorics', 'dfs and similar', 'trees', 'graphs']
from queue import Queue import sys cost = [] def readarray(): return map(int, input().split(' ')) n = int(input()) graph = [[] for i in range(n)] for i in range(n - 1): u, v, c = readarray() u, v = u - 1, v - 1 cost.append(c) graph[u].append((v, i)) graph[v].append((u, i)) order = [] used = [0] * n q = [0]...
Python
[ "math", "graphs", "trees" ]
1,617
1,321
0
0
1
1
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,401
1759fabd248d2b313ecfb8e1b3e7b0db
Ela likes to go hiking a lot. She loves nature and exploring the various creatures it offers. One day, she saw a strange type of ant, with a cannibalistic feature. More specifically, an ant would eat any ants that it sees which is smaller than it.Curious about this feature from a new creature, Ela ain't furious. She co...
['combinatorics', 'dp', 'math', 'probabilities']
import sys import math import heapq import itertools import bisect import random import time from collections import deque input=sys.stdin.readline mod=10**9+7 def power(a,n): if n==0: return 1 x=power(a,n//2) if n%2==0: return x*x%mod else: return x*x*a%mod ...
Python
[ "math", "probabilities" ]
3,003
994
0
0
0
1
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
1,259
2ff789ae0095bb7ff0e747b0d4df59bc
It is a holiday season, and Koala is decorating his house with cool lights! He owns n lights, all of which flash periodically.After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters a_i and b_i. Light with parameters a_i and b_i will toggle (on to off, or off to ...
['implementation', 'number theory', 'math']
import math n = int(input()) ini = str(input()) ab = [] maxon = 0 for i in range(n): abi = list(map(int, input().split())) ab.append(abi) for t in range(1, 241): res = [] i = 0 for abi in ab: if t-abi[1] <= 0: res.append(int(ini[i])==0) else: res.append(math....
Python
[ "number theory", "math" ]
809
459
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,853
5c3cec98676675355bb870d818704be6
Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k — the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substrin...
['constructive algorithms', 'brute force', 'strings']
import sys def main(): a = sys.stdin.readline().strip() b = sys.stdin.readline().strip() if a == "01" or a == "10": print("0") return cnt = [0] * 256 for i in map(ord, a): cnt[i] += 1 n = sum(cnt) l = 0 for i in range(1, 8): if i == len(str(n - i)): ...
Python
[ "strings" ]
703
865
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
934
efdb966e414050c5e51e8beb7bb06b20
A pair of positive integers (a,b) is called special if \lfloor \frac{a}{b} \rfloor = a \bmod b. Here, \lfloor \frac{a}{b} \rfloor is the result of the integer division between a and b, while a \bmod b is its remainder.You are given two integers x and y. Find the number of special pairs (a,b) such that 1\leq a \leq x an...
['binary search', 'brute force', 'math', 'number theory']
for test_case in range(int(input())): x,y = map(int,input().split()) res = 0 k = 1 while k*(k+1) < x and k < y: res += min(y,x//k-1)-k k += 1 print(res)
Python
[ "math", "number theory" ]
404
201
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,530
bcdd7862b718d6bcc25c9aba8716d487
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string s of length n, consisting of digits.In one operation you can delete any character from string s....
['brute force', 'greedy', 'strings']
for i in range(int(input())): n = int(input()) s = input() print('YES' if '8' in s and n - s.index('8') >= 11 else 'NO')
Python
[ "strings" ]
563
132
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,740
ed75bd272f6d3050426548435423ca92
Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance ...
['combinatorics', 'strings']
a, b, c = input(), input(), 0 p = [[0] * (len(b) + 1), [0] * (len(b) + 1)] for i in range(0, len(b)): p[0][i + 1] = p[0][i] + int(b[i] == '0') p[1][i + 1] = p[1][i] + int(b[i] != '0') for i in range(len(a)): cr = int(a[i] == '1') for j in range(2): c += abs(cr - j) * (p[j][len(b) - len(a) + i + ...
Python
[ "math", "strings" ]
552
343
0
0
0
1
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,727
61bbe7bc4698127511a0bdbc717e2526
The girl named Masha was walking in the forest and found a complete binary tree of height n and a permutation p of length m=2^n.A complete binary tree of height n is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is n. The pictu...
['dfs and similar', 'divide and conquer', 'graphs', 'sortings', 'trees']
def greater(a ,b): if len(a) > len(b): return True if len(a) < len(b): return False for i in range(len(a)): if a[i] > b[i]: return True elif a[i] < b[i]: return False return False for _ in range(int(input())): f = False n = int(input()) a...
Python
[ "graphs", "trees" ]
1,451
1,125
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,223
e70708f72da9a203b21fc4112ede9268
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.What is the lexicog...
['constructive algorithms', 'implementation', 'greedy', 'strings']
a,s,iz='',input(),0 if set(s)=={'a'}:a+=s[:-1]+'z' elif len(set(s))==1:a+=(chr(ord(s[0])-1))*len(s) while len(a)!=len(s): if s[len(a)]!='a': a,iz=a+chr(ord(s[len(a)])-1),iz+1 elif s[len(a)]=='a' and iz<1:a+=s[len(a)] else:a+=s[len(a):] print(a)
Python
[ "strings" ]
417
265
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
2,945
960e4c234666d2444b80d5966f1d285d
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consec...
['two pointers', 'implementation', 'strings']
#_________________ Mukul Mohan Varshney _______________# #Template import sys import os import math import copy from math import gcd from bisect import bisect from io import BytesIO, IOBase from math import sqrt,floor,factorial,gcd,log,ceil from collections import deque,Counter,defaultdict from itertools import permut...
Python
[ "strings" ]
785
1,415
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,333
da08dd34ac3c05af58926f70abe5acd0
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment exce...
['implementation', 'dfs and similar', 'expression parsing', 'strings']
#!/usr/bin/env python3 import collections def solve(): comments = input().split(",") comments_by_depth = collections.defaultdict(list) current_depth = 0 current_depth_limit = [10000000] cur_cmt = [0] * 2 for i, item in enumerate(comments): cur_cmt[i % 2] = item if i % 2 == ...
Python
[ "graphs", "strings" ]
1,647
975
0
0
1
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,751
d07730b7bbbfa5339ea24162df7a5cab
Chouti is working on a strange math problem.There was a sequence of n positive integers x_1, x_2, \ldots, x_n, where n is even. The sequence was very special, namely for every integer t from 1 to n, x_1+x_2+...+x_t is a square of some integer number (that is, a perfect square).Somehow, the numbers with odd indexes turn...
['greedy', 'constructive algorithms', 'number theory', 'math', 'binary search']
#!/usr/bin/env python """ This file is part of https://github.com/Cheran-Senthil/PyRival. Copyright 2018 Cheran Senthilkumar all rights reserved, Cheran Senthilkumar <hello@cheran.io> Permission to use, modify, and distribute this software is given under the terms of the MIT License. """ from __future__ import divisi...
Python
[ "number theory", "math" ]
702
4,089
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,700
68b6b4f28649dd69e73197043130fa6f
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value ai. The root of the tree is node 1.This tree has a special property: when a value val is added to a value of node i, the value -val is ad...
['data structures', 'dfs and similar', 'trees']
class BIT(): """区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する add: 区間[begin, end)にvalを加える get_val: i番目(0-indexed)の値を求める """ def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def get_val(self, i): i = i + 1 s = 0 while i <= self.n: s += self....
Python
[ "graphs", "trees" ]
788
2,512
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,199
0a476638c2122bfb236b53742cf8a89d
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths ...
['implementation', 'trees']
n = int(input()) deg = [0]*100005 leaves = [] for i in range(1,n): a,b = map(int, input().split()) deg[a]+=1 deg[b]+=1 cnt = 0 mxdeg = 0 root = 0 for j in range(1,n+1): if deg[j]>mxdeg: mxdeg = deg[j] root = j if deg[j] == 1: leaves.append(j) if deg[j] > 2: cnt+=1...
Python
[ "trees" ]
507
502
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,553
0c4bc51e5be9cc642f62d2b3df2bddc4
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call verte...
['dp', 'dfs and similar', 'trees', 'graphs']
n=int(input()) a=[0]+list(map(int,input().split())) E=[[] for _ in range(n+1)] for i in range(n-1): p,c=map(int,input().split()) E[i+2]+=[(p,c)] E[p]+=[(i+2,c)] ans=0 ch=[(1,0,0)] while ch: nom,pre,l=ch.pop() if l>a[nom]: continue ans+=1 for x,c in E[nom]: if x!=pre: ch+=[(x,nom,max...
Python
[ "graphs", "trees" ]
865
342
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,163
a30f6f5273fc6c02ac1f2bc2b0ee893e
You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation: you choose the index i (1 \le i \le |s|) such that the character at position i occurs at least two times in the string s, and delet...
['brute force', 'data structures', 'dp', 'greedy', 'strings']
in1 = lambda : int(input()) in2 = lambda : list(map(int, input().split())) #Solve import math def solve(): s = input() #print("RES: ", end='') n = len(s) stack = [] seen = set() d = {c : idx for idx, c in enumerate(s)} for i in range(n): if s[i] not in seen: ...
Python
[ "strings" ]
1,454
613
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,318
2f0cdacc14ac81249f30c8c231003a73
British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that "every positive integer was one of his personal friends."It turns out that positive integers can also be friends with each other! You are given an array a of distinct positive integers. Define a subarray a_i, a_{i+1}, \l...
['binary search', 'data structures', 'divide and conquer', 'math', 'number theory', 'two pointers']
from math import gcd def solve(arr, n): if n == 1: print(1) return # check = False # for x in range(n-1): # a = arr[x] # arr[x] = abs(a - arr[x+1]) # if arr[x] != 1: # check = True # if not check: # print(1) # return ...
Python
[ "math", "number theory" ]
646
1,919
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,635
a4e605859608d0c730ecbbee9ffc92d7
There is a new attraction in Singapore Zoo: The Infinite Zoo.The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled 1,2,3,\ldots. There is a directed edge from vertex u to vertex u+v if and only if u\&amp;v=v, where \&amp; denotes the bitwise AND operation. There are no other edges i...
['bitmasks', 'constructive algorithms', 'dp', 'greedy', 'math']
import math from collections import deque from sys import stdin, stdout, setrecursionlimit from string import ascii_letters from decimal import * letters = ascii_letters[:26] from collections import defaultdict #from functools import reduce input = stdin.readline #print = stdout.write for _ in range(int...
Python
[ "math" ]
526
887
0
0
0
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,245
c44554273f9c53d11aa1b0edeb121113
Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.We define the distance from city x to city y as the xor of numbers attached to the cities ...
['dp', 'constructive algorithms', 'bitmasks', 'math', 'data structures', 'dfs and similar', 'trees']
import operator n = input() city_numbers = [0] city_numbers.extend(map(int, raw_input().split())) adjacent_cities = [[] for _ in xrange(n + 1)] for _ in xrange(1, n): u, v = map(int, raw_input().split()) adjacent_cities[u].append(v) adjacent_cities[v].append(u) city_bit_path_counts = [[0, 0] for _ in xrange(n + ...
Python
[ "math", "graphs", "trees" ]
1,008
2,116
0
0
1
1
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,665
bb6e2f728e1c7e24d86c9352740dea38
Petya has a string of length n consisting of small and large English letters and digits.He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string re...
['data structures', 'strings']
from collections import defaultdict import sys input = raw_input range = xrange def lower_bound(A, x): a = 0 b = len(A) while a < b: c = (a + b) >> 1 if A[c] < x: a = c + 1 else: b = c return a def upper_bound(A, x): a = 0 b = len(A) while ...
Python
[ "strings" ]
442
7,249
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
722
b1959af75dfdf8281e70ae66375caa14
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the se...
['constructive algorithms', 'trees']
def wrong(x): if n < 6: print(-1) else: print("1 2") print("2 3") print("2 4") print("4 5") print("4 6") for i in range(7, x + 1): print("4", i) def true(x): for i in range(x-1): print(i+1,i+2) n = int(input()) wrong(n) true(n)
Python
[ "trees" ]
1,052
318
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,545
5cb7ce7485c86ca73c0adfd27227adf9
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and diffe...
['probabilities', 'math']
import math n = int(input()) Y = [0.0] Z = [0.0] Y = Y + [float(y) for y in input().split()] Z = Z + [float(z) for z in input().split()] S = [y + z for y, z in zip(Y, Z)] CS = [0 for i in range(n+1)] for i in range(1, n+1): CS[i] = CS[i-1] + S[i] A = [0 for i in range(0, n+1)] B = [0 for i in range...
Python
[ "math", "probabilities" ]
1,020
735
0
0
0
1
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
2,343
e4dc319588cc8eca6a5c3d824e504c22
There are n coins labeled from 1 to n. Initially, coin c_i is on position i and is facing upwards ((c_1, c_2, \dots, c_n) is a permutation of numbers from 1 to n). You can do some operations on these coins. In one operation, you can do the following:Choose 2 distinct indices i and j.Then, swap the coins on positions i ...
['constructive algorithms', 'graphs', 'math']
def swap(i, j): graph[i], graph[j] = -graph[j], -graph[i] ans.append((i, j)) def solve_pair(x, y): swap(x, y) i = x while (graph[-graph[i]] > 0): swap(i, -graph[i]) i = -graph[i] while (graph[-graph[i]] > 0): swap(i, -graph[i]) swap(i, -graph[i]) n = int(i...
Python
[ "graphs", "math" ]
783
1,110
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,884
40002052843ca0357dbd3158b16d59f4
Æsir - CHAOS Æsir - V."Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time."The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library...
['dp', 'greedy', 'graphs', 'number theory', 'math', 'trees']
from sys import stdin, stdout prime = list() factor = list() count = list() dist = list() N = 0 def find_prime(): global prime for i in range(2, 5010): is_prime = True for j in prime: if i % j == 0: is_prime = False break if is_prime is True:...
Python
[ "graphs", "math", "number theory", "trees" ]
1,514
3,278
0
0
1
1
1
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 1 }
4,578
9cae7cd63f47dc647cf2139244670aaf
This is an interactive problem.We have hidden an integer 1 \le X \le 10^{9}. You don't have to guess this number. You have to find the number of divisors of this number, and you don't even have to find the exact number: your answer will be considered correct if its absolute error is not greater than 7 or its relative e...
['constructive algorithms', 'number theory', 'interactive']
from sys import stdin, stdout import math def main(): t = int(stdin.readline()) MX = int(1.e18 + 2) for _ in range (t): # query q_num = 2 prime = [2] slot = [0] * 100000 q_cnt = 0 factor = 2 cur = 3 stable_prime = [] uniq = set() ...
Python
[ "number theory" ]
1,149
2,012
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,129
c2a506d58a80a0fb6a16785605b075ca
Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions (\frac{a}{b} and \frac{c}{d}) with integer numerators and denominators. Then children are commanded to play with their fractions.Burenka is a clever kid, so she noticed that when she claps once, she can multiply n...
['math', 'number theory']
#comment n = int(input()) def do(a, b, c, d): if a==0 and c!=0: return 1 if c==0 and a!=0: return 1 fst, snd = a * d, b * c if fst == snd: return 0 if fst % snd == 0 or snd % fst == 0: return 1 else: return 2 for i in range(n): ...
Python
[ "math", "number theory" ]
604
405
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,807
0d8b5bd6c118f98d579da8c79482cfa7
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation ...
['dp', 'bitmasks', 'implementation', 'brute force', 'strings']
from sys import stdin, stdout K = 20 def findAllStrings(s): n = len(s) sDict = {} for i in range(1,K+1): sDict[i]=set() for x in range(n-i+1): sDict[i].add(s[x:x+i]) return sDict n = int(stdin.readline().rstrip()) stringDicts = [] stringEnd = [] stringBegin = [] for i in ...
Python
[ "strings" ]
526
1,618
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
2,522
8476fd1d794448fb961248cd5afbc92d
You are given a tree, which consists of n vertices. Recall that a tree is a connected undirected graph without cycles. Example of a tree. Vertices are numbered from 1 to n. All vertices have weights, the weight of the vertex v is a_v.Recall that the distance between two vertices in the tree is the number of edges on a ...
['dp', 'trees']
visited = [0]*205 dp = [[0]*205 for i in range(205)] def dfs(node,g): sons = [] for nb in g[node]: if not visited[nb]: visited[nb] = 1 dfs(nb,g) sons.append(nb) dp[node][0] = ws[node-1] for s in sons: dp[node][0] += dp[s][k] ls = len(sons) ...
Python
[ "trees" ]
625
1,229
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,830
5aad0a82748d931338140ae81fed301d
There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from l...
['combinatorics', 'number theory', 'probabilities', 'math']
f = lambda: list(map(int, input().split())) n, p = f() t = [(l - 1, r) for l, r in [f() for i in range(n)]] t = [(r // p - l // p) / (r - l) for l, r in t] print(2000 * sum(t[i] * (2 - t[i - 1]) for i in range(n)))
Python
[ "math", "number theory", "probabilities" ]
667
214
0
0
0
1
1
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 1, "strings": 0, "trees": 0 }
416
d2d21871c068e04469047e959dcf0d09
During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal des...
['data structures', 'trees']
# pylint: disable=redefined-builtin, ungrouped-imports from __future__ import print_function from bisect import bisect_left, bisect_right, insort from collections import Sequence, MutableSequence from functools import wraps from itertools import chain, repeat, starmap from math import log as log_e import operator as op...
Python
[ "trees" ]
993
58,387
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,526
1777c06783ecd795f855a4e9811da4b2
At the foot of Liyushan Mountain, n tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.The i-th tent is located at the point of (x_i, y_i) and has a weight of w_i. A tent is important if...
['constructive algorithms', 'flows', 'graphs']
import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() Y=lambda:map(int,Z().split()) INF=float("inf");big=10**13 class D: def __init__(self, n): self.lvl = [0] * n self.ptr = [0] * n self.q = [0] * n self.adj...
Python
[ "graphs" ]
901
2,426
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
621
4aec5810e9942ae2fbe3ecd4fff3b468
Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snake...
['dp', 'probabilities', 'shortest paths']
def pos(x, y): if y & 1: return y * w + w - 1 - x return y * w + x CUBE = 6 h, w = 10, 10 n = h * w grid = [] for y in range(h): line = list(map(int, input().split())) grid.append(line) grid.reverse() # print(*grid, sep='\n') to = [0] * n for y in range(h): for x in range(w): y1 ...
Python
[ "graphs", "probabilities" ]
3,043
879
0
0
1
0
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
115
c0e18f6105f4b8129ebd73bbd12e904d
The Little Elephant loves permutations of integers from 1 to n very much. But most of all he loves sorting them. To sort a permutation, the Little Elephant repeatedly swaps some elements. As a result, he must receive a permutation 1, 2, 3, ..., n.This time the Little Elephant has permutation p1, p2, ..., pn. Its sortin...
['dp', 'probabilities', 'math']
n, m = map(int, raw_input().split()) s = map(int, raw_input().split()) dp = [[0.0] * 2000 for i in xrange(2000)] for i in xrange(n) : for j in xrange(n) : if s[i] > s[j] : dp[i][j] = 1.0 else : dp[i][j] = 0.0 for i in xrange(m) : a, b = map(int, raw_input().split()) a = a - 1 b = b - ...
Python
[ "math", "probabilities" ]
1,142
635
0
0
0
1
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
4,222
8aba8c09ed1b1b25fa92cdad32d6fec3
This is an interactive problem.You are given a sorted in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to x.More formally, there is a singly liked list built on an array of n elements. Element with index i contains two integers: valuei is the integer...
['probabilities', 'interactive', 'brute force']
from random import sample def R(): return map(int, input().split()) def ask(i): print('?', i, flush=True) v, nxt = R() if v < 0: exit() return v, nxt def ans(v): print('!', v) exit() n, s, x = R() mv = -1 i = s S = 800 q = range(1, n + 1) if n > S: q = sample(q, S) if s n...
Python
[ "probabilities" ]
973
612
0
0
0
0
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
2,918
89bf97a548fe12921102e77dda63283a
A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Eve...
['dp', 'data structures', 'binary search', 'dfs and similar', 'trees']
from sys import stdin, stdout def main(): n = int(stdin.readline()) to = [0] xt = [0] last = [0] * (n + 1) toa = to.append xta = xt.append c = 1 for _ in xrange(n - 1): a, b = map(int, stdin.readline().split()) xta(last[a]) last[a] = c toa(b) c += ...
Python
[ "graphs", "trees" ]
841
2,348
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
758
4c5187193cf7f2d2721cedbb15b2a1c3
Alice and Bob are playing a game on an array a of n positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If a_1 = 0, the player loses the game, otherwise: Player chooses some i with 2\le i \le n. Then player decreases the value of a_1 by 1 ...
['games']
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) d=min(l) if d==l[0]: print("Bob") else: print("Alice")
Python
[ "games" ]
462
175
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,004
3edd332d8359ead21df4d822af6940c7
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.Bob wants ...
['binary search', 'geometry']
__author__ = 'Darren' def solve(): t1, t2 = map(int, input().split()) cinema = complex(*map(int, input().split())) house = complex(*map(int, input().split())) shop = complex(*map(int, input().split())) cinema_to_house = abs(house - cinema) cinema_to_shop = abs(shop - cinema) shop_to_house ...
Python
[ "geometry" ]
1,270
1,749
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,144
f996224809df700265d940b12622016f
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the ...
['constructive algorithms', 'greedy', 'strings']
from sys import stdin s = stdin.readline().strip() chars = {chr(x+97):0 for x in range(26)} for x in s: chars[x] += 1 odds = sorted([x for x in chars if chars[x] % 2 == 1]) if len(s)%2 == 1: middle = odds.pop(len(odds)//2) for x in range(len(odds)//2): chars[odds[x]] += 1 for x in range(len(...
Python
[ "strings" ]
874
831
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,073
6214a85d2be0a908dcbfe089327cf51a
Volodya and Vlad play the following game. There are k pies at the cells of n × m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border ...
['games']
n, m, k = map(int, input().split()) win = False for i in range(k): x, y = map(int, input().split()) if abs(x - 1) <= 4 or abs(y - 1) <= 4 or \ abs(n - x) <= 4 or abs(m - y) <= 4: win = True print('YES' if win else 'NO')
Python
[ "games" ]
566
249
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,778
43996d7e052aa628a46d03086f9c5436
You are given a integer n (n &gt; 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:In the decimal representation of s: s &gt; 0, s consists of n digits, no digit in s equals 0, s is not divisible by any of it's digits.
['constructive algorithms', 'number theory']
# def check(n): # strng = str(n) # if not("0" in strng or "1" in strng): # if n%2 != 0 and n%3 != 0 and n%5 !=0 and n%7 != 0 : # return True # return False def solve(n): if n<2: return -1 first = "3"*(n-1)+"7" if int(first)%7 != 0: return first else : ...
Python
[ "number theory" ]
333
517
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,624
12814033bec4956e7561767a6778d77e
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...
['data structures', 'implementation', 'trees', 'brute force']
q = int(input()) ans = [] cost = {} def getn(v, k = 1): res = [] while k <= v: res.append(v) v //= 2 return res def getp(arr): res = [] for i in range(len(arr) - 1): res.append((arr[i], arr[i + 1])) return res def gets(u, v): resu, resv = getn(u), getn(v) for i...
Python
[ "trees" ]
1,147
867
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,701
3fd58cef6d06400992088da9822ff317
The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the pat...
['dp', 'trees']
from collections import deque def recurse(x,d,w,parent,v,vb): best = 0 bestt = 0 ans = 0 for t in d[x]: node = t[0] if node == parent: continue weight = int(w[node-1])-t[1] ans = max(ans,v[node]) tot = weight+vb[node] if tot > best: ...
Python
[ "trees" ]
990
1,073
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,110
8d911f79dde31f2c6f62e73b925e6996
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of...
['dfs and similar', 'trees', 'graphs']
""" Solution to Challenge 115A. A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Emplo...
Python
[ "graphs", "trees" ]
898
2,500
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,645
5891432c43cfee35a212ad92d7da2a64
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two a...
['brute force', 'math']
x = 6*int(input()) r = [] for m in range(1,10**7): d = m*(m+1) if d*m > x: break if x%d != 0: continue mx = x//d+m-1 if mx%3 != 0: continue nx = mx//3 if nx > m: r.append((m,nx)) r.append((nx,m)) elif nx == m: r.append((m,nx)) print(...
Python
[ "math" ]
423
395
0
0
0
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,762
869f94e76703cde502bd908b476d970e
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it go...
['combinatorics', 'graphs', 'dfs and similar', 'math']
n = int(input()) l = list(map(int, input().split())) l.insert(0,0) mark = {} loop, pos, res , mod= 0, 1, 1, int(1e9+7) for i in range(1, n+1): if not i in mark: start, j = pos, i while not j in mark: mark[j] = pos pos+= 1 j = l[j] if mark[j]>=start: ...
Python
[ "math", "graphs" ]
1,166
478
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,490
27a521d4d59066e50e870e7934d4b190
There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.At the...
['hashing', 'greedy', 'number theory', 'math', 'implementation', 'sortings']
n, m, k = map(int,input().split()) dm, dp = {}, {} vis = {} sensors = [] border = set() for el in [(0, m), (n, 0), (0, 0), (n, m)]: border.add(el) for _ in range(k): x, y = map(int, input().split()) if not (x - y) in dm: dm[x - y] = [] dm[x - y].append((x, y)) if not (x + y) in dp: ...
Python
[ "number theory", "math" ]
939
2,185
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,866
583168dfbaa91b79c623b44b7efee653
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings...
['data structures', 'string suffix structures', 'hashing', 'strings']
from functools import cmp_to_key def calc_lcp(s, sa): rank = [0 for _ in range(len(s))] for i in range(len(s)): rank[sa[i]] = i lcp = [0 for _ in range(len(s) - 1)] h = 0 for i in range(len(s)): if rank[i] < len(s) - 1: while max(i, sa[rank[i] + 1]) + h < len...
Python
[ "strings" ]
506
2,478
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,649
4c4ac8933f244b6ccd8b2a0bb9b254b7
Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the i...
['graphs', 'constructive algorithms', 'bitmasks', 'binary search', 'dfs and similar', 'trees']
from sys import stdin, stdout from itertools import repeat def main(): n, m = map(int, stdin.readline().split()) a = map(int, stdin.readline().split(), repeat(10, n - 1)) last = [None] * (n + 10) ne = [None] * (n + 10) for i, x in enumerate(a, 2): ne[i] = last[x] last[x] = i s = ...
Python
[ "graphs", "trees" ]
1,042
1,378
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,282
14c37283d16cb3aa8dd8fc7ea8f1096d
Given an array a, consisting of n integers, find:\max\limits_{1 \le i &lt; j \le n} LCM(a_i,a_j),where LCM(x, y) is the smallest positive integer that is divisible by both x and y. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
['combinatorics', 'binary search', 'number theory']
import sys from fractions import gcd input = sys.stdin.readline n = int(input()) A = map(int, input().split()) divisors = [[] for _ in range(10**5+2)] mobius = [1 for _ in range(10**5+2)] for i in range(1,10**5+1): for j in range(i,10**5+1,i): divisors[j].append(i) for i in range(1,10**5+1): for d i...
Python
[ "math", "number theory" ]
301
1,077
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,480
1925187d2c4b9caa1e74c29d9f33f3a6
You are given two integers l and r in binary representation. Let g(x, y) be equal to the bitwise XOR of all integers from x to y inclusive (that is x \oplus (x+1) \oplus \dots \oplus (y-1) \oplus y). Let's define f(l, r) as the maximum of all values of g(x, y) satisfying l \le x \le y \le r.Output f(l, r).
['bitmasks', 'constructive algorithms', 'greedy', 'math', 'strings', 'two pointers']
n = int(input()) le = int(input(), 2) rg = int(input(), 2) ans = rg if (2 ** (n - 1)) & le: if rg % 2 == 0 and le <= rg - 2: ans += 1 else: ans = 2 ** n - 1 if rg else 0 print('{0:b}'.format(ans))
Python
[ "math", "strings" ]
367
217
0
0
0
1
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,105
ee4038a896565a82d2d0d5293fce2a18
This is the easy version of the problem. The difference is the constraints on n, m and t. You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers n, m and k, and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score i...
['combinatorics', 'dp', 'games']
mxn=10**9 + 7 def modI(a, m): m0=m y=0 x=1; if(m==1): return 0; while(a>1): q=a//m; t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; if(x<0):x+=m0; return x; def fastfrac(a,b,M): numb = modI(b,M) return ((...
Python
[ "math", "games" ]
1,026
695
1
0
0
1
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
563
0ef40ec5578a61c93254149c59282ee3
Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v a...
['constructive algorithms', 'implementation', 'dfs and similar', 'trees']
from sys import stdin class solution(): def dfs(self, x, par, adj_arr): for adj in adj_arr[x]: if adj != par: return self.dfs(adj, x, adj_arr) return x def get_two_child(self, x, y, adj_arr): if len(adj_arr[x]) == 1: return x + 1, x + 1 ...
Python
[ "graphs", "trees" ]
1,253
1,634
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,088
822e8f394a59329fa05c96d7fb35797e
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 peo...
['number theory', 'sortings', 'greedy']
i = lambda: map(int, input().split()) n, x, y = i() a = sorted(i())[::-1] if x > y: x, y = y, x print(sum(a[:x])/x + sum(a[x:][:y])/y)
Python
[ "number theory" ]
1,182
141
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,019
436c00c832de8df739fc391f2ed6dac4
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three...
['implementation', 'brute force', 'strings']
q = ['q','w','r','t','p','s','d','f','y','g','h','j','k','l','z','x','c','v','b','n','m'] s = input() if(len(s)<3): print(s) else: a=s[0] b=s[1] print(s[:2],end='') for i in range(2,len(s)): if(s[i] in q and a in q and b in q and not(a==b and b==s[i])): print(' '+s[i],end='') ...
Python
[ "strings" ]
1,261
442
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,946
7a86885813b1b447468aca5e90910970
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coin...
['hashing', 'string suffix structures', 'greedy']
def pow(x, exp, mod): res = 1 while exp: if exp & 1: res = (res * x) % mod x = (x * x) % mod exp >>= 1 return res MOD = 2 ** 121 - 1 M = int(1e9) + 1 n = int(input()) vals = list(map(int, input().split())) groups = dict() for i in range(n): groups.setdefault(vals...
Python
[ "strings" ]
755
1,015
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,157
222fbf0693a4c1d2dd7a07d458d78a54
This is an interactive problem.There is a grid of n\times m cells. Two treasure chests are buried in two different cells of the grid. Your task is to find both of them. You can make two types of operations: DIG r c: try to find the treasure in the cell (r, c). The interactor will tell you if you found the treasure or n...
['brute force', 'constructive algorithms', 'geometry', 'interactive', 'math']
import sys input = sys.stdin.readline def d(p1, p2): return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) o1 = (14, 1) o2 = (13, 3) def query(x, y): print('SCAN',x + 1,y + 1) sys.stdout.flush() return int(input()) #return d(o1, (x, y)) + d(o2, (x, y)) def cout(x1, x2, y1, t2): ...
Python
[ "math", "geometry" ]
891
1,363
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,860
09890f75bdcfff81f67eb915379b325e
There are n segments drawn on a plane; the i-th segment connects two points (x_{i, 1}, y_{i, 1}) and (x_{i, 2}, y_{i, 2}). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every i \in [1, n] either x_{i, 1} = x_{i, 2} or y_{i, 1} = y_{i, 2} (but only one of these conditions holds). O...
['geometry', 'bitmasks', 'sortings', 'data structures', 'brute force']
import sys from array import array # noqa: F401 import typing as Tp # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') T = Tp.TypeVar('T') class FenwickSum(Tp.Generic[T]): __slots__ = ['nodes', 'size', 'unit'] def __init__(self, size: int, default: T, unit: T): sel...
Python
[ "geometry" ]
1,205
1,816
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,705
1a93a35395436f9e15760400f991f1ce
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree is a conn...
['trees', 'games']
import sys input = sys.stdin.readline Q = int(input()) Query = [] for _ in range(Q): N, X = map(int, input().split()) graph = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) Query.append((N, X-1, graph)) ...
Python
[ "games", "trees" ]
557
903
1
0
0
0
0
0
0
1
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
835
ba47e6eea45d32cba660eb6d66a9adbb
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all ...
['trees']
n = int(input()) counter = [0] * (n + 1) for i in range(n - 1): [u, v] = list(map(int, input().split())) counter[u] += 1 counter[v] += 1 if 2 in counter: print("NO") exit() print("YES")
Python
[ "trees" ]
858
206
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,724
35bd08a2f5350890b2a520672538d712
INSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyb...
['dp', 'greedy', 'combinatorics', 'dfs and similar', 'trees']
import sys range = xrange input = raw_input # Read input and build the graph inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) # R...
Python
[ "math", "graphs", "trees" ]
1,628
1,441
0
0
1
1
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,402
7d6faccc88a6839822fa0c0ec8c00251
Some time ago Lesha found an entertaining string s consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.Lesha chooses an arbitrary (possibly zero) number of pairs on positions (i, i + 1) in such a way that the follow...
['dp', 'implementation', 'greedy', 'strings']
s = input().strip();N = len(s) if len(s) == 1:print(1, s[0]);exit() X = [s[-1], s[-2]+s[-1] if s[-2]!=s[-1] else ""];Y = [1, 2 if s[-2]!=s[-1] else 0] for i in range(N-3, -1, -1): c = s[i];k1 = c+X[-1];ng = Y[-1]+1 if ng > 10:k1 = k1[:5] + "..." + k1[-2:] if c == s[i+1] and k1 > X[-2]:k1 = X[-2];ng = Y[-2] ...
Python
[ "strings" ]
820
395
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4
c151fe26b4152474c78fd71c7ab49c88
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching ps...
['dfs and similar', 'trees', 'strings']
import sys SIGMA = 26 nodes = [] pairs = [] res = 0 class Node: def __init__(self): self.ch = {} self.a = [] self.b = [] self.d = 0 def add(self, s, i): t = self for c in s: v = ord(c) - ord('a') if not v in t.ch: t.ch[v...
Python
[ "graphs", "strings", "trees" ]
880
1,438
0
0
1
0
0
0
1
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 1 }
3,074
7c41fb6212992d1b3b3f89694b579fea
There are n points on the plane, (x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n).You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
['geometry', 'math']
n = int(input()) s=0 m=0 for i in range(n): a = [ int(i) for i in input().split() ] s = sum(a) if s>=m: m=s print(m)
Python
[ "math", "geometry" ]
332
135
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,509