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
85769fb020b0d7f8e447a84a09cdddda
You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types: increase x by 1; decrease x by 1. You are given m queries of the following format: query l r — how many distinct values is x assigned to if all the instructions between...
['data structures', 'dp', 'implementation', 'strings']
from sys import* input=lambda:stdin.readline().rstrip() print=lambda x:stdout.write(str(x)+'\n') def solve(): n,m=map(int,input().split()) a=[0]+list(map(lambda x:1 if x=='+'else -1,input())) pre=a[:] for i in range(1,n+1): pre[i]+=pre[i-1] Max=pre[:]+[-10**9] Min=pre[:]+[10**9...
Python
[ "strings" ]
510
762
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,414
10c9b2d70030f7ed680297455d1f1bb0
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an...
['data structures', 'constructive algorithms', 'strings']
for _ in range(int(input())): n=int(input()) s=input() s1=input() s=list(str(x) for x in s) s1=list(str(x) for x in s1) c=[] for i in range(n-1,-1,-1): if s[len(s)-1]==s1[i]: s=s[:len(s)-1] ##print(s,i) continue if int(s1[i])+int(s[0])==1: ...
Python
[ "strings" ]
854
1,161
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 }
727
48c8ce45ab38a382dc52db1e59be234f
You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i.Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a...
['dp', 'graphs', 'flows', 'bitmasks', 'math', 'dfs and similar']
from heapq import heappush, heappop class MinCostFlow: INF = 10**18 def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap, cost): forward = [to, cap, cost, None] backward = forward[3] = [fr, 0, -cost, forward] self.G[fr].ap...
Python
[ "graphs", "math" ]
669
4,252
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,072
65a64ea63153fec4d660bad1287169d3
You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces. Space can be represented as the XY plane. You are starting at point (0, 0), and Planetforces is located in point...
['greedy', 'strings']
t = int(input()) for i in range(1,t+1): x,y = input().split() x, y = int(x), int(y) s = input() d = "" if x > 0: d += x * "R" if x < 0: d += abs(x) * "L" if y > 0: d += y * "U" if y < 0: d += abs(y) * "D" for i in range(0,len(d)): ...
Python
[ "strings" ]
1,146
530
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 }
329
f2988e4961231b9b38ca8fa78373913f
Caisa is now at home and his son has a simple task for him.Given a rooted tree with n vertices, numbered from 1 to n (vertex 1 is the root). Each vertex of the tree has a value. You should answer q queries. Each query is one of the following: Format of the query is "1 v". Let's write out the sequence of vertices along ...
['number theory', 'math', 'dfs and similar', 'trees', 'brute force']
from sys import stdin, setrecursionlimit setrecursionlimit(1000000007) _data = iter(map(int, stdin.read().split())) V = 2100000 n, q = next(_data), next(_data) a = [next(_data) for _ in range(n)] g = [[] for _ in range(n)] for _ in range(n - 1): u, v = next(_data) - 1, next(_data) - 1 g[u].append(v) g[v].ap...
Python
[ "graphs", "math", "number theory", "trees" ]
740
1,759
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 }
1,393
a186acbdc88a7ed131a7e5f999877fd6
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of tree...
['constructive algorithms', 'trees']
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): h = int(input()) a = [int(i) for i i...
Python
[ "trees" ]
1,121
3,296
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,541
148a5ecd4afa1c7c60c46d9cb4a57208
A tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is consid...
['graphs', 'constructive algorithms', 'dsu', 'dfs and similar', 'trees']
n=int(input()) a=list(map(int,input().split())) par=[] for i in range(n): if a[i]==i+1: par.append(i) v=[False for i in range(n)] for i in par: v[i]=True ccl=[] for i in range(n): if v[i]:continue s=[i] v[i]=True p=set(s) t=True while s and t: x=s.pop() j=a[x]-1 if j in p: ccl.append(j) t=False ...
Python
[ "graphs", "trees" ]
1,156
639
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,732
7d72a14dd0429e5f8ad9b75c1e35f1e7
This is an interactive problem!As part of your contribution in the Great Bubble War, you have been tasked with finding the newly built enemy fortress. The world you live in is a giant 10^9 \times 10^9 grid, with squares having both coordinates between 1 and 10^9. You know that the enemy base has the shape of a rectangl...
['binary search', 'geometry', 'interactive']
from sys import stdout from math import ceil, floor endv = 1000000000 print("? 1 1") stdout.flush() dstart = int(input()) print(("? 1000000000 1000000000")) stdout.flush() dend = int(input()) start, end = 1, min(endv, dstart) while start < end: midx = int(ceil((start + end) / 2)) print(f"? {mi...
Python
[ "geometry" ]
1,230
1,037
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,502
9089fb2547751ca140a65f03fe78c916
You are given a rooted tree consisting of n vertices. The vertices are numbered from 1 to n, and the root is the vertex 1. You are also given a score array s_1, s_2, \ldots, s_n.A multiset of k simple paths is called valid if the following two conditions are both true. Each path starts from 1. Let c_i be the number of ...
['dfs and similar', 'dp', 'greedy', 'sortings', 'trees']
from sys import stdin, stdout from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(...
Python
[ "graphs", "trees" ]
726
1,705
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,733
d1245eadd5be9051c153161d0823b6dc
A tree is an undirected connected graph without cycles.You are given a tree of n vertices. Find the number of ways to choose exactly k vertices in this tree (i. e. a k-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer c such that ...
['brute force', 'combinatorics', 'dfs and similar', 'dp', 'trees']
from sys import stdin input=lambda :stdin.readline()[:-1] mod=10**9+7 M=(10**5) fac=[1]*M ninv=[1]*M finv=[1]*M for i in range(2,M): fac[i]=fac[i-1]*i%mod ninv[i]=(-(mod//i)*ninv[mod%i])%mod finv[i]=finv[i-1]*ninv[i]%mod def binom(n,k): if n<0 or k<0: return 0 if k>n: return 0 r...
Python
[ "math", "graphs", "trees" ]
574
1,817
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 }
666
5a544816938d05da4f85fe7589d3289a
Yura owns a quite ordinary and boring array a of length n. You think there is nothing more boring than that, but Vladik doesn't agree!In order to make Yura's array even more boring, Vladik makes q boring queries. Each query consists of two integers x and y. Before answering a query, the bounds l and r for this query ar...
['data structures', 'number theory', 'math']
import sys range = xrange input = raw_input # MOD MOD = 10**9 + 7 def fast_modder(MOD): """ Returns function modmul(a,b) that quickly calculates a * b % MOD, assuming 0 <= a,b < MOD """ import sys, platform impl = platform.python_implementation() maxs = sys.maxsize if 'PyPy' in impl and MOD <= max...
Python
[ "number theory", "math" ]
999
4,547
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,692
816a82bee65cf79ba8e4d61babcd0301
You are given a tuple generator f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)}), where f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i and f^{(0)} = (x_1, x_2, \dots, x_n). Here x \bmod y denotes the remainder of x when divided by y. All p_i are primes.One can see that with fixed sequences x_i, y_i, a_i the tu...
['constructive algorithms', 'number theory']
import sys import time mod=1000000007 def sieve(s): is_not_prime=[False]*(s+1) prime=[] small=[0]*(s+1) cnt=[0]*(s+1) other=[0]*(s+1) for i in xrange(2, s+1): if not is_not_prime[i]: prime.append(i) small[i]=i cnt[i]=1 other[i]=1 for p in prime: next=p*i if next>s: break is_not_prime[...
Python
[ "number theory" ]
793
1,465
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,894
6f6bb98cee5c9e646c72f3be8969c6df
Jeevan has two arrays a and b of size n. He is fond of performing weird operations on arrays. This time, he comes up with two types of operations: Choose any i (1 \le i \le n) and increment a_j by 1 for every j which is a multiple of i and 1 \le j \le n. Choose any i (1 \le i \le n) and decrement a_j by 1 for every j w...
['binary search', 'greedy', 'implementation', 'math', 'number theory', 'sortings', 'two pointers']
# n = int(input()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # # q = int(input()) # # for i in range(q): # b[0] = int(input()) # c = [a.copy()[i] - b[i] for i in range(n)] # answer = 0 # k = 1 # while k <= n//2+1: # j = 1 # e = c.copy(...
Python
[ "math", "number theory" ]
910
2,080
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,841
b3108315889607dabcd3112bcfe3fb54
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is eve...
['constructive algorithms', 'number theory', 'math']
def isprime(a): if(a==1 or a==0 or a==2 ): return 0 x=2 while x*x<=a: if a%x==0: return 0 x+=1 return 1 primes=[] m=1 cnt=0 for x in range(1,300): if(isprime(x)): primes.append(x) n=int(input()) if(n==2): print(-1) else : for i in range(0,n-1): ...
Python
[ "number theory", "math" ]
863
376
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,065
ca6b162f945d4216055bf92d7263dbd5
Casimir has a string s which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions: he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent); or he can erase exac...
['math', 'strings']
n = int(input()) l = [input() for _ in range(n)] for i in l: a = i.count('A') b = i.count('B') c = i.count('C') if a + c == b: print("YES") else: print("NO") # Fri Apr 15 2022 17:33:44 GMT+0000 (Coordinated Universal Time) # Fri Apr 15 2022 17:33:50 GMT+0000 (Coordinated Un...
Python
[ "math", "strings" ]
1,081
334
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 }
767
904af5d6a9d84b7b7b7ff8d63e6f0254
You are given two non-empty strings s and t, consisting of Latin letters.In one move, you can choose an occurrence of the string t in the string s and replace it with dots.Your task is to remove all occurrences of the string t in the string s in the minimum number of moves, and also calculate how many different sequenc...
['combinatorics', 'dp', 'hashing', 'strings', 'two pointers']
from typing import List, Dict, Set, Sequence, Tuple, Deque, AnyStr, Optional # from sortedcontainers import SortedDict, SortedSet, SortedList from collections import deque, Counter, OrderedDict import bisect case_num = int(input()) for case_index in range(case_num): s = input() t = input() t_index...
Python
[ "math", "strings" ]
1,288
2,410
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 }
880
790739d10b9c985f2fe47ec79ebfc993
There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n-1 sections has some integer val...
['greedy', 'constructive algorithms', 'sortings', 'dfs and similar', 'trees']
import sys range = xrange input = raw_input inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] U = [] for eind in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(2*eind) coupl[v].append(2*eind + 1) U.appe...
Python
[ "graphs", "trees" ]
1,105
2,386
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,411
f00d94eb37c98a449615f0411e5a3572
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-di...
['constructive algorithms', 'geometry']
# http://codeforces.com/contest/667/problem/B # https://en.wikipedia.org/wiki/Triangle_inequality # 「Generalization to any polygon」参照。 # 三角不等式の一般化が載っている。 # ポリゴンができる条件は最長辺が残りすべての辺の長さの和より短いこと # longest< x+(total-longest) # ∴ x > 2*longest-total n = int(input()) lst = list(map(int, input().split())) print(2 * max(lst) -...
Python
[ "geometry" ]
1,465
335
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,650
7429729cdb3a42e3b0694e59d31bd994
William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.For each William's friend i it is known whether he likes currency j. There are m currenci...
['bitmasks', 'brute force', 'dp', 'probabilities']
import array import bisect import heapq import math import collections import sys import copy from functools import reduce import decimal from io import BytesIO, IOBase import os import itertools import functools from types import GeneratorType # # sys.setrecursionlimit(10 ** 9) decimal.getcontext().r...
Python
[ "probabilities" ]
699
10,774
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,907
faa26846744b7b7f90ba1b521fee0bc6
Polycarp invented a new way to encode strings. Let's assume that we have string T, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in T with its pair letter if there is a pair...
['hashing', 'string suffix structures', 'strings']
raw_input() ss = raw_input() tt = raw_input() def df(s): c = {} res = [] for i, x in enumerate(s): res.append(i - c[x] if x in c else 0) c[x] = i return res s = df(ss) t = df(tt) p = [] l = [] for i, x in enumerate(t): if not x: p.append(i) l.append(ord(tt[i]) - 97)...
Python
[ "strings" ]
878
1,148
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 }
942
6a4e5b549514814a6c72d3b1e211a7f6
Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of n lamps...
['constructive algorithms', 'greedy', 'trees']
n = int(input()) a = list(map(int,input().split())) dic = {} uexmax = n ans = [] for i in range(n-1): if i == 0: dic[a[i]] = 1 else: if a[i] in dic: dic[uexmax] = 1 ans.append([ a[i-1] , uexmax ]) else: dic[a[i]] = 1 ans.append(...
Python
[ "trees" ]
1,962
495
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,769
6cc6db6f426bb1bce59f23bfcb762b08
Recall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", ...
['dp', 'strings']
s = input() ws = [] i = 0 while i < len(s): cnt = 0 while i < len(s) and s[i] == 'v' : cnt += 1 i += 1 if cnt != 0: ws += ['w'] * (cnt - 1) if i >= len(s): break ws.append('o') i += 1 W = 0 WO = 0 WOW = 0 for c in ws: if c == 'w': W += 1 WOW +=...
Python
[ "strings" ]
1,272
361
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,627
bb1e110a7f53e6f7d43ddced7407f3d1
Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as...
['combinatorics', 'greedy']
if __name__ == '__main__': n = input() res = 1 countConsecutivePairs = 0 length = len(n) for i in range(length): if (i+1 < length and int(n[i]) + int(n[i+1]) == 9): countConsecutivePairs += 1 else: if (countConsecutivePairs % 2 == 0): res *= (c...
Python
[ "math" ]
916
397
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 }
203
fe42c7f0222497ce3fff51b3676f42d1
Recently, the bear started studying data structures and faced the following problem.You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer ...
['dp', 'number theory', 'math', 'implementation', 'data structures', 'binary search', 'brute force']
from sys import stdin from collections import * MAX = 10000000 def fast2(): import os, sys, atexit range = xrange from cStringIO import StringIO as BytesIO sys.stdout = BytesIO() atexit.register(lambda: os.write(1, sys.stdout.getvalue())) return BytesIO(os.read(0, os.fstat(0).st_size)).readli...
Python
[ "number theory", "math" ]
497
1,029
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,231
2612df3281cbb9abe328f82e2d755a08
Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k &gt; 1) if and only if: Its left hal...
['dp', 'hashing', 'brute force', 'strings']
s = raw_input() n = len(s) res = [0] * (n + 1) dp = [[0] * n for _ in xrange(n)] for l in xrange(1, n + 1): for i in xrange(n - l + 1): j = i + l - 1 if l == 1: dp[i][j] = 1 continue if s[i] == s[j] and (l == 2 or dp[i + 1][j - 1] > 0): dp[i][j] = 1 ...
Python
[ "strings" ]
734
621
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,949
36cf5a28f09a39afc1e6d1e788af71ee
Mainak has a convex polygon \mathcal P with n vertices labelled as A_1, A_2, \ldots, A_n in a counter-clockwise fashion. The coordinates of the i-th point A_i are given by (x_i, y_i), where x_i and y_i are both integers.Further, it is known that the interior angle at A_i is either a right angle or a proper obtuse angle...
['binary search', 'geometry', 'implementation', 'math']
import math pi = 3.14159265358979323846264338327950288419716939937510 eps, sq2 = 1e-13, math.sqrt(2) x, y = [], [] n = 0 def binary_find(la, lb, ra, rb, cy, fy, alpha_1, alpha_2, ab): while math.fabs(cy - fy) > eps: mid_y = cy / 2.0 + fy / 2.0 la = lb = 0.0 ra, rb = pi - alpha...
Python
[ "math", "geometry" ]
1,200
4,931
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 }
941
9f87a89c788bd7c7b66e51db9fe47e46
You are given a sequence s consisting of n digits from 1 to 9.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the re...
['greedy', 'strings']
'''input 4 6 654321 4 1337 2 33 4 2122 ''' RI = lambda : [int(x) for x in raw_input().split()] rw = lambda : raw_input().strip() for _ in range(input()): n=input() s=raw_input().strip() if n==2: if int(s[0])<int(s[1]): print "YES\n2" print s[0],s[1] else: print "NO" else: print "YES\n2" print s[...
Python
[ "strings" ]
1,260
331
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,436
0f8ad0ea2befbbe036fbd5e5f6680c21
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions: The sequence is strictly increasing, i.e. xi &lt; xi + 1 for e...
['dp', 'number theory']
n = 100001 m = int(input()) div = [[] for _ in range(n)] div[1] = [1] for i in range(2, n): if not div[i]: div[i] = [i] for j in range(2 * i, n, i): div[j].append(i) a = list(map(int, input().rstrip().split())) dp = [0] * (n + 1) for i in a: x = max(dp[j] for j in div[i]) + 1 for...
Python
[ "number theory" ]
611
366
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 }
571
cffcbdd58cc02f96d70d0819fef5131d
Lena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of n rows and m columns, and each cell is either black or white. The coordinates (i,j) denote the cell which belongs to the i-th row and j-th column for every 1\leq i \leq n and 1\leq j \leq m. To...
['data structures', 'dp', 'geometry', 'shortest paths']
from __future__ import division, print_function import math import sys import os from io import BytesIO, IOBase from collections import deque, Counter, OrderedDict, defaultdict import heapq # ceil,floor,log,sqrt,factorial,pow,pi,gcd # import bisect from bisect import bisect_left,bisect_right BUFSIZE = 8192 ...
Python
[ "graphs", "geometry" ]
815
4,112
0
1
1
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,056
1b336555c94d5d5198abe5426ff6fa7a
While walking down the street Vanya saw a label "Hide&amp;Seek". Because he is a programmer, he used &amp; as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that t...
['combinatorics', 'implementation', 'bitmasks', 'strings']
s = raw_input() d = 0 ans = 1 for c in map(ord, s): d = 0 if ord("0") <= c <= ord("9"): d += c - ord("0") elif ord("A") <= c <= ord("Z"): d += c - ord("A") + 10 elif ord("a") <= c <= ord("z"): d += c - ord("a") + 36 elif ord("-") == c: d += 62 else: d += 63 ans *= pow(3, format(d, "06b").count("0"), ...
Python
[ "math", "strings" ]
767
364
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,457
bc145a67268b42c00835dc2370804ec9
You are given an integer n and a string s consisting of 2^n lowercase letters of the English alphabet. The characters of the string s are s_0s_1s_2\cdots s_{2^n-1}.A string t of length 2^n (whose characters are denoted by t_0t_1t_2\cdots t_{2^n-1}) is a xoration of s if there exists an integer j (0\le j \leq 2^n-1) suc...
['bitmasks', 'data structures', 'divide and conquer', 'greedy', 'hashing', 'sortings', 'strings']
r=range n=int(input()) N=1<<n s=input() a=sorted([ord(s[i])*N+i for i in r(N)]) for j in r(n): p=1<<j;v=[0]*N;c=0;l=0 for i in r(N): if a[i]//N>c:c=a[i]//N;l+=1 v[a[i]%N]=l a=sorted([v[i]*N*N+v[i^p]*N+i for i in r(N)]) print(''.join([s[j^(a[0]%N)]for j in r(N)]))
Python
[ "strings" ]
900
281
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,485
f010eebcf35357f8c791a1c6101189ba
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities ...
['dp', 'greedy', 'graph matchings', 'dfs and similar', 'trees']
from collections import defaultdict from collections import deque from functools import reduce n, x, y = [int(x) for x in input().split()] E = defaultdict(set) for i in range(n-1): u, v = [int(x) for x in input().split()] E[u].add(v) E[v].add(u) if x > y: for v in E: if len(E[v]) == n-1: ...
Python
[ "graphs", "trees" ]
819
1,083
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,659
3dc14d8d19938d9a5ed8323fe608f581
You are given n segments on a number line, numbered from 1 to n. The i-th segments covers all integer points from l_i to r_i and has a value w_i.You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a s...
['data structures', 'sortings', 'trees', 'two pointers']
import bisect import sys input = sys.stdin.readline from collections import defaultdict, deque from itertools import permutations, accumulate from functools import reduce p = print r = range def I(): return int(input()) def II(): return list(map(int, input().split())) def S(): return input()[:-1] def M(n): r...
Python
[ "trees" ]
712
7,124
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,443
2c610873aa1a772a4c7f32cb74dd75fa
An identity permutation of length n is an array [1, 2, 3, \dots, n].We performed the following operations to an identity permutation of length n: firstly, we cyclically shifted it to the right by k positions, where k is unknown to you (the only thing you know is that 0 \le k \le n - 1). When an array is cyclically shif...
['brute force', 'combinatorics', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'math']
import sys input = sys.stdin.readline from collections import Counter for _ in range(int(input())): n, m = map(int, input().split()) A = list(map(int, input().split())) A = [a - 1 for a in A] B = [(i - a) % n for i, a in enumerate(A)] cnt = Counter(B) ans = [] X = list(range(1, n...
Python
[ "math", "graphs" ]
1,086
721
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,824
9578bde96aa39416a3406ffb7ca036e1
The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used.The enemy has N strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least K importan...
['dp', 'binary search', 'probabilities']
import math n = int(input()) k, epsilon = list(map(int, input().split(" "))) x0, y0 = list(map(int, input().split(" "))) epsilon /= 1000.0 l = [] for i in range(n): l.append(list(map(int, input().split(" ")))) d = sorted([(p[0] - x0) ** 2 + (p[1] - y0) ** 2 for p in l]) rmin = 0 rmax = math.sqrt(d[k - 1]) ...
Python
[ "probabilities" ]
1,364
972
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,393
2e837d3afc48177516578a950e957586
Suppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically: Cat A changes its napping place in order: n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots In other words, at th...
['math', 'number theory']
import io,os input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #print(os.fstat(0).st_size) for _ in range(int(input())): n,k=map(int,input().split()) k-=1 print((k+n%2*(k//(n//2)))%n+1)
Python
[ "math", "number theory" ]
1,089
211
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,123
6cebf9af5cfbb949f22e8b336bf07044
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.
['binary search', 'number theory', 'implementation', 'math']
from math import sqrt n = int(input()) s = [int(i) for i in input().split()] d = [1]*1000002 e = set() for i in range(2,1000002): if d[i]: e.add(i**2) for j in range(i**2,1000002,i): d[j]=0 for i in range(n): if s[i] in e: print("YES") else: print("NO")
Python
[ "number theory", "math" ]
304
267
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,943
295c768a404d11a4ac480aaaf653c45c
Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.Of course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure f...
['sortings', 'probabilities', 'math']
n=input() v=[0]*n e,f=0,0 for i in range(n): a,b=map(int,raw_input().split()) e+=a v[i]=(a*b,100-b) v.sort(cmp=lambda x,y:x[1]*y[0]-x[0]*y[1]) for x in v: e+=f*x[1]/100. f+=x[0]/100. print '%.12f'%e
Python
[ "math", "probabilities" ]
1,723
210
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 }
127
f78d04f699fc94103e5b08023949854d
Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!W...
['constructive algorithms', 'two pointers', 'greedy', 'strings']
s = input() a = [] i = 0 j = len(s) - 1 while i < j: while i < j and s[i] != '(': i += 1 while i < j and s[j] != ')': j -= 1 if i < j and s[i] == '(' and s[j] == ')': a.append(i + 1) a.append(j + 1) i += 1 j -= 1 if a: print(1) print(len(a)) p...
Python
[ "strings" ]
1,695
356
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,176
47e5ccd8220afa84c95f36b08ed1817a
Michael and Joe are playing a game. The game is played on a grid with n rows and m columns, filled with distinct integers. We denote the square on the i-th (1\le i\le n) row and j-th (1\le j\le m) column by (i, j) and the number there by a_{ij}.Michael starts by saying two numbers h (1\le h \le n) and w (1\le w \le m)....
['games']
class Subrectangle(): def __init__(self): self.create_cases() def create_cases(self): self.row_col_array = [] self.subrectangle_array = [] self.cases_num = int(input()) for i in range(self.cases_num): self.grid_row,self.grid_column = map(int,input()....
Python
[ "games" ]
1,249
2,044
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 }
2,957
fa626fb33f04323ec2dbbc235cabf7d3
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 is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she...
['constructive algorithms', 'strings']
def getstr(n): if n==1: return 'a','',1 elif n==2: return 'ab','b',2 else: if n%2==0: p,u,now=getstr((n-2)//2) c = chr(ord('a')+now) return p+c,c+u+c+c,now+1 else: p,u,now=getstr((n-1)//2) c = chr(ord('a')+now) ...
Python
[ "strings" ]
495
435
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,227
cb852bf0b62d72b3088969ede314f176
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string su...
['greedy', 'strings']
n = int(input()) s = list(input()) d = {i:0 for i in '012'} for i in s: d[i] += 1 eq = n // 3 i = 0 while d['0'] < eq: if s[i] != '0': if d[s[i]] > eq: d[s[i]] -= 1 d['0'] += 1 s[i] = '0' i += 1 i = n - 1 while d['2'] < eq: if s[i] != '2': if d[s[i]] >...
Python
[ "strings" ]
856
760
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,356
bf8bbbb225813cdf42e7a2e454f0b787
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that: b is lexicographically greater than or equal to a. bi ≥ 2. b is pairwise coprime: for every 1 ≤ i &lt; j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor ...
['constructive algorithms', 'number theory', 'greedy', 'math']
import atexit import io import sys # Buffering IO _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()) ppp = ('2 3 5 7 1...
Python
[ "number theory", "math" ]
663
1,702
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,078
49a78893ea2849aa59647846b4eaba7c
Note that girls in Arpa’s land are really attractive.Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were ...
['constructive algorithms', 'dfs and similar', 'graphs']
n=int(raw_input()) g=[[]for i in range(n+n)] c=[-1 for i in range(n+n)] e=[] for i in range(n): u,v=map(int,raw_input().split()) u-=1 v-=1 e.append([u,v]) g[u].append(v) g[v].append(u) for i in range(n): g[2*i].append(2*i+1) g[2*i+1].append(2*i) q=[-1 for i in range(2*n)] for i in range(...
Python
[ "graphs" ]
937
605
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 }
359
f35d7f9c12eea4364891e0449613f6b0
Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one...
['constructive algorithms', 'math']
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): ...
Python
[ "math" ]
698
2,048
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,559
0600b8401c8e09978661bc02691bda5d
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).To chang...
['dp', 'dfs and similar', 'trees']
from collections import defaultdict, deque class DSU: def __init__(self, n): self.parents = [i for i in range(n)] self.ranks = [0 for i in range(n)] def find_parent(self, v): if self.parents[v] == v: return v self.parents[v] = self.find_parent(self.parents[v]) ...
Python
[ "graphs", "trees" ]
795
1,577
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,653
8feb34d083d9b50c44c469e1254a885b
You are given a string s, consisting of lowercase Latin letters.You are asked q queries about it: given another string t, consisting of lowercase Latin letters, perform the following steps: concatenate s and t; calculate the prefix function of the resulting string s+t; print the values of the prefix function on positio...
['dfs and similar', 'dp', 'hashing', 'string suffix structures', 'strings', 'trees']
def get_next(j, k, nxt, p): while p[j] != '$': if k == -1 or p[j] == p[k]: j += 1 k += 1 if p[j] == p[k]: nxt[j] = nxt[k] else: nxt[j] = k else: k = nxt[k] return j, k, nxt def solve(): ...
Python
[ "graphs", "strings", "trees" ]
960
1,059
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,725
33a31edb75c9b0cf3a49ba97ad677632
Given an array a of length n, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements.
['math', 'number theory']
import math for _t in range(int(input())): n=int(input()) l=list(map(int,input().split())) ans=0 for i in l: if(int(math.sqrt(i))**2!=math.sqrt(i)**2): ans=1 if(ans==1): print("YES") else: print("NO")
Python
[ "math", "number theory" ]
289
256
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 }
991
96fac9f9377bf03e144067bf93716d3d
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a: Remove any two elements from a and append their sum to b. Th...
['constructive algorithms', 'number theory', 'math']
# cook your dish here T=int(input()) for _ in range(T): n=int(input()) s=list(map(int,input().split())) odd=[] even=[] for i in range(len(s)): if(s[i]%2!=0): odd.append(i+1) else: even.append(i+1) count=0 for i in range(0,len(odd)-1,2): if(...
Python
[ "number theory", "math" ]
871
570
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,598
274ae43b10bb15e270788d36590713c7
Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at nigh...
['dp', 'dfs and similar', 'trees']
import collections import sys Stats = collections.namedtuple( 'Stats', [ 'odd_paths_to_root', 'even_paths_to_root', 'result', 'sum_paths_to_root', 'size', ]) def _solve(children_stats): sum_paths_to_root = 0 odd_paths_to_root = 0 even_paths_to_root = 1 result = 0 size = 1 for s in ...
Python
[ "graphs", "trees" ]
1,516
2,189
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 }
348
fbb6d21b757d8d56396af1253ec9e719
You are given an array a consisting of n distinct positive integers.Let's consider an infinite integer set S which contains all integers x that satisfy at least one of the following conditions: x = a_i for some 1 \leq i \leq n. x = 2y + 1 and y is in S. x = 4y and y is in S.For example, if a = [1,2] then the 10 smalles...
['bitmasks', 'dp', 'math', 'matrices', 'number theory', 'strings']
import sys from array import array class dict_(dict): def __missing__(self, key): return 0 mod = 10 ** 9 + 7 add = lambda a, b: (a % mod + b % mod) % mod mult = lambda a, b: (a % mod * b % mod) % mod input = lambda: sys.stdin.buffer.readline().decode().strip() n, p = map(int, input().spli...
Python
[ "math", "number theory", "strings" ]
614
1,084
0
0
0
1
1
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 1, "trees": 0 }
716
c6633581d7424d670eaa0f8a5c8cc366
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known...
['implementation', 'strings']
def check(g1,g2,s,star): for idx,char in enumerate(g1): if char==s[idx]: continue elif char=='?': if alpha[ord(s[idx])-97]==1: continue else: return "NO" else: return "NO" ss=s[::-1] for idx,char in enu...
Python
[ "strings" ]
959
2,603
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,133
507e3e805e91a91e5130f53588e62dab
Heidi found out that the Daleks have created a network of bidirectional Time Corridors connecting different destinations (at different times!). She suspects that they are planning another invasion on the entire Space and Time. In order to counter the invasion, she plans to deploy a trap in the Time Vortex, along a care...
['trees', 'graphs']
from __future__ import division, print_function def main(): class DSU: def __init__ (self,n): self.parent=list(range(n)) self.size=[1]*n self.count_sets=n def find(self,u): to_update=[] while u!=self.parent[u]: to_update.app...
Python
[ "graphs", "trees" ]
1,639
3,712
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,388
db1c28e9ac6251353fbad8730f4705ea
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balan...
['number theory', 'dfs and similar', 'trees']
def gcd(a, b): while b: a, b = b, a % b return a def lcm(a, b): return a // gcd(a, b) * b def cal((f1, k1), (f2, k2)): if f1 > f2: f1, k1, f2, k2 = f2, k2, f1, k1 A = (f1 - f2) % k2 B = 0 x1 = 0 k11 = k1 % k2 k1x1 = 0 while B != A and k1x1 <= f1: if B < ...
Python
[ "graphs", "number theory", "trees" ]
661
1,797
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 }
95
d6ac9ca9cc5dfd9f43f5f65ce226349e
You are given a string s, consisting only of Latin letters 'a', and a string t, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string s with a string t. Note that after the replacement string s might contain letters other than 'a'.You can perform an arbitrary number of moves (i...
['combinatorics', 'implementation', 'strings']
''' # Submitted By Ala3rjMo7@gmail.com Don't Copy This Code, Try To Solve It By Yourself ''' # Problem Name = "Infinite Replacement" # Class: C def Solve(): ss, rs = [], [] for t in range(int(input())): ss.append(input()) rs.append(input()) for s, r in zip(ss, rs): if ...
Python
[ "math", "strings" ]
562
571
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 }
2,664
388450021f2f33177d905879485bb531
Consider the set of all nonnegative integers: {0, 1, 2, \dots}. Given two integers a and b (1 \le a, b \le 10^4). We paint all the numbers in increasing number first we paint 0, then we paint 1, then 2 and so on.Each number is painted white or black. We paint a number i according to the following rules: if i = 0, it is...
['number theory', 'math']
tests = int(input()) for _ in range(tests): n, k = map(int, input().split()) n, k = max(n, k), min(n, k) while n % k != 0: n %= k n, k = k, n if k == 1: print("Finite") else: print("Infinite")
Python
[ "math", "number theory" ]
1,737
245
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,260
22f90afe503267ff2c832430d3ffb3b4
Word s of length n is called k-complete if s is a palindrome, i.e. s_i=s_{n+1-i} for all 1 \le i \le n; s has a period of k, i.e. s_i=s_{k+i} for all 1 \le i \le n-k. For example, "abaaba" is a 3-complete word, while "abccba" is not.Bob is given a word s of length n consisting of only lowercase Latin letters and an int...
['greedy', 'dsu', 'implementation', 'dfs and similar', 'strings']
from sys import stdin t = int(stdin.readline()) for _ in range(t): n, k = map(int, stdin.readline().split()) s = stdin.readline() cnt = [[0 for i in range(26)] for j in range((k + 1) // 2)] for i in range(n): cnt[min(i % k, k - i % k - 1)][ord(s[i]) - ord('a')] += 1 ans = 0 for i in range(k // 2): ans += 2 *...
Python
[ "graphs", "strings" ]
921
404
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 }
2,353
1daa784c0eb1cde514e4319da07c8d00
Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function , that for any the formula g(g(x)) = g(x) holds.Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x)) for each k &gt; ...
['constructive algorithms', 'graphs', 'math']
from random import randint from copy import deepcopy n = int(input()) a = list(map(int, input().split())) for i in range(n): a[i] -= 1 def gen(n): a = [] for i in range(n): a.append(randint(0, n - 1)) return a def stupid(a, v=False): n = len(a) init = [a[i] for i in range(n)] ...
Python
[ "graphs", "math" ]
442
2,615
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 }
2,616
2df489560ec3d63d76afaba9e277c0f1
Petya has a rooted tree with an integer written on each vertex. The vertex 1 is the root. You are to answer some questions about the tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node v is the next vertex on the shortest path from v to the root.Each...
['data structures', 'dfs and similar', 'trees']
import io, sys, atexit raw_input = iter(sys.stdin.read().splitlines()).next sys.stdout = _OUTPUT_BUFFER = io.BytesIO() @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) def iter_dfs(q, a, adj, queries): freq = [0]*(len(adj)+1) freq_list = [[] for _ in xrange(len(adj)...
Python
[ "graphs", "trees" ]
1,494
1,962
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 }
928
69135ef7422b5811ae935a9d00796f88
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic prog...
['dp', 'brute force', 'math', 'strings']
from string import ascii_lowercase s = input() lc = {c: 0 for c in ascii_lowercase} llc = dict() for c in s: for v in lc: if v + c not in llc: llc[v + c] = lc[v] else: llc[v + c] += lc[v] lc[c] += 1 print(max(*lc.values(), *llc.values()))
Python
[ "math", "strings" ]
1,198
291
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 }
481
a01e1c545542c1641eca556439f0692e
A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.
['number theory', 'math']
def extgcd(a, b): if b == 0: return 1, 0, a x, y, g = extgcd(b, a % b) return y, x - y * (a // b), g a, b, c = map(int, raw_input().split()) x, y, g = extgcd(a, b) if c % g != 0: print -1 else: t = c // g print -x * t, -y * t
Python
[ "math", "number theory" ]
224
235
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,210
587ac3b470aaacaa024a0c6dde134b7c
You are given an integer array a_1, a_2, \ldots, a_n.The array b is called to be a subsequence of a if it is possible to remove some elements from a to get b.Array b_1, b_2, \ldots, b_k is called to be good if it is not empty and for every i (1 \le i \le k) b_i is divisible by i.Find the number of good subsequences in ...
['dp', 'number theory', 'math', 'implementation', 'data structures']
#!/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 sys import stdin def m...
Python
[ "number theory", "math" ]
712
1,450
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,802
81f7807397635c9ce01f9100e68cb420
Let's call a set of positive integers a_1, a_2, \dots, a_k quadratic if the product of the factorials of its elements is a square of an integer, i. e. \prod\limits_{i=1}^{k} a_i! = m^2, for some integer m.You are given a positive integer n.Your task is to find a quadratic subset of a set 1, 2, \dots, n of maximum size....
['constructive algorithms', 'hashing', 'math', 'number theory']
def is_square(n): return int(n ** 0.5) ** 2 == n def solve(n): if n <= 3: return range(2, n+1) k = n >> 1 if n % 4 == 0: return [k] if n % 4 == 1: return [k, n] if n % 4 == 2: if is_square(n + 2): return [k + 1] if is_square(2 ...
Python
[ "math", "number theory" ]
400
785
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,985
178222a468f37615ee260fc9d2944aec
Alice's potion making professor gave the following assignment to his students: brew a potion using n ingredients, such that the proportion of ingredient i in the final potion is r_i &gt; 0 (and r_1 + r_2 + \cdots + r_n = 1).He forgot the recipe, and now all he remembers is a set of n-1 facts of the form, "ingredients i...
['dfs and similar', 'math', 'number theory', 'trees']
import heapq import math import os import sys from array import array from bisect import bisect_left, bisect_right from collections import defaultdict, deque, Counter from fractions import Fraction from io import IOBase, BytesIO from itertools import groupby, accumulate from sys import stdin from typing impo...
Python
[ "graphs", "number theory", "math", "trees" ]
1,169
2,782
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 }
3,133
de5a9d39dcd9ad7c53ae0fa2d441d3f0
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.There are n video cards in the shop, the power of the i-th video card is equal to inte...
['number theory', 'math', 'implementation', 'data structures', 'brute force']
def main(): n = int(input()) aa = list(map(int, input().split())) aa.sort() lim = aa[-1] + 1 cnt, a = [0] * lim, aa[0] - 1 for i, b in zip(range(n, -1, -1), aa): if a != b: cnt[a + 1:b + 1] = [i] * (b - a) a = b avail, res = [True] * lim, [] for i, a in en...
Python
[ "math", "number theory" ]
1,289
486
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,168
63e130256e23bd0693c6a1bede5e937e
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers ...
['number theory', 'math', 'matrices', 'implementation', 'data structures']
def recfib(n,m): if n==0: return (0,1,) a, b = recfib(n / 2,m) return ((b*b+a*a)%m, b*(2*a+b)%m) if n%2 else (a*((2*b)-a)%m, ((b*b+a*a))%m) m,l,r,k = map(long, raw_input().split()) D = (r-l)/(k-1) while D > 1 and (1+(r/D)-((l+D-1)/D))<k: N = 1 + (r/D) D -= ( ((N*D)-r) + (N-1) ) / N print(recfib(D, m...
Python
[ "math", "number theory" ]
889
327
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 }
999
5ca990a9f93c0b9450aa22a723403b1f
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetr...
['dp', 'combinatorics', 'dfs and similar']
n, m = map(int, raw_input().split()) l = list(map(int, raw_input().split())) index = [[0 for i in range(n)] for j in range(n)] for i in range(n): mini = 10000000000000 for j in range(i, n): if l[j] < mini: inde = j mini = l[j] index[i][j] = inde prime = 998244353 d = {} val = [[1 for i in range(n + 1)] for ...
Python
[ "math", "graphs" ]
1,150
751
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,625
54f8b8e6711ff5c69e0bc38a6e2f4999
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one p...
['implementation', 'strings']
#------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w')...
Python
[ "strings" ]
1,350
2,877
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,467
d40f0f3b577a1a5cfad2a657d6a1b90a
Alperen has two strings, s and t which are both initially equal to "a". He will perform q operations of two types on the given strings: 1 \;\; k \;\; x — Append the string x exactly k times at the end of string s. In other words, s := s + \underbrace{x + \dots + x}_{k \text{ times}}. 2 \;\; k \;\; x — Append the string...
['constructive algorithms', 'greedy', 'strings']
t = int(input()) for _ in range(t): q = int(input()) s_a_count = 1 t_a_count = 1 other_than_a_t = False other_than_a_s = False for _ in range(q): line = list(map(str, input().rstrip().split())) if line[0] == '2': for char in line[2]: ...
Python
[ "strings" ]
1,439
775
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,153
4c0b0cb8a11cb1fd40fef47616987029
There is a string s of length 3, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.
['brute force', 'implementation', 'strings']
n=int(input()) for i in range(0,n): first=str(input()); if(first.upper()=="YES"): print("YES") else: print("NO")
Python
[ "strings" ]
237
146
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,640
a7d3548c4bc356b4bcd40fca7fe839b2
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n...
['dp', 'graphs', 'dfs and similar', 'shortest paths']
from sys import * from collections import * s = stdin.read().split() d = list(map(int, s)) n, m = d[:2] g = [[] for i in range(n + 1)] for j in range(m): i = 3 * j + 2 g[d[i]].append((d[i + 1], d[i + 2], j)) g[d[i + 1]].append((d[i], d[i + 2], j)) u, v = [-1] * n + [0], [1e9] * n + [0] x, y = [0] * (n + 1),...
Python
[ "graphs" ]
1,868
782
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 }
78
159365b2f037647fbaa656905e6f5252
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a...
['math', 'dsu', 'implementation', 'sortings', 'dfs and similar']
def binSearch(arr, el): if len(arr) == 0: return -1 l, p = 0, len(arr)-1 while l != p: s = (l+p) // 2 if arr[s] < el: l = s + 1 else: p = s return l if arr[l] == el else -1 n = int(input()) a = [int(i) for i in input().split()] s = sorted(a) subsList = [...
Python
[ "math", "graphs" ]
561
876
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 }
2,920
a67cdb7501e99766b20a2e905468c29c
Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this a...
['geometry', 'brute force', 'math']
def subtract(a1, a2): if a1 > a2 + 0.0000001: return a1-a2 elif abs(a1-a2) <= 0.0000001: return 0 return 360+a1-a2 def angle(a1, a2): import math return math.atan2(a2,a1)*180/math.pi def start(): n = input() degreesPositive = [] for _ in xrange(n): a1, a2 = map(...
Python
[ "math", "geometry" ]
464
868
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 }
3,883
1cc628b4e03c8b8e0c5086dc4e0e3254
Spring has come, and the management of the AvtoBus bus fleet has given the order to replace winter tires with summer tires on all buses.You own a small bus service business and you have just received an order to replace n tires. You know that the bus fleet owns two types of buses: with two axles (these buses have 4 whe...
['brute force', 'greedy', 'math', 'number theory']
for i in range(int(input())): n = int(input()) if n%2 != 0 or n < 3: print(-1) else: minimum = n // 6 maximum = n//4 if minimum * 6 != n: minimum += 1 print(minimum, maximum)
Python
[ "math", "number theory" ]
675
253
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,557
3b885c926076382f778a27a3c1f49d91
Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem!You are given n points on the plane, no three of which are collinear. The i-th point initially has a label a_i, in such a way that the labels a_1, a_2, \dots, a_n form a permutation of 1, 2, \dots, n.Yo...
['constructive algorithms', 'geometry', 'sortings']
import sys,io,os try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline except:Z=lambda:sys.stdin.readline().encode() from math import atan2;from collections import deque def path(R): H=deque();H.append(R) while P[R]>=0: R=P[R];H.append(R) if len(H)>2:P[H.popleft()]=H[-1] return ...
Python
[ "geometry" ]
1,099
2,256
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,500
1708818cf66de9fa03439f608c897a90
You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≤ a ≤ b &lt; x ≤ y ≤ |s| and substrings s[a... b], s[x... y] are palindromes.A pali...
['dp', '*special', 'brute force', 'strings']
t = input() n = len(t) a, b = [1] * n, [1] * n for x, y in [(i - 1, i + 1) for i in range(n // 2)]: while x >= 0 and t[x] == t[y]: a[y] += 1 b[x] += 1 x -= 1 y += 1 for x, y in [(i, i + 1) for i in range(n // 2)]: while x >= 0 and t[x] == t[y]: a[y] += 1 b[x] += ...
Python
[ "strings" ]
628
751
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,125
c2f3d09674190f90c940f134c3e22afe
Ashish has a string s of length n containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions: Length of the substring is at least 2 'a' occurs strictly more times in this substring than 'b' 'a' occurs strictly more times in this substring ...
['brute force', 'greedy', 'implementation', 'strings']
t = int(input()) for case in range(t): n = int(input()) s = input() ans = -1 tests = ['aa', 'aba', 'aca', 'abca', 'acba', 'abbacca', 'accabba'] for i in tests: if i in s: ans = len(i) break print(ans)
Python
[ "strings" ]
659
266
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,009
e0a3c678f6d1d89420c8162b0ddfcef7
There is an infinite set generated as follows: 1 is in this set. If x is in this set, x \cdot a and x+b both are in this set. For example, when a=3 and b=6, the five smallest elements of the set are: 1, 3 (1 is in this set, so 1\cdot a=3 is in this set), 7 (1 is in this set, so 1+b=7 is in this set), 9 (3 is in this se...
['constructive algorithms', 'math', 'number theory']
import sys input=sys.stdin.readline for _ in range(int(input())): n,a,b=map(int,input().split()) d={} x=1 while True: x=x*a if x<=n and x!=1: d[x]=0 else: break #print(d) y=0 for k in d: y=1 if (n%b==1) or ((n%b...
Python
[ "math", "number theory" ]
611
592
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,351
d5913f8208efa1641f53caaee7624622
Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
['geometry', 'combinatorics', 'math', 'sortings', 'data structures', 'brute force']
from fractions import gcd N = input() points = [map(int, raw_input().split()) for _ in xrange(N)] ans = N * (N-1) * (N-2) // 6 lines = {} for i in xrange(N-1): for j in range(i+1, N): x1, y1 = points[i] x2, y2 = points[j] g = gcd(x1-x2, y1-y2) dx, dy = (x1-x2)//g, (y1-y2)//g ...
Python
[ "math", "geometry" ]
279
596
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 }
3,776
d100092621f97b2749729914d3fabf46
Bogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest co...
['graphs', 'math', 'data structures', 'dfs and similar', 'trees']
from collections import deque import sys #import time sys.setrecursionlimit(200000) def bfs(v, d): global q1, edges, m, n, mark, dep, p, gf mark[v] = True p[v] = v #pp[v] = v dep[v] = d dd = deque([v]) maxdepth = 0 while dd: v = dd.popleft() for ui in l[v]: u = ui[0] if not mark[u]: mark[u] = Tr...
Python
[ "graphs", "math", "trees" ]
1,017
2,901
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 }
2,041
a6e13812cdf771ba480e69c0ff6f4c74
You are given a prime number n, and an array of n integers b_1,b_2,\ldots, b_n, where 0 \leq b_i &lt; n for each 1 \le i \leq n.You have to find a matrix a of size n \times n such that all of the following requirements hold: 0 \le a_{i,j} &lt; n for all 1 \le i, j \le n. a_{r_1, c_1} + a_{r_2, c_2} \not\equiv a_{r_1, c...
['constructive algorithms', 'number theory']
from sys import stdin # import tracemalloc # from sys import setrecursionlimit # import resource input = stdin.readline # setrecursionlimit(int(1e9)) # resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1)) def ii(): return int(input()) def li(): return list(map(int, input().split())) ...
Python
[ "number theory" ]
849
644
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,473
f94165f37e968442fa7f8be051018ad9
You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i.You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (u ...
['graphs', 'dsu', 'divide and conquer', 'sortings', 'trees']
def find_ancestor(i, father): if father[i] == i: return i father[i] = find_ancestor(father[i], father) return father[i] def connect(i, j, father, n_child): i_anc = find_ancestor(i, father) j_anc = find_ancestor(j, father) if n_child[i_anc] > n_child[j_anc]: n_child[i_anc] += n_c...
Python
[ "graphs", "trees" ]
492
1,232
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,148
8d9fc054fb1541b70991661592ae70b1
The Olympic Games have just started and Federico is eager to watch the marathon race.There will be n athletes, numbered from 1 to n, competing in the marathon, and all of them have taken part in 5 important marathons, numbered from 1 to 5, in the past. For each 1\le i\le n and 1\le j\le 5, Federico remembers that athle...
['combinatorics', 'graphs', 'greedy', 'sortings']
def win(a, b): cnt = 0 for i in range(5): if a[i] < b[i]: cnt += 1 if cnt >= 3: return a return b for _ in range(int(input())): n = int(input()) l = [] for i in range(n): l.append(list(map(int, input().split()))) ini = l[0] idx ...
Python
[ "math", "graphs" ]
1,015
678
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 }
925
2b346d5a578031de4d19edb4f8f2626c
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
['implementation', 'strings']
s1 = input() s2 = input() c=0 v = ['a','e','i','o','u'] if len(s1)==len(s2): i=0 while(i<len(s1)): if (s1[i] in v and s2[i] not in v) or s1[i] not in v and s2[i] in v: c=1 i+=1 if c==1: print("No") else: print("Yes") else: print("No")
Python
[ "strings" ]
651
302
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,609
9271c88a3bc3c69855daeda9bb6bbaf5
You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i - a_i (if 1 \le i - a_i) or to the position i + a_i (if i + a_i \le n).For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that a_j has th...
['graphs', 'dfs and similar', 'shortest paths']
class Solution(object): def solve(self,array): """ :type arr: List[int] :type start: int :rtype: bool """ from collections import defaultdict,deque D=defaultdict(list) self.t_max=float('inf') for i in range(0,len(array)): if array[...
Python
[ "graphs" ]
497
1,574
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,892
152aba87aaf14d1841f6622dc66051af
Given a permutation a_1, a_2, \dots, a_n of integers from 1 to n, and a threshold k with 0 \leq k \leq n, you compute a sequence b_1, b_2, \dots, b_n as follows. For every 1 \leq i \leq n in increasing order, let x = a_i. If x \leq k, set b_{x} to the last element a_j (1 \leq j &lt; i) that a_j &gt; k. If no such eleme...
['constructive algorithms', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'trees']
# def dfs(node, stack, next, visited): # if node == -1 or node in visited: # return # visited.add(node) # # print(node, next) # dfs(next[node], stack, next, visited) # stack.append(node) import sys from collections import defaultdict # sys.setrecursionlimit(200000) def dfs(no...
Python
[ "graphs", "trees" ]
1,316
2,068
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,447
20f69ee5f04c8cbb769be3ab646031ab
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef"....
['implementation', 'strings']
def do(t): ret = "" for item in t: ret += "0"*(4-len(item)) + item + ":" return ret n = int(raw_input()) for i in range(n): ip6 = str(raw_input()).split("::") if len(ip6) == 2: prefix,postfix = ip6[0].split(":"),ip6[1].split(":") res = do(prefix) +"0000:"*(8-len(prefix) ...
Python
[ "strings" ]
1,977
425
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,812
7374246c559fb7b507b0edeea6ed0c5d
Hosssam decided to sneak into Hemose's room while he is sleeping and change his laptop's password. He already knows the password, which is a string s of length n. He also knows that there are k special letters of the alphabet: c_1,c_2,\ldots, c_k.Hosssam made a program that can do the following. The program considers t...
['brute force', 'implementation', 'strings']
import sys t = int(sys.stdin.readline()) for _ in range(t): n = int(sys.stdin.readline()) s = sys.stdin.readline().strip().lower() a = sys.stdin.readline().strip().lower().split() k = int(a[0]) d = [0]*256 for i in range(1, k+1): d[ord(a[i])] = 1 parts = 0 maxlen...
Python
[ "strings" ]
1,273
1,040
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,321
4dffa25857c7719a43817e0ad01ef759
In this problem you will have to help Berland army with organizing their command delivery system.There are n officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer a is the direct superior of officer b...
['dfs and similar', 'trees', 'graphs']
n,q=map(int,input().split()) from heapq import heappush as pu from heapq import heappop as po from bisect import bisect_right as br tr=[[] for i in range(n)] size=[1 for i in range(n)] p=list(map(int,input().split())) p=[i-1 for i in p] for i in range(n-1): tr[p[i]].append(i+1) for i in range(n): tr[i].sort(rever...
Python
[ "graphs", "trees" ]
3,133
724
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,474
0197047cab6d83a189a5c1eabf5b1dd3
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, \ldots, s_n.Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1}...
['dp', 'number theory', 'math']
def DFC(maxm, u): maxm += 1 e[u] = maxm if len(st[u]) == 0: maxms.append(maxm) return 0 for i in st[u]: if e[i] <= maxm: DFC(maxm, i) return 0 # list( map(int, input().split()) ) rw = int(input()) for ewqr in range(rw): n = int(input()) maxms = [] max...
Python
[ "number theory", "math" ]
879
657
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,844
e0a1dc397838852957d0e15ec98d5efe
You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with intege...
['binary search', 'geometry', 'shortest paths', 'sortings']
import os DEBUG = 'DEBUG' in os.environ def debug(*args): if DEBUG: print(">", *args) def solution(houses): if len(houses) == 1: return 1 housesX = [] housesY = [] for house in houses: housesX.append(house[0]) housesY.append(house[1]) housesX.sort() housesY.sort() ...
Python
[ "graphs", "geometry" ]
638
946
0
1
1
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,379
8386c1a5db2565ccc8a7154cefa29391
In all schools in Buryatia, in the 1 class, everyone is told the theory of Fibonacci strings."A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci string if...
['greedy', 'implementation', 'math', 'number theory']
#!/usr/bin/env PyPy3 from collections import Counter, defaultdict, deque import itertools import re import math from functools import reduce import operator import bisect from heapq import * import functools mod=998244353 import sys import os from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO...
Python
[ "math", "number theory" ]
1,210
3,281
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,991
d78c61a218b250facd9b5bdd1b7e4dba
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.Recall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tree is goo...
['bitmasks', 'data structures', 'dfs and similar', 'dsu', 'greedy', 'trees']
from __future__ import print_function from math import * from collections import defaultdict, deque import os import random import sys from io import BytesIO, IOBase from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args,...
Python
[ "graphs", "trees" ]
653
5,822
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,469
92feda270834af751ca37bd80083aafa
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who th...
['probabilities', 'math']
for i in range(int(input())): a, b = map(int, input().split()) print(0.5 + a / (b << 4) if 4 * b > a else 1 - b / a if a else 1)
Python
[ "math", "probabilities" ]
1,038
137
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,091
fa24700412a8532b5b92c1e72d8a2e2d
You are given an undirected unrooted tree, i.e. a connected undirected graph without cycles.You must assign a nonzero integer weight to each vertex so that the following is satisfied: if any vertex of the tree is removed, then each of the remaining connected components has the same sum of weights in its vertices.
['constructive algorithms', 'dfs and similar', 'math', 'trees']
import os,sys from io import BytesIO, IOBase from collections import deque, Counter,defaultdict as dft from heapq import heappop ,heappush from math import log,sqrt,factorial,cos,tan,sin,radians,log2,ceil,floor,gcd from bisect import bisect,bisect_left,bisect_right from decimal import * import sys,thre...
Python
[ "graphs", "math", "trees" ]
314
5,759
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,310
23467790e295f49feaaf1fc64beafa86
We define a spanning tree of a graph to be a BFS tree rooted at vertex s if and only if for every node t the shortest distance between s and t in the graph is equal to the shortest distance between s and t in the spanning tree. Given a graph, we define f(x,y) to be the number of spanning trees of that graph that are BF...
['combinatorics', 'dfs and similar', 'graphs', 'math', 'shortest paths', 'trees']
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) MOD = 998244353 adjList = [] dist = [] ans = [] for _ in range(n): adjList.append([]) for _ in range(m): a,b = map(int,input().split()) ...
Python
[ "math", "graphs", "trees" ]
589
4,045
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 }
643
ebf0bf949a29eeaba3bcc35091487199
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.For example, if the str...
['greedy', 'sortings', 'games']
t = int(input()) for _ in range(t): s = sorted(input().split('0'), reverse=True)[::2] res = sum(list(map(len, s))) print(res)
Python
[ "games" ]
1,035
139
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,673
bc8b4b74c2f2d486e2d2f03982ef1013
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were pub...
['two pointers', 'dsu', 'data structures', 'binary search', 'trees']
from bisect import * n,k=map(int,input().split()) h=list(map(int,input().split())) l=[] q=[] aa=-1 j=0 for i in range(n): l.insert(bisect(l,h[i]),h[i]) while l[-1]-l[0]>k: l.pop(bisect(l,h[j])-1) j+=1 if i-j+1>aa: aa=i-j+1 q=[] if i-j+1==aa: q.append([j+1,i+1]) pr...
Python
[ "graphs", "trees" ]
1,031
367
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,900
6bb2793e275426eb076972fab69d0eba
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≤ i, j ≤ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
['strings']
def f(x=input()): d = dict() for i in x: if i in d: d[i]+=1 else: d[i] = 1 return sum([j*j for _,j in d.items()]) print(f())
Python
[ "strings" ]
217
131
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,278
5c013cdc91f88c102532a86058893f0d
An important meeting is to be held and there are exactly n people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the i-th person is a non-negative integer a_i....
['constructive algorithms', 'graphs', 'greedy']
import sys, math, collections def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_array(): return list(map(int, sys.stdin.readline().strip().split())) def input(): return sys.stdin.readline().strip() MOD = 1000000007 for _ in range(int(input())): n = int(input()) ...
Python
[ "graphs" ]
802
984
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,313