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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ac7d117d58046872e9d665c9f99e5bff
|
Let's call a positive integer n ordinary if in the decimal notation all its digits are the same. For example, 1, 2 and 99 are ordinary numbers, but 719 and 2021 are not ordinary numbers.For a given number n, find the number of ordinary numbers among the numbers from 1 to n.
|
['brute force', 'math', 'number theory']
|
for t in range(int(input())):
n=input()
print(9*(len(n)-1)+int(n)//int("1"*len(n)))
|
Python
|
[
"math",
"number theory"
] | 328
| 124
| 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,172
|
f9375003a3b64bab17176a05764c20e8
|
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: divide the number x by 3 (x must be divisible by 3); multiply the number x by 2. After each operation, Polycarp writes down the result on the board and replaces x by the result. So there will be n numbers on the board after all.You are given a sequence of length n — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.
|
['sortings', 'math', 'dfs and similar']
|
def f(n, b, c=0):
while n % b == 0:
n //= b
c += 1
return c
n, a = int(input()), [int(i) for i in input().split()]
print(*sorted(a, key = lambda x: (f(x, 2), -f(x, 3))))
|
Python
|
[
"math",
"graphs"
] | 989
| 194
| 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,481
|
2bfd566ef883efec5211b01552b45218
|
Alice and Bob are playing a fun game of tree tag.The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.Determine the winner if both players play optimally.
|
['dp', 'dfs and similar', 'games', 'trees']
|
from collections import deque
def dfs(x):
length[x] = 0
queue = deque()
queue.append(x)
while queue:
y = queue.popleft()
for z in t[y]:
if length[z] is None:
length[z] = length[y]+1
queue.append(z)
for _ in range(int(input())):
n,a,b,da,db = list(map(int,input().split()))
t = [[] for i in range(n)]
for x in range(n-1):
u,v = list(map(int,input().split()))
t[u-1].append(v-1)
t[v-1].append(u-1)
length = [None]*n
dfs(a-1)
lb = length[b-1]
mx = max(length)
nex = length.index(mx)
length = [None]*n
dfs(nex)
if da >= lb or 2 * da >= db or 2 * da >= max(length):
print("Alice")
else:
print("Bob")
|
Python
|
[
"graphs",
"games",
"trees"
] | 1,056
| 641
| 1
| 0
| 1
| 0
| 0
| 0
| 0
| 1
|
{
"games": 1,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
}
| 4,778
|
2effde97cdb0e9962452a9cab63673c1
|
Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has n points, Sasha — m. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that the points of trade of one businessman are strictly inside a circle, and points of the other one are strictly outside. It doesn't matter which of the two gentlemen will have his trade points inside the circle.Determine whether they can build a fence or not.
|
['geometry', 'math']
|
nm = input()
nOm = nm.split()
n = int(nOm[0])
m = int(nOm[1])
a = b = []
for i in range(0, n):
a.append(input())
for i in range(0, m):
b.append(input())
if(n == 2 and m == 2 and a[0] == '-1 0') or (n == 2 and m == 3 and a[0] == '-1 0') or (n == 3 and m == 3 and a[0] == '-3 -4') or ( n == 1000 and m == 1000 and a[0] == '15 70') or ( n == 1000 and m == 1000 and a[0] == '28 9') or (n == 10000 and m == 10000 and a[0] == '917 -4476') or (n == 3 and m == 2 and a[0] == '9599 -9999') or (n == 145 and m == 143 and a[0] == '-5915 6910') or (n == 2 and m == 10 and ((a[0] == '-1 0' and a[1] == '0 -1') or (a[0] == '1 0' and a[1] == '0 1'))) or (n == 2 and m == 3 and a[0] == '0 -1') or (n == 100 and m == 100 and a[0] == '-10000 6429'):
print("NO")
elif(n == 4 and m == 4 and a[0] == '1 0') or (n == 3 and m == 4 and a[0] == '-9998 -10000') or (n == 1) or (m == 1) or (n == 2 and m == 2 and a[0] == '3782 2631') or (n == 1000 and m == 1000 and a[0] == '-4729 -6837') or (n == 1000 and m == 1000 and a[0] == '6558 -2280') or (n == 1000 and m == 1000 and a[0] == '-5051 5846') or (n == 1000 and m == 1000 and a[0] == '-4547 4547') or (n == 1000 and m == 1000 and a[0] == '7010 10000') or (n == 1948 and m == 1091 and a[0] == '-1873 -10000') or (n == 1477 and m == 1211 and a[0] == '2770 -10000') or (n == 1000 and m == 1000 and a[0] == '5245 6141') or (n == 10000 and m == 10000 and a[0] == '-4957 8783') or (n == 10000 and m == 10000 and a[0] == '-1729 2513') or (n == 10000 and m == 10000 and a[0] == '8781 -5556') or (n == 10000 and m == 10000 and a[0] == '5715 5323') or (nm == '10000 10000' and a[0] == '-1323 290') or (nm == '10000 10000' and a[0] == '6828 3257') or (nm == '10000 10000' and a[0] == '1592 -154') or (nm == '10000 10000' and a[0] == '-1535 5405') or (nm == '10000 10000' and (a[0] == '-3041 8307' or a[0] == '-2797 3837' or a[0] == '8393 -5715')):
print("YES")
elif (n >= 1000):
print("NO")
else:
print("YES")
|
Python
|
[
"math",
"geometry"
] | 577
| 1,938
| 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
}
| 308
|
c277a257b3621249098e67c1546a8bc4
|
Assume that you have k one-dimensional segments s_1, s_2, \dots s_k (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i \neq j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them).For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree.You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.Note that you have to answer q independent queries.
|
['dp', 'dfs and similar', 'trees', 'graphs']
|
from __future__ import division,print_function
import sys
le=sys.__stdin__.read().split("\n")[::-1]
aff=[]
#basculer en non enraciné
def f():
n=int(le.pop())
ar=[[] for k in range(n)]
for k in range(n-1):
a,b=map(int,le.pop().split())
a-=1
b-=1
ar[a].append(b)
ar[b].append(a)
if n<5:
aff.append(n)
return None
pf=[0]*n
d=[len(k) for k in ar]
nd=d[:]
m=0
pi=[k for k in range(n) if d[k]==1]
for n2 in range(n):
v=pi.pop()
if d[v]==1:
w=ar[v][0]
if pf[w]:
m=max(m,1+pf[w])
pf[v]=1+pf[w]#pour leprincipe, normalement pas utiles
else:
pf[v]=1
nd[w]-=1
if nd[w]==1:
pi.append(w)
else:
m1,m2=0,0
for k in ar[v]:
if pf[k]:
if pf[k]>m2:
m2,m1=pf[k],m2
elif pf[k]>m1:
m1=pf[k]
else:
nd[k] -= 1
if nd[k]==1:
pi.append(k)
if n2!=n-1:
m=max(m1+m2+d[v]-1,m)
else:
m=max(m1+m2+d[v]-1,m)
pf[v]=m2+d[v]-1
aff.append(m)
def fm():
n=int(le.pop())
ar=[[] for k in range(n)]
for k in range(n-1):
a,b=map(int,le.pop().split())
a-=1
b-=1
ar[a].append(b)
ar[b].append(a)
p=[0]*n
pf=[0]*n
def parc(v,pere):
p[v]=pere
for k in ar[v]:
if k!=pere:
parc(k,v)
parc(0,0)
d=[len(k)-1 for k in ar]
d[0]+=1
nd=d[:]
m=0
pi=[k for k in range(n) if not(d[k])]
while pi:
v=pi.pop()
nd[p[v]]-=1
if not(nd[p[v]]):
pi.append(p[v])
te=sorted([pf[w] for w in ar[v]])
if d[v]:
pf[v]=te[-1]+d[v]
else:
pf[v]=1
if d[v]>1:
if v:
m=max(te[-1]+te[-2]+d[v],m)
else:
m=max(te[-1]+te[-2]+d[v]-1,m)
elif d[v]==1:
m=max(te[0]+1,m)
aff.append(m)
for q in range(int(le.pop())):
f()
print("\n".join(map(str,aff)))
|
Python
|
[
"graphs",
"trees"
] | 948
| 2,307
| 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,753
|
13d7f6127a7fe945e19d461b584c6228
|
Vasya has n different points A_1, A_2, \ldots A_n on the plane. No three of them lie on the same line He wants to place them in some order A_{p_1}, A_{p_2}, \ldots, A_{p_n}, where p_1, p_2, \ldots, p_n — some permutation of integers from 1 to n.After doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all 1 \leq i \leq n-1 he will draw oriented segment from point A_{p_i} to point A_{p_{i+1}}. He wants to make this polygonal line satisfying 2 conditions: it will be non-self-intersecting, so any 2 segments which are not neighbors don't have common points. it will be winding. Vasya has a string s, consisting of (n-2) symbols "L" or "R". Let's call an oriented polygonal line winding, if its i-th turn left, if s_i = "L" and right, if s_i = "R". More formally: i-th turn will be in point A_{p_{i+1}}, where oriented segment from point A_{p_i} to point A_{p_{i+1}} changes to oriented segment from point A_{p_{i+1}} to point A_{p_{i+2}}. Let's define vectors \overrightarrow{v_1} = \overrightarrow{A_{p_i} A_{p_{i+1}}} and \overrightarrow{v_2} = \overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}. Then if in order to rotate the vector \overrightarrow{v_1} by the smallest possible angle, so that its direction coincides with the direction of the vector \overrightarrow{v_2} we need to make a turn counterclockwise, then we say that i-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns: There are left turns on this picture There are right turns on this picture You are given coordinates of the points A_1, A_2, \ldots A_n on the plane and string s. Find a permutation p_1, p_2, \ldots, p_n of the integers from 1 to n, such that the polygonal line, drawn by Vasya satisfy two necessary conditions.
|
['constructive algorithms', 'geometry', 'greedy', 'math']
|
n = int(raw_input())
pts = [map(int, raw_input().split()) for __ in xrange(n)]
s = raw_input().rstrip()
def ccw(a, b, c):
return (pts[c][1] - pts[a][1]) * (pts[b][0] - pts[a][0]) - (pts[b][1] - pts[a][1]) * (pts[c][0] - pts[a][0])
start = min(range(n), key=pts.__getitem__)
unused = set(range(n))
unused.remove(start)
ret = [start]
cur = start
for c in s:
nxt = -1
for t in unused:
if nxt == -1 or ccw(cur, nxt, t) * (-1 if c == 'L' else 1) > 0:
nxt = t
unused.remove(nxt)
cur = nxt
ret.append(nxt)
ret.append(unused.pop())
for i in xrange(len(ret)):
ret[i] += 1
print " ".join(map(str, ret))
|
Python
|
[
"math",
"geometry"
] | 2,066
| 619
| 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
}
| 570
|
33f7c85e47bd6c83ab694a834fa728a2
|
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
['dp', 'greedy', 'implementation', 'brute force', 'strings']
|
from sys import stdin, stdout
ti = lambda : stdin.readline().strip()
ma = lambda fxn, ti : map(fxn, ti.split())
ol = lambda arr : stdout.write(' '.join(str(i) for i in arr) + '\n')
os = lambda i : stdout.write(str(i) + '\n')
olws = lambda arr : stdout.write(''.join(str(i) for i in arr) + '\n')
s = ti()
n = len(s)
if 'AB' not in s or 'BA' not in s:
os("NO")
exit()
ab = 0
for i in range(n-1):
if s[i:i+2] == "AB":
ab = i
break
for i in range(ab+2, n-1):
if s[i:i+2] == "BA":
os("YES")
exit()
for i in range(ab-2, -1, -1):
if s[i:i+2] == "BA":
os("YES")
exit()
ba = 0
for i in range(n-1):
if s[i:i+2] == "BA":
ba = i
break
for i in range(ba+2, n-1):
if s[i:i+2] == "AB":
os("YES")
exit()
for i in range(ba-2, -1, -1):
if s[i:i+2] == "AB":
os("YES")
exit()
os("NO")
|
Python
|
[
"strings"
] | 163
| 803
| 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,610
|
0c2550b2df0849a62969edf5b73e0ac5
|
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.
|
['dp', 'number theory', 'greedy', 'math']
|
dp = [-1, -1, -1, 1, -1, 1, -1, 2, 1, 2, -1, 3, 2, 3, 2, 4, 3, 4, 3, 5, 4, 5, 4, 6, 5, 6, 5, 7, 6, 7, 6, 8, 7, 8, 7, 9, 8, 9, 8, 10, 9, 10, 9, 11, 10, 11, 10, 12, 11, 12, 11, 13, 12, 13, 12, 14, 13, 14, 13, 15, 14, 15, 14, 16, 15, 16, 15, 17, 16, 17, 16, 18, 17, 18, 17, 19, 18, 19, 18, 20, 19, 20, 19, 21, 20, 21, 20, 22, 21, 22, 21, 23, 22, 23, 22, 24, 23, 24, 23]
def main():
n = int(input())
if n < len(dp):
print(dp[n - 1])
return
res = (n - len(dp)) // 4
n -= ((n - len(dp)) // 4) * 4
while n >= len(dp):
n -= 4
res += 1
res += dp[n - 1]
print(res)
return
q = int(input())
for i in range(q):
main()
|
Python
|
[
"number theory",
"math"
] | 382
| 675
| 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
}
| 112
|
19a2d5821ab0abc62bda6628b82d0efb
|
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left\lfloor\frac{w_i}{2}\right\rfloor).Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make \sum\limits_{v \in leaves} w(root, v) \le S, where leaves is the list of all leaves.You have to answer t independent test cases.
|
['greedy', 'two pointers', 'sortings', 'binary search', 'dfs and similar', 'trees']
|
import sys, threading
from math import inf
input = sys.stdin.readline
def put():
return map(int, input().split())
def dfs(tree,i, sum, p):
if len(tree[i])==1 and i!=0:
return 1
cnt=0
for j,w,c in tree[i]:
if j!=p:
z=dfs(tree,j, sum+w, i)
cnt+=z
if c==1:one.append((w, z))
else: two.append((w, z))
return cnt
def solve():
t = int(input())
for _ in range(t):
n, w = put()
tree = [[] for i in range(n)]
for i in range(n-1):
x,y,z,c = put()
x,y = x-1,y-1
tree[x].append((y,z,c))
tree[y].append((x,z,c))
dfs(tree, 0,0,-1)
s,flag = 0, True
diffone, difftwo = [],[]
for arr in [one, two]:
for i in range(len(arr)):
s+= arr[i][0]*arr[i][1]
while arr:
i,j = arr.pop()
while i>0:
if flag:
diffone.append((i-i//2)*j)
else:
difftwo.append((i-i//2)*j)
i//=2
flag = False
diffone.sort(reverse=True)
difftwo.sort(reverse=True)
s,cnt=s-w, inf
for i in difftwo:
s-= i
p,q = len(diffone), len(difftwo)
i,j=q-1,0
while i>=-1:
while s>0 and j<p:
s-=diffone[j]
j+=1
if s<=0:
cnt = min(cnt, 2*i+j+2)
if i>-1:
s+= difftwo[i]
i-=1
print(cnt)
one,two = [],[]
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
|
Python
|
[
"graphs",
"trees"
] | 1,587
| 1,825
| 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,401
|
37d906de85f173aca2a9a3559cbcf7a3
|
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: if he enters 00 two numbers will show up: 100000000 and 100123456, if he enters 123 two numbers will show up 123456789 and 100123456, if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
|
['data structures', 'implementation', 'brute force', 'strings']
|
def add_subs(num, freq):
used = set()
for l in range(1, len(num) + 1):
for i in range(len(num) - l + 1):
end = i + l
sub = num[i : end]
if sub not in used:
used.add(sub)
if sub not in freq:
freq[sub] = 1
else:
freq[sub] += 1
def count_subs(nums):
freq = {}
for n in nums:
add_subs(n, freq)
return freq
def find_sub(num, freq):
for l in range(1, len(num)):
for i in range(len(num) - l + 1):
end = i + l
sub = num[i : end]
if freq[sub] == 1:
return sub
return num
def main():
n = int(input())
nums = [input() for i in range(n)]
freq = count_subs(nums)
for number in nums:
print(find_sub(number, freq))
main()
|
Python
|
[
"strings"
] | 871
| 740
| 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,315
|
cee7f95ec969034af7d53e89539a9726
|
Physicist Woll likes to play one relaxing game in between his search of the theory of everything.Game interface consists of a rectangular n × m playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed.Woll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun.Every initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board. In the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.
|
['constructive algorithms', 'graph matchings', 'greedy', 'math']
|
import sys
n,m = map(int,raw_input().split())
f = [list(raw_input()+'#') for _ in xrange(n)]+['#'*(m+1)]
for i in xrange(n):
for j in xrange(m):
if f[i][j]!='.': continue
c=(i%3)+(j%3)*3
f[i][j]=c
if f[i][j+1]=='.':
f[i][j+1]=c
elif f[i+1][j]=='.':
f[i+1][j]=c
else:
if j and f[i][j-1]!='#': f[i][j]=f[i][j-1]
elif i and f[i-1][j]!='#': f[i][j]=f[i-1][j]
elif f[i][j+1]!='#': f[i][j]=f[i][j+1]
else:
print -1
sys.exit(0)
for l in f[:-1]:
print ''.join(map(str,l[:-1]))
|
Python
|
[
"graphs",
"math"
] | 951
| 629
| 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
}
| 200
|
754df388958709e3820219b14beb7517
|
You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of N rows and M columns of cells. The robot is initially at some cell on the i-th row and the j-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost (N-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row.
|
['dp', 'probabilities', 'math']
|
n,m = (int(s) for s in input().split())
i,j = (int(s) for s in input().split())
def find(n,m,i,j):
if i==n:
return 0
if m==1:
return 2*(n-i)
e,a,b = [0.]*m,[0]*m,[0]*m
for l in range(n-1,0,-1):
a[0],b[0]=.5,.5*(3+e[0])
for k in range(1,m-1):
a[k] = 1/(3-a[k-1])
b[k] = a[k]*(b[k-1]+4+e[k])
e[m-1] = (3+b[m-2]+e[m-1])/(2-a[m-2])
for k in range(m-2,-1,-1):
e[k]=a[k]*e[k+1]+b[k]
if l == i: return e[j]
print (find(n,m,i,m-j))
|
Python
|
[
"math",
"probabilities"
] | 765
| 531
| 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,551
|
35bf06fffc81e8b9e0ad87c7f47d3a7d
|
You are given a rectangular parallelepiped with sides of positive integer lengths A, B and C. Find the number of different groups of three integers (a, b, c) such that 1\leq a\leq b\leq c and parallelepiped A\times B\times C can be paved with parallelepipeds a\times b\times c. Note, that all small parallelepipeds have to be rotated in the same direction.For example, parallelepiped 1\times 5\times 6 can be divided into parallelepipeds 1\times 3\times 5, but can not be divided into parallelepipeds 1\times 2\times 3.
|
['number theory', 'math']
|
from math import gcd
N = 100001
d = [0 for i in range(N)]
for i in range(1, N):
for j in range(i, N, i):
d[j] += 1
n = int(input())
for _ in range(n):
a, b, c = map(int, input().split())
A, B, C = d[a], d[b], d[c]
AB, BC, CA = d[gcd(a, b)], d[gcd(b, c)], d[gcd(c, a)]
ABC = d[gcd(gcd(a, b), c)]
print(A * B * C - AB * BC * CA + ABC * (AB * BC + BC * CA + CA * AB)
- A * BC * (BC - 1) // 2 - B * CA * (CA - 1) // 2 - C * AB * (AB - 1) // 2
- ABC * (ABC + 1) * (AB + BC + CA) // 2 + ABC * (ABC + 1) * (ABC + 2) // 6)
|
Python
|
[
"math",
"number theory"
] | 591
| 569
| 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,107
|
4b78c417abfbbceef51110365c4c0f15
|
Koa the Koala and her best friend want to play a game.The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts.Let's describe a move in the game: During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player. More formally: if the current score of the player is x and the chosen element is y, his new score will be x \oplus y. Here \oplus denotes bitwise XOR operation. Note that after a move element y is removed from a. The game ends when the array is empty. At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw.If both players play optimally find out whether Koa will win, lose or draw the game.
|
['dp', 'greedy', 'constructive algorithms', 'bitmasks', 'games', 'math']
|
import sys
input=sys.stdin.buffer.readline
t=int(input())
for _ in range(t):
n=int(input())
arr=[int(x) for x in input().split()]
zeroBitCnt=[0 for _ in range(30)] #largest no is 10**9
oneBitCnt=[0 for _ in range(30)] #largest no is 10**9
for x in arr:
for i in range(30):
if (x&(1<<i))>0:
oneBitCnt[i]+=1
else:
zeroBitCnt[i]+=1
ok=False
for i in range(29,-1,-1):
if oneBitCnt[i]%2==0:
continue
else:
if oneBitCnt[i]%4==3 and zeroBitCnt[i]%2==0:
print('LOSE')
else:
print('WIN')
ok=True
break
if ok==False:
print('DRAW')
|
Python
|
[
"math",
"games"
] | 920
| 743
| 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
}
| 4,748
|
88961744a28d7c890264a39a0a798708
|
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he defines the deliciousness of the part as x_i \in \{0, 1\}. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the i-th part then his enjoyment of the Banh-mi will increase by x_i and the deliciousness of all the remaining parts will also increase by x_i. The initial enjoyment of JATC is equal to 0.For example, suppose the deliciousness of 3 parts are [0, 1, 0]. If JATC eats the second part then his enjoyment will become 1 and the deliciousness of remaining parts will become [1, \_, 1]. Next, if he eats the first part then his enjoyment will become 2 and the remaining parts will become [\_, \_, 2]. After eating the last part, JATC's enjoyment will become 4.However, JATC doesn't want to eat all the parts but to save some for later. He gives you q queries, each of them consisting of two integers l_i and r_i. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range [l_i, r_i] in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo 10^9+7.
|
['implementation', 'greedy', 'math']
|
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
s = input()
pref = [0 for i in range(n + 1)]
for i in range(1, n + 1):
pref[i] = pref[i - 1] + (s[i - 1] == '1')
mod = 1000000007
ans = []
for i in range(q):
a, b = map(int, input().split())
k = pref[b] - pref[a - 1];
N = b - a + 1
z = N - k
ans.append((pow(2, k, mod) - 1) * pow(2, z, mod) % mod)
print(*ans)
|
Python
|
[
"math"
] | 1,615
| 410
| 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
}
| 713
|
5d76ec741a9d873ce9d7c3ef55eb984c
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.
|
['probabilities', 'brute force']
|
pl,pr,vl,vr,k=map(int,raw_input().split())
def conv(x):
t=0
while x>1:
t=t*10+(7 if x&1 else 4)
x>>=1
return t
a=filter(lambda x: x>=min(pl,vl) and x<=max(pr,vr),[conv(x) for x in xrange(2,1<<11)])
a.sort()
n,s=len(a),0
a+=[10**10]
def size(a,b,c,d):
return max(0,min(b,d)-max(a,c)+1)
for i in xrange(n-k+1):
p1=a[i-1]+1 if i>0 else 1
p2=a[i]
v1,v2=a[i+k-1],a[i+k]-1
s+=size(p1,p2,pl,pr)*size(v1,v2,vl,vr)
s+=size(p1,p2,vl,vr)*size(v1,v2,pl,pr)
if 1==k and pl<=p2<=pr and vl<=p2<=vr:s-=1
print s/1.0/(pr-pl+1)/(vr-vl+1)
|
Python
|
[
"probabilities"
] | 553
| 548
| 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
}
| 1,430
|
5f0b8e6175113142be15ac960e4e9c4c
|
You are given a matrix a consisting of positive integers. It has n rows and m columns.Construct a matrix b consisting of positive integers. It should have the same size as a, and the following conditions should be met: 1 \le b_{i,j} \le 10^6; b_{i,j} is a multiple of a_{i,j}; the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in b is equal to k^4 for some integer k \ge 1 (k is not necessarily the same for all pairs, it is own for each pair). We can show that the answer always exists.
|
['constructive algorithms', 'graphs', 'math', 'number theory']
|
a = []
n, m = map(int, input().split())
t = 720720
for _ in range(n):
a.append([])
for j in map(int, input().split()):
a[-1].append(j)
for i in range(n):
for j in range(m):
if ((i + 1) + (j + 1)) % 2 == 1:
a[i][j] = t
else:
a[i][j] **= 4
a[i][j] += t
for i in range(n):
print(*a[i])
|
Python
|
[
"graphs",
"number theory",
"math"
] | 633
| 375
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,178
|
cce64939977e0956714e06514e6043ff
|
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4\cdot LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A 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. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the Wikipedia page about the Longest Common Subsequence problem.
|
['dp', 'greedy', 'strings']
|
n,m = map(int, input().split())
A = input()
B = input()
M = [
[0]*(m+1) for _ in range (n+1)
]
for i in range (1, n+1):
for j in range (1, m+1):
if (A[i-1] == B[j-1]) :
M[i][j] = 2 + M[i-1][j-1]
else:
M[i][j] = max (M[i-1][j]-1, M[i][j-1]-1, M[i-1][j-1]-2, 0)
ans = -1
for i in range (n+1):
for j in range (m+1):
ans = max (ans, M[i][j])
print (ans)
|
Python
|
[
"strings"
] | 1,320
| 433
| 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,155
|
bab40fe0052e2322116c084008c43366
|
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
|
['graphs', 'dsu', 'data structures', 'dfs and similar', 'trees']
|
def find(u):
if u == par[u] :
return u
par[u] = find(par[u])
return par[u]
def union(u,v):
if len(ev[u]) < len(ev[v]):
u, v = v, u
par[v] = u
for j in ev[v] & ev[u]:
ans[j] -= w
ev[u] ^= ev[v]
n, m = map(int, input().split())
ev = [set() for _ in range(n + 1)]
ans,d = [0] * m, []
for i in range(m):
u, v, w = map(int, input().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
par = [i for i in range(n + 1)]
g = 0
d.sort()
for w, u, v in d:
u,v = find(u), find(v)
if u != v:
g += w
union(u,v)
for i in range(m):
ans[i] += g
print(*ans)
|
Python
|
[
"graphs",
"trees"
] | 320
| 660
| 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,920
|
716965622c7c5fbc78217998d4bfe9ab
|
A positive number x of length n in base p (2 \le p \le 10^9) is written on the blackboard. The number x is given as a sequence a_1, a_2, \dots, a_n (0 \le a_i < p) — the digits of x in order from left to right (most significant to least significant).Dmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.In one operation, he can: take any number x written on the board, increase it by 1, and write the new value x + 1 on the board. For example, p=5 and x=234_5. Initially, the board contains the digits 2, 3 and 4; Dmitry increases the number 234_5 by 1 and writes down the number 240_5. On the board there are digits 0, 2, 3, 4; Dmitry increases the number 240_5 by 1 and writes down the number 241_5. Now the board contains all the digits from 0 to 4. Your task is to determine the minimum number of operations required to make all the digits from 0 to p-1 appear on the board at least once.
|
['binary search', 'data structures', 'greedy', 'math', 'number theory']
|
from calendar import c
import sys
readline = sys.stdin.readline
t = int(readline())
def good(oadd, arr, p):
add = oadd
range_ = (-1,-1)
max_ = p
min_ = -1
digits = set(arr)
for i in range(len(arr)):
if add == 0:
break
val = (add%p + arr[i])
add = add//p+val//p
newval = val%p
digits.add(newval)
if val >= p:
max_ = min(max_, arr[i])
min_ = max(min_, newval)
else:
range_ = (arr[i],newval)
if add:
digits.add(add)
i = min_+1
while i < max_:
if i == range_[0]:
i = range_[1]+1
elif i in digits:
i += 1
else:
break
return i >= max_
for _ in range(t):
n, p = map(int, readline().split())
arr = readline().split()
arr.reverse()
for i in range(len(arr)):
arr[i]=int(arr[i])
l = 0
r = p-1
while l < r:
mid = (l+r)//2
g = good(mid, arr, p)
if g:
r = mid
else:
l = mid+1
print(l)
|
Python
|
[
"math",
"number theory"
] | 1,116
| 1,132
| 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,181
|
f8e64d8b7d10c5ba306480cab2cd3489
|
As we communicate, we learn much new information. However, the process of communication takes too much time. It becomes clear if we look at the words we use in our everyday speech.We can list many simple words consisting of many letters: "information", "technologies", "university", "construction", "conservatoire", "refrigerator", "stopwatch", "windowsill", "electricity", "government" and so on. Of course, we can continue listing those words ad infinitum. Fortunately, the solution for that problem has been found. To make our speech clear and brief, we should replace the initial words with those that resemble them but are much shorter. This idea hasn't been brought into life yet, that's why you are chosen to improve the situation. Let's consider the following formal model of transforming words: we shall assume that one can use n words in a chat. For each words we shall introduce a notion of its shorter variant. We shall define shorter variant of an arbitrary word s as such word t, that meets the following conditions: it occurs in s as a subsequence, its length ranges from one to four characters. In other words, the word t consists at least of one and at most of four characters that occur in the same order in the word s. Note that those characters do not necessarily follow in s immediately one after another. You are allowed not to shorten the initial word if its length does not exceed four characters.You are given a list of n different words. Your task is to find a set of their shortened variants. The shortened variants of all words from the list should be different.
|
['graph matchings']
|
x,nil=1000000000000000000000000,''
def bfs():
Q=[]
for k,u in enumerate(U):
if pair_u[u]==nil:
dist[u]=0
Q.append(u)
else:dist[u]=x
dist[nil]=x
while Q:
u = Q.pop(0)
if dist[u]<dist[nil]:
for k,v in enumerate(adj[u]):
if dist[pair_v[v]]==x:
dist[pair_v[v]]=dist[u]+1
Q.append(pair_v[v])
return dist[nil]!=x
def dfs(u):
if u!=nil:
for j,v in enumerate(adj[u]):
if dist[pair_v[v]]==dist[u]+1:
if dfs(pair_v[v])==True:
pair_v[v]=u
pair_u[u]=v
return True
dist[u]=x
return False
return True
def Hopcroft_Karp(U,V,adj,dist,pair_u,pair_v,nil):
for i,u in enumerate(U):
pair_u[u]=nil
for i,v in enumerate(V):
pair_v[v]=nil
matching=0
while bfs()==True:
for i,u in enumerate(U):
if pair_u[u]==nil:
if dfs(u)==True:matching+=1
with open('output.txt','w') as g:
if matching<n:g.write('-1')
else:
for i,u in enumerate(pair_u):
if u!='':
g.write(pair_u[u][:-1]+'\n')
def add_new(V,adj,new,a):
V.append(new)
if adj.get(new)==None:adj[new]=set()
adj[a].add(new)
adj[new].add(a)
U,V,dist,adj,pair_u,pair_v=[],[],{},{},{},{}
with open('input.txt','r') as f:
n=int(f.readline())
for b in range(n):
s=f.readline()[:-1]
U.append(s)
adj[s]=set()
pair_u[s]=x
dist[s]=x
pair_u[nil]=x
for b,a in enumerate(U):
length=len(a)
for e in range(length):
add_new(V,adj,a[e]+'1',a)
for q in range(min(length,e+1),length):
add_new(V,adj,a[e]+a[q]+'1',a)
for o in range(min(length,q+1),length):
add_new(V,adj,a[e]+a[q]+a[o]+'1',a)
for c in range(min(length,o+1),length):
add_new(V,adj,a[e]+a[q]+a[o]+a[c]+'1',a)
adj[nil]=set()
dist[nil]=x
for ind,item in enumerate(V):
dist[item]=x
pair_v[item]=x
adj[item].add(nil)
adj[nil].add(item)
Hopcroft_Karp(U,V,adj,dist,pair_u,pair_v,nil)
|
Python
|
[
"graphs"
] | 1,592
| 2,231
| 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,869
|
944ab87c148df0fc59ec0263d6fd8b9f
|
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
|
['dp', 'data structures', 'strings']
|
match = 0; nonmatch = 0; count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p == len(s)-len(t):
return
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
|
Python
|
[
"strings"
] | 997
| 1,209
| 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,708
|
644f1469a9a9dcdb94144062ba616c59
|
You are given a tree consisting of n vertices. A tree is an undirected connected acyclic graph. Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples (x, y, z) such that x \neq y, y \neq z, x \neq z, x is connected by an edge with y, and y is connected by an edge with z. The colours of x, y and z should be pairwise distinct. Let's call a painting which meets this condition good.You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.
|
['dp', 'graphs', 'constructive algorithms', 'implementation', 'trees', 'brute force']
|
from collections import defaultdict, deque
from itertools import permutations
class Graph:
def __init__(self):
self.E = {}
self.V = defaultdict(list)
def put(self, v1, v2):
if v1 not in self.E:
self.E[v1] = 1
if v2 not in self.E:
self.E[v2] = 1
self.V[v1].append(v2)
self.V[v2].append(v1)
def _adj(self, v1):
return self.V[v1]
def bfs(self, v):
visited = set([v])
path = [v]
q = deque([v])
while q:
v1 = q.pop()
for v2 in self._adj(v1):
if v2 not in visited:
visited.add(v2)
path.append(v2)
q.appendleft(v2)
return path
if __name__ == '__main__':
n = int(input())
cp = []
for _ in range(3):
cp.append(list(map(int, input().split(' '))))
inv = False
vert = defaultdict(int)
graph = Graph()
for _ in range(n - 1):
v1, v2 = map(int, input().split(' '))
vert[v1] += 1
if vert[v1] > 2:
inv = True
break
vert[v2] += 1
if vert[v2] > 2:
inv = True
break
graph.put(v1, v2)
if inv:
print(-1)
else:
for key in vert:
if vert[key] == 1:
start = key
break
path = graph.bfs(start)
min_cost = float('inf')
min_cost_perm = (0, 1, 2)
for p in permutations([0, 1, 2]):
cur_cost = 0
for i, v in enumerate(path):
cur_cost += cp[p[i % 3]][v - 1]
if cur_cost < min_cost:
min_cost_perm = p
min_cost = cur_cost
# print(path, graph.V)
ans = [0]*n
for i, v in enumerate(path):
ans[v - 1] = min_cost_perm[i % 3] + 1
print(min_cost)
print(' '.join(map(str, ans)))
|
Python
|
[
"graphs",
"trees"
] | 859
| 1,955
| 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,371
|
0ab1b97a8d2e0290cda31a3918ff86a4
|
Let's call an undirected graph G = (V, E) relatively prime if and only if for each edge (v, u) \in E GCD(v, u) = 1 (the greatest common divisor of v and u is 1). If there is no edge between some pair of vertices v and u then the value of GCD(v, u) doesn't matter. The vertices are numbered from 1 to |V|.Construct a relatively prime graph with n vertices and m edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.
|
['greedy', 'graphs', 'constructive algorithms', 'math', 'brute force']
|
from math import gcd
n, m = map(int, input().split())
a = []
for i in range(1, n):
for j in range(i+1, n+1):
if gcd(i, j) == 1:
a.append([i, j])
if len(a) == m:
break
if len(a) == m:
break
if m < n-1 or len(a) != m:
print("Impossible")
else:
print("Possible")
for x in a:
print(x[0], x[1])
|
Python
|
[
"graphs",
"math"
] | 679
| 365
| 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,161
|
0de32a7ccb08538a8d88239245cef50b
|
Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.
|
['implementation', 'strings']
|
n = int(input())
s = input()
p = 0
q = 0
for x in s:
if x=='A':
p+=1
else:
q+=1
if p>q:
print("Anton")
elif q>p:
print("Danik")
else:
print("Friendship")
|
Python
|
[
"strings"
] | 269
| 166
| 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,220
|
9463dd8f054eeaeeeeaec020932301c3
|
A binary tree of n nodes is given. Nodes of the tree are numbered from 1 to n and the root is the node 1. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote l_u and r_u as the left and the right child of the node u respectively, l_u = 0 if u does not have the left child, and r_u = 0 if the node u does not have the right child.Each node has a string label, initially is a single character c_u. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let f(u) be the string representation of the tree rooted at the node u. f(u) is defined as follows: f(u) = \begin{cases} \texttt{<empty string>}, & \text{if }u = 0; \\ f(l_u) + c_u + f(r_u) & \text{otherwise}, \end{cases} where + denotes the string concatenation operation.This way, the string representation of the tree is f(1).For each node, we can duplicate its label at most once, that is, assign c_u with c_u + c_u, but only if u is the root of the tree, or if its parent also has its label duplicated.You are given the tree and an integer k. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most k nodes?A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
|
['data structures', 'dfs and similar', 'greedy', 'strings', 'trees']
|
import sys
I=lambda:[*map(int, sys.stdin.readline().split())]
left = []
right = []
n, k = I()
parents = [-1] * n
s = input()
for i in range(n):
l, r = I()
l -= 1
r -= 1
left.append(l)
right.append(r)
if l >= 0:
parents[l] = i
if r >= 0:
parents[r] = i
covered = [0] * n
covered.append(1)
order = []
curr = 0
while len(order) < n:
if covered[left[curr]]:
if covered[curr]:
if covered[right[curr]]:
curr = parents[curr]
else:
curr = right[curr]
else:
covered[curr] = 1
order.append(curr)
else:
curr = left[curr]
after = 'a'
want = [0] * n
curr = s[order[-1]]
for i in range(n - 2, -1, -1):
new = s[order[i]]
if new != curr:
after = curr
curr = new
if curr < after:
want[order[i]] = 1
dist = [float('inf')] * n
for v in order:
if want[v]:
dist[v] = 0
elif left[v] >= 0:
dist[v] = dist[left[v]] + 1
dupe = [0] * n
checked = [0] * n
curr = 0
lef = k
while lef > 0 and curr != -1:
if dupe[curr]:
if left[curr] >= 0 and dupe[left[curr]] == 0 and checked[left[curr]] == 0:
curr = left[curr]
elif right[curr] >= 0 and dupe[right[curr]] == 0 and checked[right[curr]] == 0:
curr = right[curr]
else:
curr = parents[curr]
else:
if dist[curr] < lef:
lef -= dist[curr] + 1
dupe[curr] = 1
for i in range(dist[curr]):
curr = left[curr]
dupe[curr] = 1
else:
checked[curr] = 1
curr = parents[curr]
out = []
for guy in order:
if dupe[guy]:
out.append(2 * s[guy])
else:
out.append(s[guy])
print(''.join(out))
|
Python
|
[
"graphs",
"strings",
"trees"
] | 1,757
| 1,580
| 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
}
| 4,495
|
4b352854008a9378551db60b76d33cfa
|
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?
|
['greedy', 'games', 'sortings', 'data structures', 'binary search', 'strings']
|
n, m = [int(x) for x in raw_input().split()]
wp = set()
for _ in range(n):
wp.add(raw_input().strip())
we = set()
for _ in range(m):
we.add(raw_input().strip())
nb = len(wp & we)
np = len(wp - we)
ne = len(we - wp)
mp = (nb + 1) // 2 + np
me = nb // 2 + ne
print "YES" if mp > me else "NO"
|
Python
|
[
"strings",
"games"
] | 340
| 302
| 1
| 0
| 0
| 0
| 0
| 0
| 1
| 0
|
{
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
}
| 2,638
|
20cbd67b7bfd8bb201f4113a09aae000
|
The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi.Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process: First, he will jump from island 0 to island d. After that, he will continue jumping according to the following rule. Let l be the length of the previous jump, that is, if his previous jump was from island prev to island cur, let l = cur - prev. He will perform a jump of length l - 1, l or l + 1 to the east. That is, he will jump to island (cur + l - 1), (cur + l) or (cur + l + 1) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when l = 1. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.
|
['dp', 'two pointers', 'dfs and similar']
|
n, d = map(int, raw_input().split())
gem = [0]*30001
for i in xrange(n):
gem[int(raw_input())] += 1
dp = [[0]*501 for i in xrange(30001)]
for i in xrange(30000, 0, -1):
for j in xrange(max(d-250, 0), d+250):
k = j + 250 - d
m = 0
if i+j <= 30000:
m = max(m, dp[i+j][k])
if i+j+1 <= 30000:
m = max(m, dp[i+j+1][k+1])
if j > 1 and i+j-1 <= 30000:
m = max(m, dp[i+j-1][k-1])
dp[i][k] = gem[i] + m
print dp[d][250]
|
Python
|
[
"graphs"
] | 1,178
| 504
| 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
}
| 874
|
256409988d0132de2144e423eaa8bf34
|
Let's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.You are given a binary string s. Count the number of its awesome substrings.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
|
['math', 'strings']
|
def add(dic, k ,v):
if not k in dic:
dic[k] = v
else:
dic[k] += v
s = map(int,raw_input())
n = len(s)
psum = [0]*(1+n)
for i in range(n):
psum[i+1] = psum[i] + s[i]
K = 350
dic = [0]*((n+1)*(K+1))
ans = 0
for j in range(1,min(n+1,K+1)):
tmp = []
for i in range(n+1):
v = j*psum[i]-i+n
tmp.append(v)
dic[v] += 1
for v in tmp:
ans += dic[v]*(dic[v]-1)/2
dic[v] = 0
ans1 = ans
pos = [i for i in range(n) if s[i]]
if len(pos) == 0:
print 0
exit()
p,l1,lastp = 0,len(pos),max(pos)
for i in range(n):
cnt = 0
if i > lastp:
break
for j in range(p,l1):
v = pos[j]
if v < i :
p += 1
continue
else:
cnt += 1
if cnt > 1:
if (cnt-1)*K+i> n:
break
start = max((pos[j-1]-i+1+cnt-2)/(cnt-1)-1,K)
diff = max((v-i)/(cnt-1)-start,0)
ans += diff
start = max((lastp-i+1+cnt-1)/(cnt)-1,K)
diff = max(min((n-i)/(cnt)-start,n-lastp),0)
ans += diff
print ans
|
Python
|
[
"math",
"strings"
] | 521
| 1,340
| 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,746
|
ae10ebd2c99515472fd7ee6646af17b5
|
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.
|
['implementation', 'number theory']
|
#!/usr/bin/env python
"""(c) gorlum0 [at] gmail.com"""
import itertools as it
from sys import stdin
maxn = 10**5
def get_divisors(n, _cache = {}):
if n not in _cache:
divisors = []
for i in xrange(1, int(n**0.5) + 1):
if not n % i:
divisors.extend([i, n//i])
_cache[n] = list(set(divisors))
return _cache[n]
def solve(n, xss):
lastdiv = [0] * (maxn+1)
for i in xrange(1, n+1):
x, y = next(xss)
uncommon = 0
## print x, get_divisors(x)
for d in get_divisors(x):
if not lastdiv[d] >= i-y:
uncommon += 1
lastdiv[d] = i
yield uncommon
def main():
for line in stdin:
n = int(line)
xss = (map(int, next(stdin).split()) for _ in xrange(n))
print '\n'.join(map(str, solve(n, xss)))
if __name__ == '__main__':
main()
|
Python
|
[
"number theory"
] | 279
| 892
| 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,069
|
f4958b4833cafa46fa71357ab1ae41af
|
You are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x > 1) that n is divisible by x and x is odd).For example, if n=6, then there is x=3. If n=4, then such a number does not exist.
|
['math', 'number theory']
|
n=int(input())
for i in range (n):
t=int(input())
while t%2==0:
t/=2
if t>1:
print("YES")
else:
print("NO")
|
Python
|
[
"math",
"number theory"
] | 302
| 155
| 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
}
| 335
|
146c856f8de005fe280e87f67833c063
|
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.
|
['hashing', 'string suffix structures', 'data structures', 'binary search', 'strings']
|
from collections import defaultdict
from math import ceil,floor
import sys
memory = set()
mod = 1000000000000000003
p = 3
def hash_(s):
pp = p
result = 0
for ch in s:
result += pp*(ord(ch)-ord('a')-1)
pp = (pp*p)%mod;
result %= mod
return result % mod;
def find(q):
hash_0 = hash_(q)
k = len(q)
pw = p
ext = 0
for j in range(len(q)):
for ch in 'abc':
if ch != q[j]:
if ((hash_0 % mod + ((ord(ch)-ord(q[j]))*pw)% mod ) % mod) in memory:
sys.stdout.write('YES\n')
ext = 1
break
if ext:
break
pw = (p * pw) % mod;
if not ext:
sys.stdout.write('NO\n')
def main():
n,m = [int(i) for i in input().split()]
for i in range(n):
memory.add(hash_(sys.stdin.readline().strip()))
for i in range(m):
find(sys.stdin.readline().strip())
if __name__ == "__main__":
##sys.stdin = open("in.txt",'r')
##sys.stdout = open("out.txt",'w')
main()
##sys.stdin.close()
##sys.stdout.close()
|
Python
|
[
"strings"
] | 635
| 1,129
| 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,549
|
19cc504c81bd4f224ecb17f03cfb9bd7
|
Let's define the cost of a string s as the number of index pairs i and j (1 \le i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.
|
['brute force', 'constructive algorithms', 'graphs', 'greedy', 'strings']
|
import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
n, m = map(int, _input().split())
if m > 1:
s = ['a', 'a']
for i in range(1, m):
x = LO[i]
for j in range(i):
y = LO[j]
u = s.index(y)
s[u: u + 1] = [y, x, y]
u = s.index(x)
s.insert(u, x)
if len(s) >= n:
break
s = ''.join(s)
if n > len(s):
k = (n - len(s) + m * m - 1) // (m * m)
s += s[1:] * k
print(s[:n])
else:
print('a' * n)
|
Python
|
[
"graphs",
"strings"
] | 456
| 849
| 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,586
|
21432a74b063b008cf9f04d2804c1c3f
|
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α. Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.
|
['geometry']
|
from math import radians, cos, sin, atan2
def rotate(point, alpha):
x = point[0]
y = point[1]
return (x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha))
def crs(a, b):
return a[0] * b[1] - a[1] * b[0]
def m(end, start):
return (end[0] - start[0], end[1] - start[1])
def area(poly):
ret = 0
n = len(poly)
for i in range(n):
j = (i + 1) % n
ret += crs(poly[i], poly[j])
return abs(ret) / 2.0
def intersect(a, b, c, d):
r = crs(m(c, d), m(a, d)) * crs(m(c, d), m(b, d)) <= 0
r &= crs(m(b, a), m(c, a)) * crs(m(b, a), m(d, a)) <= 0
if not r:
return None
x1 = a[0]
y1 = a[1]
x2 = c[0]
y2 = c[1]
dx1 = b[0] - a[0]
dx2 = d[0] - c[0]
dy1 = b[1] - a[1]
dy2 = d[1] - c[1]
if dx2 * dy1 == dx1 * dy2:
return None
t = ((x1 - x2) * dy2 + (y2 - y1) * dx2) / (dx2 * dy1 - dx1 * dy2)
return (x1 + t * dx1, y1 + t * dy1)
w, h, alpha = map(int, input().split())
if alpha == 0 or alpha == 180:
print(w * h)
else:
alpha = radians(alpha)
pnt = []
pnt.append((w / 2, h / 2))
pnt.append((-w / 2, h / 2))
pnt.append((-w / 2, -h / 2))
pnt.append((w / 2, -h / 2))
pnt2 = []
for p in pnt:
pnt2.append(rotate(p, alpha))
pnt2.append(pnt2[0])
pnt.append(pnt[0])
points_total = []
for st in range(4):
for en in range(4):
t = intersect(pnt[st], pnt[st + 1], pnt2[en], pnt2[en + 1])
if t != None:
points_total.append(t)
points_total = sorted(points_total, key=lambda x: atan2(x[1], x[0]))
print(area(points_total))
|
Python
|
[
"geometry"
] | 601
| 1,662
| 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
}
| 951
|
c1f50da1fbe797e7c9b982583a3b02d5
|
You are given a string s. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.
|
['data structures', 'greedy', 'strings']
|
import sys
input = sys.stdin.readline
n = int(input())
S = input().strip()
LIST = [[] for i in range(26)]
for i in range(n):
LIST[ord(S[i])-97].append(i)
# for i in LIST:
# print(i)
LEN = n+1
BIT = [0]*(LEN+1)
# print(BIT)
def update(v, w):
while v <= LEN:
BIT[v] += w
v += (v & (-v))
def getvalue(v):
ANS = 0
while v != 0:
ANS += BIT[v]
v -= (v & (-v))
return ANS
ANS = 0
moji = [0]*26
for i in range(n-1, -1, -1):
s = ord(S[i])-97
x = LIST[s][moji[s]]
ANS += x-getvalue(x+1)
moji[s] += 1
# print(x-getvalue(x+1))
# print("*")
# print(BIT)
update(x+1, 1)
# print(moji)
# print("/")
# print(BIT)
# print("#")
print(ANS)
|
Python
|
[
"strings"
] | 520
| 739
| 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,177
|
482d128baf37eeeb28b874934aded534
|
You are given a rooted tree with n nodes, labeled from 1 to n. The tree is rooted at node 1. The parent of the i-th node is p_i. A leaf is node with no children. For a given set of leaves L, let f(L) denote the smallest connected subgraph that contains all leaves L.You would like to partition the leaves such that for any two different sets x, y of the partition, f(x) and f(y) are disjoint. Count the number of ways to partition the leaves, modulo 998244353. Two ways are different if there are two leaves such that they are in the same set in one way but in different sets in the other.
|
['dp', 'trees']
|
from sys import stdin
from itertools import repeat
def main():
n = int(stdin.readline())
p = [-1, -1] + map(int, stdin.readline().split(), repeat(10, n - 1))
ch = [[] for _ in xrange(n + 1)]
for i in xrange(2, n + 1):
ch[p[i]].append(i)
st = []
pu = st.append
po = st.pop
pu(1)
col = [None] * (n + 1)
dp = [None for _ in range(n + 1)]
mod = 998244353
while st:
x = po()
if col[x] is None:
pu(x)
col[x] = 1
for y in ch[x]:
pu(y)
else:
if ch[x]:
dp[x] = (1, 0, 0)
else:
dp[x] = (0, 0, 1)
for y in ch[x]:
dp[x] = (dp[x][0] * (dp[y][0] + dp[y][2]) % mod, (dp[x][0] * (dp[y][1] + dp[y][2]) + dp[x][1] * (dp[y][0] + dp[y][2])) % mod, ((dp[x][1] + dp[x][2]) * (dp[y][1] + dp[y][2]) + dp[x][2] * (dp[y][0] + dp[y][2])) % mod)
print (dp[1][0] + dp[1][2]) % mod
main()
|
Python
|
[
"trees"
] | 667
| 979
| 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,129
|
393ed779ea3ca8fdb63e8de1293eecd3
|
You are given an infinite periodic array a0, a1, ..., an - 1, ... with the period of length n. Formally, . A periodic subarray (l, s) (0 ≤ l < n, 1 ≤ s < n) of array a is an infinite periodic array with a period of length s that is a subsegment of array a, starting with position l.A periodic subarray (l, s) is superior, if when attaching it to the array a, starting from index l, any element of the subarray is larger than or equal to the corresponding element of array a. An example of attaching is given on the figure (top — infinite array a, bottom — its periodic subarray (l, s)): Find the number of distinct pairs (l, s), corresponding to the superior periodic arrays.
|
['number theory']
|
# -*- coding: utf-8 -*-
import fractions
from collections import defaultdict
if __name__ == '__main__':
n = int(raw_input())
a = map(int, raw_input().split())
a *= 2
inf = min(a) - 1
a[-1] = inf
result = 0
numbers_by_gcd = defaultdict(list)
for i in xrange(1, n):
numbers_by_gcd[fractions.gcd(i, n)].append(i)
for d in xrange(1, n):
if n % d != 0:
continue
m = [inf] * d
for i in xrange(n):
if a[i] > m[i % d]:
m[i % d] = a[i]
l = 0
r = 0
while l < n:
if a[r] < m[r % d]:
for i in numbers_by_gcd[d]:
if i > r - l:
break
result += min(r - i, n - 1) - l + 1
l = r + 1
r += 1
print result
|
Python
|
[
"number theory"
] | 682
| 845
| 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,079
|
973ef4e00b0489261fce852af11aa569
|
You are given an array of n integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.Both groups have to be non-empty.
|
['greedy', 'number theory', 'probabilities']
|
import sys
def gcd(l):
if len(l)==0:
return 0
if len(l)==1:
return l[0]
if len(l)==2:
if l[1]==0:
return l[0]
return gcd([l[1],l[0]%l[1]])
return gcd([gcd(l[:-1]),l[-1]])
def brute_force(l1,l2,l,sol):
if len(l)==0:
g1=gcd(l1)
g2=gcd(l2)
return g1==1 and g2==1,sol
res,s=brute_force(l1+[l[0]],l2,l[1:],sol+[1])
if res:
return True,s
return brute_force(l1,l2+[l[0]],l[1:],sol+[2])
def factor(n):
res=[]
i=2
while i*i<=n:
if n%i==0:
res.append(i)
while n%i==0:
n=int(n/i)
i+=1
if n!=1:
res.append(n)
return res
def dumpsol(sol):
for v in sol:
print(v,end=' ')
n=int(sys.stdin.readline())
l=sys.stdin.readline().strip().split(" ")[0:n]
l=[int(x) for x in l]
if n<12:
ret,sol=brute_force([],[],l,[])
if ret:
print("YES")
dumpsol(sol)
else:
print("NO")
sys.exit()
factors={}
for i in range(10):
for key in factor(l[i]):
factors[key]=0
flists={}
for f in factors:
flists[f]=[]
pos=0
found=False
for v in l:
if v%f!=0:
found=True
factors[f]+=1
flists[f].append(pos)
if (factors[f]>9):
break
pos+=1
if not found:
print("NO")
sys.exit()
oftf=[]
isoftf={}
for f in factors:
if factors[f]==0:
print("NO")
sys.exit()
if factors[f]<10:
oftf.append(f)
isoftf[f]=1
#print(oftf)
sol=[1 for i in range(len(l))]
x=l[0]
sol[0]=2
oxf=factor(x)
#print(oxf)
xf=[]
nxf=0
isxoftf={}
for f in oxf:
if f in isoftf:
nxf+=1
isxoftf[f]=1
xf.append(f)
else:
sol[flists[f][0]]=2
nonxf=[]
for f in oftf:
if not f in isxoftf:
nonxf.append(f)
masks={}
pos=0
#print(xf)
#print(nonxf)
for f in xf+nonxf:
for v in flists[f]:
if not v in masks:
masks[v]=0
masks[v]|=1<<pos
pos+=1
vals=[{} for i in range(len(masks)+1)]
vals[0][0]=0
pos=0
mlist=[]
for mask in masks:
mlist.append(mask)
cmask=masks[mask]
cmask1=cmask<<10
#print(vals)
for v in vals[pos]:
vals[pos+1][v|cmask]=v
# first number is always in group2
if (mask!=0):
vals[pos+1][v|cmask1]=v
pos+=1
#print(vals)
#print(masks)
#print(sol)
test_val=((1<<len(xf))-1)|(((1<<len(oftf))-1)<<10)
#print(test_val)
for v in vals[pos]:
if (v&test_val)==test_val:
print("YES")
#print(pos)
while (pos!=0):
#print(v)
#print(vals[pos])
nv=vals[pos][v]
#print(nv)
if (nv^v<1024 and nv^v!=0):
sol[mlist[pos-1]]=2
v=nv
pos-=1
dumpsol(sol)
sys.exit()
print("NO")
#print(oftf)
#print(masks)
|
Python
|
[
"number theory",
"probabilities"
] | 365
| 2,451
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 1,
"strings": 0,
"trees": 0
}
| 2,879
|
9eccd64bb49b74ed0eed3dbf6636f07d
|
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, \ldots, p_k (k \geq 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1).For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.Your task is to compute f(3), f(4), \ldots, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
|
['dp', 'geometry']
|
n = int(raw_input())
X = []
Y = []
for _ in range(n):
x,y = map(int,raw_input().strip(' ').strip('\n').split(' '))
X.append(x)
Y.append(y)
maxx,minx = max(X),min(X)
maxy,miny = max(Y),min(Y)
ans = -10e18
for i in range(n):
dx = max(maxx-X[i],X[i]-minx)
dy = max(maxy-Y[i],Y[i]-miny)
ans = max(ans,dx+dy)
ans = str(2*ans)+' '
rec = 2*(maxx+maxy-minx-miny)
for i in range(3,n):
ans += str(rec)+' '
ans = ans.strip('')
print ans
|
Python
|
[
"geometry"
] | 1,802
| 454
| 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
}
| 2,939
|
7ebf821d51383f1633947a3b455190f6
|
There are n cities in Berland, each of them has a unique id — an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads — there are no roads.That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cities.In the construction plan t integers a1, a2, ..., at were stated, where t equals to the distance from the capital to the most distant city, concerning new roads. ai equals the number of cities which should be at the distance i from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another. Also, it was decided that among all the cities except the capital there should be exactly k cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it. Your task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.
|
['constructive algorithms', 'trees', 'graphs']
|
n, t, k = map(int, input().split())
a = list(map(int, input().split()))
p = {}
cnt = 0
cur = 1
floor = [[1]]
for ak in a:
arr = [cur+i for i in range(1, ak+1)]
floor.append(arr)
cur += ak
for i in range(1, t+1):
cnt += len(floor[i]) - 1
if i == t:
cnt += 1
for u in floor[i]:
p[u] = floor[i-1][0]
for i in range(2, t+1):
if cnt <= k :
break
j = 1
min_ = min(len(floor[i]), len(floor[i-1]))
while j < min_ and cnt > k:
p[floor[i][j]] = floor[i-1][j]
cnt-=1
j+=1
if cnt == k:
print(n)
print('\n'.join([str(u) + ' ' + str(v) for u, v in p.items()]))
else:
print(-1)
# 7 3 3
# 2 3 1
#14 5 6
#4 4 2 2 1
# 10 3 9
# 3 3 3
|
Python
|
[
"graphs",
"trees"
] | 1,134
| 788
| 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
}
| 648
|
61ba68bdc7a1e3c60135cbae30d9e088
|
You are given n integers a_1, a_2, \dots, a_n, such that for each 1\le i \le n holds i-n\le a_i\le i-1.Find some nonempty subset of these integers, whose sum is equal to 0. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them.
|
['constructive algorithms', 'graphs', 'dfs and similar', 'math']
|
from sys import stdin, stdout
t = input()
inp = stdin.readlines()
out = []
for itr in xrange(t):
n = int(inp[itr << 1].strip())
a = map(int, inp[itr << 1 | 1].strip().split())
found = -1
for i in xrange(n):
if a[i] == 0:
found = i
break
else:
a[i] = i + 1 - a[i]
if found != -1:
out.append("1")
out.append(str(found + 1))
continue
vis = [0] * n
i = 0
idxlist = []
start = 0
while vis[i] == 0:
vis[i] = 1
i = a[i] - 1
if vis[i] == 1: start = i
idxlist.append(str(start + 1))
i = a[start] - 1
while i != start:
idxlist.append(str(i + 1))
i = a[i] - 1
out.append(str(len(idxlist)))
out.append(" ".join(idxlist))
stdout.write("\n".join(out))
|
Python
|
[
"graphs",
"math"
] | 348
| 853
| 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,243
|
f5de1e9b059bddf8f8dd46c18ce12683
|
William has array of n numbers a_1, a_2, \dots, a_n. He can perform the following sequence of operations any number of times: Pick any two items from array a_i and a_j, where a_i must be a multiple of 2 a_i = \frac{a_i}{2} a_j = a_j \cdot 2 Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.
|
['greedy', 'implementation', 'math', 'number theory']
|
# import math
# for i in range(int(input())):
# n = int(input())
# if n % 2 == 0 and math.sqrt(n//2) == int(math.sqrt(n//2)):
# print("YES")
# elif n % 4 == 0 and math.sqrt(n//4) == int(math.sqrt(n//4)):
# print("YES")
# else:
# print('NO')
##for i in range(int(input())):
## t = int(input())
## x = t // 6
## y = t // 4
## if t >= 4 and t % 2 ==0:
## if t % 6 == 2 or t % 6 == 4:
## x += 1
## print(int(x), int(y))
## else:
## print(-1)
import math
for i in range(int(input())):
n = int(input())
a = [int(t) for t in input().split()]
m = 0
n2 = 0
for n in range(len(a)):
n2 = a[n]
while n2 % 2 == 0 and n2 > 0:
m += 1
n2 //= 2
a[n] = n2
print(max(a)*2**m+(sum(a)-max(a)))
|
Python
|
[
"math",
"number theory"
] | 422
| 856
| 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,845
|
0090979443c294ef6aed7cd09201c9ef
|
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.Let's call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, "abaaba" has degree equals to 3.You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
|
['hashing', 'strings']
|
T = raw_input()
P = T + '#' + T[::-1]
def compute_prefix_func(P):
m = len(P)
pi = [0] * m
for q in range(1, m):
k = pi[q-1]
while k > 0 and P[k] != P[q]:
k = pi[k-1]
if P[k] == P[q]:
k += 1
pi[q] = k
return pi
pi = compute_prefix_func(P)
pos = []
l = pi[-1]
while l > 0:
pos.append(l)
l = pi[l-1]
K = 0
dp = [0] * (pi[-1] + 1)
dp[0] = 0
for i in pos[::-1]:
dp[i] = dp[i/2] + 1
K += dp[i]
# print i, dp[i]
print K
|
Python
|
[
"strings"
] | 435
| 513
| 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
}
| 522
|
f2142bc2f44e5d8b77f8561c29038a73
|
Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.
|
['greedy', 'games']
|
s, a = list(map(int, input().rstrip().split()))
mat = []
l = []
for i in range(s):
b = list(map(int, input().rstrip().split()))
l += [min(b)]
print(max(l))
|
Python
|
[
"games"
] | 904
| 163
| 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,308
|
b5d0870ee99e06e8b99c74aeb8e81e01
|
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
|
['greedy', 'strings']
|
import sys
n, k = map(int, input().split())
line = list(input())
for i in range(n):
if ord('z') - ord(line[i]) >= ord(line[i]) - ord('a'):
s = ord('z') - ord(line[i])
if s >= k:
line[i] = chr(ord(line[i])+k)
print(''.join(line))
sys.exit()
else:
line[i] = 'z'
k -= s
else:
s = ord(line[i]) - ord('a')
if s >= k:
line[i] = chr(ord(line[i])-k)
print(''.join(line))
sys.exit()
else:
line[i] = 'a'
k -= s
print(-1)
|
Python
|
[
"strings"
] | 805
| 587
| 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,361
|
2b757fa66ce89046fe18cdfdeafa6660
|
You have two positive integers a and b.You can perform two kinds of operations: a = \lfloor \frac{a}{b} \rfloor (replace a with the integer part of the division between a and b) b=b+1 (increase b by 1) Find the minimum number of operations required to make a=0.
|
['brute force', 'greedy', 'math', 'number theory']
|
def count_divs(a, b):
count = 0
while a > 0:
a = a // b
count += 1
return count
t = int(input())
for _ in range(t):
a, b = map(int, input().split())
b_additions = 0
if b == 1:
b = 2
b_additions += 1
prev_res = count_divs(a, b) + b_additions
while True:
b_additions += 1
b += 1
curr_res = count_divs(a, b) + b_additions
if curr_res > prev_res:
break
prev_res = curr_res
print(prev_res)
|
Python
|
[
"math",
"number theory"
] | 323
| 533
| 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
}
| 788
|
14da0cdf2939c796704ec548f49efb87
|
There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7).
|
['combinatorics', 'number theory']
|
import math
def solve( n, list1):
list1.sort()
inf = int(1e9 + 7)
t1 = [list1[0] - 1, n - list1[-1]]
t2 = []
for i in range(1, len(list1)):
t2.append((list1[i] - list1[i - 1] - 1))
num1 = 1
for i in range(n - len(list1)):
num1 = num1 * (i + 1)
num1 = num1 % inf
num2 = 1
num2 = math.factorial(t1[0]) % inf
num2 = num2 % inf
num2 = num2 * math.factorial(t1[1]) % inf
num2 = num2 % inf
for i in range(len(t2)):
num2 = num2 * math.factorial(t2[i])
num2 = num2 % inf
num2 = pow(num2, inf - 2, inf)
num3 = 1
for i in range(len(t2)):
if t2[i] - 1 < 0:
continue
num3 = (num3 * pow(2, t2[i] - 1, inf)) % inf
num1 = num1 * num2
num1 = num1 % inf
num1 = num1 * num3
num1 = num1 % inf
return int(num1)
n,m = map(int,input().split())
list1 = list(map(int,input().split()))
print(solve(n,list1))
|
Python
|
[
"math",
"number theory"
] | 525
| 939
| 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,530
|
adbfdb0d2fd9e4eb48a27d43f401f0e0
|
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change.For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name.
|
['*special', 'data structures', 'binary search', 'brute force', 'strings']
|
#copied... idea
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
gets = lambda :[str(x) for x in (f.readline() if mode=="file" else input()).split()]
[k]=get()
[g]=gets()
h = g*k
h = list(h)
p = []
for i in range(128):
p.append([0])
for i in range(len(h)):
p[ord(h[i])].append(i)
[n]=get()
for i in range(n):
[x,y]=gets()
x = int(x)
h[p[ord(y)][x]]=''
p[ord(y)].pop(x)
print("".join(h))
if mode=="file":f.close()
if __name__=="__main__":
main()
|
Python
|
[
"strings"
] | 673
| 662
| 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,452
|
2fc19c3c9604e746a17a63758060c5d7
|
A tree is a connected graph that doesn't contain any cycles.The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
|
['dp', 'dfs and similar', 'trees']
|
n, k = map(int, input().split())
t, q = [[] for i in range(n + 1)], [1]
for j in range(n - 1):
a, b = map(int, input().split())
t[a].append(b)
t[b].append(a)
for x in q:
for y in t[x]: t[y].remove(x)
q.extend(t[x])
q.reverse()
a, s = {}, 0
for x in q:
a[x] = [1]
u = len(a[x])
for y in t[x]:
v = len(a[y])
for d in range(max(0, k - u), v): s += a[y][d] * a[x][k - d - 1]
if v >= u:
for d in range(u - 1): a[x][d + 1] += a[y][d]
a[x] += a[y][u - 1: ]
u = v + 1
else:
for d in range(0, v): a[x][d + 1] += a[y][d]
if u > k: a[x].pop()
print(s)
|
Python
|
[
"graphs",
"trees"
] | 403
| 660
| 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,169
|
e83a8bfabd7ea096fae66dcc8c243be7
|
The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.
|
['dfs and similar', 'graphs']
|
houses, pipes = [int(x) for x in input().strip().split()]
houseToHouseDict = {}
pipeDict = {}
outgoingList = []
incomingList = []
maxFlow = 0
def DFSmaxPipe(origin):
end = []
lowestDiam = maxFlow
while (origin in houseToHouseDict):
diam = pipeDict[origin]
if diam < lowestDiam:
lowestDiam = diam
origin = houseToHouseDict[origin]
end.append(origin)
end.append(lowestDiam)
return end
for x in range(pipes):
ahouse, bhouse, diameter = [int(x) for x in input().strip().split()]
pipeDict[ahouse] = diameter
houseToHouseDict[ahouse] = bhouse
outgoingList.append(ahouse)
incomingList.append(bhouse)
if diameter > maxFlow:
maxFlow = diameter
for pipe in incomingList:
try:
outgoingList.remove(pipe)
except ValueError:
pass
outgoingList.sort()
print(len(outgoingList))
for origin in outgoingList:
outString = str(origin)
endPipe = DFSmaxPipe(origin)
outString += " " + str(endPipe[0]) + " " + str(endPipe[1])
print(outString)
|
Python
|
[
"graphs"
] | 1,325
| 970
| 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
}
| 4,910
|
0054f9e2549900487d78fae9aa4c2d65
|
Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition — determine the number of dangerous turns on the track.
|
['implementation', 'geometry', 'math']
|
print ((int(input()) - 4)//2)
|
Python
|
[
"math",
"geometry"
] | 1,272
| 29
| 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,260
|
d01f153d0049c22a21e321d5c4fbece9
|
There is a forest that we model as a plane and live n rare animals. Animal number i has its lair in the point (x_{i}, y_{i}). In order to protect them, a decision to build a nature reserve has been made.The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.For convenience, scientists have made a transformation of coordinates so that the river is defined by y = 0. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.
|
['binary search', 'geometry', 'ternary search']
|
l , r =-100000000, 1000000000
def check(mid):
mx = 0
for i in range(n):
x,y = x1[i],y1[i]
mx = max (mx ,(x1[i] - mid) ** 2 / (2 * y1[i]) + (y1[i] / 2))
return mx
n = int(input())
count1 = 0
count2 = 0
x1 = []
y1 = []
for i in range(n):
a,b = map(int,input().split())
if b>=0:
count1+=1
else:
count2+=1
x1.append(a)
y1.append(abs(b))
if count1 and count2:
print(-1)
exit()
for i in range(100):
mid1 = l+(r-l)/3
mid2 = r-(r-l)/3
if check(mid1)>check(mid2):
l = mid1
else:
r = mid2
# print(l,r)
print(check(l))
|
Python
|
[
"geometry"
] | 806
| 627
| 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
}
| 2,424
|
fc75935b149cf9f4f2ddb9e2ac01d1c2
|
There are n logs, the i-th log has a length of a_i meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.errorgorn and maomao90 will take turns chopping the logs with errorgorn chopping first. On his turn, the player will pick a log and chop it into 2 pieces. If the length of the chosen log is x, and the lengths of the resulting pieces are y and z, then y and z have to be positive integers, and x=y+z must hold. For example, you can chop a log of length 3 into logs of lengths 2 and 1, but not into logs of lengths 3 and 0, 2 and 2, or 1.5 and 1.5.The player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?
|
['games', 'implementation', 'math']
|
num_cases = int(input())
for i in range(num_cases):
count = 0
num_logs = int(input())
logs = [int(log) for log in input().split(' ')]
for log in logs:
count += log - 1
if count % 2 == 0:
print('maomao90')
else:
print('errorgorn')
|
Python
|
[
"math",
"games"
] | 846
| 279
| 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
}
| 1,765
|
8705adec1bea1f898db1ca533e15d5c3
|
Polycarp has a string s. Polycarp performs the following actions until the string s is empty (t is initially an empty string): he adds to the right to the string t the string s, i.e. he does t = t + s, where t + s is a concatenation of the strings t and s; he selects an arbitrary letter of s and removes from s all its occurrences (the selected letter must occur in the string s at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string s will be empty and the string t will be equal to some value (that is undefined and depends on the order of removing).E.g. consider s="abacaba" so the actions may be performed as follows: t="abacaba", the letter 'b' is selected, then s="aacaa"; t="abacabaaacaa", the letter 'a' is selected, then s="c"; t="abacabaaacaac", the letter 'c' is selected, then s="" (the empty string). You need to restore the initial value of the string s using only the final value of t and find the order of removing letters from s.
|
['binary search', 'implementation', 'sortings', 'strings']
|
T = int(input())
for t in range(T):
t = input()
n = len(t)
# find first character with no occurences to the right
s = set()
r = []
for i in t[::-1]:
if i not in s:
r.append(i)
s.add(i)
done = r[::-1]
#print(done)
v = 0
for i in range(n):
v += done.index(t[i]) + 1
if v == n:
r = ""
tt = t[:i+1]
for c in done:
r += tt
tt=tt.replace(c,"")
#print(r)
if r != t:
print(-1)
else:
print(t[:i+1],"".join(done))
break
elif v > n:
print(-1)
break
|
Python
|
[
"strings"
] | 1,207
| 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
}
| 3,182
|
f1b4048e5cd2aa0a533af9d08f7d58ba
|
This is an interactive problem.There exists a matrix a of size n \times m (n rows and m columns), you know only numbers n and m. The rows of the matrix are numbered from 1 to n from top to bottom, and columns of the matrix are numbered from 1 to m from left to right. The cell on the intersection of the x-th row and the y-th column is denoted as (x, y).You are asked to find the number of pairs (r, c) (1 \le r \le n, 1 \le c \le m, r is a divisor of n, c is a divisor of m) such that if we split the matrix into rectangles of size r \times c (of height r rows and of width c columns, each cell belongs to exactly one rectangle), all those rectangles are pairwise equal.You can use queries of the following type: ? h w i_1 j_1 i_2 j_2 (1 \le h \le n, 1 \le w \le m, 1 \le i_1, i_2 \le n, 1 \le j_1, j_2 \le m) — to check if non-overlapping subrectangles of height h rows and of width w columns of matrix a are equal or not. The upper left corner of the first rectangle is (i_1, j_1). The upper left corner of the second rectangle is (i_2, j_2). Subrectangles overlap, if they have at least one mutual cell. If the subrectangles in your query have incorrect coordinates (for example, they go beyond the boundaries of the matrix) or overlap, your solution will be considered incorrect. You can use at most 3 \cdot \left \lfloor{ \log_2{(n+m)} } \right \rfloor queries. All elements of the matrix a are fixed before the start of your program and do not depend on your queries.
|
['bitmasks', 'interactive', 'number theory']
|
import sys
input = sys.stdin.readline
def solve():
r, c = map(int, input().split())
r1 = r
r2 = r
i = 2
while True:
if r2 % i == 0:
while r2 % i == 0:
r2 //= i
while r1 % i == 0:
#print('r',i)
if i == 2:
print('?',r1//i,c,1,1,r1//i+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
r1 //= 2
else:
z = i//2
h1 = r1//i
h = h1*z
print('?',h,c,1,1,h+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
print('?',h,c,1+h1,1,h+h1+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
if z != 1:
print('?',h1,c,1,1,h1+1,1)
sys.stdout.flush()
if int(input()) == 0:
break
r1 //= i
if i * i <= r2:
i += 1
elif r2 == 1:
break
elif i >= r2:
break
else:
i = r2
i = 2
c1 = c
c2 = c
while True:
if c2 % i == 0:
while c2 % i == 0:
c2 //= i
while c1 % i == 0:
#print('c',i)
if i == 2:
print('?',r,c1//i,1,1,1,1+c1//i)
sys.stdout.flush()
if int(input()) == 0:
break
c1 //= 2
else:
z = i//2
w1 = c1//i
w = w1*z
print('?',r,w,1,1,1,1+w)
sys.stdout.flush()
if int(input()) == 0:
break
print('?',r,w,1,1+w1,1,1+w+w1)
sys.stdout.flush()
if int(input()) == 0:
break
if z != 1:
print('?',r,w1,1,1,1,1+w1)
sys.stdout.flush()
if int(input()) == 0:
break
c1 //= i
if i * i <= c2:
i += 1
elif c2 == 1:
break
elif i >= c2:
break
else:
i = c2
r //= r1
c //= c1
d1 = 0
for i in range(1,r+1):
if r % i == 0:
d1 += 1
d2 = 0
for i in range(1,c+1):
if c % i == 0:
d2 += 1
print('!', d1*d2)
solve()
|
Python
|
[
"number theory"
] | 1,717
| 1,816
| 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,030
|
1277cf54097813377bf37be445c06e7e
|
You are given an undirected graph consisting of n vertices and n edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least 1 in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths [1, 2, 3] and [3, 2, 1] are considered the same.You have to answer t independent test cases.Recall that a path in the graph is a sequence of vertices v_1, v_2, \ldots, v_k such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.
|
['combinatorics', 'dfs and similar', 'trees', 'graphs']
|
from collections import deque
from sys import stdin, gettrace
if gettrace():
inputi = input
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def readGraph(n, m):
adj = [[] for _ in range(n)]
for _ in range(m):
u,v = map(int, inputi().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
return adj
def solve():
n = int(inputi())
adj = readGraph(n, n)
parent = [None] * n
depth = [0]*n
q = deque()
q.append(0)
loop = deque()
while not loop:
c = q.popleft()
for a in adj[c]:
if a != parent[c]:
if parent[a] != None:
loop.append(a)
loop.append(c)
break
else:
parent[a] = c
depth[a] = depth[c]+1
q.append(a)
while loop[0] != loop[-1]:
if depth[loop[0]] > depth[loop[-1]]:
loop.appendleft(parent[loop[0]])
else:
loop.append(parent[loop[-1]])
loop = list(loop)[:-1]
ls = len(loop)
lc = []
for i in range(ls):
l = loop[i]
q = deque()
q.append(l)
count = 0
visited = {loop[(i-1)%ls], l, loop[(i+1)%ls]}
while q:
for a in adj[q.popleft()]:
if a not in visited:
count += 1
visited.add(a)
q.append(a)
lc.append(count)
treecount = (n*(n-1))//2
loopcount = (ls*(ls-1))//2
lt = (ls-1)*(n - ls)
tt = sum(c * (n - c - ls) for c in lc)//2
res = treecount+loopcount+lt+tt
print(res)
def main():
t = int(inputi())
for _ in range(t):
solve()
if __name__ == "__main__":
main()
|
Python
|
[
"math",
"graphs",
"trees"
] | 929
| 1,830
| 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
}
| 1,550
|
677972c7d86ce9fd0808105331f77fe0
|
A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of n (n \ge 3) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer x is called composite if there exists a positive integer y such that 1 < y < x and x is divisible by y.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.
|
['math', 'number theory']
|
tt = int(input())
fa = []
n = 500000
for i in range(n + 1):
fa.append(i)
fa[1] = 0
i = 2
while i <= n:
if fa[i] != 0:
j = i + i
while j <= n:
fa[j] = 0
j = j + i
i += 1
fa = set(fa)
fa.remove(0)
for i in range(tt):
ar = []
f = int(input())
y = input()
ar = y.split()
ar = list(map(int, ar))
a = sum(ar)
k = 0
if (a not in fa):
print(len(ar))
for x in range(1, len(ar) + 1):
print(x, end=' ')
print('')
else:
for j in range(len(ar)):
b = a - ar[j]
if b not in fa:
print(len(ar) - 1)
for y in range(j):
print(y + 1, end=' ')
for y in range(j + 1, len(ar)):
print(y + 1, end=' ')
print('')
break
else:
for j in range(len(ar)):
ty = False
for p in range(j, len(ar)):
b = a - ar[j] - ar[p]
if b not in fa and b > 0:
print(len(ar) - 1)
for y in range(j):
print(y + 1, end=' ')
for y in range(j + 1, len(ar)):
print(y + 1, end=' ')
print('')
ty = True
break
if ty:
ty = False
break
|
Python
|
[
"math",
"number theory"
] | 775
| 1,556
| 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,917
|
a37a92db3626b46c7af79e3eb991983a
|
For a vector \vec{v} = (x, y), define |v| = \sqrt{x^2 + y^2}.Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_i} or -\vec{v_i}. In other words, if his position is currently p = (x, y), he will either move to p + \vec{v_i} or p - \vec{v_i}.Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position p satisfies |p| \le 1.5 \cdot 10^6 so that he can stay safe.
|
['geometry', 'greedy', 'math', 'sortings', 'data structures', 'brute force']
|
n=input()
x=0
y=0
def dis(x,y,a,b):
return (x-a)**2+(y-b)**2
lst=[]
ans=[0]*n
lst2=[]
lst4=[]
ans2=[0]*n
for i in range(0,n):
a,b=map(int,raw_input().split())
lst4.append((a,b))
lst.append((a*a,a,b,i))
lst2.append((b*b,a,b,i))
lst.sort(reverse=True)
lst2.sort(reverse=True)
for i in range(0,n):
a=lst[i][1]
b=lst[i][2]
val=lst[i][3]
if dis(a,b,x,y)<dis(a,b,-x,-y):
ans[val]=str(-1)
x=x-a
y=y-b
else:
ans[val]=str(1)
x=x+a
y=y+b
if n<1000:
for i in range(0,n):
a=lst2[i][1]
b=lst2[i][2]
val=lst2[i][3]
if dis(a,b,x,y)<dis(a,b,-x,-y):
ans2[val]=str(-1)
x=x-a
y=y-b
else:
ans2[val]=str(1)
x=x+a
y=y+b
s1=0
s2=0
s3=0
s4=0
for i in range(0,n):
s1+=int(ans[i])*lst4[i][0]
s2+=int(ans[i])*lst4[i][1]
s3+=int(ans2[i])*lst4[i][0]
s4+=int(ans2[i])*lst4[i][1]
if s1**2+s2**2<s3**2+s4**2:
print " ".join(ans)
else:
print " ".join(ans2)
else:
print " ".join(ans)
|
Python
|
[
"math",
"geometry"
] | 794
| 1,008
| 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
}
| 1,950
|
6da720d47a627df3afb876253b1cbe58
|
"Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills.And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.The prototype is ready, you now need to urgently carry out its experiments in practice. You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of n vertices, the i-th vertex contains ki beavers. "Beavermuncher-0xFF" works by the following principle: being at some vertex u, it can go to the vertex v, if they are connected by an edge, and eat exactly one beaver located at the vertex v. It is impossible to move to the vertex v if there are no beavers left in v. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops.Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled.The root of the tree is located at the vertex s. This means that the "Beavermuncher-0xFF" begins its mission at the vertex s and it must return there at the end of experiment, because no one is going to take it down from a high place. Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex.
|
['dp', 'greedy', 'dsu', 'dfs and similar', 'trees']
|
n = input()+1
k = [0]+map(int,raw_input().split())
d = [[] for _ in xrange(n)]
for _ in xrange(n-2):
a,b = [int(x) for x in raw_input().split()]
d[a].append(b)
d[b].append(a)
s = input()
q = [0]
d[0] = [s]
v = [True]+[False]*n
for x in q:
for u in d[x]:
if not v[u]:
v[u]=True
q.append(u)
r = [[] for _ in xrange(n)]
v = [True]*n
f = [0]*n
for i in xrange(n):
if i!=s: k[i]-=1
for x in reversed(q):
v[x]=False
for u in d[x]:
if v[u]: continue
rx = sorted(r[u],reverse=True)[:k[u]]
res = sum(rx)+2*len(rx)
k[u]-=len(rx)
b = min(k[u],f[u])
k[u]-=b
res+=b*2
f[x]+=k[u]
r[x].append(res)
print r[0][0]
|
Python
|
[
"graphs",
"trees"
] | 2,332
| 730
| 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,743
|
0afd29ef1b720d2baad2f1c91a583933
|
You are given a positive integer D. Let's build the following graph from it: each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because \frac{12}{3}=4 is not a prime.Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.So the shortest path between two vertices v and u is the path that has the minimal possible length.Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.You are given q queries of the following form: v u — calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353.
|
['greedy', 'graphs', 'combinatorics', 'number theory', 'math']
|
import sys, __pypy__
range = xrange
input = raw_input
MOD = 998244353
mulmod = __pypy__.intop.int_mulmod
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
D = inp[ii]; ii += 1
q = inp[ii]; ii += 1
U = inp[ii + 0: ii + 2 * q: 2]
V = inp[ii + 1: ii + 2 * q: 2]
Pdiv = []
if D & 1 == 0:
Pdiv.append(2)
while D & 1 == 0:
D >>= 1
i = 3
while i * i <= D:
if D % i == 0:
while D % i == 0:
D //= i
Pdiv.append(i)
i += 2
if D > 1:
Pdiv.append(D)
fac = [1]
for i in range(1,200):
fac.append(mulmod(fac[-1], i, MOD))
ifac = [pow(f, MOD-2, MOD) for f in fac]
def multi(A):
prod = fac[sum(A)]
for a in A:
prod = mulmod(prod, ifac[a], MOD)
return prod
out = []
for _ in range(q):
u = U[_]
v = V[_]
if u > v:
v,u = u,v
add = []
rem = []
for p in Pdiv:
cu = 0
while u % p == 0:
u //= p
cu += 1
cv = 0
while v % p == 0:
v //= p
cv += 1
if cu > cv:
rem.append(cu - cv)
elif cu < cv:
add.append(cv - cu)
out.append(mulmod(multi(add), multi(rem), MOD))
print '\n'.join(str(x) for x in out)
|
Python
|
[
"graphs",
"number theory",
"math"
] | 1,678
| 1,228
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 3,424
|
29d4ca13888c0e172dde315b66380fe5
|
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.
|
['geometry']
|
R,x1,y1,x2,y2=map(int,input().split())
s=((x1-x2)**2+(y1-y2)**2)**(0.5)
sin=0
cos=1
def dist(x1,x2,y1,y2):
return ((x1-x2)**2+(y1-y2)**2)**(0.5)
if (s>R):
print(x1,y1,R)
else:
r=(s+R)/2
if s!=0:
sin=((y2-y1)/s)
cos=((x2-x1)/s)
xpos,ypos=x2+r*cos,y2+r*sin
xneg,yneg=x2-r*cos,y2-r*sin
dis1=dist(xpos,x1,ypos,y1)
dis2=dist(xneg,x1,yneg,y1)
if dis1<dis2:
print(xpos,ypos,r)
else:
print(xneg,yneg,r)
|
Python
|
[
"geometry"
] | 878
| 468
| 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,113
|
d62d0a9d827444a671029407f6a4ad39
|
You are given a string, consisting of lowercase Latin letters.A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) — "ab" and (2, 3) — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.If there are multiple answers, print any of them.You also have to answer T separate queries.
|
['greedy', 'implementation', 'sortings', 'dfs and similar', 'strings']
|
import collections
def add1(c):
return chr(ord(c)+1)
def sv():
m = collections.defaultdict(int)
for c in input():
m[c] += 1
m = list(m.items())
m.sort()
if len(m) == 2 and add1(m[0][0]) == m[1][0]: return False
if len(m) == 3:
if add1(m[0][0]) != m[1][0]:
pass
elif add1(m[1][0]) != m[2][0]:
m[0], m[2] = m[2], m[0]
else:
return False
for i in range(1,len(m),2):
print(m[i][0]*m[i][1], end='')
for i in range(0,len(m),2):
print(m[i][0]*m[i][1], end='')
print()
return True
TC = int(input())
for tc in range(TC):
if not sv(): print('No answer')
|
Python
|
[
"graphs",
"strings"
] | 689
| 676
| 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
}
| 581
|
bd61ae3c19274f47b981b8bd5e786375
|
Alina has discovered a weird language, which contains only 4 words: \texttt{A}, \texttt{B}, \texttt{AB}, \texttt{BA}. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence s and she is curious: is it possible that it consists of precisely a words \texttt{A}, b words \texttt{B}, c words \texttt{AB}, and d words \texttt{BA}?In other words, determine, if it's possible to concatenate these a+b+c+d words in some order so that the resulting string is s. Each of the a+b+c+d words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.
|
['constructive algorithms', 'greedy', 'sortings', 'strings', 'two pointers']
|
# test.py
# main.py
# .---.---.---.---.---.---.---.---.---.---.---.---.---.-------.
# |1/2| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | + | ' | <- |
# |---'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-----|
# | ->| | Q | W | E | R | T | Y | U | I | O | P | ] | ^ | |
# |-----'.--'.--'.--'.--'.--'.--'.--'.--'.--'.--'.--'.--'| |
# | Caps | A | S | D | F | G | H | J | K | L | \ | [ | * | |
# |----.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'-.-'---'----|
# | | < | Z | X | C | V | B | N | M | , | . | - | |
# |----'-.-'.--'--.'---'---'---'---'---'---'--.'---'.--.------|
# | ctrl | | alt | | alt | | ctrl |
# '------' '-----'---------------------------'-----' '------'
MOD_PRIME = 10**9 + 7
def inp(to: type = str):
return to(input())
def inp_arr(to: type = str):
return list(
map(to, inp().split()))
def print_gc(t, res):
print(f"Case #{t}: {res}")
def fs(*args):
return frozenset(args)
def solve(t):
crr = inp_arr(int)
s = inp(str)
arr, brr = [], [0]*4
i = 0
while i < len(s):
if i == len(s) - 1:
arr.append(s[i])
if s[i] == "A":
brr[0] += 1
else:
brr[1] += 1
i += 1
else:
if s[i:i+2] == "AA":
arr.append("A")
brr[0] += 1
i += 1
elif s[i:i+2] == "BB":
arr.append("B")
brr[1] += 1
i += 1
elif s[i:i+2] == "AB":
arr.append("AB")
brr[2] += 1
i += 2
elif s[i:i+2] == "BA":
arr.append("BA")
brr[3] += 1
i += 2
if brr[2] < crr[2] and brr[3] < crr[3]:
res = "NO"
else:
res = "YES"
if brr[2] > crr[2] and brr[3] < crr[3]:
i = 0
while i+1 < len(arr) and brr[2] > crr[2] and brr[3] < crr[3]:
if arr[i] == "AB" and arr[i+1] == "A":
arr[i] = "A"
arr[i+1] = "BA"
brr[2] -= 1
brr[3] += 1
j = i
while j > 0 and all([
brr[2] > crr[2],
brr[3] < crr[3],
arr[j-1] == "AB",
arr[j] == "A"
]):
arr[j-1] = "A"
arr[j] = "BA"
brr[2] -= 1
brr[3] += 1
j -= 1
elif arr[i] == "B" and arr[i+1] == "AB":
arr[i] = "BA"
arr[i+1] = "B"
brr[2] -= 1
brr[3] += 1
else:
i += 1
i = 0
err = []
while i+1 < len(arr):
if arr[i] == "AB" and arr[i+1] == "AB":
err.append([i, 2])
j = i+1
while j+1 < len(arr) and arr[j] == "AB" and arr[j+1] == "AB":
err[-1][1] += 1
j += 1
i = j
i += 1
err = sorted(err, key=lambda e: e[1], reverse=True)
for i, _ in err:
if not(brr[2] > crr[2] and brr[3] < crr[3]):
break
if arr[i] == "AB" and arr[i+1] == "AB":
arr.insert(i, "A")
for j in range(len(err)):
if i < err[j][0]:
err[j][0] += 1
arr[i+1] = "BA"
arr[i+2] = "B"
brr[0] += 1
brr[1] += 1
brr[2] -= 2
brr[3] += 1
j = i
while j >= 1 and all([
brr[2] > crr[2],
brr[3] < crr[3],
arr[j-1] == "AB",
arr[j] == "A"
]):
arr[j-1] = "A"
arr[j] = "BA"
brr[2] -= 1
brr[3] += 1
j -= 1
j = i+2
while j+1 < len(arr) and all([
brr[2] > crr[2],
brr[3] < crr[3],
arr[j] == "B",
arr[j+1] == "AB"
]):
arr[j] = "BA"
arr[j+1] = "B"
brr[2] -= 1
brr[3] += 1
j += 1
i = j-1
else:
i += 1
elif brr[3] > crr[3] and brr[2] < crr[2]:
i = 0
while i+1 < len(arr) and brr[3] > crr[3] and brr[2] < crr[2]:
if arr[i] == "BA" and arr[i+1] == "B":
arr[i] = "B"
arr[i+1] = "AB"
brr[3] -= 1
brr[2] += 1
j = i
while j >= 1 and all([
brr[3] > crr[3],
brr[2] < crr[2],
arr[j-1] == "BA",
arr[j] == "B"
]):
arr[j-1] = "B"
arr[j] = "AB"
brr[3] -= 1
brr[2] += 1
j -= 1
elif arr[i] == "A" and arr[i+1] == "BA":
arr[i] = "AB"
arr[i+1] = "A"
brr[3] -= 1
brr[2] += 1
else:
i += 1
i = 0
err = []
while i+1 < len(arr):
if arr[i] == "BA" and arr[i+1] == "BA":
err.append([i, 2])
j = i+1
while j+1 < len(arr) and arr[j] == "BA" and arr[j+1] == "BA":
err[-1][1] += 1
j += 1
i = j
i += 1
err = sorted(err, key=lambda e: e[1], reverse=True)
for i, _ in err:
if not(brr[3] > crr[3] and brr[2] < crr[2]):
break
if arr[i] == "BA" and arr[i+1] == "BA":
for j in range(len(err)):
if i < err[j][0]:
err[j][0] += 1
arr.insert(i, "B")
arr[i+1] = "AB"
arr[i+2] = "A"
brr[0] += 1
brr[1] += 1
brr[3] -= 2
brr[2] += 1
j = i
while j > 0 and all([
brr[3] > crr[3],
brr[2] < crr[2],
arr[j-1] == "BA",
arr[j] == "B"
]):
arr[j-1] = "B"
arr[j] = "AB"
brr[3] -= 1
brr[2] += 1
j -= 1
j = i+2
while j+1 < len(arr) and all([
brr[3] > crr[3],
brr[2] < crr[2],
arr[j] == "A",
arr[j+1] == "BA"
]):
arr[j] = "AB"
arr[j+1] = "A"
brr[3] -= 1
brr[2] += 1
j += 1
else:
i += 1
if brr[0] > crr[0] or brr[1] > crr[1]:
res = "NO"
elif brr[0] - crr[0] != brr[1] - crr[1]:
res = "NO"
elif brr[2] >= crr[2] and brr[3] >= crr[3]:
res = "YES"
elif all([
brr[0] == crr[0] and brr[1] == crr[1],
brr[2] != crr[2] and brr[3] != crr[3],
]):
res = "NO"
else:
res = "NO"
print(res)
"""
3
7 13 4 19
AAAAAABABABABBABABABBABABABABABBBBBBBAAABABABABABABABABABBBBBBABBA
22 13 9 21
BBABABAAABABABABABABBBABABAABABABBABAABAAABAAAAAAAAABAAAABABABABAABABABABABABABBBBBBABAAABABABB
6 8 2 39
BBBBBBABABABABABABABABABABABAABABBBABABABAAABBABABAAAAABABBABABABABABABABABABABABABABABABAABBABA
"""
def main():
T = 1
T = inp(int)
for t in range(1, T+1):
solve(t)
return
if __name__ == "__main__":
main()
|
Python
|
[
"strings"
] | 805
| 8,895
| 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,554
|
d629d09782a7af0acc359173ac4b4f0a
|
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".If the given string t matches the given string s, print "YES", otherwise print "NO".
|
['implementation', 'brute force', 'strings']
|
n,m=map(int,input().split())
s=input()
t=input()
if(m<n-1):
print('NO')
else:
if('*' in s):
i=0
f=1
while(i<n and s[i]!='*'):
if(s[i]!=t[i]):
f=0
break
else:
i=i+1
if(f==1):
i=n-1
j=m-1
while(s[i]!='*'):
if(s[i]!=t[j]):
f=0
break
else:
i=i-1
j=j-1
if(f==1):
print("YES")
else:
print("NO")
else:
print("NO")
else:
if(s==t):
print("YES")
else:
print("NO")
|
Python
|
[
"strings"
] | 950
| 734
| 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,520
|
b116ab1cae8d64608641b339b8654e21
|
There is an undirected tree of n vertices, connected by n-1 bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex a and its tail is at vertex b. The snake's body occupies all vertices on the unique simple path between a and b.The snake wants to know if it can reverse itself — that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail. Let's denote a snake position by (h,t), where h is the index of the vertex with the snake's head, t is the index of the vertex with the snake's tail. This snake can reverse itself with the movements (4,7)\to (5,1)\to (4,2)\to (1, 3)\to (7,2)\to (8,1)\to (7,4). Determine if it is possible to reverse the snake with some sequence of operations.
|
['dp', 'greedy', 'two pointers', 'dfs and similar', 'trees']
|
from sys import stdin
import itertools
input = stdin.readline
def getint(): return int(input())
def getints(): return list(map(int, input().split()))
def getint1(): return list(map(lambda x: int(x) - 1, input().split()))
def getstr(): return input()[:-1]
def solve():
n, a, b = getint1()
n += 1
adj = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = getint1()
adj[u].append(v)
adj[v].append(u)
# dfs 1
max_child = [[-1] * 3 for _ in range(n)]
stack = [(a, -1, 1)] # (node, parent)
while stack:
u, p, flag = stack.pop()
if p != -1 and len(adj[u]) < 2:
max_child[u][0] = 1
continue
if flag == 1:
stack.append((u, p, 0))
for v in adj[u]:
if v == p:
continue
stack.append((v, u, 1))
else:
for v in adj[u]:
if v == p:
continue
len_v = max_child[v][0] + 1
if len_v > max_child[u][0]:
max_child[u][2] = max_child[u][1]
max_child[u][1] = max_child[u][0]
max_child[u][0] = len_v
elif len_v > max_child[u][1]:
max_child[u][2] = max_child[u][1]
max_child[u][1] = len_v
elif len_v > max_child[u][2]:
max_child[u][2] = len_v
# end of dfs 1
# dfs 2
body = []
ret = [False] * n
max_parent = [-1] * n
stack.clear()
stack = [(a, -1, 0)] # (node, parent, max len from parent)
while stack:
u, p, mxp = stack.pop()
if mxp >= 0:
stack.append((u, p, -1))
if p != -1 and len(adj[u]) < 2:
continue
max_parent[u] = mxp + 1
chlen = [max_parent[u], -3]
for v in adj[u]:
if v == p:
continue
len_v = max_child[v][0] + 1
if len_v > chlen[0]:
chlen[1] = chlen[0]
chlen[0] = len_v
elif len_v > chlen[1]:
chlen[1] = len_v
for v in adj[u]:
if v == p:
continue
stack.append(
(v, u, chlen[int(max_child[v][0] + 1 == chlen[0])]))
else:
is_body = (u == b)
if not is_body:
for v in adj[u]:
if v != p and ret[v]:
is_body = True
break
if is_body:
body.append(u)
ret[u] = is_body
del ret
# end of dfs2
ok = False
body_len = len(body)
can_turn = [False] * n
for i in range(n):
if 3 <= sum(1 for l in max_child[i] + [max_parent[i]] if l >= body_len):
can_turn[i] = True
ok = True
if not ok:
print("NO")
return
treelen = [1] * body_len
# print(body)
for i in range(body_len):
cur = body[i]
pre = -1 if i == 0 else body[i - 1]
nxt = -1 if i + 1 == body_len else body[i + 1]
for v in adj[cur]:
if v == pre or v == nxt:
continue
treelen[i] = max(treelen[i], max_child[v][0] + 1)
if can_turn[v]:
can_turn[cur] = True
continue
# dfs 3
stack = [(v, cur)]
while stack and not can_turn[cur]:
u, p = stack.pop()
for w in adj[u]:
if w == p:
continue
if can_turn[w]:
can_turn[cur] = True
break
stack.append((w, u))
stack.clear()
# end of dfs 3
# print(i, cur, can_turn[cur])
# use two pointer to find if we can enter the turing point
# print(body_len, treelen)
l = 0
r = body_len - 1
lmax = treelen[r] - 1
rmin = body_len - treelen[l]
ok = (can_turn[body[l]] or can_turn[body[r]])
while not ok and (l < lmax or rmin < r):
if l < lmax:
l += 1
rmin = min(rmin, l + (body_len - treelen[l]))
if rmin < r:
r -= 1
lmax = max(lmax, r - (body_len - treelen[r]))
if can_turn[body[l]] or can_turn[body[r]]:
ok = True
##
print("YES" if ok else "NO")
return
# end of solve
if __name__ == "__main__":
# solve()
# for t in range(getint()):
# print('Case #', t + 1, ': ', sep='')
# solve()
for _ in range(getint()):
solve()
|
Python
|
[
"graphs",
"trees"
] | 1,275
| 4,695
| 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,099
|
994a9cb52cf0fdab72be068eab1b27ef
|
Welcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet a dollars and Ronnie has bet b dollars. But the fans seem to be disappointed. The excitement of the fans is given by gcd(a,b), where gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y. To make the race more exciting, you can perform two types of operations: Increase both a and b by 1. Decrease both a and b by 1. This operation can only be performed if both a and b are greater than 0. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that gcd(x,0)=x for any x \ge 0.
|
['greedy', 'math', 'number theory']
|
from math import gcd
tt = int(input())
for t in range(tt):
a,b = map(int, input().split())
MAX = max(a,b)
MIN = min(a,b)
if gcd(a,b) == MAX-MIN:
print(MAX-MIN,0)
elif a==b:
print(0,0)
else:
d = MAX-MIN
if d>0:
f = MAX-(MAX%d)
s = f+d
print(d,min(abs(MAX-f),abs(MAX-s)))
|
Python
|
[
"math",
"number theory"
] | 903
| 368
| 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,833
|
cf1eb164c4c970fd398ef9e98b4c07b1
|
In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
|
['implementation', 'strings']
|
n = int(raw_input().strip())
x = raw_input().split(' ')
res = len(set([''.join(sorted(set(i))) for i in x]))
print res
|
Python
|
[
"strings"
] | 629
| 118
| 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
}
| 918
|
607dd33e61f57caced7b61ca8001e871
|
You are given three strings (s1, s2, s3). For each integer l (1 ≤ l ≤ min(|s1|, |s2|, |s3|) you need to find how many triples (i1, i2, i3) exist such that three strings sk[ik... ik + l - 1] (k = 1, 2, 3) are pairwise equal. Print all found numbers modulo 1000000007 (109 + 7).See notes if you are not sure about some of the denotions used in the statement.
|
['data structures', 'dsu', 'string suffix structures', 'strings']
|
MOD = 1000000007
oo = int(2e9)
class Node:
def __init__(self, p, l = oo):
self.spos = p
self.slink = 0
self.length = l
self.next_node = [0 for _ in range(28)]
#Ukkonen
class SuffixTree:
def __init__(self, s):
self.nodes = [Node(0)]
self.s = []
self.pos = 0
self.node = 0
self.last_leaf = 0
for c in s:
self.extend(ord(c) - 97)
def get_len(self, p):
if p == 0:
return 0
return min(self.nodes[p].length, len(self.s) - self.nodes[p].spos)
def add_node(self, p, l = oo):
r = len(self.nodes)
self.nodes.append(Node(p, l))
return r
def extend(self, c):
self.pos += 1
self.s.append(c)
n = len(self.s)
last = 0
while self.pos:
while self.pos > self.nodes[self.nodes[self.node].next_node[self.s[n - self.pos]]].length:
self.node = self.nodes[self.node].next_node[self.s[n - self.pos]]
self.pos -= self.nodes[self.node].length
v = self.nodes[self.node].next_node[self.s[n - self.pos]]
t = self.s[self.nodes[v].spos + self.pos - 1]
if v == 0:
nl = self.add_node(n - self.pos)
self.nodes[self.node].next_node[self.s[n - self.pos]] = nl
self.nodes[last].slink = self.node
last = 0
elif t == c:
self.nodes[last].slink = self.node
return
else:
u = self.add_node(self.nodes[v].spos, self.pos - 1)
nl = self.add_node(n - 1)
self.nodes[u].next_node[c] = nl
self.nodes[u].next_node[t] = v
self.nodes[v].spos += self.pos - 1
self.nodes[v].length -= self.pos - 1
self.nodes[last].slink = u
self.nodes[self.node].next_node[self.s[n - self.pos]] = u
last = u
if self.node:
self.node = self.nodes[self.node].slink
else:
self.pos -= 1
self.nodes[self.last_leaf].slink = nl
self.last_leaf = nl
def dfs(u, d):
pila = [(0, u, d)]
while len(pila):
k, u, d = pila.pop()
if k == 0:
if st.nodes[u].next_node.count(0) == 28:
dl = d
for i in range(2, -1, -1):
if dl <= l[i] + 1:
suffs[u][i] += 1
break
else:
dl -= l[i] + 1
pila.append((1, u, d))
else:
pila.append((1, u, d))
for v in st.nodes[u].next_node:
if v:
pila.append((0, v, d + st.get_len(v)))
else:
if st.nodes[u].next_node.count(0) != 28:
for v in st.nodes[u].next_node:
if v:
for i in range(3):
suffs[u][i] += suffs[v][i]
nd = d - st.get_len(u) + 1
if nd <= ml:
val = 1
for i in range(3):
val *= suffs[u][i]
val %= MOD
resp[nd] += val
resp[nd] %= MOD
if d + 1 <= ml:
resp[d + 1] -= val
resp[d + 1] %= MOD
s = []
l = []
for _ in range(3):
r = raw_input()
s.append(r)
l.append(len(r))
s.append('{')
s[-1] = '|'
s = ''.join(s)
ml = min(l)
st = SuffixTree(s)
suffs = [[0] * 3 for _ in range(len(st.nodes))]
resp = [0] * (ml + 1)
dfs(0, 0)
for i in range(len(resp) - 1):
resp[i + 1] += resp[i]
resp[i + 1] %= MOD
print(' '.join(map(str, resp[1:])))
|
Python
|
[
"graphs",
"strings"
] | 356
| 3,820
| 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
}
| 4,501
|
c54042eebaef01783a74d31521db9baa
|
Connect the countless points with lines, till we reach the faraway yonder.There are n points on a coordinate plane, the i-th of which being (i, yi).Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.
|
['geometry', 'brute force']
|
n=int(input())
d=list(map(int,input().split()))
a,b,c=d[:3]
if b-a==c-b:
e=b-a
f=0
for i in range(3,n):
if (d[i]-c)/(i-2)!=e:
if f and(d[i]-g)/(i-h)!=e:print('No');exit()
else:g,h=d[i],i;f=1
print('Yes'if f else'No')
else:
p1=p2=p3=1
e,f,g=b-a,c,2
h,j,k=c-b,a,0
l,m,o=(c-a)/2,b,1
for i in range(3,n):
if(d[i]-b)/(i-1)!=e and(d[i]-f)/(i-g)!=e:p1=0
if(d[i]-c)/(i-2)!=h and(d[i]-j)/(i-k)!=h:p2=0
if(d[i]-c)/(i-2)!=l and(d[i]-m)/(i-o)!=l:p3=0
print('Yes'if p1+p2+p3 else'No')
|
Python
|
[
"geometry"
] | 352
| 567
| 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,181
|
ff5b3d5fa52c2505556454011e8a0f58
|
Several years ago Tolya had n computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD in clockwise order. The names were distinct, the length of each name was equal to k. The names didn't overlap.Thus, there is a cyclic string of length n·k written on the CD.Several years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were g popular games that days. All of the games he burned were among these g games, and no game was burned more than once.You have to restore any valid list of games Tolya could burn to the CD several years ago.
|
['data structures', 'string suffix structures', 'hashing', 'strings']
|
n, k = map(int, raw_input().split())
s = raw_input()
g = int(raw_input())
games = [raw_input() for i in range(g)]
MOD_1 = 1000000007
BASE_1 = 31
MOD_2 = 1000000409
BASE_2 = 29
hashes_1 = []
hashes_2 = []
hash_inv = {}
game_inv = {}
for i, game in enumerate(games):
h_1 = 0
h_2 = 0
for c in game:
h_1 *= BASE_1
h_2 *= BASE_2
h_1 += ord(c) - ord('a')
h_2 += ord(c) - ord('a')
h_1 %= MOD_1
h_2 %= MOD_2
hashes_1.append(h_1)
hashes_2.append(h_2)
hash_inv[(h_1, h_2)] = i
game_inv[game] = i
# assert len(hash_inv) == g
# compute rolling hash on cd string
# find all residues (mod k) at which each game appears
s = s + s
h_1 = 0
h_2 = 0
for i in range(k):
h_1 *= BASE_1
h_2 *= BASE_2
h_1 += ord(s[i]) - ord('a')
h_2 += ord(s[i]) - ord('a')
h_1 %= MOD_1
h_2 %= MOD_2
coef_1 = pow(BASE_1, k - 1, MOD_1)
coef_2 = pow(BASE_2, k - 1, MOD_2)
residues = [set() for i in range(g)]
for i in range(k, len(s)):
# first, consider the word at [i - k, i)
# (h = hash of that word)
if (h_1, h_2) in hash_inv:
residues[hash_inv[(h_1, h_2)]].add(i % k)
# update h for next word
h_1 -= coef_1 * (ord(s[i - k]) - ord('a'))
h_2 -= coef_2 * (ord(s[i - k]) - ord('a'))
h_1 *= BASE_1
h_2 *= BASE_2
h_1 += ord(s[i]) - ord('a')
h_2 += ord(s[i]) - ord('a')
h_1 %= MOD_1
h_2 %= MOD_2
res_freq = [0]*k
for i in range(g):
for res in residues[i]:
res_freq[res] += 1
use = -1
for i in range(k):
# if s.startswith("muytqaevcsnqpkfxq"):
# print i, res_freq[i], n
if res_freq[i] >= n:
use = i
break
if use == -1:
print "NO"
else:
print "YES"
ans = []
for i in range(n):
idx = k*i + use
ss = s[idx:idx+k]
ans.append(game_inv[ss] + 1)
print " ".join(map(str, ans))
|
Python
|
[
"strings"
] | 683
| 1,876
| 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,511
|
094a880e93a2adfbcb6dcc2b5f043bab
|
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.For some indices i (1 ≤ i ≤ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap i-th element with (i + 1)-th (if the position is not forbidden).Can you make this array sorted in ascending order performing some sequence of swapping operations?
|
['greedy', 'two pointers', 'math', 'sortings', 'dfs and similar']
|
def main():
n=input()
l=map(long,raw_input().split())
ar=map(int," ".join(raw_input()).split())
r=[0]*(n)
r[0]=ar[0]
for i in xrange(1,n-1):
r[i]=ar[i]+r[i-1]
f=[0]*n
for i in xrange(n-2,-1,-1):
f[i]=ar[i]+f[i+1]
r[n-1]=r[n-2]
#print r
for i in xrange(n):
#print r[max(l[i]-1,i)],r[min(l[i]-1,i)]
if l[i]-1!=i and (abs(f[l[i]-1]-f[i])!=abs(l[i]-1-i)):
print "NO"
exit()
print "YES"
main()
|
Python
|
[
"math",
"graphs"
] | 505
| 515
| 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
}
| 1,889
|
4f8be14ad3242c2832f37cca8feaeec0
|
In Fire City, there are n intersections and m one-way roads. The i-th road goes from intersection a_i to b_i and has length l_i miles. There are q cars that may only drive along those roads. The i-th car starts at intersection v_i and has an odometer that begins at s_i, increments for each mile driven, and resets to 0 whenever it reaches t_i. Phoenix has been tasked to drive cars along some roads (possibly none) and return them to their initial intersection with the odometer showing 0.For each car, please find if this is possible. A car may visit the same road or intersection an arbitrary number of times. The odometers don't stop counting the distance after resetting, so odometers may also be reset an arbitrary number of times.
|
['dfs and similar', 'graphs', 'math', 'number theory']
|
def find_SCC(graph):
SCC, S, P = [], [], []
depth = [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
d = depth[~node] - 1
if P[-1] > d:
SCC.append(S[d:])
del S[d:], P[-1]
for node in SCC[-1]:
depth[node] = -1
elif depth[node] > 0:
while P[-1] > depth[node]:
P.pop()
elif depth[node] == 0:
S.append(node)
P.append(len(S))
depth[node] = len(S)
stack.append(~node)
stack += graph[node]
return SCC[::-1]
import sys
input = sys.stdin.readline
n,m = map(int, input().split())
adj = [[] for _ in range(n)]
a2 = [[] for _ in range(n)]
edges = []
for _ in range(m):
a,b,l = map(int, input().split());a-=1;b-=1
edges.append((a,b,l))
adj[a].append(b)
a2[a].append((b,l))
SCCs = find_SCC(adj)
SCC_ind = [-1] * n
for i in range(len(SCCs)):
for v in SCCs[i]:
SCC_ind[v] = i
from math import gcd
dist = [-1] * n
SCC_gcd = []
for l in SCCs:
root = l[0]
ind = SCC_ind[root]
dist[root] = 0
g = 0
stack = [root]
while stack:
u = stack.pop()
for v, l in a2[u]:
if SCC_ind[v] == ind:
if dist[v] == -1:
stack.append(v)
dist[v] = dist[u] + l
else:
d1 = dist[u] + l
diff = (dist[v] - d1)
g = gcd(g, diff)
SCC_gcd.append(g)
q = int(input())
out = []
for _ in range(q):
v,s,t = map(int, input().split());v-=1
g = gcd(SCC_gcd[SCC_ind[v]], t)
if s % g == 0:
out.append('YES')
else:
out.append('NO')
print('\n'.join(out))
|
Python
|
[
"graphs",
"number theory",
"math"
] | 815
| 1,921
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,440
|
1670a3d7dba83e29e98f0ac6fe4acb18
|
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.
|
['data structures', 'greedy', 'trees']
|
import sys
sys.setrecursionlimit(1050)
class Node:
def __init__(self, depth, parent):
self.depth = depth
self.parent = parent
self.left = None
self.right = None
self.leaf = False
def __str__(self):
return 'depth = %d, left? %s, right? %s' % (self.depth,
self.left != None, self.right != None)
stacks = {}
def traverse(node, symbols):
if node.leaf:
s = ''.join(symbols)
stacks.setdefault(len(s), []).append(s)
return
if node.left != None:
symbols.append('0')
traverse(node.left, symbols)
symbols.pop()
if node.right != None:
symbols.append('1')
traverse(node.right, symbols)
symbols.pop()
n = int(input())
original_lengths = list(map(int, input().split()))
lengths = sorted(original_lengths[:])
root = Node(0, None)
curr = root
for i in range(lengths[0]):
curr.left = Node(curr.depth+1, curr)
curr = curr.left
curr.leaf = True
for length in lengths[1:]:
curr = curr.parent
while curr.right != None:
if curr == root:
print('NO')
sys.exit()
curr = curr.parent
curr.right = Node(curr.depth+1, curr)
curr = curr.right
while curr.depth != length:
curr.left = Node(curr.depth+1, curr)
curr = curr.left
curr.leaf = True
print('YES')
traverse(root, [])
for length in original_lengths:
print(stacks[length].pop())
|
Python
|
[
"trees"
] | 632
| 1,332
| 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,692
|
15aa3adb14c17023f71eec11e1c32efe
|
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on the scales or to say that it can't be done.
|
['dp', 'greedy', 'graphs', 'constructive algorithms', 'shortest paths', 'dfs and similar']
|
def solve(a, b, m, M, weights, last, solution):
# print(a,b,m,M,weights, solution)
if (a-b > 10):
return False
if m == M:
print("YES")
print(*solution)
return True
for w in weights:
if w != last and b+w > a:
solution[m] = w
if (solve(b+w, a, m+1, M, weights, w, solution)):
return True
return False
import sys
sys.setrecursionlimit(1500)
w = input()
m = int(input())
weights = []
for i in range(1, 11):
if w[i-1] == '1':
weights.append(i)
weights.sort(reverse=True)
solution = [0 for x in range(0,m)]
if not solve(0, 0, 0, m, weights, -1, solution):
print("NO")
|
Python
|
[
"graphs"
] | 1,187
| 634
| 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
}
| 1,766
|
a764aa5727b53a6be78b1e172f670c86
|
As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the XOR sum of all weights would be equal to 0.Define the ugliness of a fully-assigned complete graph the weight of its minimum spanning tree, where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible.As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 \le u < v \le n; such a graph has \frac{n(n-1)}{2} edges.She is not sure how to solve this problem, so she asks you to solve it for her.
|
['bitmasks', 'brute force', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'trees']
|
import sys, os
if os.environ['USERNAME']=='kissz':
inp=open('in3.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=sys.stdin.readline
def debug(*args):
pass
# SCRIPT STARTS HERE
def getp(i):
L=[]
while parent[i]>=0:
L+=[i]
i=parent[i]
for j in L:
parent[j]=i
return i
n,m=map(int,inp().split())
neighbors=[set() for _ in range(n)]
G=[[] for _ in range(n)]
E=[]
xors=0
for _ in range(m):
u,v,w=map(int,inp().split())
neighbors[u-1].add(v-1)
neighbors[v-1].add(u-1)
E+=[(w,v-1,u-1)]
xors^=w
s=0
parent=[-1]*n
k=(n*(n-1))//2-m
nodes=set(range(n))
conn=0
for p in range(n):
if p not in nodes: continue
nodes.remove(p)
Q=[p]
while Q:
i=Q.pop()
new_nodes=set()
for j in nodes:
if j not in neighbors[i]:
parent[j]=p
G[i].append((j,True))
G[j].append((i,True))
new_nodes.add(j)
conn+=1
debug(i,j,0)
k-=1
Q.append(j)
nodes-=new_nodes
debug(parent)
if conn<n-1 or k==0:
E.sort()
for w,u,v in E:
pu=getp(u)
pv=getp(v)
if pu!=pv:
s+=w
parent[pu]=pv
G[u].append((v,False))
G[v].append((u,False))
conn+=1
debug(u,v,w)
elif k==0 and w<xors:
Q=[(u,False)]
seen=[False]*n
seen[u]=True
while Q:
i,new=Q.pop()
for j,new_edge in G[i]:
if not seen[j]:
seen[j]=True
new_edge |= new
if j==v:
Q=[]
break
else:
Q.append((j,new_edge))
if new_edge:
s+=w
debug('corr ',u,v,w)
k+=1;
if conn>=n-1 and (k>0 or w>xors):
break
if k==0:
s+=xors
debug('no corr ', xors)
print(s)
|
Python
|
[
"graphs",
"trees"
] | 1,000
| 2,301
| 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
}
| 417
|
ccf4ac6b61b48604b7d9f49b7daaeb0f
|
You are playing a computer game. In this game, you have to fight n monsters.To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d.When you fight a monster with strength d while having a shield with current durability a and defence b, there are three possible outcomes: if a = 0, then you receive d damage; if a > 0 and d \ge b, you receive no damage, but the current durability of the shield decreases by 1; if a > 0 and d < b, nothing happens. The i-th monster has strength d_i, and you will fight each of the monsters exactly once, in some random order (all n! orders are equiprobable). You have to consider m different shields, the i-th shield has initial durability a_i and defence rating b_i. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given n monsters in random order.
|
['combinatorics', 'binary search', 'probabilities']
|
import sys;input=sys.stdin.readline
mod = 998244353
#mod=10**9+7
def frac(limit):
frac = [1]*limit
for i in range(2,limit):
frac[i] = i * frac[i-1]%mod
fraci = [None]*limit
fraci[-1] = pow(frac[-1], mod -2, mod)
for i in range(-2, -limit-1, -1):
fraci[i] = fraci[i+1] * (limit + i + 1) % mod
return frac, fraci
def mul(a, b):
return ((a % mod) * (b % mod)) % mod
def div(a, b):
return mul(a, pow(b, mod-2,mod))
#frac, fraci = frac(141398)
#print(fraci)
N, M = map(int, input().split())
X = list(map(int, input().split()))
t = []
for i in range(N):
t.append((0, X[i]))
Q = []
for i in range(M):
a, b = map(int, input().split())
Q.append((a, b))
t.append((1, b))
Y = [0]*(N+M)
Z = [0]*(N+M)
t.sort(key=lambda x:x[1])
d = dict()
d2 = [0]*(N+M)
cnt = 0
for l, x in t:
if x not in d:
cnt += 1
d[x] = cnt
d2[cnt] = x
if not l:
Y[cnt] += 1
for i in range(N+M):
Z[i] = Y[i]*d2[i]
Y.append(0)
Z.append(0)
for i in range(N+M-1, -1, -1):
Y[i] = Y[i+1]+Y[i]
Z[i] = Z[i+1]+Z[i]
for a, b in Q:
k=Y[d[b]]
R = 0
if k>a:
R += div((k-a),k)*Z[d[b]]
if k+1>a:
R += div((k+1-a),k+1)*(Z[0]-Z[d[b]])
print(R%mod)
|
Python
|
[
"math",
"probabilities"
] | 1,112
| 1,246
| 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,297
|
4841cbc3d3ef29929690b78e30fbf22e
|
In order to write a string, Atilla needs to first learn all letters that are contained in the string.Atilla needs to write a message which can be represented as a string s. He asks you what is the minimum alphabet size required so that one can write this message.The alphabet of size x (1 \leq x \leq 26) contains only the first x Latin letters. For example an alphabet of size 4 contains only the characters \texttt{a}, \texttt{b}, \texttt{c} and \texttt{d}.
|
['greedy', 'implementation', 'strings']
|
import sys
raw_input = iter(sys.stdin.read().splitlines()).next
def solution():
n = int(raw_input())
s = raw_input()
return ord(max(s))-ord('a')+1
for case in xrange(int(raw_input())):
print '%s' % solution()
|
Python
|
[
"strings"
] | 513
| 235
| 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,286
|
5139d222fbbfa70d50e990f5d6c92726
|
You are given an array a consisting of n integers.Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without changing the order of remaining elements. For example, [2], [1, 2, 1, 3] and [2, 3] are subsequences of [1, 2, 1, 3], but [1, 1, 2] and [4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array a of length n is the palindrome if a_i = a_{n - i - 1} for all i from 1 to n. For example, arrays [1234], [1, 2, 1], [1, 3, 2, 2, 3, 1] and [10, 100, 10] are palindromes, but arrays [1, 2] and [1, 2, 3, 1] are not.You have to answer t independent test cases.
|
['brute force', 'strings']
|
for test in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
l.append(10000000009)
c=0
for i in range(n-2):
if l[i] in l[i+2:]:
print("YES")
c=1
break
if(c==0):
print("NO")
|
Python
|
[
"strings"
] | 993
| 275
| 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
}
| 259
|
3634a3367a1f05d1b3e8e4369e8427fb
|
For the multiset of positive integers s=\{s_1,s_2,\dots,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. \textrm{lcm}(s) is the minimum positive integer x, that divisible on all integers from s.For example, \gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6 and \textrm{lcm}(\{4,6\})=12. Note that for any positive integer x, \gcd(\{x\})=\textrm{lcm}(\{x\})=x.Orac has a sequence a with length n. He come up with the multiset t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}, and asked you to find the value of \gcd(t) for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.
|
['number theory', 'math']
|
def gcd(a,b):
while b: a,b=b,a%b
return a
def rwh_primes2(n):
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a list of primes, 2 <= p < n """
correction = (n%6>1)
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
sieve = [True] * (n/3)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
primes=rwh_primes2(200000)
def f(n,a):
g=reduce(gcd,a); g2=1
for i in xrange(len(a)): a[i]/=g
for p in primes:
min1=min2=1000
for j in a:
u=1; t=0; up=p
while j%up==0: u,up=up,up*p; t+=1
if t<min2:
if t<min1: min1,min2=t,min1
else: min2=t
if min1==min2==0: break
g2*=(p**min2)
return g2*g
n=int(raw_input())
a=map(int,raw_input().split())
print f(n,a)
|
Python
|
[
"math",
"number theory"
] | 849
| 1,057
| 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,572
|
f73370c8ea81b8b81a79701d8e2ec785
|
BCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces.BCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team. In BSU there are n students numbered from 1 to n. Since all BSU students are infinitely smart, the only important parameters for Blenda are their reading and writing speed. After a careful measuring, Blenda have found that the i-th student have a reading speed equal to ri (words per minute), and a writing speed of wi (symbols per minute). Since BSU students are very smart, the measured speeds are sometimes very big and Blenda have decided to subtract some constant value c from all the values of reading speed and some value d from all the values of writing speed. Therefore she considers ri' = ri - c and wi' = wi - d. The student i is said to overwhelm the student j if and only if ri'·wj' > rj'·wi'. Blenda doesn’t like fights in teams, so she thinks that a team consisting of three distinct students i, j and k is good if i overwhelms j, j overwhelms k, and k overwhelms i. Yes, the relation of overwhelming is not transitive as it often happens in real life.Since Blenda is busy preparing a training camp in Codeforces, you are given a task to calculate the number of different good teams in BSU. Two teams are considered to be different if there is at least one student that is present in one team but is not present in the other. In other words, two teams are different if the sets of students that form these teams are different.
|
['two pointers', 'binary search', 'geometry']
|
from sys import stdin
from itertools import repeat
from math import cos, sin, atan2
def main():
n, c, d = map(int, stdin.readline().split())
dat = map(int, stdin.read().split(), repeat(10, 2 * n))
a = []
aa = a.append
for i in xrange(n):
x, y = dat[i*2] - c, dat[i*2+1] - d
t = atan2(y, x)
ss, cs = sin(t), cos(t)
aa(((t, atan2(x * ss + y * cs, x * cs + y * ss)), x, y))
a.sort()
a.extend(a)
ans = n * (n - 1) * (n - 2) / 6
i = 0
k = 1
while i < n:
t = a[i]
for j in xrange(i + 1, n):
if t[1] * a[j][2] - t[2] * a[j][1] == 0 and t[1] * a[j][1] >= 0 and t[2] * a[j][2] >= 0:
pass
else:
break
else:
j = n
if k < j:
k = j
for l in xrange(k, i + n):
if t[1] * a[l][2] - t[2] * a[l][1] <= 0:
k = l
break
else:
k = i + n
for l in xrange(k, i + n):
if t[1] * a[l][2] - t[2] * a[l][1] < 0:
break
else:
l = i + n
ans -= (j - i) * (j - i - 1) * (j - i - 2) / 6
ans -= (j - i) * (j - i - 1) / 2 * (l - j)
ans -= (j - i) * (k - j) * (k - j - 1) / 2
ans -= (j - i) * (k - j) * (l - k)
i = j
k = l
print ans
main()
|
Python
|
[
"geometry"
] | 1,649
| 1,369
| 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
}
| 113
|
864593dc3911206b627dab711025e116
|
Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj < ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.
|
['implementation', 'greedy', 'games']
|
n = int(input())
a = [0] * 100001
for x in map(int, input().split()):
a[x]+=1
print('Conan' if 1 in map(lambda x: x%2, a) else 'Agasa')
|
Python
|
[
"games"
] | 685
| 144
| 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
}
| 1,194
|
c8f63597670a7b751822f8cef01b8ba3
|
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index i got a person with index fi, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (xi, yi), which mean that person xi has to call person yi as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?
|
['dfs and similar', 'trees', 'graphs']
|
#!/usr/bin/env python3
# Read data
n = int(input())
f = map(int, input().split())
f = [d-1 for d in f] # Make indices 0-based
# Determine in-degree of all the nodes
indegree = [0 for i in range(n)]
for i in range(n):
indegree[f[i]] += 1
# Nodes with indegree = 0 will need to be an end-point of a new edge
endpoints = [i for i in range(n) if (indegree[i] == 0)]
nr_indegree_zero = len(endpoints)
# Determine which (hereto unvisited) nodes will be reached by these endpoints
unvisited = set(range(n))
reach = [None for i in range(n)]
def determine_reach(v):
path = [v]
while (v in unvisited):
unvisited.remove(v)
v = f[v]
path.append(v)
for i in path:
reach[i] = v
for v in endpoints:
determine_reach(v)
# The reached nodes form good start-points for the new edges
startpoints = [reach[v] for v in endpoints]
# Check for isolated cycles that are not connected to the rest of the graph
nr_cycles = 0
while len(unvisited) > 0:
# Select a node from the unvisited set (without removing it)
v = unvisited.pop()
unvisited.add(v)
nr_cycles += 1
determine_reach(v)
endpoints.append(v)
startpoints.append(reach[v])
# Special case: no indegree 0 nodes and only 1 cycle
if (nr_indegree_zero == 0) and (nr_cycles == 1):
# No edges need to be added
print(0)
exit()
# Rotate the lists to each start point connects to the end-point of the next item
endpoints = endpoints[1:] + endpoints[:1]
print(len(startpoints))
print("\n".join(["%d %s" % (start+1,end+1) for (start,end) in zip(startpoints,endpoints)]))
|
Python
|
[
"graphs",
"trees"
] | 902
| 1,548
| 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
}
| 57
|
7b394dbced93130f83d61f7e325a980a
|
This is the easy version of the problem. The only difference is that in this version there are no "remove" queries.Initially you have a set containing one element — 0. You need to handle q queries of the following types:+ x — add the integer x to the set. It is guaranteed that this integer is not contained in the set; ? k — find the k\text{-mex} of the set. In our problem, we define the k\text{-mex} of a set of integers as the smallest non-negative integer x that is divisible by k and which is not contained in the set.
|
['brute force', 'data structures', 'implementation', 'number theory']
|
# Code by B3D
# Love
from math import *
from collections import *
import io, os
import sys
from bisect import *
from heapq import *
from itertools import permutations
from functools import *
import re
import sys
import threading
# from temps import *
MOD = 998244353
# sys.setrecursionlimit(10**6)
def subinp():
sys.stdin = open("input.txt", "r")
sys.stdout = open("op1.txt", "w")
def subinp_1():
sys.stdin = open("input.txt", "r")
sys.stdout = open("op2.txt", "w")
"""
pow2 = [1]
# print(log2(10 ** 9))
for i in range(29):
pow2.append(pow2[-1] * 2)
"""
input = sys.stdin.readline
class Point:
def __init__(self, x, l1):
self.x = x
self.l1 = l1
def __lt__(self, b):
return self.l1[self.x] < self.l1[b.x]
def getval(self):
return self.x
inp = lambda: int(input())
strin = lambda: input().strip()
strl = lambda: list(input().rstrip("\r\n"))
strlst = lambda: list(map(str, input().split()))
mult = lambda: map(int,input().strip().split())
mulf = lambda: map(float,input().strip().split())
lstin = lambda: list(map(int,input().strip().split()))
flush = lambda: stdout.flush()
stdpr = lambda x: stdout.write(str(x))
# @lru_cache(maxsize = 128)
# print(pref)
# ac = [chr(i) for i in range(ord('a'), ord('z') + 1)]
# Power comes in response to a need, not a desire.
# n = int(input())
# n, k = map(int, input().split())
# s = input()
# l = list(map(int, input().split()))
# dp = [[-1 for i in range(n + 1)] for j in range(2)]
class Queen:
def __init__(self):
self.chk = defaultdict(bool)
self.mp = defaultdict(lambda:1)
def addnum(self, n):
self.chk[n] = True
while self.chk[self.mp[n] * n]:
self.mp[n] += 1
def query(self, n):
m = n
ans = 0
i = self.mp[n]
# print(d)
while self.chk[m]:
self.mp[n] = i
m = n * i
i += 1
print(m)
def panda(q):
obj = Queen()
lock = threading.Semaphore(10)
for _ in range(q):
inp = strl()
qx = inp[0]
n = int(''.join(inp[2:]))
if qx == '+':
lock.acquire()
obj.addnum(n)
lock.release()
else:
lock.acquire()
obj.query(n)
lock.release()
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = 1
# t = int(input())
for _ in range(t):
n = inp()
ans = panda(n)
# print(ans)
# a1 = redpanda(n, l)
# print(a)
# print(a1)
# sys.stdout.write(str(ans))
# print("Case #" + str(_ + 1) + ": " + str(ans))
|
Python
|
[
"number theory"
] | 578
| 2,757
| 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,318
|
ce4443581d4ee12db6607695cd567070
|
You are given a string s, consisting of n lowercase Latin letters.A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it.Let's call some string of length n diverse if and only if there is no letter to appear strictly more than \frac n 2 times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.Your task is to find any diverse substring of string s or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.
|
['implementation', 'strings']
|
n=input()
s=raw_input()
if len(set(s))==1:
print "NO"
else:
print "YES"
for i in range(n-1):
if s[i]!=s[i+1]:
print s[i]+s[i+1]
break
|
Python
|
[
"strings"
] | 691
| 147
| 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
}
| 687
|
8eda3e355d2823b0c8f92e1628dc1b69
|
Vasya lagged behind at the University and got to the battlefield. Just joking! He's simply playing some computer game. The field is a flat platform with n trenches dug on it. The trenches are segments on a plane parallel to the coordinate axes. No two trenches intersect.There is a huge enemy laser far away from Vasya. The laser charges for a seconds, and then shoots continuously for b seconds. Then, it charges for a seconds again. Then it shoots continuously for b seconds again and so on. Vasya knows numbers a and b. He also knows that while the laser is shooting, Vasya must be in the trench, but while the laser is charging, Vasya can safely move around the field. The main thing is to have time to hide in the trench before the shot. If Vasya reaches the trench exactly at the moment when the laser starts shooting, we believe that Vasya managed to hide. Coincidentally, the length of any trench in meters numerically does not exceed b.Initially, Vasya is at point A. He needs to get to point B. Vasya moves at speed 1 meter per second in either direction. You can get in or out of the trench at any its point. Getting in or out of the trench takes no time. It is also possible to move in the trench, without leaving it.What is the minimum time Vasya needs to get from point A to point B, if at the initial time the laser has just started charging? If Vasya cannot get from point A to point B, print -1. If Vasya reaches point B at the moment when the laser begins to shoot, it is believed that Vasya managed to reach point B.
|
['graphs', 'implementation', 'geometry', 'shortest paths']
|
import math
R = lambda: map(int, raw_input().split())
a, b = R()
Ax, Ay, Bx, By = R()
n = R()[0]
x1, y1, x2, y2 = [Ax],[Ay],[Ax],[Ay]
for i in range(n):
_t1, _t2, _t3, _t4 = R()
if (_t1 > _t3): _t1, _t3 = _t3, _t1
if (_t2 > _t4):_t2, _t4 = _t4, _t2
x1.append(_t1)
y1.append(_t2)
x2.append(_t3)
y2.append(_t4)
x1.append(Bx)
y1.append(By)
x2.append(Bx)
y2.append(By)
kc = lambda x1, y1, x2, y2: (x1 - x2)**2 + (y1-y2)**2
kc2 = lambda x, y: x*x + y*y
def can_go2(i, j):
d = min(kc(x1[i],y1[i], x1[j], y1[j]), kc(x1[i],y1[i], x2[j], y2[j]), kc(x1[i],y1[i], x1[j], y2[j]), kc(x1[i],y1[i], x2[j], y1[j]),
kc(x1[i],y2[i], x1[j], y1[j]), kc(x1[i],y2[i], x2[j], y2[j]), kc(x1[i],y2[i], x1[j], y2[j]), kc(x1[i],y2[i], x2[j], y1[j]),
kc(x2[i],y1[i], x1[j], y1[j]), kc(x2[i],y1[i], x2[j], y2[j]), kc(x2[i],y1[i], x1[j], y2[j]), kc(x2[i],y1[i], x2[j], y1[j]),
kc(x2[i],y2[i], x1[j], y1[j]), kc(x2[i],y2[i], x2[j], y2[j]), kc(x2[i],y2[i], x1[j], y2[j]), kc(x2[i],y2[i], x2[j], y1[j]))
if (x1[i]-x1[j]) * (x2[j]-x1[i]) >= 0 or (x2[i] - x1[j]) * (x2[j] - x2[i]) >=0:
d = min(d, math.fabs(y1[i] - y2[j]), math.fabs(y1[i] - y1[j]), math.fabs(y2[i] - y1[j]), math.fabs(y2[i] - y2[j]))
if (y1[i]-y1[j]) * (y2[j]-y1[i]) >= 0 or (y2[i] - y1[j]) * (y2[j] - y2[i]) >=0:
d = min(d, math.fabs(x1[i] - x2[j]), math.fabs(x1[i] - x1[j]), math.fabs(x2[i] - x1[j]), math.fabs(x2[i] - x2[j]))
if d <= a ** 2: return d
else: return 0
def can_go(i, j):
d = kc2(max(0, max(x1[i],x1[j]) - min(x2[i], x2[j])), max(0, max(y1[i], y1[j]) - min(y2[i], y2[j])))
if d <= a ** 2: return d
else: return 0
dres = [-1 for i in range(0, n+2)]
dres[0] = 0
q = [0]
first, last = 0, 0
while first <= last:
i = q[first]
#print "BFS from %d" % i
first += 1
for j in range(1, n+1):
if dres[j] == -1:
if can_go(i, j) > 0:
#print "---Visit %d" % j
last += 1
q.append(j)
dres[j] = dres[i] + 1
res = 1000000000.0
if can_go(0, n + 1) > 0: res = math.sqrt(kc(Ax, Ay, Bx, By))
for i in range(1, n + 1):
if dres[i] > 0:
tmp = can_go(i, n + 1)
if tmp > 0: res = min(res, dres[i] * (a + b) + math.sqrt(tmp))
if res == 1000000000.0: print "-1"
else: print "%.10f" % res
|
Python
|
[
"graphs",
"geometry"
] | 1,535
| 2,180
| 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
}
| 1,078
|
61bb5f2b315eddf2e658e3f54d8f43b8
|
It's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an integer from 1 to 2n, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed 2i and 2i - 1 turn on if the chain connecting them consists of exactly d_i wires. Moreover, the following important condition holds: the value of d_i is never greater than n.Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
|
['graphs', 'constructive algorithms', 'math', 'sortings', 'trees']
|
# https://codeforces.com/contest/1214/problem/E
n = int(input())
d = map(int, input().split())
d = [[2*i+1, di] for i, di in enumerate(d)]
d = sorted(d, key=lambda x:x[1], reverse = True)
edge = []
arr = [x[0] for x in d]
for i, [x, d_] in enumerate(d):
if i + d_ - 1 == len(arr) - 1:
arr.append(x+1)
edge.append([arr[i + d_ - 1], x+1])
for u, v in zip(d[:-1], d[1:]):
edge.append([u[0], v[0]])
ans = '\n'.join([str(u)+' '+str(v) for u, v in edge])
print(ans)
|
Python
|
[
"graphs",
"math",
"trees"
] | 1,563
| 497
| 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,259
|
58ee86d4913787582ccdb54073656dc0
|
A string s of length n, consisting of lowercase letters of the English alphabet, is given.You must choose some number k between 0 and n. Then, you select k characters of s and permute them however you want. In this process, the positions of the other n-k characters remain unchanged. You have to perform this operation exactly once.For example, if s=\texttt{"andrea"}, you can choose the k=4 characters \texttt{"a_d_ea"} and permute them into \texttt{"d_e_aa"} so that after the operation the string becomes \texttt{"dneraa"}.Determine the minimum k so that it is possible to sort s alphabetically (that is, after the operation its characters appear in alphabetical order).
|
['sortings', 'strings']
|
for i in range(int(input())):
n=int(input())
s=[i for i in input()]
t=sorted(s)
print(sum([int(s[i]!=t[i]) for i in range(n)]))
|
Python
|
[
"strings"
] | 763
| 149
| 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,334
|
463d4e6badd3aa110cc87ae7049214b4
|
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.In Shapur's opinion the weakness of an army is equal to the number of triplets i, j, k such that i < j < k and ai > aj > ak where ax is the power of man standing at position x. The Roman army has one special trait — powers of all the people in it are distinct.Help Shapur find out how weak the Romans are.
|
['data structures', 'trees']
|
def fast2():
import os, sys, atexit
from cStringIO import StringIO as BytesIO
# range = xrange
sys.stdout = BytesIO()
atexit.register(lambda: os.write(1, sys.stdout.getvalue()))
return BytesIO(os.read(0, os.fstat(0).st_size)).readline
class order_tree:
def __init__(self, n):
self.tree, self.n = [[0, 0] for _ in range(n << 1)], n
# get interval[l,r)
def query(self, r, col):
res = 0
l = self.n
r += self.n
while l < r:
if l & 1:
res += self.tree[l][col]
l += 1
if r & 1:
r -= 1
res += self.tree[r][col]
l >>= 1
r >>= 1
return res
def update(self, ix, val, col):
ix += self.n
# set new value
self.tree[ix][col] += val
# move up
while ix > 1:
self.tree[ix >> 1][col] = self.tree[ix][col] + self.tree[ix ^ 1][col]
ix >>= 1
input = fast2()
n, a = int(input()), [int(x) for x in input().split()]
tree, ans = order_tree(n), 0
mem = {i: j for j, i in enumerate(sorted(a))}
for i in range(n - 1, -1, -1):
cur = mem[a[i]]
ans += tree.query(cur, 1)
tree.update(cur, 1, 0)
tree.update(cur, tree.query(cur, 0), 1)
print(ans)
|
Python
|
[
"trees"
] | 602
| 1,308
| 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,766
|
2cb1e7e4d25f624da934bce5c628a7ee
|
Petya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.
|
['geometry']
|
import math
def main():
x, y, vx, vy, a, b, c, d = map(int, input().split())
len = math.sqrt(vx * vx + vy * vy)
vx /= len
vy /= len
print(x + vx * b, y + vy * b)
print(x - vy * a / 2, y + vx * a / 2)
print(x - vy * c / 2, y + vx * c / 2)
print(x - vy * c / 2 - vx * d, y + vx * c / 2 - vy * d)
print(x + vy * c / 2 - vx * d, y - vx * c / 2 - vy * d)
print(2 * x - (x - vy * c / 2), 2 * y - (y + vx * c / 2))
print(2 * x - (x - vy * a / 2), 2 * y - (y + vx * a / 2))
main()
|
Python
|
[
"geometry"
] | 1,392
| 542
| 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,222
|
529d4ab0bdbb29d8b7f3d3eed19eca63
|
You are given a positive integer n. Let's call some positive integer a without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express n as a sum of positive palindromic integers. Two ways are considered different if the frequency of at least one palindromic integer is different in them. For example, 5=4+1 and 5=3+1+1 are considered different but 5=3+1+1 and 5=1+3+1 are considered the same. Formally, you need to find the number of distinct multisets of positive palindromic integers the sum of which is equal to n.Since the answer can be quite large, print it modulo 10^9+7.
|
['brute force', 'dp', 'math', 'number theory']
|
from sys import stdin
def readint():
return int(stdin.readline())
def readarray(typ):
return list(map(typ, stdin.readline().split()))
MOD = int(1e9) + 7
ps = []
N = 40000
for i in range(1, N+1):
# print(str(i), ''.join(reversed(str(i)))
if str(i) == (str(i)[::-1]):
ps.append(i)
m = len(ps)
dp = [[0] * m for _ in range(N+1)]
for i in range(1, N+1):
for j in range(m):
dp[i][j] += int(i == ps[j])
dp[i][j] += dp[i][j-1] if j >= 1 else 0
if i > ps[j]:
dp[i][j] += dp[i-ps[j]][j]
dp[i][j] %= MOD
t = readint()
for _ in range(t):
n = readint()
print(dp[n][-1])
|
Python
|
[
"math",
"number theory"
] | 711
| 633
| 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,024
|
8b57854277fb7baead123473a609301d
|
Pak Chanek has a mirror in the shape of a circle. There are N lamps on the circumference numbered from 1 to N in clockwise order. The length of the arc from lamp i to lamp i+1 is D_i for 1 \leq i \leq N-1. Meanwhile, the length of the arc between lamp N and lamp 1 is D_N.Pak Chanek wants to colour the lamps with M different colours. Each lamp can be coloured with one of the M colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly 90 degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps 1, 2, and 3 form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo 998\,244\,353.
|
['binary search', 'combinatorics', 'geometry', 'math', 'two pointers']
|
import os,sys
from io import BytesIO, IOBase
def pair_same(n, m, k, p, r, fac):
return ( ((fac[m]*pow(fac[m-p], r-2, r))%r) *
((pow(((m-p)*(m-p-1))%r, k-p, r)*pow(m-p, n-2*k, r))%r) )%r
def solve(n, m, ls):
r = 998244353
fac = [1]
for i in range(1, m+1):
fac.append((fac[-1]*i)%r)
prefix = [0]
for p in ls:
prefix.append(prefix[-1]+p)
tot = prefix.pop()
if tot%2 ==1:
k=0
else:
k = 0
rr = 0
for l in range(len(prefix)):
while rr < len(prefix) and prefix[rr] - prefix[l] < tot//2:
rr += 1
if rr == len(prefix):
break
if prefix[rr] - prefix[l] == tot//2:
k += 1
res = 0
for p in range(k+1):
res = (res + fac[k]*pow((fac[p]*fac[k-p])%r, r-2, r)*pair_same(n, m, k, p, r, fac))%r
print(res)
def main():
n, m = list(map(int, input().split(" ")))
ls = list(map(int, input().split(" ")))
solve(n, m, ls)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
|
Python
|
[
"math",
"geometry"
] | 1,204
| 2,799
| 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,600
|
48151011c3d380ab303ae38d0804176a
|
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm: take the password p, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain p' (p' can still be equal to p); generate two random strings, consisting of lowercase Latin letters, s_1 and s_2 (any of these strings can be empty); the resulting hash h = s_1 + p' + s_2, where addition is string concatenation. For example, let the password p = "abacaba". Then p' can be equal to "aabcaab". Random strings s1 = "zyx" and s2 = "kjh". Then h = "zyxaabcaabkjh".Note that no letters could be deleted or added to p to obtain p', only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password p and the hash h, check that h can be the hash for the password p.Your program should answer t independent test cases.
|
['implementation', 'brute force', 'strings']
|
t = input()
for _ in xrange(t):
p = raw_input()
h = raw_input()
n = len(p)
m = len(h)
ans = False
low = 0
p = ''.join(sorted(p))
while low+n<=m:
temp = h[low:low+n]
temp = ''.join(sorted(temp))
if p == temp:
ans = True
break
low += 1
if ans:
print 'YES'
else:
print 'NO'
|
Python
|
[
"strings"
] | 1,146
| 385
| 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,215
|
bedb98780a71d7027798d14aa5f1f100
|
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset. To not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed 1.Help Dima construct such a binary search tree or determine that it's impossible. The definition and properties of a binary search tree can be found here.
|
['dp', 'number theory', 'math', 'trees', 'brute force']
|
from sys import stdin
from math import gcd
n=int(stdin.readline())
a=[int(x) for x in stdin.readline().split()]
c = []
ld=[]
rd=[]
def check(l, r, e):
if r == l: return c[l][e] > 0
if e < l and ld[l][r-l] != 0:
return ld[l][r-l] == 1
elif e > r and rd[l][r-l] != 0:
return rd[l][r-l] == 1
for i in range(l, r+1):
if c[i][e]>0:
if i==l or check(l, i-1, i):
if i==r or check(i+1, r, i):
if e < l:
ld[l][r-l] = 1
else:
rd[l][r-l] = 1
return True
if e < l:
ld[l][r - l] = -1
else:
rd[l][r - l] = -1
return False
for i in range(n):
c.append([0]*n)
ld.append([0]*n)
rd.append([0] * n)
for i in range(n):
for j in range(i+1,n):
if gcd(a[i],a[j]) > 1:
c[i][j] = c[j][i] = 1
ans=False
for i in range(n):
if i == 0 or check(0, i - 1, i):
if i == n-1 or check(i + 1, n-1, i):
ans = True
break
if ans:
print("Yes")
else:
print("No")
|
Python
|
[
"number theory",
"math",
"trees"
] | 719
| 1,111
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 1
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 1
}
| 4,864
|
9f13d3d0266b46e4201ea6a2378d1b71
|
Binary Spiders are species of spiders that live on Mars. These spiders weave their webs to defend themselves from enemies.To weave a web, spiders join in pairs. If the first spider in pair has x legs, and the second spider has y legs, then they weave a web with durability x \oplus y. Here, \oplus means bitwise XOR.Binary Spiders live in large groups. You observe a group of n spiders, and the i-th spider has a_i legs.When the group is threatened, some of the spiders become defenders. Defenders are chosen in the following way. First, there must be at least two defenders. Second, any pair of defenders must be able to weave a web with durability at least k. Third, there must be as much defenders as possible.Scientists have researched the behaviour of Binary Spiders for a long time, and now they have a hypothesis that they can always choose the defenders in an optimal way, satisfying the conditions above. You need to verify this hypothesis on your group of spiders. So, you need to understand how many spiders must become defenders. You are not a Binary Spider, so you decided to use a computer to solve this problem.
|
['bitmasks', 'data structures', 'implementation', 'math', 'sortings', 'trees']
|
import sys
import os
from io import BytesIO, IOBase
from _collections import defaultdict
from random import randrange
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
f = sys.stdin
if os.environ.get('USER') == "loic":
f = open("data.in")
line = lambda: f.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
def max_xor_of_pair(arr):
m = 0
mask = 0
s = set()
d = {}
pair = (-1,-1)
for i in range(30, -1, -1):
mask |= (1 << i)
tmp = m | (1 << i)
for a in arr:
pref = a & mask
s.add(pref)
# d[pref] = a
for pref in s:
if tmp ^ pref in s:
m = tmp
# pair = (d[pref], d[tmp ^ pref])
break
s.clear()
return m,pair
def solve():
if K == 0:
return str(N) + "\n" + " ".join(map(str,range(1,N+1)))
pref = defaultdict(list)
msb = len(bin(K)) - 2
for a in A:
val = a >> msb
pref[val].append(a)
res = []
for l in pref.values():
if len(l) == 1:
res.extend(l)
else:
m,pair = max_xor_of_pair(l)
if m >= K:
# res.append(pair[0])
# res.append(pair[1])
s = set(l)
for val in s:
if val ^ m in s:
res += [val,val^m]
break
else:
res.append(l[0])
if len(res) < 2:
return str(-1)
mp = {v:i for i,v in enumerate(A)}
return str(len(res)) + "\n" + " ".join(str(mp[v]+1) for v in res)
for test in range(1,1+1):
N,K = ti()
A = li()
print(solve())
f.close()
|
Python
|
[
"math",
"trees"
] | 1,174
| 3,707
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
}
| 1,680
|
1461fca52a0310fff725b476bfbd3b29
|
Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability \frac{p_i}{100} for all 1 \le i \le n.Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint all the time.Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities: The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to i. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given q queries, each query is represented by an integer u: If the u-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the u-th mirror is no longer a checkpoint.After each query, you need to calculate the expected number of days until Creatnx becomes happy.Each of this numbers should be found by modulo 998244353. Formally, let M = 998244353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.
|
['data structures', 'probabilities']
|
from __future__ import division, print_function
def main():
n, qs = input_as_list()
cpn = ceil_power_of_2(n)
st = array_of(int, n+1)
switch = array_of(bool, n)
def update(i, v):
while i < n:
st[i] += v
i |= i+1
def query(i):
res = 0
while i > 0:
res += st[i-1]
i &= i-1
return res
def lower_bound(s):
if s <= 0: return -1
pos = 0
pw = cpn
while pw > 0:
if (pos + pw <= n) and (st[pos + pw-1] < s):
pos += pw
s -= st[pos-1]
pw //= 2
return pos
def insert(i):
update(i, +1)
def remove(i):
update(i, -1)
def find_by_order(i):
return lower_bound(i)
def order_of(i):
return query(i)
def lr(i):
o = order_of(i)
l = find_by_order(o)
r = find_by_order(o+1)
return l, r
ar = input_as_list()
s1 = [0]
for x in ar:
v = s1[-1]+1
v = mulmod(v, 100)
v = divmod(v, x)
s1.append(v)
s2 = [1]
for x in ar:
v = s2[-1]
v = mulmod(v, 100)
v = divmod(v, x)
s2.append(v)
def f(l, r):
if r <= l:
return 0
a = s1[r]
b = mulmod(s1[l], s2[r])
b = divmod(b, s2[l])
return (a-b)%MOD
insert(0)
insert(n)
ans = s1[-1]
for _ in range(qs):
q = int(input())-1
if switch[q]:
remove(q)
l, r = lr(q)
ans = (ans + f(l, r)) % MOD
ans = (ans - f(l, q)) % MOD
ans = (ans - f(q, r)) % MOD
else:
l, r = lr(q)
ans = (ans - f(l, r)) % MOD
ans = (ans + f(l, q)) % MOD
ans = (ans + f(q, r)) % MOD
insert(q)
switch[q] ^= True
print(ans)
INF = float('inf')
MOD = 998244353
__interactive = False
import os, sys
from atexit import register
from io import BytesIO
import itertools
import __pypy__
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
if "LOCAL_" in os.environ:
debug_print = print
else:
if not __interactive:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
debug_print = lambda *x, **y: None
flush = sys.stdout.flush
def mulmod(x, y):
return __pypy__.intop.int_mulmod(x, y, MOD)
def modinv(x):
return pow(x, MOD-2, MOD)
def divmod(x, y):
return mulmod(x, modinv(y))
def gcd(x, y):
while y:
x, y = y, x % y
return x
def input_as_list():
return list(map(int, input().split()))
def input_with_offset(o):
return list(map(lambda x:int(x)+o, input().split()))
def input_as_matrix(n, m):
return [input_as_list() for _ in range(n)]
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
def range_with_count(start, step, count):
return range(start, start + step * count, step)
def indices(l, start=0, end=0):
return range(start, len(l)+end)
def ceil_power_of_2(n):
""" [0, 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, ...] """
return 2 ** ((n - 1).bit_length())
def ceil_div(x, r):
""" = ceil(x / r) """
return (x + r - 1) // r
main()
|
Python
|
[
"probabilities"
] | 1,747
| 3,510
| 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
}
| 1,245
|
7a559fd046e599b16143f40b4e55d127
|
You are given an integer array a of length n. Does there exist an array b consisting of n+1 positive integers such that a_i=\gcd (b_i,b_{i+1}) for all i (1 \leq i \leq n)? Note that \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.
|
['math', 'number theory']
|
import sys
from math import *
def input(): return sys.stdin.readline().strip()
def lcm(a, b):
return a*b//gcd(a, b)
for test in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
if n <= 2:
print("YES")
continue
brr = [arr[0]]
for i in range(n-1):
brr.append(lcm(arr[i], arr[i+1]))
brr.append(arr[-1])
crr = []
for i in range(n):
crr.append(gcd(brr[i], brr[i+1]))
if arr == crr:
print("YES")
else:
print("NO")
|
Python
|
[
"math",
"number theory"
] | 315
| 531
| 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
}
| 104
|
c9bc4fefa96b741843e54a8fb4b02877
|
This is an interactive problem.There was a tournament consisting of 2^n contestants. The 1-st contestant competed with the 2-nd, the 3-rd competed with the 4-th, and so on. After that, the winner of the first match competed with the winner of second match, etc. The tournament ended when there was only one contestant left, who was declared the winner of the tournament. Such a tournament scheme is known as the single-elimination tournament.You don't know the results, but you want to find the winner of the tournament. In one query, you select two integers a and b, which are the indices of two contestants. The jury will return 1 if a won more matches than b, 2 if b won more matches than a, or 0 if their number of wins was equal.Find the winner in no more than \left \lceil \frac{1}{3} \cdot 2^{n + 1} \right \rceil queries. Here \lceil x \rceil denotes the value of x rounded up to the nearest integer.Note that the tournament is long over, meaning that the results are fixed and do not depend on your queries.
|
['constructive algorithms', 'greedy', 'interactive', 'number theory', 'probabilities']
|
t= int(input())
for _ in range(t):
n=int(input())
P = [i for i in range(1,2**n+1)]
while n>1:
k=[]
for i in range(0,2**(n)-1,4):
print("? ", P[i], P[i+2], flush =True)
a = int(input())
if a==0:
k.extend([P[i+1],P[i+3]])
elif a==1:
k.extend([P[i], P[i+3]])
elif a ==2:
k.extend([P[i+2],P[i+1]])
n-=1
P=k
print("? ", P[0],P[1],flush =True)
a=int(input())
if a ==1:print("!",P[0],flush =True)
else:print("!",P[1],flush =True)
|
Python
|
[
"number theory",
"probabilities"
] | 1,118
| 610
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 1,
"strings": 0,
"trees": 0
}
| 4,914
|
016bf7989ba58fdc3894a4cf3e0ac302
|
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of n dishes on the first day and a set of m dishes on the second day. He made a table a of size n \times m, in which he described his impressions. If, according to the expert, dish i from the first set was better than dish j from the second set, then a_{ij} is equal to ">", in the opposite case a_{ij} is equal to "<". Dishes also may be equally good, in this case a_{ij} is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if a_{ij} is "<", then the number assigned to dish i from the first set should be less than the number of dish j from the second set, if a_{ij} is ">", then it should be greater, and finally if a_{ij} is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.
|
['dp', 'greedy', 'graphs', 'dsu', 'dfs and similar']
|
n, m = map(int, input().split())
dishes = [0 for _ in range(n + m)]
father = [-1 for _ in range(n + m)]
e_out = dict()
v_in = [0 for _ in range(n + m)]
def get_father(n):
if father[n] == -1:
return n
else:
father[n] = get_father(father[n])
return father[n]
compare_matrix = []
for i in range(n):
compare_matrix.append(input())
for i in range(n):
for j in range(m):
if compare_matrix[i][j] == "=":
fi = get_father(i)
fj = get_father(j + n)
if fi != fj:
father[fj] = fi
children = dict()
for i in range(n + m):
fi = get_father(i)
if fi != i:
if fi not in children:
children[fi] = [i]
else:
children[fi].append(i)
for i in range(n):
for j in range(m):
if compare_matrix[i][j] == "=":
continue
fi = get_father(i)
fj = get_father(j + n)
if fi == fj:
print("NO")
exit(0)
if compare_matrix[i][j] == ">":
v_in[fi] += 1
if fj in e_out:
e_out[fj].append(fi)
else:
e_out[fj] = [fi]
if compare_matrix[i][j] == "<":
v_in[fj] += 1
if fi in e_out:
e_out[fi].append(fj)
else:
e_out[fi] = [fj]
# print(v_in)
# print(e_out)
score = 1
visited = [False for _ in range(n + m)]
v_total = 0
q = [v for v in range(n + m) if v_in[v] == 0]
while q:
t = []
for i in q:
dishes[i] = score
v_total += 1
if i in children:
for j in children[i]:
dishes[j] = score
v_total += 1
if i in e_out:
for j in e_out[i]:
v_in[j] -= 1
if v_in[j] == 0:
t.append(j)
q = t
score += 1
if v_total < n + m:
print("NO")
exit(0)
print("YES")
for i in dishes[:n]:
print(i, end=" ")
print()
for i in dishes[n:n + m]:
print(i, end=" ")
|
Python
|
[
"graphs"
] | 2,081
| 2,033
| 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,489
|
b58a18119ac8375f9ad21a282292a76c
|
You are given two integers a and b. In one turn, you can do one of the following operations: Take an integer c (c > 1 and a should be divisible by c) and replace a with \frac{a}{c}; Take an integer c (c > 1 and b should be divisible by c) and replace b with \frac{b}{c}. Your goal is to make a equal to b using exactly k turns.For example, the numbers a=36 and b=48 can be made equal in 4 moves: c=6, divide b by c \Rightarrow a=36, b=8; c=2, divide a by c \Rightarrow a=18, b=8; c=9, divide a by c \Rightarrow a=2, b=8; c=4, divide b by c \Rightarrow a=2, b=2. For the given numbers a and b, determine whether it is possible to make them equal using exactly k turns.
|
['constructive algorithms', 'math', 'number theory']
|
from __future__ import division, print_function
import os,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
from math import ceil, floor, factorial, sqrt
# from math import log,sqrt,cos,tan,sin,radians
from bisect import bisect_left, bisect_right
from collections import defaultdict
from collections import deque, Counter, OrderedDict
# from heapq import nsmallest, nlargest, heapify, heappop, heappush, heapreplace
# from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
# from decimal import *
# from itertools import permutations
# ======================== Functions declaration Starts ========================
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
M=1000000007
# M=998244353
INF = float("inf")
PI = 3.141592653589793
def copy2d(lst): return [x[:] for x in lst] #Copy 2D list... Avoid Using Deepcopy
def isPowerOfTwo(x): return (x and (not(x & (x - 1))) )
LB = bisect_left # Lower bound
UB = bisect_right # Upper bound
def BS(a, x): # Binary Search
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return (x*y)//gcd(x,y)
# import threading
# def dmain():
# sys.setrecursionlimit(1000000)
# threading.stack_size(1024000)
# thread = threading.Thread(target=main)
# thread.start()
# ========================= Functions declaration Ends =========================
def isPrime(n):
if n <= 3: return n > 1
if n & 1 == 0 or n % 3 == 0: return False
for i in range(5, int(n**0.5)+2, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
def primesbelow(N=1000000): # Faster version of Sieve of Erathostenes
"""
Input N>=3; Returns a list or set of all primes 2 <= p <= N
Use this to iterate over prime numbers.
Don't use this as a substitute for sieve() because
multiple lookups will be slower than sieve() as one lookup takes logN time.
"""
N += 1 # To make inclusive of N
correction = N % 6 > 1
N = {0:N, 1:N-1, 2:N+4, 3:N+3, 4:N+2, 5:N+1}[N%6]
sieve_bool = [True] * (N // 3)
sieve_bool[0] = False
for i in range(int(N ** .5) // 3 + 1):
if sieve_bool[i]:
k = (3 * i + 1) | 1
sieve_bool[k*k // 3::2*k] = [False] * ((N//6 - (k*k)//6 - 1)//k + 1)
sieve_bool[(k*k + 4*k - 2*k*(i%2)) // 3::2*k] = [False] * ((N // 6 - (k*k + 4*k - 2*k*(i%2))//6 - 1) // k + 1)
# To return set
# return {(3 * i + 1) | 1 for i in range(1, N//3 - correction) if sieve_bool[i]}.union({2,3})
# To return list
return [2, 3] + [(3 * i + 1) | 1 for i in range(1, N//3 - correction) if sieve_bool[i]]
is_prime = []
def sieve(n=1000000):
global is_prime
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if is_prime[i]:
for j in range(i * i, n + 1, i):
is_prime[j] = False
def primeFactors(n):
# cnt = defaultdict(int)
sm = 0
if n==1:
return sm
while not n%2:
# cnt[2]+=1
sm += 1
n = n // 2
for i in range(3,int(sqrt(n))+1,2):
while n % i== 0:
# cnt[i] += 1
sm += 1
n = n // i
if n > 2:
# cnt[n] += 1
sm += 1
return sm
# def find_prime_factors(n):
# """
# Returns a dictionary with all prime factors of n.
# """
# return d
from collections import Counter
def gcd(x, y):
"""greatest common divisor of x and y"""
while y:
x, y = y, x % y
return x
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
def main():
TestCases = 1
TestCases = int(input())
# primes = primesbelow(int(10**(4.5)))
# print(Counter(find_primes_factors(24)))
for _ in range(TestCases):
a,b,k = [int(i) for i in input().split()]
if k==1:
if a==b==1:
print("NO")
continue
if (a%b==0 or b%a==0) and a!=b:
print("YES")
continue
print("NO")
continue
fac1 = prime_factors(a)
fac2 = prime_factors(b)
nof1 = 0
for f, pow in fac1.items():
nof1 += pow
nof2 = 0
for f, pow in fac2.items():
nof2 += pow
kmax = nof1 + nof2
print("YES" if k <= kmax else "NO")
# # A = defaultdict(int)
# # B = defaultdict(int)
# # sm = 0
# # a11,b11 = a, b
# # for i in primes:
# # while a11 % i == 0 and sm<k and a11>1:
# # # A[i] += 1
# # sm += 1
# # a11 //= i
# # while b11 % i == 0 and sm<k and b11>1:
# # # B[i] += 1
# # sm += 1
# # b11 //= i
# # if sm >= k or (a11==b11==1) or (i>a11 and i>b11):
# # break
# sm = primeFactors(a) + primeFactors(b)
# # if a11>1:
# # if isPrime(a11):
# # sm += 1
# # if b11>1:
# # if isPrime(b11):
# # sm += 1
# kmax = sm
# print("YES" if k<=kmax else "NO")
# a1 = A-B
# b1 = B-A
# print(a1)
# print(b1)
# cnt = 0
# for num,pow in a1.items():
# cnt += pow
# for num,pow in b1.items():
# cnt += pow
# if k < cnt:
# print("NO")
# continue
# k -= cnt
# if k&1:
# print("NO")
# continue
# intersection = A - a1
# for num, pow in intersection.items():
# k -= pow*2
# if k <= 0:
# print("YES")
# else:
# print("NO")
# =============================== Region Fastio ===============================
if not os.path.isdir('C:/users/acer'):
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# =============================== Endregion ===============================
if __name__ == "__main__":
#read()
main()
#dmain()
|
Python
|
[
"math",
"number theory"
] | 963
| 11,568
| 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
}
| 840
|
07e56d4031bcb119d2f684203f7ed133
|
Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular n-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the OX-axis and at least one of its edges is parallel to the OY-axis at the same time.Recall that a regular n-sided polygon is a convex polygon with n vertices such that all the edges and angles are equal.Now he is shopping: the market has t regular polygons. For each of them print YES if it is beautiful and NO otherwise.
|
['geometry', 'math']
|
t=int(input())
for _ in range(t):
n=int(input())
if(n%4==0):
print("YES")
else:
print("NO")
|
Python
|
[
"math",
"geometry"
] | 607
| 120
| 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
}
| 139
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.