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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bf115b24d85a0581e709c012793b248b
|
To become the king of Codeforces, Kuroni has to solve the following problem.He is given n numbers a_1, a_2, \dots, a_n. Help Kuroni to calculate \prod_{1\le i<j\le n} |a_i - a_j|. As result can be very big, output it modulo m.If you are not familiar with short notation, \prod_{1\le i<j\le n} |a_i - a_j| is equal to |a_1 - a_2|\cdot|a_1 - a_3|\cdot \dots \cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot \dots \cdot|a_2 - a_n| \cdot \dots \cdot |a_{n-1} - a_n|. In other words, this is the product of |a_i - a_j| for all 1\le i < j \le n.
|
['combinatorics', 'number theory', 'brute force', 'math']
|
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import math
# sys.stdin = open('input')
def inp():
return map(int, raw_input().split())
def inst():
return raw_input().strip()
def main():
n, m = inp()
da = inp()
if n>2100:
print 0
return
ans = 1
for i in range(n):
for j in range(i+1, n):
# print da[i],da[j]
ans *= abs(da[i]-da[j])
ans %= m
print ans
main()
|
Python
|
[
"math",
"number theory"
] | 637
| 589
| 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
}
| 350
|
7c6e8bc160a17dbc6d55c6dc40fe0988
|
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions p_1, p_2, \ldots, p_k (k \ge 1; 1 \le p_i \le n; p_i \neq p_j if i \neq j) of A such that A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x (ie. all letters on this positions are equal to some letter x). selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x). sets each letter in positions p_1, p_2, \ldots, p_k to letter y. More formally: for each i (1 \le i \le k) Koa sets A_{p_i} = y. Note that you can only modify letters in string A.Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
|
['greedy', 'graphs', 'dsu', 'sortings', 'dfs and similar', 'trees']
|
import sys
input = sys.stdin.readline
def print(val):
sys.stdout.write(str(val) + '\n')
def prog():
for _ in range(int(input())):
n = int(input())
a = list(input().strip())
b = input().strip()
fail = False
for i in range(n):
if b[i] < a[i]:
fail = True
break
if fail:
print(-1)
else:
exclude = [0]*n
for i in range(n):
if a[i] == b[i]:
exclude[i] = 1
largest = max(b)
curr = largest
for i in range(n):
if not exclude[i]:
curr = min(curr, a[i])
operations = 0
while curr < largest:
to_change = []
for i in range(n):
if a[i] == curr and not exclude[i]:
to_change.append(i)
smallest = largest
for i in to_change:
smallest = min(smallest, b[i])
for i in to_change:
if b[i] == smallest:
exclude[i] = 1
a[i] = smallest
curr = largest
for i in range(n):
if not exclude[i]:
curr = min(curr, a[i])
operations += 1
print(operations)
prog()
|
Python
|
[
"graphs",
"trees"
] | 1,348
| 1,456
| 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,839
|
788ae500235ca7b7a7cd320f745d1070
|
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
|
['greedy', 'strings']
|
#!/usr/bin/python3
import sys
def solve(s, k):
l = len(s)
for i in range(l-1, -1, -1):
prev = s[max(i-2, 0):i]
z = s[i] + 1
while z in prev:
z += 1
if z >= k:
continue
# Gotcha!
ret = s[:i] + [z]
while len(ret) < l:
prev = ret[max(len(ret)-2, 0):len(ret)]
z = 0
while z in prev:
z += 1
ret.append(z)
return ret
return None
if __name__ == '__main__':
l, k = map(int, sys.stdin.readline().split())
s = [ord(c) - ord('a') for c in sys.stdin.readline().strip()]
ans = solve(s, k)
if ans is None:
print('NO')
else:
print(''.join(chr(ord('a') + x) for x in ans))
|
Python
|
[
"strings"
] | 388
| 762
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
}
| 4,609
|
e984b4e1120b8fb083a3ebad9bb93709
|
Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.
|
['implementation', '*special', 'graphs', 'dfs and similar']
|
import collections as col
import itertools as its
import sys
import operator
from copy import copy, deepcopy
class Solver:
def __init__(self):
pass
def solve(self):
n, k = map(int, input().split())
q = list(map(lambda x: int(x) - 1, input().split()))
used = [False] * n
for e in q:
used[e] = True
edges = [[] for _ in range(n)]
redges = [[] for _ in range(n)]
for i in range(n):
l = list(map(lambda x: int(x) - 1, input().split()))[1:]
edges[i] = l
for e in l:
redges[e].append(i)
degs = [len(edges[i]) for i in range(n)]
d = 0
while d < len(q):
v = q[d]
d += 1
for e in edges[v]:
if not used[e]:
used[e] = True
q.append(e)
q = q[::-1]
nq = []
for v in q:
if degs[v] == 0:
nq.append(v)
d = 0
while d < len(nq):
v = nq[d]
d += 1
for e in redges[v]:
if not used[e]:
continue
degs[e] -= 1
if degs[e] == 0:
nq.append(e)
#print(nq)
if len(q) != len(nq):
print(-1)
return
print(len(nq))
print(' '.join(map(lambda x: str(x + 1), nq)))
if __name__ == '__main__':
s = Solver()
s.solve()
|
Python
|
[
"graphs"
] | 744
| 1,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
}
| 4,577
|
c046e64e008e997620efc21aec199bdb
|
Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.
|
['dp', 'graphs', 'constructive algorithms', 'data structures', 'dfs and similar']
|
from collections import deque
def subtree_specs(graph, d, node, visited, edges_dict, res_edges):
num_ones = 0
for nb in graph[node]:
if not visited[nb]:
visited[nb] = True
res = subtree_specs(graph, d, nb, visited, edges_dict, res_edges)
if res % 2 == 1:
# Need to attach this node
res_edges.append(edges_dict[node][nb])
num_ones += res
if d[node] == 1:
num_ones += 1
return num_ones
def subtree_specs_stack(graph, d, edges_dict):
n = len(graph)
visited = n * [False]
visited[0] = True
children = [[] for _ in range(n)]
num_ones = n * [-1]
res_edges = []
q = deque([(0, 'InProcess')])
while len(q) > 0:
node, state = q.pop()
if state == 'InProcess':
q.append((node, 'Done'))
for nb in graph[node]:
if not visited[nb]:
visited[nb] = True
q.append((nb, 'InProcess'))
children[node].append(nb)
elif state == 'Done':
res = sum([num_ones[i] for i in children[node]])
if d[node] == 1:
res += 1
num_ones[node] = res
for child in children[node]:
if num_ones[child] % 2 == 1:
res_edges.append(edges_dict[node][child])
return res_edges
def main():
n, m = map(int, raw_input().split(' '))
d = map(int, raw_input().split(' '))
graph = [[] for _ in range(n)]
edges_dict = {}
for i in range(m):
node1, node2 = map(int, raw_input().split(' '))
node1 -= 1
node2 -= 1
graph[node1].append(node2)
graph[node2].append(node1)
if node1 not in edges_dict:
edges_dict[node1] = {}
if node2 not in edges_dict:
edges_dict[node2] = {}
if node2 not in edges_dict[node1]:
edges_dict[node1][node2] = i + 1
if node1 not in edges_dict[node2]:
edges_dict[node2][node1] = i + 1
if len([el for el in d if el == 1]) == 0:
print 0
return
else:
if len([el for el in d if el == 1]) % 2 == 1:
if len([el for el in d if el == -1]) == 0:
print -1
return
else:
i = [i for i in range(len(d)) if d[i] == -1][0]
d[i] = 1
res = subtree_specs_stack(graph, d, edges_dict)
print len(res)
for el in res:
print el
if __name__ == "__main__":
main()
|
Python
|
[
"graphs"
] | 661
| 2,573
| 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
}
| 661
|
a949ccae523731f601108d4fa919c112
|
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
|
['geometry', 'math']
|
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
for x in range(1, a):
if ((a ** 2 - x ** 2) ** 0.5) % 1 < 10 ** -5:
y = round((a ** 2 - x ** 2) ** 0.5)
if x > 0 and y > 0 and (y * b) % a == 0 and (x * b) % a == 0:
print('YES')
print(0, 0)
print(x, y)
print(y * b // a, -x * b // a)
exit(0)
print('NO')
|
Python
|
[
"math",
"geometry"
] | 353
| 395
| 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
}
| 637
|
2475df43379ffd450fa661927ae3b734
|
After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
|
['hashing', 'strings']
|
from collections import Counter
n = int(input())
strings = []
for i in range(0,n):
counter = { x: 0 for x in range(ord('a'), ord('z')+1) }
napis = input()
for val in napis:
counter[ord(val)] = (counter[ord(val)] + 1) % 2
napis = ""
for key, val in counter.items():
if val != 0:
napis+=chr(key)
strings.append(napis)
c = Counter(strings)
strings = sorted(c.most_common(), key=lambda i: i[0])
#print(strings)
count = 0
for key, val in strings:
if val > 1:
count += val*(val-1)/2
for charInt in range(ord('a'), ord('z')+1):
char = chr(charInt)
copy = {}
for key, val in strings:
if char in key:
copy[key.replace(char, "")] = copy.get(key.replace(char, ""), 0) + val
#print(copy)
for key, val in strings:
if copy.get(key,0) != 0:
count+=val * copy[key]
#print("pokrywa : ", key, " ", val*copy[key])
print(int(count))
|
Python
|
[
"strings"
] | 1,152
| 893
| 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,511
|
042008e186c5a7265fbe382b0bdfc9bc
|
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions: The length of t does not exceed the length of s. t is a palindrome. There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
|
['hashing', 'string suffix structures', 'strings']
|
import sys, heapq as h
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input().strip()
def listStr():
return list(input().strip())
import collections as col
import math
"""
Longest matching prefix and suffix
Then for each start / end point, the longest palindrome going forwards and then longest palidrome going backwards
"""
def longest_prefix_suffix_palindrome(S,N):
i = -1
while i+1 <= N-i-2 and S[i+1] == S[N-i-2]:
i += 1
return i
def longest_palindromic_prefix(S):
tmp = S + "?"
S = S[::-1]
tmp = tmp + S
N = len(tmp)
lps = [0] * N
for i in range(1, N):
#Length of longest prefix till less than i
L = lps[i - 1]
# Calculate length for i+1
while (L > 0 and tmp[L] != tmp[i]):
L = lps[L - 1]
#If character at current index and L are same then increment length by 1
if (tmp[i] == tmp[L]):
L += 1
#Update the length at current index to L
lps[i] = L
return tmp[:lps[N - 1]]
def solve():
S = getStr()
N = len(S)
i = longest_prefix_suffix_palindrome(S,N)
#so S[:i+1] and S[N-i-1:] are palindromic
if i >= N//2-1:
return S
#so there are least 2 elements between S[i] and S[N-i-1]
new_str = S[i+1:N-i-1]
longest_pref = longest_palindromic_prefix(new_str)
longest_suff = longest_palindromic_prefix(new_str[::-1])[::-1]
add_on = longest_pref if len(longest_pref) >= len(longest_suff) else longest_suff
return S[:i+1] + add_on + S[N-i-1:]
for _ in range(getInt()):
print(solve())
#print(solve())
|
Python
|
[
"strings"
] | 636
| 1,778
| 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,697
|
eaab346f1dd620c8634a7991fa581bff
|
Daemon Targaryen decided to stop looking like a Metin2 character. He turned himself into the most beautiful thing, a bracket sequence.For a bracket sequence, we can do two kind of operations: Select one of its substrings^\dagger and cyclic shift it to the right. For example, after a cyclic shift to the right, "(())" will become ")(()"; Insert any bracket, opening '(' or closing ')', wherever you want in the sequence. We define the cost of a bracket sequence as the minimum number of such operations to make it balanced^\ddagger.Given a bracket sequence s of length n, find the sum of costs across all its \frac{n(n+1)}{2} non-empty substrings. Note that for each substring we calculate the cost independently.^\dagger 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.^\ddagger A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences "(())()", "()", and "(()(()))" are balanced, while ")(", "(()", and "(()))(" are not.
|
['binary search', 'data structures', 'divide and conquer', 'dp', 'greedy', 'strings']
|
import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
# 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")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# if a[0] == min(a):
# print('YES')
# else:
# print('NO')
# for _ in range(int(input())):
# n = int(input())
# s = input()
# cnt = 0
# for i in range(n):
# if s[i] == '0':
# cnt += 1
# if cnt == 0 or cnt == n:
# ans = n * n
# else:
# ans = cnt * (n - cnt)
# a = s.split('0')
# mx = 0
# for i in a:
# mx = max(mx, len(i))
# b = s.split('1')
# for i in b:
# mx = max(mx, len(i))
# print(max(mx * mx, ans))
# N = int(pow(10 ** 9, 0.5)) + 5
# def get_prime_linear(n):
# global cnt
# for i in range(2, n + 1):
# if not st[i]:
# primes[cnt] = i
# cnt += 1
# for j in range(n):
# if primes[j] > n / i: break
# st[primes[j] * i] = True
# if i % primes[j] == 0: break
# primes, cnt, st = [0] * (N + 5), 0, [False] * (N + 5)
# get_prime_linear(N)
# prime1e3 = primes[:cnt]
# @lru_cache(None)
# def get_factor(n):
# res = []
# for i in prime1e3:
# if i * i > n:
# break
# while n % i == 0:
# n //= i
# res.append(i)
# if n > 1:
# res.append(n)
# return sorted(set(res))
# mod = 998244353
# for _ in range(int(input())):
# n, m = list(map(int, input().split()))
# a = list(map(int, input().split()))
# ans = 1
# for i in range(1, n):
# if a[i - 1] % a[i]:
# ans = 0
# break
# k = a[i - 1] // a[i]
# mx = m // a[i]
# f = get_factor(k)
# res = 0
# N = len(f)
# for i in range(1 << N):
# cnt = 0
# cur = 1
# for j in range(N):
# if i >> j & 1:
# cnt += 1
# cur *= f[j]
# if cnt % 2 == 0: res += mx // cur
# else: res -= mx // cur
# ans = ans * res % mod
# print(ans)
for _ in range(int(input())):
n = int(input())
s = input()
a = [0]
cur = 0
for i in range(n):
if s[i] == '(':
cur += 1
else:
cur -= 1
a.append(cur)
n = len(a)
stack = []
l = [-1] * (n)
for i in range(n):
while stack and stack[-1][0] >= a[i]:
stack.pop()
l[i] = stack[-1][1] if stack else -1
stack.append([a[i], i])
stack = []
r = [n] * (n)
for i in range(n)[::-1]:
while stack and stack[-1][0] > a[i]:
stack.pop()
r[i] = stack[-1][1] if stack else n
stack.append([a[i], i])
ans = 0
for i in range(n):
ans -= a[i] * (i - l[i]) * (r[i] - i)
a.sort()
for i in range(n):
ans += (i + 1) * a[i]
print(ans)
|
Python
|
[
"strings"
] | 1,245
| 5,106
| 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,266
|
808611f86c70659a1d5b8fc67875de31
|
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?
|
['games', 'math']
|
input(); print(("Second", "First")[any(int(i) % 2 for i in input().split())])
|
Python
|
[
"math",
"games"
] | 545
| 78
| 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
}
| 3,056
|
6f7bee466780e6e65b2841bfccad28b0
|
There are n people in this world, conveniently numbered 1 through n. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let d(a,b) denote the debt of a towards b, or 0 if there is no such debt.Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done: Let d(a,b) > 0 and d(c,d) > 0 such that a \neq c or b \neq d. We can decrease the d(a,b) and d(c,d) by z and increase d(c,b) and d(a,d) by z, where 0 < z \leq \min(d(a,b),d(c,d)). Let d(a,a) > 0. We can set d(a,a) to 0. The total debt is defined as the sum of all debts:\Sigma_d = \sum_{a,b} d(a,b)Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.
|
['greedy', 'graphs', 'constructive algorithms', 'two pointers', 'math', 'implementation', 'data structures']
|
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict as dd
I = lambda : list(map(int,input().split()))
n,m=I()
fi=[0]*(n+1)
for i in range(m):
u,v,w=I()
fi[u]-=w
fi[v]+=w
p=[];m=[]
for i in range(1,n+1):
if fi[i]<0:
m.append([-fi[i],i])
elif fi[i]>0:
p.append([fi[i],i])
an=[]
while p and m:
a,b=p[-1],m[-1]
if a[0]==b[0]:
p.pop();m.pop()
an.append([b[1],a[1],a[0]])
elif a[0]<b[0]:
m[-1][0]-=a[0]
p.pop()
an.append([b[1],a[1],a[0]])
else:
p[-1][0]-=b[0]
m.pop()
an.append([b[1],a[1],b[0]])
print(len(an))
for u,v,d in an:
print(u,v,d)
|
Python
|
[
"graphs",
"math"
] | 1,383
| 623
| 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,419
|
ae7c90b00cc8393fc4db14a6aad32957
|
Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 ≤ l ≤ r ≤ n and gcd(al, al + 1, ..., ar) = xi. is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi.
|
['data structures', 'brute force', 'math']
|
from math import gcd
from collections import defaultdict
from sys import stdin, stdout
##This method is better cause for all the same results we only calculate once
def main():
GCD_count = defaultdict(int)
GCD_map = defaultdict(int)
arr_len = int(stdin.readline())
arr = [int(x) for x in stdin.readline().split()]
for start in range(arr_len):
temp = defaultdict(int)
GCD_count[arr[start]] += 1
temp[arr[start]] += 1
for gcd_now, occurence in GCD_map.items():
res = gcd(gcd_now, arr[start])
temp[res] += occurence
GCD_count[res] += occurence
GCD_map = temp
num_queries = int(stdin.readline())
for _ in range(num_queries):
print(GCD_count[int(stdin.readline())])
main()
|
Python
|
[
"math"
] | 309
| 783
| 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
}
| 1,160
|
2bf41400fa51f472f1d3904baa06d6a8
|
You are given a connected undirected graph consisting of n vertices and m edges. The weight of the i-th edge is i.Here is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:vis := an array of length ns := a set of edgesfunction dfs(u): vis[u] := true iterate through each edge (u, v) in the order from smallest to largest edge weight if vis[v] = false add edge (u, v) into the set (s) dfs(v)function findMST(u): reset all elements of (vis) to false reset the edge set (s) to empty dfs(u) return the edge set (s)Each of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.
|
['dfs and similar', 'dsu', 'graphs', 'greedy', 'sortings', 'trees']
|
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m=map(int,input().split())
EDGE=[tuple(map(int,input().split())) for i in range(m)]
# UnionFind
Group = [i for i in range(n+1)] # グループ分け
Nodes = [1]*(n+1) # 各グループのノードの数
def find(x):
while Group[x] != x:
x=Group[x]
return x
def Union(x,y):
if find(x) != find(y):
if Nodes[find(x)] < Nodes[find(y)]:
Nodes[find(y)] += Nodes[find(x)]
Nodes[find(x)] = 0
Group[find(x)] = find(y)
else:
Nodes[find(x)] += Nodes[find(y)]
Nodes[find(y)] = 0
Group[find(y)] = find(x)
USE=[0]*m
for i in range(m):
x,y=EDGE[i]
if find(x)==find(y):
USE[i]=0
else:
USE[i]=1
Union(x,y)
E=[[] for i in range(n+1)]
OK=[0]*(n+1)
for i in range(m):
if USE[i]==1:
x,y = EDGE[i]
E[x].append(y)
E[y].append(x)
OK[x]=1
OK[y]=1
# 木のHL分解+LCA
N=n+1
ROOT=1
QUE=[ROOT]
Parent=[-1]*(N+1)
Height=[-1]*(N+1)
Parent[ROOT]=N # ROOTの親を定めておく.
Height[ROOT]=0
Child=[[] for i in range(N+1)]
TOP_SORT=[] # トポロジカルソート
while QUE: # トポロジカルソートと同時に親を見つける
x=QUE.pop()
TOP_SORT.append(x)
for to in E[x]:
if Parent[to]==-1:
Parent[to]=x
Height[to]=Height[x]+1
Child[x].append(to)
QUE.append(to)
Children=[1]*(N+1)
for x in TOP_SORT[::-1]: #(自分を含む)子ノードの数を調べる
Children[Parent[x]]+=Children[x]
USE=[0]*N
Group=[i for i in range(N)]
for x in TOP_SORT: # HL分解によるグループ分け
USE[x]=1
MAX_children=0
select_node=0
for to in E[x]:
if USE[to]==0 and Children[to]>MAX_children:
select_node=to
MAX_children=Children[to]
for to in E[x]:
if USE[to]==0 and to==select_node:
Group[to]=Group[x]
def LCA(a,b): # HL分解を利用してLCAを求める
while Group[a]!=Group[b]:
if Children[Parent[Group[a]]]<Children[Parent[Group[b]]]:
a=Parent[Group[a]]
else:
b=Parent[Group[b]]
if Children[a]>Children[b]:
return a
else:
return b
Parents=[Parent]
for i in range(30):
X=[-1]*(N+1)
for i in range(N+1):
X[i]=Parents[-1][Parents[-1][i]]
Parents.append(X)
def LCA_mae(x,y):
while Height[x]>Height[y]+1:
for i in range(30):
k=Parents[i][x]
if k==-1 or k>=n or Height[k]<=Height[y]:
x=Parents[i-1][x]
break
return x
DOWN=[0]*(N+1)
score=0
for x,y in EDGE:
if OK[x]==1 and OK[y]==1:
if Parent[x]==y or Parent[y]==x:
continue
k=LCA(x,y)
if k==x:
DOWN[y]+=1
k=LCA_mae(y,x)
DOWN[k]-=1
elif k==y:
DOWN[x]+=1
k=LCA_mae(x,y)
DOWN[k]-=1
else:
score+=1
DOWN[x]+=1
DOWN[y]+=1
for x in TOP_SORT[1:]:
DOWN[x]+=DOWN[Parent[x]]
ANS=[0]*N
for i in range(N):
if OK[i]==1 and DOWN[i]==score:
ANS[i]=1
print("".join(map(str,ANS[1:N])))
|
Python
|
[
"graphs",
"trees"
] | 757
| 3,318
| 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
}
| 58
|
3b6814b6753f307ec6f3a68179274caa
|
Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all nodes for which v is the parent. A vertex is a leaf if it has no children.The rooted tree Serval owns has n nodes, node 1 is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation \max or \min written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively. Assume that there are k leaves in the tree. Serval wants to put integers 1, 2, \ldots, k to the k leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?
|
['dp', 'greedy', 'binary search', 'dfs and similar', 'trees']
|
import sys
n = int(input())
minmax = list(map(int, input().split()))
childs = [[] for i in range(n)]
for idx, father in enumerate(list(map(int,input().split()))):
childs[father-1].append(idx+1)
stack = []
stack.append(0)
ans = [None for ele in range(n)]
vis = [False for ele in range(n)]
while len(stack):
index = stack[-1]
if not vis[index]:
vis[index] = True
if len(childs[index]) == 0:
ans[index] = (0,1)
stack.pop()
else:
for child in childs[index]:
stack.append(child)
else:
stack.pop()
res = [ans[child] for child in childs[index]]
total = sum([ele[1] for ele in res])
if minmax[index] == 1:
ans[index] = min([ele[0] for ele in res]), total
else:
bigger_than = sum([ele[1] - ele[0] - 1 for ele in res])
ans[index] = total - bigger_than - 1, total
print(ans[0][1] - ans[0][0])
|
Python
|
[
"graphs",
"trees"
] | 1,226
| 960
| 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,278
|
f6e219176e846b16c5f52dee81601c8e
|
Hanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge. n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of n people can open it. For exampe, in the picture there are n=4 people and 5 chains. The first person knows passcodes of two chains: 1-4 and 1-2. The fridge 1 can be open by its owner (the person 1), also two people 2 and 4 (acting together) can open it. The weights of these fridges are a_1, a_2, \ldots, a_n. To make a steel chain connecting fridges u and v, you have to pay a_u + a_v dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly m steel chains so that all fridges are private. A fridge is private if and only if, among n people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge i is not private if there exists the person j (i \ne j) that the person j can open the fridge i.For example, in the picture all the fridges are private. On the other hand, if there are n=2 fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly m chains, and if yes, output any solution that minimizes the total cost.
|
['implementation', 'graphs']
|
t=int(input())
while t>0:
n,m =map(int,input().split())
a=[int(x) for x in input().split()]
if(n==2):
print(-1)
elif(n>m):
print(-1)
else:
print(2*sum(a))
for _ in range(0,n):
print(_+1,(_+1)%n+1)
t-=1
|
Python
|
[
"graphs"
] | 1,950
| 218
| 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,926
|
7f9853be7ac857bb3c4eb17e554ad3f1
|
You are given a keyboard that consists of 26 keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word s on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions 8, 5, 12 and 15, respectively. Therefore, it will take |5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13 units of time to type the word "hello". Determine how long it will take to print the word s.
|
['implementation', 'strings']
|
t = int(input())
for j in range(t):
letters = str(input())
s = str(input())
dictiony = {}
calculating = []
word = []
sum = 0
for m in s:
word.append(m)
for i in letters:
dictiony[i] = letters.index(i)
for k in word:
calculating.append(dictiony.get(k))
n = 0
while n != (len(word)-1) and len(s) > 0:
calc = abs(calculating[n + 1] - calculating[n])
sum += calc
n += 1
print(sum)
|
Python
|
[
"strings"
] | 1,129
| 495
| 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,213
|
82ff8ae62e39b8e64f9a273b736bf59e
|
The BFS algorithm is defined as follows. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new queue containing only vertex 1, mark the vertex 1 as used. Extract a vertex v from the head of the queue q. Print the index of vertex v. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. If the queue is not empty, continue from step 2. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.
|
['graphs', 'dfs and similar', 'trees', 'shortest paths']
|
from collections import deque
from sys import stdin
input = stdin.readline
class N:
def __init__(self, v) -> None:
self.c = []
self.v = v
if __name__ == '__main__':
n = int(input())
arr = [N(i + 1) for i in range(n)]
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
arr[x].c.append(arr[y])
arr[y].c.append(arr[x])
narr = list(map(int, input().split()))
q = deque()
s = {1}
v = set()
v.add(1)
good = True
for x in narr:
if x not in s:
good = False
break
s.remove(x)
ns = set()
for c in arr[x - 1].c:
if c.v not in v:
v.add(c.v)
ns.add(c.v)
if ns:
q.append(ns)
if not s:
if q:
s = q.popleft()
else:
s = set()
print('Yes' if good else 'No')
|
Python
|
[
"graphs",
"trees"
] | 979
| 959
| 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,583
|
94278e9c55f0fc82b48145ebecbc515f
|
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 recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.
|
['constructive algorithms', 'strings']
|
import sys
n = int(sys.stdin.readline())
s = 'abcd'
if n < 4:
print s[:n]
else:
print s * (n/4) + s[:n%4]
|
Python
|
[
"strings"
] | 1,233
| 116
| 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,269
|
7dd891cef0aa40cc1522ca4b37963b92
|
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
|
['geometry', 'bitmasks', 'brute force']
|
from collections import Counter
MV = 400020
a = [0] * MV
for i in range(MV):
a[i] = set()
n ,m = list(map(int , input().split()))
first = list(map(int , input().split()))
second = list(map(int , input().split()))
for fid, f in enumerate(first):
for sid, s in enumerate(second):
a[f+s].add(fid + MV)
a[f+s].add(sid)
a.sort(key = lambda x: -len(x))
b = [len(k) for k in a]
# for k in range(MV):
# if b[k]>0:
# print(k, b[k], a[k])
best_res = b[0]
for pos in range(MV):
for pos2 in range(MV):
if b[pos] + b [pos2] <= best_res:
break
cur = len(a[pos].union(a[pos2]))
if cur > best_res :
best_res = cur
print(best_res)
|
Python
|
[
"geometry"
] | 1,036
| 709
| 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,518
|
5e73099c7ec0b82aee54f0841c00f15e
|
"Duel!"Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.There are n cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly k consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these n cards face the same direction after one's move, the one who takes this move will win.Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.
|
['greedy', 'games', 'brute force']
|
import sys
import copy
input = sys.stdin.readline
n,k=map(int,raw_input().split())
C=list(raw_input().strip())
def JUDGE(C):
ANS_one=0
ANS_zero=0
for c in C:
if c=="0":
ANS_zero+=1
else:
break
for c in C[::-1]:
if c=="0":
ANS_zero+=1
else:
break
for c in C:
if c=="1":
ANS_one+=1
else:
break
for c in C[::-1]:
if c=="1":
ANS_one+=1
else:
break
if ANS_zero>=n-k or ANS_one>=n-k:
return 1
else:
return 0
if JUDGE(C)==1:
print("tokitsukaze")
sys.exit()
if k>=n-1:
print("quailty")
sys.exit()
if k<n/2:
print("once again")
sys.exit()
CAN1=copy.copy(C)
CAN2=copy.copy(C)
if C[0]=="0":
for i in range(1,k+1):
CAN1[i]="1"
else:
for i in range(1,k+1):
CAN1[i]="0"
if C[-1]=="0":
for i in range(n-1,n-k-1,-1):
CAN2[i]="1"
else:
for i in range(n-2,n-k-2,-1):
CAN2[i]="0"
if JUDGE(CAN1)==1 and JUDGE(CAN2)==1:
print("quailty")
sys.exit()
else:
print("once again")
sys.exit()
|
Python
|
[
"games"
] | 773
| 1,159
| 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
}
| 73
|
85b78251160db9d7ca1786e90e5d6f21
|
Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.
|
['probabilities', 'implementation', 'trees', 'math']
|
n = input()
edge = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, raw_input().split())
edge[a - 1].append(b - 1)
edge[b - 1].append(a - 1)
d = [0] * n
d[0] = 1
p = [0]
for u in p:
for v in edge[u]:
if not d[v]:
d[v] = d[u] + 1
p.append(v)
print sum((1. / x for x in d))
|
Python
|
[
"math",
"probabilities",
"trees"
] | 684
| 332
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 1
}
| 1,778
|
2ebfcb54231d115a4aa9e5fc52b4ebe7
|
Suppose you have a special x-y-counter. This counter can store some value as a decimal number; at first, the counter has value 0. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either x or y to its value. So all sequences this counter generates are starting from 0. For example, a 4-2-counter can act as follows: it prints 0, and adds 4 to its value, so the current value is 4, and the output is 0; it prints 4, and adds 4 to its value, so the current value is 8, and the output is 04; it prints 8, and adds 4 to its value, so the current value is 12, and the output is 048; it prints 2, and adds 2 to its value, so the current value is 14, and the output is 0482; it prints 4, and adds 4 to its value, so the current value is 18, and the output is 04824. This is only one of the possible outputs; for example, the same counter could generate 0246802468024 as the output, if we chose to add 2 during each step.You wrote down a printed sequence from one of such x-y-counters. But the sequence was corrupted and several elements from the sequence could be erased.Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string s — the remaining data of the sequence. For all 0 \le x, y < 10, calculate the minimum number of digits you have to insert in the string s to make it a possible output of the x-y-counter. Note that you can't change the order of digits in string s or erase any of them; only insertions are allowed.
|
['dp', 'brute force', 'shortest paths']
|
dist = []
for i in range(10):
t = []
for j in range(10):
t.append([32]*10)
dist.append(t)
for i in range(10):
for j in range(10):
row = dist[i][j]
for a in range(10):
for b in range(10):
val = ( a*i + b*j )%10
s = a+b
if s > 0 and s<row[val]:
row[val] = s
for k in range(10):
if row[k] == 32:
row[k] = -1
else:
row[k] -= 1
# for i in range(10):
# for j in range(10):
# print(i,j,dist[i][j])
import sys
d = [int(i) for i in input()]
data = [(d[i+1] - d[i])%10 for i in range(len(d) - 1)]
#offs = 1 - len(data)
#print(data)
cnt = [0]*10
for d in data:
cnt[d] += 1
for i in range(10):
for j in range(10):
ans = 0
for c in range(10):
inc = dist[i][j][c]
if inc == -1 and cnt[c] > 0:
ans = -1
break
ans += inc * cnt[c]
# for d in data:
# inc = dist[i][j][d]
# #print(d, inc, end='#######\n')
# if inc == -1:
# ans = -1
# break
# else:
# ans += inc
sys.stdout.write(str(ans) + ' ')
#print(ans - offs , end=" ")
sys.stdout.write("\n")
|
Python
|
[
"graphs"
] | 1,770
| 1,364
| 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
}
| 748
|
6744d8bcba9ef2853788ca7168b76373
|
In Morse code, an letter of English alphabet is represented as a string of some length from 1 to 4. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".Because there are 2^1+2^2+2^3+2^4 = 30 strings with length 1 to 4 containing only "0" and/or "1", not all of them correspond to one of the 26 English letters. In particular, each string of "0" and/or "1" of length at most 4 translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".You will work with a string S, which is initially empty. For m times, either a dot or a dash will be appended to S, one at a time. Your task is to find and report, after each of these modifications to string S, the number of non-empty sequences of English letters that are represented with some substring of S in Morse code.Since the answers can be incredibly tremendous, print them modulo 10^9 + 7.
|
['dp', 'hashing', 'string suffix structures', 'sortings', 'data structures', 'binary search', 'strings']
|
import os, sys
nums = list(map(int, os.read(0, os.fstat(0).st_size).split()))
MOD = 10 ** 9 + 7
BAD = ([0, 0, 1, 1], [0, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1])
def zfunc(s):
z = [0] * len(s)
l = r = 0
for i in range(1, len(s)):
if i <= r:
z[i] = min(r - i + 1, z[i - l])
while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] - 1 > r:
l, r = i, i + z[i] - 1
return z
n = nums[0]
s = []
sm = 0
ans = []
for i in range(1, n + 1):
s.append(nums[i])
cur = 0
f = [0] * (i + 1)
sum4 = f[i] = 1
for j in range(i - 1, -1, -1):
if j + 4 < i:
sum4 -= f[j + 5]
if j + 4 <= i and s[j : j + 4] in BAD:
f[j] -= f[j + 4]
f[j] = (f[j] + sum4) % MOD
sum4 += f[j]
z = zfunc(s[::-1])
new = i - max(z)
sm = (sm + sum(f[:new])) % MOD
ans.append(sm)
print(*ans, sep='\n')
|
Python
|
[
"strings"
] | 1,125
| 939
| 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,841
|
9336bfed41e9b277bdfa157467066078
|
n people live on the coordinate line, the i-th one lives at the point x_i (1 \le i \le n). They want to choose a position x_0 to meet. The i-th person will spend |x_i - x_0| minutes to get to the meeting place. Also, the i-th person needs t_i minutes to get dressed, so in total he or she needs t_i + |x_i - x_0| minutes. Here |y| denotes the absolute value of y.These people ask you to find a position x_0 that minimizes the time in which all n people can gather at the meeting place.
|
['binary search', 'geometry', 'greedy', 'implementation', 'math', 'ternary search']
|
import math
def balanced(m,l):
leftMax = float("-inf")
rightMax = float("-inf")
for i in l:
if i>m:
rightMax = max(max(l[i]) + i-m,rightMax)
elif i<m:
leftMax = max(max(l[i]) + m-i,leftMax)
return rightMax-leftMax
for k in range(int(input())):
n = int(input())
x = list(map(int,input().split()))
t = list(map(int,input().split()))
l = {}
for i in range(n):
l[x[i]] = []
for i in range(n):
l[x[i]].append(t[i])
qleft = min(x)
qright = max(x)
prev_mid = -1
while qleft<=qright:
m = qleft + (qright-qleft)/2
if prev_mid != -1 and math.fabs(m-prev_mid)<0.0005:
print("%.2f"%m)
break
if balanced(qleft,l)==0:
print(qleft)
break
if balanced(qright,l)==0:
print(qright)
break
b = balanced(m,l)
if b==0:
print("%.2f"%m)
break
if b<0:
qright = m
prev_mid = m
else:
qleft = m
prev_mid = m
|
Python
|
[
"math",
"geometry"
] | 570
| 1,240
| 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,012
|
ce3f65acc33d624ed977e1d8f3494597
|
You are given a directed acyclic graph with n vertices and m edges. For all edges a \to b in the graph, a < b holds.You need to find the number of pairs of vertices x, y, such that x > y and after adding the edge x \to y to the graph, it has a Hamiltonian path.
|
['dfs and similar', 'dp', 'graphs']
|
import io,os,sys
read = io.BytesIO(os.read(0, os.fstat(0).st_size))
I = lambda:map(int, read.readline().split())
import time
#I = lambda:map(int, sys.stdin.readline().split())
t, = I()
for _ in range(t):
n, m = I()
# if n > 100:
# print(time.time())
to = [[] for i in range(n)]
fro = [[] for i in range(n)]
for i in range(m):
a, b = I()
a -= 1
b -= 1
to[b].append(a)
fro[a].append(b)
# if n > 100:
# print(time.time())
for i in range(n):
to[i].sort()
fro[i].sort()
# if n > 100:
# print(time.time())
first = None
last = None
for i in range(n - 1):
if len(fro[i]) == 0 or fro[i][0] != i + 1:
if first is None:
first = i
last = i
if first is None:
print(n * (n - 1) // 2)
continue
# if n > 100:
# print(time.time())
y = first
i = first + 1
blue = {y}
red = set()
ruse = []
buse = []
if first == last:
buse.append(y)
while i < n - 1:
#print(i, red, blue)
i += 1
if len(to[i]) == 0:
blue = red = set()
break
if to[i][-1] != i - 1:
newr = set()
newb = set()
else:
newr = red
newb = blue
for guy in to[i]:
if guy < i - 1 and guy in blue:
newr.add(i - 1)
if guy < i - 1 and guy in red:
newb.add(i - 1)
blue = newb
red = newr
if i > last:
if i - 1 in blue:
buse.append(i - 1)
if i - 1 in red:
ruse.append(i - 1)
if len(blue) > 0:
ruse.append(n - 1)
if len(red) > 0:
buse.append(n - 1)
# if n > 100:
# print(time.time())
# print(i, red, blue)
# print(ruse, buse)
i = y
blue = set()
red = {y + 1}
ruse1 = []
buse1 = []
ruse1.append(y + 1)
while i > 0:
i -= 1
if len(fro[i]) == 0:
blue = red = set()
break
if fro[i][0] != i + 1:
newr = set()
newb = set()
else:
newr = red
newb = blue
for guy in fro[i]:
if guy > y + 1:
break
if guy > i + 1 and guy in blue:
newr.add(i + 1)
if guy > i + 1 and guy in red:
newb.add(i + 1)
blue = newb
red = newr
if i + 1 in blue:
buse1.append(i + 1)
if i + 1 in red:
ruse1.append(i + 1)
if len(blue) > 0:
ruse1.append(0)
if len(red) > 0:
buse1.append(0)
# print(ruse1, buse1)
# if n > 100:
# print(time.time())
ruse = set(ruse)
buse = set(buse)
ruse1 = set(ruse1)
buse1 = set(buse1)
both = ruse & buse
both1 = ruse1 & buse1
ruse -= both
buse -= both
ruse1 -= both1
buse1 -= both1
# print(ruse, buse, both, ruse1, buse1, both1)
x = len(ruse1) * (len(both) + len(buse)) + len(buse1) * (len(both) + len(ruse)) + len(both1) * (len(both) + len(ruse) + len(buse))
# print(x)
if first == last:
x -= 1
if y in ruse1 or y in both1:
x -= 1
if y + 1 in buse or y + 1 in both:
x -= 1
print(x)
# if n > 100:
# print(time.time())
# exit()
|
Python
|
[
"graphs"
] | 316
| 2,844
| 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,620
|
206a9a83a1d143a1a8d8d3a7512f59e2
|
To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way:Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any k consecutive lights contain more than one turned on light, then the device finishes working.William doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.
|
['combinatorics', 'dp', 'math', 'probabilities']
|
import os, sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter
from bisect import bisect_left, bisect_right
from heapq import heappush, heappop
from functools import lru_cache
from itertools import accumulate
import math
import sys
# sys.setrecursionlimit(10 ** 6)
# 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")
# # sys.setrecursionlimit(800)
ii = lambda: int(input())
mii = lambda: map(int, input().split())
fii = lambda: map(float, input().split())
lmii = lambda: list(map(int, input().split()))
i2c = lambda n: chr(ord('a') + n)
c2i = lambda c: ord(c) - ord('a')
mod = 10 ** 9 + 7
def rev(n, mod=10 ** 9 + 7):
r = 1
while n > 1:
b = mod // n
n = n * (b + 1) - mod
r *= b + 1
r %= mod
return r
def solve():
n, k = mii()
T, F = 1, 1
res = 0
for p in range(1, n):
if k * (p - 1) + 1 > n:
break
T = T * (n - p + 1) % mod
if p == 1:
F = n
else:
for i in range(n - (k - 1) * (p - 2), n - (k - 1) * (p - 1), -1):
F = (F * rev(i)) % mod
for i in range(n - (k - 1) * (p - 2) - p + 1, n - (k - 1) * (p - 1) - p, -1):
F = (F * i) % mod
# for i in range(n - (k - 1) * (p - 1), n - (k - 1) * (p - 1) - p, -1):
# F = (F * i) % mod
res += F * rev(T) % mod
res %= mod
print(res + 1)
for _ in range(ii()):
solve()
|
Python
|
[
"math",
"probabilities"
] | 720
| 3,195
| 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,132
|
679f7243fe1e072af826a779c44b5056
|
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
|
['number theory', 'bitmasks', 'math']
|
n = int(input())
B = list(map(int, input().split()))
A = []
for i in range(100):
A.append([])
for i in B:
x = i
c = 0
while x % 2 == 0:
x //= 2
c += 1
A[c].append(i)
mlen = 0
f = 1
for lst in A:
mlen = max(mlen, len(lst))
ans = []
for lst in A:
if len(lst) == mlen and f:
f = 0
else:
for x in lst:
ans.append(x)
print(len(ans))
print(' '.join(list(map(str, ans))))
|
Python
|
[
"math",
"number theory"
] | 1,104
| 441
| 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,590
|
edd556d60de89587f1b8daa893538530
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
['implementation', 'strings']
|
n, m = map(int, raw_input().split())
a = dict()
for i in xrange(m):
s1, s2 = raw_input().split()
if len(s2) < len(s1):
a[s1] = s2
else:
a[s1] = s1
for s in raw_input().split():
print a[s],
|
Python
|
[
"strings"
] | 1,035
| 255
| 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,841
|
259e39c9e63e43678e596c0d8c66937c
|
Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is P. Gregor wants to find two bases of P. Formally, Gregor is looking for two integers a and b which satisfy both of the following properties. P \bmod a = P \bmod b, where x \bmod y denotes the remainder when x is divided by y, and 2 \le a < b \le P. Help Gregor find two bases of his favorite prime number!
|
['math', 'number theory']
|
for _ in range(int(input())):
print(2,int(input())-1,sep=" ")
|
Python
|
[
"math",
"number theory"
] | 550
| 66
| 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,971
|
fb46e7a175719eabd9f82a116bccd678
|
Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.Roger can move his arm in two different ways: He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray. In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated. He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint. In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A. Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.
|
['data structures', 'geometry']
|
from cmath import rect
import sys
import math
from functools import reduce
class SegmentTree():
def __init__(self, L, function = lambda x,y: x+y):
self.function = function
N = self.size = len(L)
M = 1 << N.bit_length()
self.margin = 2*M - N
self.L = [None for i in range(self.margin)] + L
for i in range(M-1, 0, -1):
x, y = self.L[i<<1], self.L[i<<1|1]
self.L[i] = None if x is None or y is None else function(x, y)
def modify(self, pos, value):
p = pos + self.margin
self.L[p] = value
while p > 1:
x, y = self.L[p], self.L[p^1]
if p&1: x, y = y, x
self.L[p>>1] = None if x is None or y is None else self.function(x, y)
p>>=1
def query(self, left, right):
l, r = left + self.margin, right + self.margin
stack = []
void = True
while l < r:
if l&1:
if void:
result = self.L[l]
void = False
else:
result = self.function(result, self.L[l])
l+=1
if r&1:
r-=1
stack.append(self.L[r])
l>>=1
r>>=1
init = stack.pop() if void else result
return reduce(self.function, reversed(stack), init)
def degrect(r, phi):
return rect(r, math.radians(phi))
def vsum(u, v): #u = (x + y*1j, phi)
return (u[0] + v[0]*degrect(1, u[1]), (u[1] + v[1])%360)
def solve(f):
n, m = [int(x) for x in f.readline().split()]
segments = [[1,0] for i in range(n)]
arm = SegmentTree([(1,0) for i in range(n)], vsum)
for line in f:
q, i, a = [int(x) for x in line.split()]
if q == 1:
segments[i-1][0] += a
else:
segments[i-1][1] -= a
arm.modify(i-1, (degrect(segments[i-1][0], segments[i-1][1]), segments[i-1][1]))
query = arm.query(0,n)[0]
print(query.real, query.imag)
solve(sys.stdin)
|
Python
|
[
"geometry"
] | 1,823
| 2,043
| 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,492
|
5ae6585bf96e0bff343bb76c1af3ebc2
|
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either: Remove a single cow from a chosen non-empty pile. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.
|
['games', 'math']
|
def grundy(n, k):
if k % 2 == 0:
if n <= 2:
return n
else:
return n % 2 == 0
else:
if n <= 4:
return [0, 1, 0, 1, 2][n]
elif n % 2 == 1:
return 0
else:
return 2 if grundy(n // 2, k) == 1 else 1
if __name__ == "__main__":
n, k = map(int, input().split())
xList = map(int, input().split())
res = 0
for x in xList:
res ^= grundy(x, k)
print("Kevin" if res else "Nicky")
|
Python
|
[
"math",
"games"
] | 674
| 506
| 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,932
|
712bef1b0f737cb9c2b35a96498d50bc
|
This problem is interactive.We have hidden an array a of n pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of k different elements of the array, it will return the position and value of the m-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember k, but don't remember m. Your task is to find m using queries to this device. You can ask not more than n queries.Note that the array a and number m are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array a. You just have to guess m.
|
['math', 'constructive algorithms', 'sortings', 'interactive']
|
import sys
n, k = map(int, input().split())
k1 = 0
k2 = 0
b1 = 0
b2 = 0
for i in range(k + 1):
print('?', end=' ')
for j in range(k + 1):
if i != j:
print(j + 1, end=' ')
sys.stdout.flush()
a, x = map(int, input().split())
if i == 0:
b1 = x
if x == b1:
k1 += 1
else:
b2 = x
k2 += 1
if b1 > b2:
print('!', k1)
else:
print('!', k2)
sys.stdout.flush()
|
Python
|
[
"math"
] | 988
| 437
| 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
}
| 1,107
|
9f019c3898f27d687c5b3498586644e8
|
Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle: its vertices have integer coordinates, the coordinates of vertices are non-negative, and its vertices are not on a single line. He calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from at least one point of the line y = 0 walking along some straight line, without crossing the interior of the triangle. In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct. Find the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.
|
['geometry']
|
n=int(input(""))
k=0
ne=[]
for i in range(n):
d=0
a=input("")
b=input("")
c=input("")
a=a.split()
b=b.split()
c=c.split()
l=[a,b,c]
if int(a[1])==int(b[1]) and int(c[1])<int(a[1]):
d=d+int(a[0])-int(b[0])
if int(b[1])==int(c[1]) and int(a[1])<int(c[1]):
d=d+int(b[0])-int(c[0])
if int(a[1])==int(c[1]) and int(b[1])<int(a[1]):
d=d+int(a[0])-int(c[0])
ne.append((d**2)**(1/2))
for j in ne:
print(j)
|
Python
|
[
"geometry"
] | 874
| 505
| 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,558
|
5179d7554a08d713da7597db41f0ed43
|
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree — a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.Each vertex v is assigned its beauty x_v — a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, \dots, t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.Your task is to find the sum \sum_{u\text{ is an ancestor of }v} f(u, v). As the result might be too large, please output it modulo 10^9 + 7.Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
|
['dp', 'graphs', 'number theory', 'math', 'data structures', 'binary search', 'dfs and similar', 'trees']
|
from __future__ import division, print_function
from collections import deque
def main():
def gcd(a,b):
if a<b:
a,b=b,a
while b:
a,b=b,a%b
return a
n=int(input())
val=list(map(int,input().split()))
gcds=[ {} for _ in range(n) ]
edges={}
for i in range(n-1):
u,v=map(int,input().split())
if u not in edges:
edges[u]=[v]
else :
edges[u].append(v)
if v not in edges:
edges[v]=[u]
else :
edges[v].append(u)
visited=[0]*n
q=deque()
q.append(1)
visited[0]=1
mod=10**9+7
result=0
while q:
u=q.popleft()
x=val[u-1]
if x not in gcds[u-1]:
gcds[u-1][x]=1
else :
gcds[u-1][x]+=1
for k in gcds[u-1]:
result=(result+gcds[u-1][k]*k)%mod
for v in edges[u]:
if visited[v-1]==0:
temp=val[v-1]
for item in gcds[u-1]:
a=gcd(item,temp)
if a not in gcds[v-1]:
gcds[v-1][a]=gcds[u-1][item]
else :
gcds[v-1][a]+=gcds[u-1][item]
visited[v-1]=1
q.append(v)
print(result)
######## Python 2 and 3 footer by Pajenegod and c1729
# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.
# So on cf, use PyPy2 for best string performance.
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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')
# Cout implemented in Python
import sys
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'0' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main()
|
Python
|
[
"graphs",
"math",
"number theory",
"trees"
] | 1,460
| 4,255
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 1
|
{
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 1
}
| 4,031
|
f8d064c90f1f2b4a18386795dbcd9cb9
|
You are given an integer n (n > 1).Your task is to find a sequence of integers a_1, a_2, \ldots, a_k such that: each a_i is strictly greater than 1; a_1 \cdot a_2 \cdot \ldots \cdot a_k = n (i. e. the product of this sequence is n); a_{i + 1} is divisible by a_i for each i from 1 to k-1; k is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer n > 1.You have to answer t independent test cases.
|
['constructive algorithms', 'number theory', 'math']
|
def decompose(number):
prime_factors = []
while number % 2 == 0:
prime_factors.append(2)
number = number / 2
for i in range(3, int(number**(1/2)) + 1, 2):
while number % i == 0:
prime_factors.append(int(i))
number = number / i
if number > 2:
prime_factors.append(int(number))
return prime_factors
def check_double(A):
S = set(A)
my_dict = {x: A.count(x) for x in S if A.count(x)>1}
try:
return max(my_dict.keys(), key=(lambda k: my_dict[k]))
except ValueError:
return False
def prod(L):
result = 1
for x in L:
result *= x
return result
for _ in range(int(input())):
n = int(input())
prems = decompose(n)
comp = check_double(prems)
if comp == False:
print(1, n, sep='\n')
else:
remainder = int(comp*prod([prem for prem in prems if prem != comp]))
count = prems.count(comp)
print(count, end='\n')
for k in range(count-1):
print(comp, end=' ')
print(remainder, end='\n')
|
Python
|
[
"number theory",
"math"
] | 670
| 1,079
| 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,698
|
2508a347f02aa0f49e0d154c54879b13
|
You are given an array of integers a_1, a_2, \ldots, a_n.You can do the following operation any number of times (possibly zero): Choose any index i and set a_i to any integer (positive, negative or 0). What is the minimum number of operations needed to turn a into an arithmetic progression? The array a is an arithmetic progression if a_{i+1}-a_i=a_i-a_{i-1} for any 2 \leq i \leq n-1.
|
['brute force', 'data structures', 'graphs', 'math']
|
import sys
input=sys.stdin.readline
from collections import defaultdict,deque
from heapq import heappush,heappop
from functools import lru_cache
import time
from math import gcd
def lcm(x, y):
return int(x * y / gcd(x, y))
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# for _ in range(int(input())):
# n = int(input())
# nums = list(map(int,input().split(' ')))
# nums.sort()
# print(nums[-1]+nums[-2])
# for _ in range(int(input())):
# s = input()
# n = len(s)
# nums = list(s)
# d = defaultdict(list)
# for i,j in enumerate(nums):
# d[j].append(i)
# ans = 10**9
# for i in range(97,123):
# if len(d[chr(i)]) >= 1:
# ans = min(ans,d[chr(i)][-1])
# print(s[ans:])
# for _ in range(int(input())):
# n = int(input())
# nums = list(map(int,input().split(' ')))
# nums.sort()
# total = sum(nums)
# q = SortedList()
# q.add(total)
# while q and nums and q[-1] >= nums[-1]:
# while q and nums and q[-1] == nums[-1]:
# q.pop()
# nums.pop()
# if q:
# t = q.pop()
# a,b = t//2,t-t//2
# q.add(a)
# q.add(b)
# if not nums:
# print('YES')
# else:
# print('NO')
# for _ in range(int(input())):
# n = int(input())
# deg = [0]*(n+1)
# d = defaultdict(list)
# for _ in range(n-1):
# i,j,x,y = list(map(int,input().split(' ')))
# d[i].append((j,x,y))
# d[j].append((i,y,x))
# deg[i] += 1
# deg[j] += 1
# # print(deg)
# degg = SortedList([(deg[i],i) for i in range(1,n+1)])
# vis = set()
# ans = [1]*(n+1)
# q = deque()
# for i,j in degg:
# if i == 1:
# q.append(j)
# # while degg and n >= 1:
# # i = degg[0][1]
# while q:
# i = q.popleft()
# vis.add(i)
# for idx in d[i]:
# if idx[0] not in vis:
# j,x,y = idx
# r = gcd(x,y)
# x,y = x//r,y//r
# a,b = ans[i],ans[j]
# c = lcm(a,b)
# x1,y1 = c*x,c*y
# xm,ym = x1//a,y1//b
# r1 = gcd(xm,ym)
# # r1 = gcd(x1,y1)
# x1,y1 = x1//r1,y1//r1
# x2,y2 = x1//a,y1//b
# print(i,j,x,y,a,b,x2,y2)
# print('vis',vis)
# print(d[i],d[j])
# for k in d[i]:
# # print(k)
# if k[0] in vis:
# ans[k[0]] *= x2
# for k in d[j]:
# # print(k)
# if k[0] in vis and k[0] != i:
# ans[k[0]] *= y2
# ans[i] *= x2
# ans[j] *= y2
# print('ans',ans)
# n -= 1
# deg[i] -= 1
# # degg.pop(0)
# # degg.remove((deg[j],j))
# deg[j] -= 1
# if deg[j] == 1:
# q.append(j)
# # if deg[j] > 0:
# # degg.add((deg[j],j))
# print(ans)
n = int(input())
a = list(map(int,input().split(' ')))
ans = 0
K = 317**3
dic = [0]*K*2
for d in range(-317,317):
for i in range(n):
ai = a[i]-i*d+K
dic[ai] += 1
ans = max(ans,dic[ai])
for i in range(n):
ai = a[i]-i*d+K
dic[ai] = 0
for i in range(n):
for j in range(i+1,min(n,i+317)):
da = a[j] - a[i]
dx = j - i
if da % dx != 0:
continue
d = da//dx
dic[d] += 1
ans = max(ans,dic[d]+1)
for j in range(i+1,min(n,i+317)):
da = a[j] - a[i]
dx = j - i
d = da//dx
dic[d] = 0
print(n-ans)
|
Python
|
[
"graphs",
"math"
] | 436
| 11,544
| 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,257
|
d8a5578de51d6585d434516da6222204
|
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rotate, translate or shorten their edges as much as he wants.For both hoops, you are given the number of their vertices, as well as the position of each vertex, defined by the X , Y and Z coordinates. The vertices are given in the order they're connected: the 1st vertex is connected to the 2nd, which is connected to the 3rd, etc., and the last vertex is connected to the first one. Two hoops are connected if it's impossible to pull them to infinity in different directions by manipulating their edges, without having their edges or vertices intersect at any point – just like when two links of a chain are connected. The polygons' edges do not intersect or overlap. To make things easier, we say that two polygons are well-connected, if the edges of one polygon cross the area of the other polygon in two different directions (from the upper and lower sides of the plane defined by that polygon) a different number of times.Cowboy Beblop is fascinated with the hoops he has obtained and he would like to know whether they are well-connected or not. Since he’s busy playing with his dog, Zwei, he’d like you to figure it out for him. He promised you some sweets if you help him!
|
['geometry']
|
from math import gcd, sqrt
from functools import reduce
import sys
input = sys.stdin.readline
EPS = 0.000000001
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def GCD(args):
return reduce(gcd, args)
def plane_value(plane, point):
A, B, C, D = plane
x, y, z = point
return A*x + B*y + C*z + D
def plane(p1, p2, p3):
x1, y1, z1 = p1
x2, y2, z2 = p2
x3, y3, z3 = p3
a1, b1, c1 = x2 - x1, y2 - y1, z2 - z1
a2, b2, c2 = x3 - x1, y3 - y1, z3 - z1
a, b, c = b1 * c2 - b2 * c1, a2 * c1 - a1 * c2, a1 * b2 - b1 * a2
d = (- a * x1 - b * y1 - c * z1)
g = GCD([a,b,c,d])
return a//g, b//g, c//g, d//g
def cross(a, b):
return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])
def intersection_of_two_planes(p1, p2):
A1, B1, C1, D1 = p1
A2, B2, C2, D2 = p2
crossprod = cross([A1,B1,C1],[A2,B2,C2])
if (A1*B2-A2*B1) != 0:
x = ((B1*D2-B2*D1)/(A1*B2-A2*B1), crossprod[0])
y = ((A2*D1-A1*D2)/(A1*B2-A2*B1), crossprod[1])
z = (0,crossprod[2])
elif (B1*C2-B2*C1) != 0:
x = (0,crossprod[0])
y = ((C1*D2-C2*D1)/(B1*C2-B2*C1), crossprod[1])
z = ((B2*D1-B1*D2)/(B1*C2-B2*C1), crossprod[2])
elif (A1*C2-A2*C1) != 0:
x = ((C1*D2-C2*D1)/(A1*C2-A2*C1), crossprod[0])
y = (0,crossprod[1])
z = ((A2*D1-A1*D2)/(A1*C2-A2*C1), crossprod[2])
else:
return None
return x, y, z
def line_parametric(p1, p2):
x1, y1, z1 = p1
x2, y2, z2 = p2
return (x2,x1-x2), (y2,y1-y2), (z2,z1-z2)
def solve_2_by_2(row1, row2):
a1, b1, c1 = row1
a2, b2, c2 = row2
if a1*b2-b1*a2:
return (c1*b2-b1*c2)/(a1*b2-b1*a2), (a1*c2-c1*a2)/(a1*b2-b1*a2)
else:
return None
def sgn(x):
return 1 if x>0 else 0 if x==0 else -1
def lines_intersection_point(i1, i2):
x1, y1, z1 = i1
x2, y2, z2 = i2
try:
t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [y1[1], -y2[1], y2[0]-y1[0]])
if abs(t1*z1[1] - t2*z2[1] - z2[0] + z1[0]) < EPS:
return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
else:
return None
except:
try:
t1, t2 = solve_2_by_2([x1[1], -x2[1], x2[0]-x1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
if abs(t1*y1[1] - t2*y2[1] - y2[0] + y1[0]) < EPS:
return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
else:
return None
except:
try:
t1, t2 = solve_2_by_2([y1[1], -y2[1], y2[0]-y1[0]], [z1[1], -z2[1], z2[0]-z1[0]])
if abs(t1*x1[1] - t2*x2[1] - x2[0] + x1[0]) < EPS:
return (x1[0]+t1*x1[1], y1[0]+t1*y1[1], z1[0]+t1*z1[1]), t2
else:
return None
except:
return None
def foo(points):
down_cnt, up_cnt = 0, 0
first = points[0]
other = 1-first
down = True
intrusion = True
for p in points[1:]:
if p==first:
intrusion = not intrusion
else:
if intrusion:
if down:
down_cnt+=1
else:
up_cnt+=1
down = not down
return down_cnt==up_cnt
def populate(plane, poly, tag):
res = []
prev = plane_value(plane,poly[-1])
prev_serious = plane_value(plane,poly[-2]) if not prev else prev
p_prev = poly[-1]
for i in range(len(poly)+1):
p = poly[i%len(poly)]
curr = plane_value(plane,p)
if sgn(curr) == -sgn(prev_serious):
intersector = line_parametric(p_prev,p)
point, t = lines_intersection_point(intersector,intersectee)
res.append((t,tag))
prev_serious = curr
if sgn(curr):
prev_serious = curr
prev, p_prev = curr, p
return res
x_poly, y_poly = [], []
for _ in range(inp()):
x_poly.append(inlt())
for _ in range(inp()):
y_poly.append(inlt())
x_plane = plane(*x_poly[:3])
y_plane = plane(*y_poly[:3])
intersectee = intersection_of_two_planes(x_plane,y_plane)
if intersectee:
points = sorted(set(populate(y_plane,x_poly,0) + populate(x_plane,y_poly,1)))
points = [i[1] for i in points]
print('NO' if foo(points) else 'YES')
else:
print('NO')
|
Python
|
[
"geometry"
] | 1,498
| 4,344
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,613
|
a4563e6aea9126e20e7a33df664e3171
|
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.
|
['dfs and similar', 'trees', 'graphs']
|
import sys
from math import sqrt, gcd, ceil, log
# from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
# from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))
sys.setrecursionlimit(10**6)
def main():
n = int(input()); par = read()
adj = defaultdict(list)
for i in range(n-1):
adj[par[i]].append(i+2)
# print(adj)
lvl = [1]
ans = 0
while lvl:
ans += len(lvl)%2
lvl = [j for i in lvl for j in adj[i]]
print(ans)
if __name__ == "__main__":
main()
|
Python
|
[
"graphs",
"trees"
] | 1,321
| 585
| 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,999
|
b8bb5a361ce643f591c37d70336532c9
|
You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are three stones positioned on three distinct vertices. All stones are the same. With one move you can move the stone to another free vertex along some diagonal. The color of this diagonal must be the same as the color of the diagonal, connecting another two stones. Your goal is to move stones in such way that the only vertices occupied by stones are 1, 2 and 3. You must achieve such position using minimal number of moves. Write a program which plays this game in an optimal way.
|
['dp', 'implementation', 'graphs', 'shortest paths']
|
from collections import deque
__author__ = 'asmn'
n = int(input())
end = tuple(sorted(map(lambda x: int(x) - 1, input().split())))
st = (0, 1, 2)
mat = [input() for i in range(n)]
v = set([st])
path = {}
dist = {st: 0}
queue = deque([st])
while end not in v and len(queue) > 0:
p = queue.popleft()
for x in range(-2, 1):
p1, p2, p3 = p[x], p[x + 1], p[x + 2]
for i in range(n):
if i not in (p1, p2, p3) and mat[i][p3] == mat[p1][p2]:
np = tuple(sorted((p1, p2, i)))
if np not in v:
v.add(np)
queue.append(np)
path[np] = p
dist[np] = dist[p] + 1
def pathinfo(fr, to):
return str((set(fr) - set(to)).pop() + 1) + ' ' + str((set(to) - set(fr)).pop() + 1)
if end not in dist:
print(-1)
exit()
print(dist[end])
while end in path:
print(pathinfo(end, path[end]))
end = path[end]
|
Python
|
[
"graphs"
] | 799
| 950
| 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,472
|
b533572dd6d5fe7350589c7f4d5e1c8c
|
Ashishgup and FastestFinger play a game. They start with a number n and play in turns. In each turn, a player can make any one of the following moves: Divide n by any of its odd divisors greater than 1. Subtract 1 from n if n is greater than 1. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.
|
['number theory', 'games', 'math']
|
for t in range(int(input())):
n = int(input())
N = n
if n == 1:
winner = 2
elif n == 2 or n % 2 != 0:
winner = 1
else:
numTwo = 0
while n % 2 == 0:
n //= 2
numTwo += 1
numOdd = 0
for i in range(3, int(N ** 0.5 + 2), 2):
while n > 0 and n % i == 0:
n //= i
numOdd += 1
# print(n)
if n > 2:
numOdd += 1
if numOdd == 0 and numTwo > 1:
winner = 2
elif numOdd == 1 and numTwo == 1:
winner = 2
else:
winner = 1
if winner == 1:
print("Ashishgup")
else:
print("FastestFinger")
|
Python
|
[
"math",
"number theory",
"games"
] | 478
| 539
| 1
| 0
| 0
| 1
| 1
| 0
| 0
| 0
|
{
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,279
|
99f37936b243907bf4ac1822dc547a61
|
A telephone number is a sequence of exactly 11 digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string s becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
|
['implementation', 'greedy', 'games']
|
n=int(raw_input())
s=list(raw_input())
cnt=n-11
cntt=[0 for i in xrange(10)]
for i in xrange(n):
cntt[int(s[i])] += 1
if cntt[8] <= cnt/2:
print "NO"
else:
summ=0
for i in xrange(n):
if s[i] == "8":
summ += 1
s[i]='0'
if summ == cnt/2:
break
flag = -1
for i in xrange(0,cnt+1):
if s[i] == '8':
print "YES"
flag = 0
break
if flag == -1:
print "NO"
|
Python
|
[
"games"
] | 745
| 478
| 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,079
|
b4f8a6f5b1d1fa641514e10d18c316f7
|
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following: choose one kid x equiprobably among all n kids; choose some item y equiprobably among all k_x items kid x wants; choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot. If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
|
['combinatorics', 'probabilities', 'math']
|
# template begins
#####################################
# import libraries for input/ output handling
# on generic level
import atexit, io, sys
# A stream implementation using an in-memory bytes
# buffer. It inherits BufferedIOBase.
buffer = io.BytesIO()
sys.stdout = buffer
# print via here
@atexit.register
def write():
sys.__stdout__.write(buffer.getvalue())
n=input()
v=998244353
from fractions import Fraction as f
b=[]
k=[]
for _ in range(n):
c=map(int,raw_input().split())
b.append(c[0])
k.append(c[1:])
m={}
for j in range(n):
for i in k[j]:
if i in m:
m[i]+=1
else:
m[i]=1
s=f(0,1)
for j in range(n):
p=0
for i in k[j]:
p+=m[i]
s+=f(p,b[j])
c=s.denominator
c=c*((n*n)%v)%v
c=pow(c,v-2,v)
print (s.numerator*c)%v
|
Python
|
[
"math",
"probabilities"
] | 1,236
| 846
| 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
}
| 3,118
|
6db42771fdd582578194c7b69a4ef575
|
You are given a decimal representation of an integer x without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in x and replace them with their sum without leading zeros (if the sum is 0, it's represented as a single 0).For example, if x = 10057, the possible reductions are: choose the first and the second digits 1 and 0, replace them with 1+0=1; the result is 1057; choose the second and the third digits 0 and 0, replace them with 0+0=0; the result is also 1057; choose the third and the fourth digits 0 and 5, replace them with 0+5=5; the result is still 1057; choose the fourth and the fifth digits 5 and 7, replace them with 5+7=12; the result is 10012. What's the largest number that can be obtained?
|
['greedy', 'strings']
|
'''
# Submitted By [email protected]
Don't Copy This Code, Try To Solve It By Yourself
'''
# Problem Name = "Minor Reduction"
# Class: B
def Solve():
lst=[]
for t in range(int(input())):
n=input()[::-1]
lst.append(n)
for num in lst:
e=True
for i in range(len(num)-1):
z=int(num[i])+int(num[i+1])
if z > 9:
e=False
break
z=str(z)[::-1]
if e:
num=num[::-1]
print(str(int(num[0])+int(num[1]))+num[2:])
else:
ans=(num[:i]+z+num[i+2:])[::-1]
print(ans)
if __name__ == "__main__":
Solve()
|
Python
|
[
"strings"
] | 897
| 702
| 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,857
|
8ad06ac90b258a8233e2a1cf51f68078
|
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n.He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.The prefix of string s of length l (1 \le l \le n) is a string s[1..l].For example, for the string s="abba" there are two prefixes of the even length. The first is s[1\dots2]="ab" and the second s[1\dots4]="abba". Both of them have the same number of 'a' and 'b'.Your task is to calculate the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.
|
['strings']
|
n,a,b=int(input()),0,0
s=input()
tot = 0
l=list(s)
for i in range(len(s)):
if s[i] == 'a':a+=1
else:b+=1
# print(s[i],a,b)
if i&1:
tot+=1
if a>b:
a-=1
b+=1
# print(l)
l[i]='b'
# print(l,a,b,i)
elif b>a:
a+=1
b-=1
l[i]='a'
# print(l)
else:tot-=1
print(tot)
print(''.join(l))
|
Python
|
[
"strings"
] | 1,086
| 429
| 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,674
|
8b61213e2ce76b938aa68ffd1e4c1429
|
The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = ki·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1 < x2. In other words, is it true that there are 1 ≤ i < j ≤ n and x', y', such that: y' = ki * x' + bi, that is, point (x', y') belongs to the line number i; y' = kj * x' + bj, that is, point (x', y') belongs to the line number j; x1 < x' < x2, that is, point (x', y') lies inside the strip bounded by x1 < x2. You can't leave Anton in trouble, can you? Write a program that solves the given task.
|
['sortings', 'geometry']
|
# -*- coding: utf-8 -*-
from operator import itemgetter
n = int(raw_input())
x1, x2 = map(int, raw_input().split(' '))
x1 += 0.0000001
x2 -= 0.0000001
k = []
b = []
positive = False
starts, ends = [], []
for i in xrange(n):
new_k, new_b = map(int, raw_input().split(' '))
starts.append({
'index': i,
'value': new_k * x1 + new_b
})
ends.append({
'index': i,
'value': new_k * x2 + new_b
})
starts.sort(key=itemgetter('value'))
ends.sort(key=itemgetter('value'))
for i in xrange(n):
if starts[i]['index'] != ends[i]['index']:
print('YES')
break
else:
print('NO')
|
Python
|
[
"geometry"
] | 784
| 641
| 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,670
|
74713233dd60acfbc0b26cd3772ed223
|
We'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if , then . In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.Your task is to find any beautiful set, where the number of elements is equal to k and each element doesn't exceed 2k2.
|
['number theory', 'brute force']
|
import sys, math, random
k = int(sys.stdin.read().strip())
if k in [2169, 2198, 2301, 2302, 2303]:
random.seed(0x1337)
else:
random.seed(0x7831505)
res = set()
maxval = 2 * k * k
for p2 in range(0, 1+int(math.log(maxval, 2)) if k > 00 else 1):
for p3 in range(0, 1+int(math.log(maxval, 3)) if k > 00 else 1):
for p5 in range(0, 1+int(math.log(maxval, 5)) if k > 65 else 1):
for p7 in range(0, 1+int(math.log(maxval, 7)) if k > 406 else 1):
for p11 in range(0, 1+int(math.log(maxval, 11)) if k > 2034 else 1):
n = 2**p2
if n <= maxval: n *= 3**p3
if n <= maxval: n *= 5**p5
if n <= maxval: n *= 7**p7
if n <= maxval: n *= 11**p11
if n <= maxval:
if n not in res:
res.add(n)
res = list(res)
random.shuffle(res)
res = res[:k]
d11 = len(filter(lambda x: x % 11 == 0, res))
if 0 < d11 <= k/2:
i = 0
while i <= k/2 - d11:
n = 1
while n % 11:
n = random.choice(res)
n *= 11
if n not in res and n <= maxval:
res.remove(n/11)
res.append(n)
i += 1
#d2 = len(filter(lambda x: x % 2 == 0, res))
#d3 = len(filter(lambda x: x % 3 == 0, res))
#d5 = len(filter(lambda x: x % 5 == 0, res))
#d7 = len(filter(lambda x: x % 7 == 0, res))
#d11 = len(filter(lambda x: x % 11 == 0, res))
#if (d2 == 0 or d2 >= k/2) and (d3 == 0 or d3 >= k/2) and (d5 == 0 or d5 >= k/2) and (d7 == 0 or d7 >= k/2) and (d11== 0 or d11>= k/2) and len(res) == k:
# print 'OK', k
#else:
# print 'FAIL AT ', k
res = ' '.join(map(str, sorted(res)))
sys.stdout.write(str(res))
|
Python
|
[
"number theory"
] | 364
| 1,688
| 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
}
| 2,443
|
47a9d72651f1407de89e28fb4b142367
|
This is an easier version of the problem. In this version, n \le 2000.There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.You'd like to remove all n points using a sequence of \frac{n}{2} snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if \min(x_a, x_b) \le x_c \le \max(x_a, x_b), \min(y_a, y_b) \le y_c \le \max(y_a, y_b), and \min(z_a, z_b) \le z_c \le \max(z_a, z_b). Note that the bounding box might be degenerate. Find a way to remove all points in \frac{n}{2} snaps.
|
['constructive algorithms', 'geometry', 'greedy']
|
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
#from __future__ import print_function, division #while using python2
import math
def modinv(n,p):
return pow(n,p-2,p)
def dist(x1, y1, z1, x2, y2, z2):
# return math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2)
return abs(x2 - x1) + abs(y2 - y1) + abs(z2 - z1)
def main():
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
n = int(input())
points = []
for i in range(n):
pts = [int(x) for x in input().split()]
pts.append(i)
points.append(pts)
answers = []
visited = [0] * (n+1)
# print(points)
for i in range(n):
if visited[i] == 1:
continue
min_d = 1e18
min_j = -1
x1, y1, z1, temp = points[i]
for j in range(i+1,n):
if visited[j] == 1:
continue
x2, y2, z2, temp2 = points[j]
if dist(x1, y1, z1, x2, y2, z2) < min_d:
min_d = dist(x1, y1, z1, x2, y2, z2)
min_j = j
if min_j != -1:
answers.append([points[i][-1], points[min_j][-1]])
visited[points[i][-1]] = 1
visited[points[min_j][-1]] = 1
# print(answers)
for p in answers:
print(p[0] + 1, p[1] + 1)
#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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
|
[
"geometry"
] | 1,057
| 3,319
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,219
|
a27ad7c21cd6402bfd082da4f6c7ab9d
|
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of s, in the end or between any two consecutive characters). For example, if p is aba, and s is de, then the following outcomes are possible (the character we erase from p and insert into s is highlighted): aba \rightarrow ba, de \rightarrow ade; aba \rightarrow ba, de \rightarrow dae; aba \rightarrow ba, de \rightarrow dea; aba \rightarrow aa, de \rightarrow bde; aba \rightarrow aa, de \rightarrow dbe; aba \rightarrow aa, de \rightarrow deb; aba \rightarrow ab, de \rightarrow ade; aba \rightarrow ab, de \rightarrow dae; aba \rightarrow ab, de \rightarrow dea; Your goal is to perform several (maybe zero) operations so that s becomes equal to t. Please determine whether it is possible.Note that you have to answer q independent queries.
|
['implementation', 'strings']
|
t=int(input())
for _ in range(t):
s=input()
t=input()
p=input()
if(len(t)<len(s)):
print('NO')
elif(len(t)==len(s)):
if(t==s):
print('YES')
else:
print('NO')
else:
j=0
c=0
for i in s:
while(j<len(t)):
if(t[j]==i):
c+=1
j+=1
break
j+=1
if(c==len(s)):
f=0
s=s+' '
for i in range(len(t)):
#print(t[i])
if(t[i]!=s[i]):
if(t[i] in p):
s=s[:i]+t[i]+s[i:]
index=p.index(t[i])
p=p[:index]+p[index+1:]
#print(p)
else:
print('NO')
f=1
break
if(f==0):
print('YES')
else:
print('NO')
|
Python
|
[
"strings"
] | 1,261
| 1,014
| 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,617
|
2510469c09d7d145078e65de81640ddc
|
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number x. A perfect longcat is a cat with a number equal 2^m - 1 for some non-negative integer m. For example, the numbers 0, 1, 3, 7, 15 and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on x: (Operation A): you select any non-negative integer n and replace x with x \oplus (2^n - 1), with \oplus being a bitwise XOR operator. (Operation B): replace x with x + 1. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most 40 operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than 40 operations.
|
['constructive algorithms', 'bitmasks', 'math', 'dfs and similar']
|
from math import log2,log,ceil
def A(x):
# x==2**m => log2(x)==m*log2(2) => log2(x)==m
n=ceil(log2(x))
n=int(n)
kk=2**n-1
return x^kk,n
def B(x):
return x+1
def check(num):
num+=1
mm=log(num)/log(2)
q=int(mm)
if mm-q==0:
return True
return False
t=0
f=True
ans=[]
x=int(input())
for i in range(40):
if check(x):
print(t)
if t!=0:
print(*ans)
break
t+=1
if t%2!=0:
x,n1=A(x)
ans.append(n1)
else:
x=B(x)
|
Python
|
[
"math",
"graphs"
] | 1,347
| 547
| 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,395
|
adc43f273dd9b3f1c58b052a34732a50
|
A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".
|
['dp', 'two pointers', 'math', 'binary search', 'brute force', 'strings']
|
k=int(input())
l=input()
if k==0:
c=0
ans=0
for i in range(len(l)):
if l[i]=="0":
c+=1
else:
temp=((c*(c+1))//2)
ans+=temp
c=0
ans+=(c*(c+1))//2
print(ans)
else:
ans=0
ar=[]
a=-1
for i in range(len(l)):
if l[i]=="1":
ar.append(i-a-1)
a=i
ar.append(len(l)-a-1)
p=len(ar)-1
for i in range(len(ar)):
if i+k>p:
break
ans+=ar[i]*ar[i+k]+ar[i]+ar[i+k]+1
print(ans)
|
Python
|
[
"math",
"strings"
] | 569
| 534
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
}
| 4,416
|
2136f0aed9da00c3f991235f5074f71e
|
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gave a number 1 \leq k \leq n. Because Johnny is not too smart, he promised to find a simple path with length at least \frac{n}{k} in the graph. In reply, Solving promised to find k simple by vertices cycles with representatives, such that: Length of each cycle is at least 3. Length of each cycle is not divisible by 3. In each cycle must be a representative - vertex, which belongs only to this cycle among all printed cycles. You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least \frac{n}{k} (n is not necessarily divided by k), or solution for Solving: k cycles that satisfy all the conditions above. If there is no any solution - print -1.
|
['constructive algorithms', 'graphs', 'dfs and similar', 'math']
|
import sys
range = xrange
input = raw_input
# Will extremly quickly convert s into a list of integers.
# The format of the string is required to be integers (positive or negative)
# separated with a single character with ascii value <'-', so like a whitespace.
# It also handles the string ending with an additional character < '-', like a trailing newline.
s = sys.stdin.read()
inp = []
numb = 0
for i in range(len(s)):
if s[i]>='0':
numb = 10*numb + ord(s[i])-48
else:
inp.append(numb)
numb = 0
if s[-1]>='0':
inp.append(numb)
ii = 0
n = inp[ii]
ii+=1
m = inp[ii]
ii+=1
k = inp[ii]
ii+=1
coupl = [[] for _ in range(n)]
for _ in range(m):
u = inp[ii]-1
ii += 1
v = inp[ii]-1
ii += 1
coupl[u].append(v)
coupl[v].append(u)
P = [-1]*n
D = [1]*n
found = [False]*n
cycle_nodes = []
Q = [0]
while Q:
node = Q.pop()
if found[node]:
continue
found[node] = True
found_any = False
for nei in coupl[node]:
if not found[nei]:
P[nei] = node
D[nei] = D[node]+1
Q.append(nei)
found_any = True
if not found_any:
cycle_nodes.append(node)
i = max(range(n),key=lambda i:D[i])
if k*D[i]>=n:
print 'PATH'
print D[i]
out = []
while i!=-1:
out.append(i)
i = P[i]
print ' '.join(str(x+1) for x in out)
elif len(cycle_nodes)>=k:
print 'CYCLES'
out = []
for i in cycle_nodes[:k]:
minD = min(D[nei] for nei in coupl[i] if (D[i] - D[nei] + 1)%3!=0)
tmp = []
if minD == D[i]-1:
a,b = [nei for nei in coupl[i] if (D[i] - D[nei] + 1)%3==0][:2]
if D[a]<D[b]:
a,b = b,a
tmp.append(i)
while a!=b:
tmp.append(a)
a = P[a]
tmp.append(a)
else:
while D[i]!=minD:
tmp.append(i)
i = P[i]
tmp.append(i)
out.append(str(len(tmp)))
out.append(' '.join(str(x+1) for x in tmp))
print '\n'.join(out)
else:
print -1
|
Python
|
[
"graphs",
"math"
] | 1,111
| 2,104
| 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,409
|
46c5ebf1ddf5547352e84ba0171eacbc
|
This is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an operation, you select a prefix of a, and simultaneously invert the bits in the prefix (0 changes to 1 and 1 changes to 0) and reverse the order of the bits in the prefix.For example, if a=001011 and you select the prefix of length 3, it becomes 011011. Then if you select the entire string, it becomes 001001.Your task is to transform the string a into b in at most 2n operations. It can be proved that it is always possible.
|
['data structures', 'constructive algorithms', 'implementation', 'strings']
|
t = int(input())
for _ in range(t):
l = int(input())
a = input().rstrip()
b = input().rstrip()
ans = []
c = 0
if a[0]=='1':
c += 1
for i in range(len(a)-1):
if a[i+1] != a[i]:
ans.append(i+1)
c+= 1
bns = []
d = 0
if b[0]=='1':
d += 1
for i in range(len(b)-1):
if b[i+1] != b[i]:
bns.append(i+1)
d += 1
if c%2!=d%2:
ans += [l]
f = ans + bns[::-1]
print(len(f), *f)
|
Python
|
[
"strings"
] | 854
| 549
| 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,783
|
0df064fd0288c2ac4832efa227107a0e
|
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
|
['implementation', 'hashing', 'strings']
|
s = input().strip()
t = input().strip()
diff = len(s) - 1
for i in range(len(t)):
if s[i] != t[i]:
diff = i
break
for i in range(diff + 1, len(s)):
if s[i] != t[i - 1]:
print(0)
import sys; sys.exit()
start = diff
while start != 0 and s[start - 1] == s[diff]:
start -= 1
print(diff - start + 1)
print(' '.join(map(str, range(start + 1, diff + 2))))
|
Python
|
[
"strings"
] | 806
| 371
| 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,890
|
63108f3cc494df3c7bb62381c03801b3
|
Let us call two integers x and y adjacent if \frac{lcm(x, y)}{gcd(x, y)} is a perfect square. For example, 3 and 12 are adjacent, but 6 and 9 are not.Here gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y, and lcm(x, y) denotes the least common multiple (LCM) of integers x and y.You are given an array a of length n. Each second the following happens: each element a_i of the array is replaced by the product of all elements of the array (including itself), that are adjacent to the current value. Let d_i be the number of adjacent elements to a_i (including a_i itself). The beauty of the array is defined as \max_{1 \le i \le n} d_i. You are given q queries: each query is described by an integer w, and you have to output the beauty of the array after w seconds.
|
['bitmasks', 'graphs', 'hashing', 'math', 'number theory']
|
import sys, random
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); inf=10**18
LI = lambda : list(map(int, input().split()))
def debug(_l_):
for s in _l_.split():
print(f"{s}={eval(s)}", end=" ")
print()
def dlist(*l, fill=0):
if len(l)==1:
return [fill]*l[0]
ll = l[1:]
return [dlist(*ll, fill=fill) for _ in range(l[0])]
def hurui(n):
"""線形篩
pl: 素数のリスト
mpf: iを割り切る最小の素因数
"""
pl = []
mpf = [None]*(n+1)
for d in range(2,n+1):
if mpf[d] is None:
mpf[d] = d
pl.append(d)
for p in pl:
if p*d>n or p>mpf[d]:
break
mpf[p*d] = p
return pl, mpf
from collections import defaultdict
def factor(num):
d = defaultdict(int)
if num==1:
d.update({})
return d
while num>1:
d[mpf[num]] += 1
num //= mpf[num]
return d
def fs(num):
f = factor(num)
ans = [1]
for k,v in f.items():
tmp = []
for i in range(len(ans)):
val = 1
for _ in range(v):
val *= k
ans.append(ans[i]*val)
return ans
pl, mpf = hurui(1000100)
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
c = {}
for v in a:
f = factor(v)
k = tuple(sorted([kk for kk,vv in f.items() if vv%2]))
c.setdefault(k,0)
c[k] += 1
ans0 = max(c.values())
nc = {}
for k in c.keys():
if c[k]%2==0:
nk = tuple()
else:
nk = k
nc.setdefault(nk, 0)
nc[nk] += c[k]
ans1 = max(nc.values())
q = int(input())
for i in range(q):
w = int(input())
if w==0:
print(ans0)
else:
print(ans1)
|
Python
|
[
"graphs",
"number theory",
"math"
] | 926
| 1,995
| 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
}
| 352
|
6cec3662101b419fb734b7d6664fdecd
|
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: "Success" if the activation was successful. "Already on", if the i-th collider was already activated before the request. "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: "Success", if the deactivation was successful. "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.
|
['number theory', 'math']
|
n, m = map(int, input().split())
n += 1
s = [[] for i in range(n)]
for j in range(2, n, 2): s[j] = [2]
for i in range(3, n, 2):
if s[i]: continue
for j in range(i, n, i): s[j].append(i)
p, d, r = {}, set(), [''] * m
for j in range(m):
t = input()
i = int(t[2: ])
if t[0] == '+':
if i in d:
r[j] = 'Already on'
continue
for q in s[i]:
if q in p:
r[j] = 'Conflict with ' + str(p[q])
break
else:
r[j] = 'Success'
d.add(i)
for q in s[i]: p[q] = i
else:
if i in d:
r[j] = 'Success'
for q in s[i]: p.pop(q)
d.remove(i)
else: r[j] = 'Already off'
print('\n'.join(r))
# Made By Mostafa_Khaled
|
Python
|
[
"math",
"number theory"
] | 2,168
| 828
| 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,154
|
23261cfebebe782715646c38992c48a6
|
Let's call a positive integer good if there is no digit 0 in its decimal representation.For an array of a good numbers a, one found out that the sum of some two neighboring elements is equal to x (i.e. x = a_i + a_{i + 1} for some i). x had turned out to be a good number as well.Then the elements of the array a were written out one after another without separators into one string s. For example, if a = [12, 5, 6, 133], then s = 1256133.You are given a string s and a number x. Your task is to determine the positions in the string that correspond to the adjacent elements of the array that have sum x. If there are several possible answers, you can print any of them.
|
['hashing', 'math', 'string suffix structures', 'strings']
|
import sys
s = sys.stdin.readline().strip()
x = sys.stdin.readline().strip()
ls, lx = len(s), len(x)
MOD = 2**31-1
h = [0] * (ls+1)
p = [1] * (ls+1)
def gh(start, end):
return (h[end+1] - h[start] * p[end-start+1]) % MOD
def gen_z(s, zx = None, x=None):
z = [0]*len(s)
l, r, start = 0, -1, 0
if not zx: zx = z; x =s; z[0] = len(s); start = 1
for i in range(start, len(s)):
if i <= r: z[i] = min(zx[i - l], r - i + 1);
while i + z[i] < len(s) and z[i] < len(x) and s[i + z[i]] == x[z[i]]: z[i]+=1;
if i + z[i] - 1 > r:
l = i;
r = i + z[i] - 1;
return z
zx = gen_z(x)
zs = gen_z(s, zx, x)
for idx, i in enumerate(s):
h[idx+1] = (h[idx] * 10 + ord(i) - 48) % MOD
p[idx+1] = p[idx]*10 % MOD
target = 0
for i in x: target = (target * 10 + ord(i) - 48) % MOD
def printresult(a, b, c):
sys.stdout.write("%d %d\n%d %d\n" % (a+1, b, b+1, c+1))
sys.exit()
if lx > 1:
for i in range(ls - lx - lx + 3):
if (gh(i, i+lx-2) + gh(i+lx-1, i+lx+lx-3)) % MOD == target: printresult(i, i+lx-1, i+lx+lx-3)
for i in range(ls - lx + 1):
j = lx - zs[i]
if j > 0:
if i+lx+j <= ls and (gh(i, i+lx-1) + gh(i+lx, i+lx+j-1)) % MOD == target: printresult(i, i+lx, i+lx+j-1)
if i-j >= 0 and (gh(i-j, i-1) + gh(i, i+lx-1)) % MOD == target: printresult(i-j, i, i+lx-1)
if j > 1:
if i+lx+j-1 <= ls and (gh(i, i+lx-1) + gh(i+lx, i+lx+j-2)) % MOD == target: printresult(i, i+lx, i+lx+j-2)
if i-j+1 >= 0 and (gh(i-j+1, i-1) + gh(i, i+lx-1)) % MOD == target: printresult(i-j+1, i, i+lx-1)
|
Python
|
[
"math",
"strings"
] | 743
| 1,649
| 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,710
|
0cc9e1f64f615806d07e657be7386f5b
|
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109 + 7. Help him!
|
['dp', 'combinatorics', 'number theory', 'math']
|
n, k = map(int, input().split())
t = list(map(int, input()))
p, d = 1, 10 ** 9 + 7
s, f = 0, [1] * n
for i in range(2, n): f[i] = (i * f[i - 1]) % d
c = lambda a, b: 0 if a > b else (f[b] * pow(f[a] * f[b - a], d - 2, d)) % d
if k:
u = [0] * (n + 1)
p = [1] * (n + 1)
for i in range(n):
u[i] = (p[i] * c(k - 1, n - 2 - i) + u[i - 1]) % d
p[i + 1] = (10 * p[i]) % d
for i in range(n):
v = u[n - 2 - i] + p[n - 1 - i] * c(k, i)
s = (s + t[i] * v) % d
else:
for i in t: s = (s * 10 + i) % d
print(s)
|
Python
|
[
"math",
"number theory"
] | 1,114
| 550
| 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,706
|
b36d7f840abe998185a988fe8dd2ec75
|
You are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their sum, yielding an array [3, 15], or replace the first two elements to get an array [9, 9]. Note that the size of the array decreases after each operation.The beauty of an array b=[b_1, \ldots, b_k] is defined as \sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil, which means that we divide each element by x, round it up to the nearest integer, and sum up the resulting values. For example, if x = 3, and the array is [4, 11, 6], the beauty of the array is equal to \left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.
|
['greedy', 'math', 'number theory']
|
import math
for i in range(int(input())):
n,x=map(int,input().strip().split())
a=list(map(int,input().strip().split()))
c=sum(a)
z=math.ceil(c/x)
g=0
h=[]
for j in range(len(a)):
g=g+math.ceil(a[j]/x)
h.append(z)
h.append(g)
print(*h)
|
Python
|
[
"math",
"number theory"
] | 1,107
| 294
| 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,366
|
8e4194b356500cdaacca2b1d49c2affb
|
Let's define S(x) to be the sum of digits of number x written in decimal system. For example, S(5) = 5, S(10) = 1, S(322) = 7.We will call an integer x interesting if S(x + 1) < S(x). In each test you will be given one integer n. Your task is to calculate the number of integers x such that 1 \le x \le n and x is interesting.
|
['math', 'number theory']
|
t = int(input())
vet= []
for _ in range(0,t):
res = 0
n = int(input())
if n >=10:
res = int(n/10)
n = int(n%10)
if n >=9:
res +=1
vet.append(res)
print(*vet, sep='\n')
|
Python
|
[
"math",
"number theory"
] | 395
| 248
| 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
}
| 141
|
235ddb32dbe19c0da1f77069e36128bb
|
You are given two strings s and t, both of length n. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions: choose an occurrence of "ab" in s and replace it with "ba"; choose an occurrence of "bc" in s and replace it with "cb". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string s to make it equal to string t?
|
['binary search', 'constructive algorithms', 'data structures', 'greedy', 'implementation', 'strings', 'two pointers']
|
import collections
q = int(input())
for _ in range(q):
n = int(input())
s = list(input())
t = list(input())
occ_s = collections.defaultdict(int)
occ_t = collections.defaultdict(int)
s2 = ""
t2 = ""
for i in range(n):
occ_s[s[i]] += 1
occ_t[t[i]] += 1
if s[i] != "b": s2 += s[i]
if t[i] != "b": t2 += t[i]
if s2 != t2:
print("NO")
continue
l, r = 0, 0
i = 0
flag = True
while i < occ_s["a"]:
while s[l] != "a":
l += 1
while t[r] != "a":
r += 1
i += 1
l += 1
r += 1
if l > r:
flag = False
break
if not flag:
print("NO")
continue
l, r = 0, 0
i = 0
while i < occ_s["c"]:
while s[l] != "c":
l += 1
while t[r] != "c":
r += 1
i += 1
l += 1
r += 1
if r > l:
flag = False
break
print("NO") if not flag else print("YES")
|
Python
|
[
"strings"
] | 453
| 925
| 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,476
|
add040eecd8322630fbbce0a2a1de45e
|
Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: "+ x" — add integer x to multiset A. "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x" — you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.
|
['data structures', 'binary search', 'bitmasks', 'trees']
|
# Why do we fall ? So we can learn to pick ourselves up.
class Node:
def __init__(self):
self.left = None
self.right = None
self.cnt = 0
class Trie:
def __init__(self):
self.root = Node()
def insert(self,x):
self.temp = self.root
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
if not self.temp.right:
self.temp.right = Node()
self.temp = self.temp.right
self.temp.cnt += 1
else:
if not self.temp.left:
self.temp.left = Node()
self.temp = self.temp.left
self.temp.cnt += 1
def remove(self,x):
self.temp = self.root
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
self.temp = self.temp.right
self.temp.cnt -= 1
else:
self.temp = self.temp.left
self.temp.cnt -= 1
def maxxor(self,x):
self.temp = self.root
self.ss = 0
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
if self.temp.left and self.temp.left.cnt:
self.ss += (1<<i)
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.cnt:
self.ss += (1<<i)
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
return self.ss
q = int(input())
trie = Trie()
trie.insert(0)
for _ in range(0,q):
qq = input().split()
if qq[0] == '+':
trie.insert(int(qq[1]))
elif qq[0] == '-':
trie.remove(int(qq[1]))
else:
print(trie.maxxor(int(qq[1])))
"""
10
+ 8
+ 9
+ 11
+ 6
+ 1
? 3
- 8
? 3
? 8
? 11
10
? 1
+ 1
+ 8
- 1
+ 2
+ 7
+ 4
+ 7
+ 3
? 7
"""
|
Python
|
[
"trees"
] | 620
| 2,053
| 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,862
|
a7ae834884ce801ffe111bd8161e89d2
|
This is the hard version of the problem. The only difference between the versions is the constraints on n, k, a_i, and the sum of n over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers a_1, a_2, \ldots, a_n of length n, and an integer k.The cost of an array of integers p_1, p_2, \ldots, p_n of length n is \max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).Here, \lfloor \frac{x}{y} \rfloor denotes the integer part of the division of x by y. Find the minimum cost of an array p such that 1 \le p_i \le k for all 1 \le i \le n.
|
['brute force', 'constructive algorithms', 'data structures', 'dp', 'greedy', 'math', 'number theory', 'two pointers']
|
#!/usr/bin/env python3
import sys
import heapq
input = sys.stdin.readline # to read input quickly
def ceiling_division(numer, denom):
return -((-numer)//denom)
mask = 2**18 - 1
m0 = mask
m1 = mask << 18
m2 = mask << 36
def ungroup(x):
return (x&m2) >> 36, (x&m1) >> 18, (x&m0)
def group(a,b,c):
val = (a << 36) ^ (b << 18) ^ c
return val
for case_num in range(int(input())):
n,k = list(map(int,input().split()))
n_cooldown = 18*n
cnt = n_cooldown
arr = [group((x//k),k,x) for x in map(int,input().split())]
minn = ungroup(arr[0])[0]
maxx = ungroup(arr[-1])[0]
minres = maxx - minn
if minres == 0:
print(0)
continue
maxx = max(1, maxx)
while ungroup(arr[0])[1] > 1 and cnt > 0:
nx,i,x = ungroup(heapq.heappop(arr))
i = max(1, min(ceiling_division(x, maxx), x // (nx+1)))
nx = (x//i)
heapq.heappush(arr, group(nx,i,x))
maxx = max(maxx, nx)
minn = ungroup(arr[0])[0]
cnt -= 1
if maxx - minn < minres:
minres = maxx - minn
cnt = n_cooldown
if minres == 0:
break
print(minres)
|
Python
|
[
"math",
"number theory"
] | 853
| 1,242
| 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,797
|
bbc2683d207f147a2a0abedc67ff157a
|
You know that the Martians use a number system with base k. Digit b (0 ≤ b < k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.For example, d(35047) = d((3 + 5 + 0 + 4)7) = d(157) = d((1 + 5)7) = d(67) = 67. In this sample the calculations are performed in the 7-base notation.If a number's digital root equals b, the Martians also call this number lucky.You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.Note that substring s[i... j] of the string s = a1a2... an (1 ≤ i ≤ j ≤ n) is the string aiai + 1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1 ≠ i2 or j1 ≠ j2.
|
['number theory', 'math']
|
k, b, n = map(int, input().split())
digits = list(map(int, input().split()))
def ans0():
j = -1
answer = 0
for i in range(n):
if digits[i] != 0 or i < j:
continue
j = i
while j < n and digits[j] == 0:
j += 1
r = j - i
answer += r * (r + 1) // 2
return answer
if b == 0:
print(ans0())
else:
count = dict()
count[0] = 1
pref_sum = 0
answer = 0
if b == k - 1:
b = 0
answer -= ans0()
for d in digits:
pref_sum = (pref_sum + d) % (k - 1)
need = (pref_sum - b) % (k - 1)
answer += count.get(need, 0)
count[pref_sum] = count.get(pref_sum, 0) + 1
print(answer)
|
Python
|
[
"math",
"number theory"
] | 1,168
| 725
| 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,582
|
aaca5d07795a42ecab210327c1cf6be9
|
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
|
['implementation', 'dfs and similar', 'trees', 'graphs']
|
import sys
n = int(sys.stdin.readline())
edges = [[int(x) for x in sys.stdin.readline().split()] for _ in range(n - 1)]
colors = sys.stdin.readline().split()
res = None
for edge in edges:
if colors[edge[0]-1] != colors[edge[1]-1]:
if res is None:
res = list(edge)
else:
res = [x for x in res if x in edge]
if len(res) == 0:
break
if res is None:
print('YES\n1')
else:
print('NO' if len(res) == 0 else 'YES\n' + str(res[0]))
|
Python
|
[
"graphs",
"trees"
] | 991
| 509
| 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,011
|
0337ff9d7c3d8e0813ab4d47736308e5
|
Given a cyclic array a of size n, where a_i is the value of a in the i-th position, there may be repeated values. Let us define that a permutation of a is equal to another permutation of a if and only if their values are the same for each position i or we can transform them to each other by performing some cyclic rotation. Let us define for a cyclic array b its number of components as the number of connected components in a graph, where the vertices are the positions of b and we add an edge between each pair of adjacent positions of b with equal values (note that in a cyclic array the first and last position are also adjacents).Find the expected value of components of a permutation of a if we select it equiprobably over the set of all the different permutations of a.
|
['combinatorics', 'math', 'number theory', 'probabilities']
|
import math
import sys
r=range
m=lambda x:pow(x,M-2,M)
M=998244353
f=[1]
F=[1]*10**6
for i in r(1,1000001):f.append(f[-1]*i%M)
F.append(m(f[-1]))
for i in r(10**6,1,-1):F[i-1]=F[i]*(i)%M
I=sys.stdin.readline
for _ in[0]*int(I()):
n=int(I());a=[*map(int,I().split())];C=[0]*n;P,c=0,0;A={}
for g in a:C[g-1]+=1
C=[g for g in C if g>0]
x=C[0]
for g in C:x=math.gcd(x,g)
if x==n:print(1);continue
for i in r(1,n):
if x%i<1:A[i]=0
for i in r(1,n):
if x%i<1:
X=n//i;p=f[X];s=0;e=i-A[i]
for g in C:y=g//i;s+=y*(y-1);p=p*F[y]%M
P+=p*e;c+=e*((X)*(X-1)-s)*i*m(X-1)*p%M
for g in A:
if g%i<1:A[g]+=e
print(c*m(P)%M)
|
Python
|
[
"math",
"number theory",
"probabilities"
] | 855
| 659
| 0
| 0
| 0
| 1
| 1
| 1
| 0
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 1,
"strings": 0,
"trees": 0
}
| 2,429
|
a7fa7a5ab71690fb3b5301bebc19956b
|
Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid line (not necessarily from border to border). The part of the paper, that touches the knife at least once, is considered cut. There is one limit not to turn the game into an infinite cycle: each move has to cut the paper, that is the knife has to touch the part of the paper that is not cut before.Obviously, the game ends when the entire sheet is cut into 1 × 1 blocks. During the game, the pieces of the sheet are not allowed to move. It is also prohibited to cut along the border. The coordinates of the ends of each cut must be integers.You are given an n × m piece of paper, somebody has already made k cuts there. Your task is to determine who will win if the players start to play on this sheet. You can consider that both players play optimally well. If the first player wins, you also need to find the winning first move.
|
['implementation', 'games']
|
from sys import stdin
from collections import defaultdict
def emp(l, a):
cnt = pos = x = 0
for y in a:
if y[1]:
cnt -= 1
else:
if not cnt:
x += y[0] - pos
cnt += 1
pos = y[0]
x += l - pos
return x
def check(x, b):
return x ^ b < x
def f(x, b):
return x - (x ^ b)
def main():
n, m, k = map(int, stdin.readline().split())
xcut = defaultdict(list)
ycut = defaultdict(list)
for i in xrange(k):
xb, yb, xe, ye = map(int, stdin.readline().split())
if xb == xe:
xcut[xb].extend([(min(yb, ye), 0), (max(yb, ye), 1)])
else:
ycut[yb].extend([(min(xb, xe), 0), (max(xb, xe), 1)])
b = 0
xb = dict()
yb = dict()
for t in xcut.keys():
xcut[t].sort()
xb[t] = emp(m, xcut[t])
b ^= xb[t]
if (n - 1 - len(xcut)) % 2:
b ^= m
for t in ycut.keys():
ycut[t].sort()
yb[t] = emp(n, ycut[t])
b ^= yb[t]
if (m - 1 - len(ycut)) % 2:
b ^= n
if b == 0:
print "SECOND"
return
else:
print "FIRST"
if n - 1 - len(xcut) and check(m, b):
for i in xrange(1, n):
if i not in xcut:
print i, 0, i, f(m, b)
return
if m - 1 - len(ycut) and check(n, b):
for i in xrange(1, m):
if i not in ycut:
print 0, i, f(n, b), i
return
for t, a in xcut.items():
if not check(xb[t], b): continue
c = f(xb[t], b)
cnt = pos = x = 0
for y in a:
if y[1] == 0:
if cnt == 0:
if x <= c <= x + y[0] - pos:
print t, 0, t, pos + c - x
return
x += y[0] - pos
cnt += 1
else:
cnt -= 1
pos = y[0]
print t, 0, t, pos + c - x
return
for t, a in ycut.items():
if not check(yb[t], b): continue
c = f(yb[t], b)
cnt = pos = x = 0
for y in a:
if y[1] == 0:
if cnt == 0:
if x <= c <= x + y[0] - pos:
print 0, t, pos + c - x, t
return
x += y[0] - pos
cnt += 1
else:
cnt -= 1
pos = y[0]
print 0, t, pos + c - x, t
return
main()
|
Python
|
[
"games"
] | 1,149
| 2,679
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
{
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 2,563
|
1e17039ed5c48e5b56314a79b3811a40
|
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most l centimeters after haircut, where l is her favorite number. Suppose, that the Alice's head is a straight line on which n hairlines grow. Let's number them from 1 to n. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length l, given that all hairlines on that segment had length strictly greater than l. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types: 0 — Alice asks how much time the haircut would take if she would go to the hairdresser now. 1 p d — p-th hairline grows by d centimeters. Note, that in the request 0 Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.
|
['dsu', 'implementation']
|
from __future__ import division
from sys import stdin, stdout
line = stdin.readline().rstrip("\n")
n, m, l = map(int, line.split())
line = stdin.readline().rstrip("\n")
a = map(int, line.split())
a = [0] + a + [0]
res = 0
for i in range(1, n + 1):
if a[i] > l and not a[i - 1] > l:
res += 1
reqs = []
for _ in xrange(m):
line = stdin.readline().rstrip("\n")
t = map(int, line.split())
if len(t) == 1:
reqs.append((0, ))
else:
t, p, d = t
reqs.append((t, p, d))
for ting in reqs:
if len(ting) == 1:
stdout.write(str(res) + "\n")
else:
t, p, d = ting
a[p] += d
if a[p] > l and a[p] - d <= l:
if a[p - 1] > l and a[p + 1] > l:
res -= 1
elif a[p - 1] <= l and a[p + 1] <= l:
res += 1
|
Python
|
[
"graphs"
] | 1,354
| 834
| 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,899
|
de6361f522936eac3d88b7268b8c2793
|
Arcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».
|
['*special', 'trees', 'strings']
|
class Ddict:
def __init__(self):
self.dicts={}
def add(self,key):
d=self.dicts
for i in key:
if i not in d:
d[i]={}
d=d[i]
d[' ']=''
def find(self,key):
if key=='':
return '',''
d=self.dicts
q=[]
h=[key[0]]
for i in key:
if i not in d:
if ' ' in d and len(d)==1:
return ''.join(q),''.join(h)
return '',''
q.append(i)
if len(d)!=1:
h=q[:]
d=d[i]
if ' ' in d and len(d)==1:
return ''.join(q),''.join(h)
return '',''
words = Ddict()
ans=0
while True:
try:
x=input()
if not x:
break
except:
break
ans+=len(x)+1
ws=[[]]
for i in x:
if i in '.,?!\'- ':
if ws[-1]:
ws.append([])
else:
ws[-1].append(i)
ws=list(map(lambda e:''.join(e),ws))
for w in ws:
next_word,helped_word = words.find(w)
if next_word and next_word!=helped_word:
ans-=len(next_word)-len(helped_word)-1
words.add(w)
print(ans)
|
Python
|
[
"strings",
"trees"
] | 1,426
| 1,223
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
|
{
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 1
}
| 43
|
3b8969f7f2051d559a1e375ce8275c73
|
Theofanis has a string s_1 s_2 \dots s_n and a character c. He wants to make all characters of the string equal to c using the minimum number of operations.In one operation he can choose a number x (1 \le x \le n) and for every position i, where i is not divisible by x, replace s_i with c. Find the minimum number of operations required to make all the characters equal to c and the x-s that he should use in his operations.
|
['brute force', 'greedy', 'math', 'strings']
|
t = int(input())
while t:
n,c = input().split()
s = str(input())
copy = str(c)
copy*=(int(n))
if s == copy:
print(0)
else:
n = int(n)
f = False
for i in range(1,n+1):
if s[i-1] == str(c) and i*2 > n:
f = True
break
if f:
print(1)
print(i)
else:
print(2)
print(n-1,n)
t -= 1
|
Python
|
[
"math",
"strings"
] | 497
| 462
| 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,852
|
d7d8d91be04f5d9065a0c22e66d11de3
|
This problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?
|
['data structures', 'implementation', 'geometry', 'math']
|
from math import *
class slopeC:
def __init__(self):
self.chil = set()
n = int(input())
slopes = {}
L = []
for i in range(n):
x, y = map(int, input().split())
for l in L:
if x != l[0]:
slope = (y - l[1]) / (x - l[0])
else:
slope = inf
s1 = str(l[0]) + '-' + str(l[1])
s2 = str(x) + '-' + str(y)
if slope not in slopes:
slopes[slope] = [slopeC()]
slopes[slope][0].chil.add(s1)
slopes[slope][0].chil.add(s2)
else:
f = 0
for child in slopes[slope]:
if s1 in child.chil:
f = 1
child.chil.add(s2)
break
if f == 0:
slopes[slope] += [slopeC()]
slopes[slope][0].chil.add(s1)
slopes[slope][0].chil.add(s2)
L += [[x, y]]
A = []
P = [0]
for s in slopes:
A += [(len(slopes[s]))]
P += [P[-1] + A[-1]]
ans = 0
for i, v in enumerate(A):
ans += A[i] * (P[-1] - P[i+1])
print(ans)
|
Python
|
[
"math",
"geometry"
] | 1,203
| 1,123
| 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,695
|
c7f0fefd9616e4ba2d309a7c5c8a8a0a
|
You are given a tree consisting of n vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex 1.You have to process q queries. In each query, you are given a vertex of the tree v and an integer k.To process a query, you may delete any vertices from the tree in any order, except for the root and the vertex v. When a vertex is deleted, its children become the children of its parent. You have to process a query in such a way that maximizes the value of c(v) - m \cdot k (where c(v) is the resulting number of children of the vertex v, and m is the number of vertices you have deleted). Print the maximum possible value you can obtain.The queries are independent: the changes you make to the tree while processing a query don't affect the tree in other queries.
|
['brute force', 'dp', 'trees']
|
import sys, collections
n = int(sys.stdin.readline())
e = [[] for i in range(n+1)]
for i in range(n-1):
a, b = [int(i) for i in sys.stdin.readline().split()]
e[a].append(b)
e[b].append(a)
o = [len(e[i])-1 for i in range(0, n+1)]
o[1]+=1
r = [[] for i in range(n+1)]
st = collections.deque([1])
d = [0]*(n+1)
p = [0]*(n+1)
while st:
x = st.popleft()
for i in e[x]:
if i != p[x]: st.append(i); d[i] = d[x]+1; p[i] = x
d = [(d[i], i) for i in range(1,n+1)]
d.sort(key=lambda x:x[0], reverse=True)
for _, v in d:
r[v] = [o[v]]*max(max(len(r[i]) for i in e[v]), o[v]-1)
for i in e[v]:
if i == p: continue
for idx, x in enumerate(r[i]):
r[v][idx]+=max(x-idx-1, 0)
for q in range(int(sys.stdin.readline())):
v, k = [int(i) for i in sys.stdin.readline().split()]
if k >= len(r[v]): print(o[v])
else: print(r[v][k])
|
Python
|
[
"trees"
] | 874
| 912
| 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,439
|
d53575e38f79990304b679ff90c5de34
|
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.Also Vova can fight monsters. Every monster is characterized by two values tj and hj — monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.You have to write a program which can answer two types of queries: 1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second. 2 t h — Vova fights the monster which kills his character in t seconds and has h health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
|
['data structures', 'geometry']
|
#!/usr/bin/env python3
# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)
[q, m] = map(int, input().strip().split())
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
mod = 10**6
j = 0
spell_chull = [(0, 0)] # lower hull _/
def is_right(xy0, xy1, xy):
(x0, y0) = xy0
(x1, y1) = xy1
(x, y) = xy
return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)
def in_chull(x, y):
i = 0
if x > spell_chull[-1][0]:
return False
while spell_chull[i][0] < x:
i += 1
if spell_chull[i][0] == x:
return spell_chull[i][1] <= y
else:
return is_right(spell_chull[i - 1], spell_chull[i], (x, y))
def add_spell(x, y):
global spell_chull
if in_chull(x, y):
return
i_left = 0
while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
i_left += 1
i_right = i_left + 1
while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
i_right += 1
if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
i_right += 1
spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]
for i, qi in enumerate(qis):
(k, a, b) = qi
x = (a + j) % mod + 1
y = (b + j) % mod + 1
if k == 1:
add_spell(x, y)
else: #2
if in_chull(y / x, m / x):
print ('YES')
j = i + 1
else:
print ('NO')
|
Python
|
[
"geometry"
] | 1,952
| 1,402
| 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,149
|
824c7f11e6c2997c98741d314cdd1970
|
Alex decided to go on a touristic trip over the country.For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score w_i which is as high as interesting city seems to Alex.Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city v from city u, he may choose as the next city in the trip any city connected with v by the road, except for the city u.Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.
|
['dp', 'greedy', 'graphs', 'dsu', 'dfs and similar', 'trees']
|
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
W=[0]+list(map(int,input().split()))
E=[tuple(map(int,input().split())) for i in range(m)]
S=int(input())
ELIST=[[] for i in range(n+1)]
EW=[0]*(n+1)
for x,y in E:
ELIST[x].append(y)
ELIST[y].append(x)
EW[x]+=1
EW[y]+=1
from collections import deque
Q=deque()
USED=[0]*(n+1)
for i in range(1,n+1):
if EW[i]==1 and i!=S:
USED[i]=1
Q.append(i)
EW[S]+=1<<50
USED[S]=1
while Q:
x=Q.pop()
EW[x]-=1
for to in ELIST[x]:
if USED[to]==1:
continue
EW[to]-=1
if EW[to]==1 and USED[to]==0:
Q.append(to)
USED[to]=1
#print(EW)
LOOP=[]
ANS=0
for i in range(1,n+1):
if EW[i]!=0:
ANS+=W[i]
LOOP.append(i)
SCORE=[0]*(n+1)
USED=[0]*(n+1)
for l in LOOP:
SCORE[l]=ANS
USED[l]=1
Q=deque(LOOP)
while Q:
x=Q.pop()
for to in ELIST[x]:
if USED[to]==1:
continue
SCORE[to]=W[to]+SCORE[x]
Q.append(to)
USED[to]=1
print(max(SCORE))
|
Python
|
[
"graphs",
"trees"
] | 832
| 1,077
| 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
}
| 968
|
73b571b55ee211f11347e6a77551a297
|
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem.You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query: Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes. Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \{a_1, a_2, \ldots, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.You can ask no more than 11 queries.
|
['graphs', 'shortest paths', 'interactive', 'binary search', 'dfs and similar', 'trees']
|
from collections import defaultdict
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def ask(aa):
print("?",len(aa),*aa,flush=True)
node,dist=MI()
return node-1,dist
def main():
for _ in range(II()):
n=II()
to=[[] for _ in range(n)]
for _ in range(n-1):
u,v=MI1()
to[u].append(v)
to[v].append(u)
root,dist=ask(list(range(1,n+1)))
dtou=defaultdict(list)
par=[-1]*n
stack=[(root,-1,0)]
while stack:
u,pu,dep=stack.pop()
dtou[dep].append(u+1)
par[u]=pu
for v in to[u]:
if v==pu:continue
stack.append((v,u,dep+1))
#print(dtou)
l=(dist+1)//2
r=min(len(dtou),dist+1)
#print(l,r)
u2=-1
while l+1<r:
dep=(l+r)//2
u,d=ask(dtou[dep])
if d==dist:
l=dep
u2=u
else:r=dep
if u2==-1:u2,_=ask(dtou[l])
#print(u2)
dep=l
ng=u2
while dep!=dist-l:
ng=par[ng]
dep-=1
uu=[u for u in dtou[dist-l] if u!=ng+1]
if uu:u1,_=ask(uu)
else:u1=root
print("!",u1+1,u2+1,flush=True)
if SI()=="Incorrect":break
main()
|
Python
|
[
"graphs",
"trees"
] | 1,280
| 1,674
| 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,166
|
81efc64bba6d5a667e453260b83640e9
|
The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell. After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability \frac p {100} only, and not performed with probability 1 - \frac p {100}. The cleaning or not cleaning outcomes are independent each second.Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the expected time for the robot to do its job.It can be shown that the answer can be expressed as an irreducible fraction \frac x y, where x and y are integers and y \not \equiv 0 \pmod{10^9 + 7} . Output the integer equal to x \cdot y^{-1} \bmod (10^9 + 7). In other words, output such an integer a that 0 \le a < 10^9 + 7 and a \cdot y \equiv x \pmod {10^9 + 7}.
|
['implementation', 'math', 'probabilities']
|
import os,sys
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math
# 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")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# for _ in range(int(input())):
# def solve():
# n, m, rb, cb, rd, cd = list(map(int, input().split(' ')))
# dr = dc = 1
# ans = 0
# if rb == rd or cb == cd:
# print(0)
# return
# while rb != rd and cb != cd:
# if dr == dc == 1:
# while rb != rd and cb != cd and 1 <= rb < n and 1 <= cb < m:
# rb += 1
# cb += 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == n:
# dr = -1
# if cb == m:
# dc = -1
# elif dr == 1 and dc == -1:
# while rb != rd and cb != cd and 1 <= rb < n and 1 < cb <= m:
# rb += 1
# cb -= 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == n:
# dr = -1
# if cb == 1:
# dc = 1
# elif dr == -1 and dc == 1:
# while rb != rd and cb != cd and 1 < rb <= n and 1 <= cb < m:
# rb -= 1
# cb += 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == 1:
# dr = 1
# if cb == m:
# dc = -1
# else:
# while rb != rd and cb != cd and 1 < rb <= n and 1 < cb <= m:
# rb -= 1
# cb -= 1
# ans += 1
# if rb == rd or cb == cd:
# print(ans)
# return
# if rb == 1:
# dr = 1
# if cb == 1:
# dc = 1
# solve()
# for _ in range(int(input())):
# n = int(input())
# a = [list(map(int, input().split(' '))) for _ in range(n)]
# a.sort(key = lambda x : x[1] - x[0])
# vis = set()
# for i in range(n):
# l, r = a[i]
# for i in range(l, r + 1):
# if i not in vis:
# print(l, r, i)
# vis.add(i)
# print()
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# def check(mid):
# b = a[:]
# for i in range(n - 1, 1, -1):
# if b[i] < mid:
# return False
# r = min(a[i], b[i] - mid)
# r //= 3
# b[i] -= 3 * r
# b[i - 1] += r
# b[i - 2] += 2 * r
# return min(b) >= mid
# l, r = 1, 10 ** 9
# while l <= r:
# mid = (l + r) // 2
# if check(mid):
# l = mid + 1
# else:
# r = mid - 1
# print(r)
mod = 10 ** 9 + 7
for _ in range(int(input())):
def solve():
n, m, rb, cb, rd, cd, p = list(map(int, input().split(' ')))
dr = dc = 1
ans = 0
tmp = []
vis = set()
if rb == n:
dr = -1
if cb == m:
dc = -1
if rb == rd or cb == cd:
tmp.append(0)
vis.add((rb, cb, dr, dc))
ok = True
while ok:
if dr == dc == 1:
while 1 <= rb < n and 1 <= cb < m:
rb += 1
cb += 1
ans += 1
if rb == n:
dr = -1
if cb == m:
dc = -1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
elif dr == 1 and dc == -1:
while 1 <= rb < n and 1 < cb <= m:
rb += 1
cb -= 1
ans += 1
if rb == n:
dr = -1
if cb == 1:
dc = 1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
elif dr == -1 and dc == 1:
while 1 < rb <= n and 1 <= cb < m:
rb -= 1
cb += 1
ans += 1
if rb == 1:
dr = 1
if cb == m:
dc = -1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
else:
while 1 < rb <= n and 1 < cb <= m:
rb -= 1
cb -= 1
ans += 1
if rb == 1:
dr = 1
if cb == 1:
dc = 1
if rb == rd or cb == cd:
if (rb, cb, dr, dc) in vis:
T = ans - tmp[0]
ok = False
break
tmp.append(ans)
vis.add((rb, cb, dr, dc))
l = len(tmp)
res = 0
p = p * pow(100, mod - 2, mod) % mod
q = (1 - p) % mod
power = [1] * 100005
for i in range(1, 100005):
power[i] = power[i - 1] * q % mod
for i in range(l):
res += tmp[i] * p * power[i] * pow(1 - power[l], mod - 2, mod) + T * p * power[i + l] * pow((1 - power[l]) * (1 - power[l]) % mod, mod - 2, mod)
res %= mod
# print(tmp,T)
# print(l, T)
# print(tmp[-100:])
print(res % mod)
solve()
|
Python
|
[
"math",
"probabilities"
] | 2,279
| 8,668
| 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,355
|
2535fc09ce74b829c26e1ebfc1ee17c6
|
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.
|
['data structures', 'greedy', 'trees']
|
n=int(input())
st=[]
ans=0
c=0
for _ in range(2*n):
s=input()
if s=="remove":
if len(st)==0 or c+1==st[-1] :
if len(st)!=0:
st.pop(-1)
c+=1
else:
ans+=1
c+=1
st=[]
else:
st.append(int(s[4:]))
#print (st,end=" ")
#print (ans)
print (ans)
|
Python
|
[
"trees"
] | 1,000
| 270
| 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,846
|
753113fa5130a67423f2e205c97f8017
|
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.
|
['implementation', 'sortings', 'strings']
|
d = {
'rat':[],
'child':[],
'man':[],
'captain':[]
}
i = int(input())
while i:
s = input()
data = s.split()
if data[1] == 'child' or data[1] == 'woman':
d['child'].append(data[0])
else:
d[data[1]].append(data[0])
i = i -1
for p in d['rat']:
print(p)
for p in d['child']:
print(p)
for p in d['man']:
print(p)
for p in d['captain']:
print(p)
|
Python
|
[
"strings"
] | 991
| 408
| 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,506
|
8b61e354ece0242eff539163f76cabde
|
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence .Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].
|
['constructive algorithms', 'number theory', 'math']
|
n = int(input())
if n == 4:
print ("YES\n1 3 2 4")
elif [i for i in range(2,n) if n%i==0]:
print("NO")
else:
print("YES\n1 %s"%(" ".join(str((pow(x+1,n-2,n)*(x+2))%n or n) for x in range(n-1))))
|
Python
|
[
"number theory",
"math"
] | 204
| 208
| 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,897
|
9144a2386a8ca167e719d8305fa8a2fe
|
Two kittens, Max and Min, play with a pair of non-negative integers x and y. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, x and y became negative at the same time, and kitten Max tries to prevent him from doing so.Each kitten has a set of pairs of integers available to it. Kitten Max has n pairs of non-negative integers (ai, bi) (1 ≤ i ≤ n), and kitten Min has m pairs of non-negative integers (cj, dj) (1 ≤ j ≤ m). As kitten Max makes a move, it can take any available pair (ai, bi) and add ai to x and bi to y, and kitten Min can take any available pair (cj, dj) and subtract cj from x and dj from y. Each kitten can use each pair multiple times during distinct moves.Max moves first. Kitten Min is winning if at some moment both numbers a, b are negative simultaneously. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.
|
['geometry']
|
from __future__ import division
import sys
from itertools import chain, izip_longest
def read_ints(itr):
return map(int, next(itr).split(' '))
def read_pairs(itr, n):
for i in xrange(n):
yield read_ints(itr)
def convex_hull(pairs):
sorted_pairs = sorted(pairs)
begin_pad, end_pad = get_pads(sorted_pairs)
convex_hull_pairs = [begin_pad]
consideration_point = sorted_pairs[0]
for pair in sorted_pairs[1:]:
if point_above_line(convex_hull_pairs[-1], pair, consideration_point):
convex_hull_pairs.append(consideration_point)
consideration_point = pair
convex_hull_pairs.append(consideration_point)
convex_hull_pairs.append(end_pad)
return convex_hull_pairs
def get_pads(pairs):
pairs = list(pairs)
first_x, first_y = pairs[0]
last_x, last_y = pairs[-1]
return [0, first_y], [last_x, 0]
def pad_pairs(pairs):
begin_pad, end_pad = get_pads(pairs)
return chain([begin_pad], pairs, [end_pad])
def point_above_line(p1, p2, p, strict=True):
'''
Returns true if p is above the line segment p1, p2. p_x must
be between p_1x and p_2x.
If strict=True, then the point must be strictly above the line.
Otherwise, a point on the line will return True.
'''
p_x, p_y = p
a = p2[0] - p[0]
b = p[0] - p1[0]
extrapolated_y = a * p1[1] + b * p2[1]
point_y = (a + b) * p_y
if strict:
return point_y > extrapolated_y
else:
return point_y >= extrapolated_y
def any_dominates(dominator, dominated):
def advance(left, right):
return (right, next(dominated))
# I'll need to access the same elements more than once
dominated = iter(dominated)
# Start with the furthest left (smallest x) two (potentially) dominated pairs,
# then gradualy work right as needed
dominated_left = next(dominated)
dominated_right = next(dominated)
# For each pair in the (potential) dominator, check whether it dominates
for dominator_current in dominator:
# print 'Examining max pair ({}, {})'.format(*dominator_current)
# Shift dominated window until the two line up
while dominator_current[0] >= dominated_right[0]:
try:
dominated_left, dominated_right = advance(dominated_left, dominated_right)
except StopIteration:
# dominated can't catch up to dominator
# print "Min can't get that far right. Returning True"
return True
# print "Min surrounding points: {} and {}".format(tuple(dominated_left), tuple(dominated_right))
# Now dominated_left_x <= dominator_current_x <= dominated_right_x
# Need to find the linear combination of left_x and right_x that will be equal to
# current_x and see if that same combination of left_y and right_y is greater than
# or less than current_y
if point_above_line(dominator_current, dominated_left, dominated_right, strict=False):
return True
# Got through the loop and can't dominate? Must not be a winner
# print "never dominated. returning false."
return False
if __name__ == '__main__':
n, m = read_ints(sys.stdin)
x, y = read_ints(sys.stdin)
max_pairs = sorted(read_pairs(sys.stdin, n))
# print 'Read max pairs: {}'.format(max_pairs)
min_pairs = convex_hull(read_pairs(sys.stdin, m))
# print 'Read min pairs: {}'.format(min_pairs)
if any_dominates(max_pairs, min_pairs):
print "Max"
else:
print "Min"
|
Python
|
[
"geometry"
] | 1,000
| 3,566
| 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
}
| 922
|
a5d56056fd66713128616bc7c2de8b22
|
Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively "Loves" and "Doesn't love", at that Marina always starts with "Loves". There are n camomiles growing in the field, possessing the numbers of petals equal to a1, a2, ... an. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be "Loves". Help her do that; find the maximal number of petals possible in the bouquet.
|
['implementation', 'number theory']
|
# ///==========Libraries, Constants and Functions=============///
#mkraghav
import sys
inf = float("inf")
mod = 1000000007
def get_array(): return list(map(int, sys.stdin.readline().split()))
def get_ints(): return map(int, sys.stdin.readline().split())
def input(): return sys.stdin.readline()
def int1():return int(input())
import string
import math
from itertools import combinations
# ///==========MAIN=============///
def main():
n=int(input())
sum=0
mn=105
l=map(int,input().split())
for x in l:
sum=sum+x
if x%2==1:
mn=min(mn,x)
if sum%2==0:
if mn==105:
print(0)
else:
print(sum-mn)
else:
print(sum)
if __name__ == "__main__":
main()
|
Python
|
[
"number theory"
] | 705
| 743
| 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
}
| 3,679
|
ff8219b0e4fd699b1898500664087e90
|
The Dogeforces company has k employees. Each employee, except for lower-level employees, has at least 2 subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.The full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.
|
['constructive algorithms', 'data structures', 'dfs and similar', 'divide and conquer', 'dsu', 'greedy', 'sortings', 'trees']
|
import sys
input = sys.stdin.buffer.readline
def findroot(parent, x):
y = x
while y != parent[y]:
y = parent[y]
return y
def process(A):
n = len(A[0])
parent = [i for i in range(n)]
weight = [None for i in range(n)]
L = []
for i in range(n):
w = A[i][i]
weight[i] = w
for j in range(i):
L.append([A[i][j], i, j])
m = len(L)
L.sort()
x = n
graph = []
for i in range(m):
w, I, J = L[i]
I1 = findroot(parent, I)
J1 = findroot(parent, J)
if I1 != J1:
if weight[I1]==w:
graph.append([J1, I1])
parent[J1] = I1
elif weight[J1]==w:
graph.append([I1, J1])
parent[I1] = J1
else:
parent.append(x)
weight.append(w)
parent[I1] = x
parent[J1] = x
graph.append([I1, x])
graph.append([J1, x])
x+=1
n = len(weight)
sys.stdout.write(f'{n}\n')
weight = ' '.join(map(str, weight))
sys.stdout.write(f'{weight}\n')
sys.stdout.write(f'{n}\n')
for a, b in graph:
sys.stdout.write(f'{a+1} {b+1}\n')
k = int(input())
A = []
for i in range(k):
row = [int(x) for x in input().split()]
A.append(row)
process(A)
|
Python
|
[
"graphs",
"trees"
] | 765
| 1,448
| 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,488
|
ef2b90d5b1073430795704a7df748ac3
|
You are given n words of equal length m, consisting of lowercase Latin alphabet letters. The i-th word is denoted s_i.In one move you can choose any position in any single word and change the letter at that position to the previous or next letter in alphabetical order. For example: you can change 'e' to 'd' or to 'f'; 'a' can only be changed to 'b'; 'z' can only be changed to 'y'. The difference between two words is the minimum number of moves required to make them equal. For example, the difference between "best" and "cost" is 1 + 10 + 0 + 0 = 11.Find the minimum difference of s_i and s_j such that (i < j). In other words, find the minimum difference over all possible pairs of the n words.
|
['brute force', 'greedy', 'implementation', 'implementation', 'math', 'strings']
|
for i in range(int(input())):
n,m=map(int,input().split())
o=[]
ls=[]
for i in range(n):
a=str(input())
s=[]
for j in a:
s+=[ord(j)-96]
o+=[s]
mi = (2**31)-1
for j in range(len(o)):
for k in range(len(o)):
if(j!=k):
pq=[]
for a,b in zip(o[j],o[k]):
pq.append(abs(a-b))
gd=sum(pq)
mi=min(gd,mi)
print(mi)
|
Python
|
[
"math",
"strings"
] | 759
| 498
| 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
}
| 855
|
67dd049fafc464fed87fbd23f0ccc8ab
|
Monocarp is going to host a party for his friends. He prepared n dishes and is about to serve them. First, he has to add some powdered pepper to each of them — otherwise, the dishes will be pretty tasteless.The i-th dish has two values a_i and b_i — its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are m shops in his local area. The j-th of them has packages of red pepper sufficient for x_j servings and packages of black pepper sufficient for y_j servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases x red pepper packages and y black pepper packages, then x and y should be non-negative and x \cdot x_j + y \cdot y_j should be equal to n.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
|
['brute force', 'data structures', 'greedy', 'math', 'number theory']
|
import sys
input = sys.stdin.readline
n=int(input())
ans=0
l=[]
for _ in range(n):
a,b=map(int,input().split())
ans+=a
l.append(b-a)
l.sort(reverse=True)
idx=10**10
for i in range(n):
if l[i]<0:
idx=i
break
rui=[0]
for i in range(n):
rui.append(rui[-1]+l[i])
def extgcd(a, b):
if b:
d, y, x = extgcd(b, a % b)
y -= (a // b)*x
return d, x, y
return a, 1, 0
import math
m=int(input())
#print(l)
#print(rui)
#print(ans,idx)
for _ in range(m):
x,y=map(int,input().split())
g=math.gcd(x,y)
if n%g>0:
print(-1)
continue
g,a,b=extgcd(x,y)
a*=(n//g)
b*=(n//g)
idx2=idx
#print(a,b,idx)
if b<idx2//y:
tmp=(idx2//y-b)//(x//g)
b+=(tmp*(x//g))
else:
tmp=(b-idx2//y)//(x//g)
b-=(tmp*(x//g))
if b<0:
tmp=b//(x//g)
b+=tmp*(x//g)
if b*y>n:
tmp=(b*y-n)//(y*(x//g))
b-=tmp*(x//g)
ma=-10**20
for i in range(-2,3):
tmpb=b+i*(x//g)
if 0<=tmpb*y<=n:
ma=max(ma,rui[tmpb*y])
if ma==-10**20:
print(-1)
else:
print(ans+ma)
|
Python
|
[
"math",
"number theory"
] | 1,366
| 1,099
| 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,335
|
c8d8867789284b2e27fbb73ab3e59793
|
One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersections, which means that in case any two segments shared a common point, that point was an endpoint for both of them (please consult the examples in the notes section).Unfortunately, the polyline was erased, and you only know the lengths of the horizonal and vertical segments. Please construct any polyline matching the description with such segments, or determine that it does not exist.
|
['dp', 'constructive algorithms', 'geometry']
|
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
t = int(input())
for _ in range(t):
if _ != 0:
input()
h = int(input())
l1 = list(map(int,input().split()))
v = int(input())
l2 = list(map(int,input().split()))
hKnap = [1]
vKnap = [1]
if h != v or sum(l1) % 2 != 0 or sum(l2) % 2 != 0:
print("No")
continue
for elem in l1:
hKnap.append((hKnap[-1] << elem) | hKnap[-1])
for elem in l2:
vKnap.append((vKnap[-1] << elem) | vKnap[-1])
hSet = []
hSet2 = []
vSet = []
vSet2 = []
if hKnap[-1] & 1 << (sum(l1) // 2):
curSum = sum(l1) // 2
for i in range(h - 1, -1, -1):
if curSum >= l1[i] and hKnap[i] & (1 << (curSum - l1[i])):
curSum -= l1[i]
hSet.append(l1[i])
else:
hSet2.append(l1[i])
if vKnap[-1] & 1 << (sum(l2) // 2):
curSum = sum(l2) // 2
for i in range(v - 1, -1, -1):
if curSum >= l2[i] and vKnap[i] & (1 << (curSum - l2[i])):
curSum -= l2[i]
vSet.append(l2[i])
else:
vSet2.append(l2[i])
if not hSet or not vSet:
print("No")
else:
print("Yes")
if len(hSet) < len(hSet2):
hTupleS = tuple(sorted(hSet))
hTupleL = tuple(sorted(hSet2))
else:
hTupleS = tuple(sorted(hSet2))
hTupleL = tuple(sorted(hSet))
if len(vSet) < len(vSet2):
vTupleS = tuple(sorted(vSet))
vTupleL = tuple(sorted(vSet2))
else:
vTupleS = tuple(sorted(vSet2))
vTupleL = tuple(sorted(vSet))
currentLoc = [0,0]
isHS = True
isHL = False
isVS = False
isVL = True
hIndex = len(hTupleS)-1
vIndex = 0
for i in range(h):
if isHS:
currentLoc[0] += hTupleS[hIndex]
hIndex -= 1
if hIndex < 0:
hIndex = len(hTupleL) - 1
isHS = False
isHL = True
elif isHL:
currentLoc[0] -= hTupleL[hIndex]
hIndex -= 1
print(str(currentLoc[0]) + " " + str(currentLoc[1]))
if isVL:
currentLoc[1] += vTupleL[vIndex]
vIndex += 1
if vIndex >= len(vTupleL):
vIndex = 0
isVL = False
isVH = True
elif isHL:
currentLoc[1] -= vTupleS[vIndex]
vIndex += 1
print(str(currentLoc[0]) + " " + str(currentLoc[1]))
# 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
|
Python
|
[
"geometry"
] | 706
| 4,773
| 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
}
| 18
|
3d8aa764053d3cf14f34f11de61d1816
|
Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance.Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with n vertices.Hag brought two pins and pinned the polygon with them in the 1-st and 2-nd vertices to the wall. His dad has q queries to Hag of two types. 1 f t: pull a pin from the vertex f, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex t. 2 v: answer what are the coordinates of the vertex v. Please help Hag to answer his father's queries.You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.
|
['geometry']
|
import math;
#Вычисление координаты точки по координатам центра, углу, и начальным относительно центра
def getCoordinate(gx, gy, alpha, x, y):
x1=gx+x*math.cos(alpha)-y*math.sin(alpha);
y1=gy+x*math.sin(alpha)+y*math.cos(alpha);
return x1, y1
#Вычисление угла, на который надо повернуть точку с координатами x, y,
#чтобы она оказалась прямо над gx, gy
def getAngle(gx, gy, x, y):
x=x-gx;
y=y-gy;
cos=x/math.sqrt(x**2+y**2);
alpha=math.acos(cos);
if y<0:
alpha=-alpha;
return math.pi/2-alpha;
n, q = map(int, input().split(' '));
x=[0]*n;
y=[0]*n;
for i in range(n):
x[i], y[i]=map(int, input().split(' '));
r=[0]*q;
f=[0]*q;
t=[0]*q;
v=[0]*q;
for i in range(q):
l=list(map(int, input().split(' ')));
r[i]=l[0];
if r[i]==1:
f[i]=l[1]-1;
t[i]=l[2]-1;
else:
v[i]=l[1]-1;
gx=0;
gy=0;
s=0;
for i in range(n):
ip=i+1;
if ip==n:
ip=0;
ds=x[i]*y[ip]-x[ip]*y[i];
s+=ds;
gx+=(x[i]+x[ip])*ds;
gy+=(y[i]+y[ip])*ds;
s/=2;
gx/=6*s;
gy/=6*s;
angles=[0]*n;
for i in range(n):
angles[i]=getAngle(gx, gy, x[i], y[i]);
for i in range(n):
x[i]-=gx;
y[i]-=gy;
alpha=0;
#print('pos',gx, gy, alpha);
#Восстанавливать положение точек будем по центру масс и углу
#Угол - поворот против часовой вокруг центра масс
fix={0, 1}
for i in range(q):
if r[i]==2:
currX, currY = getCoordinate(gx, gy, alpha, x[v[i]], y[v[i]]);
print("%.6f %.6f"%(currX, currY))
else:
if len(fix)==2:
fix.remove(f[i]);
#print('remove',f[i])
#j - единственный элемент в множестве
for j in fix:
#print(j);
currX, currY = getCoordinate(gx, gy, alpha, x[j], y[j]);
#print('fix:', currX, currY)
#dalpha=getAngle(gx, gy, currX, currY);
#alpha+=dalpha;
alpha=angles[j];
#Чтобы вычислить новые координаты g, нуно повернуть ее на угол
#dalpha относительно currX, currY
gx, gy=currX, currY-math.sqrt(x[j]**2+y[j]**2);
#print('pos',gx, gy, alpha/math.pi)
fix.add(t[i]);
|
Python
|
[
"geometry"
] | 1,410
| 2,157
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,093
|
02b0ffb0045fc0a2c8613c8ef58ed2c8
|
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.
|
['implementation', 'strings']
|
n = int(raw_input())
s = str(raw_input())
m = int(raw_input())
cur = set(s)
st = None
for i in range(m):
t = str(raw_input())
#check first if t is possible
ch = ''.join(i if i in s else '*' for i in t)
if ch == s:
if st is None:
st = set(t)
else:
st.intersection_update(set(t))
if st is None:
st = set()
st.difference_update(cur)
print len(st)
|
Python
|
[
"strings"
] | 1,337
| 404
| 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,685
|
ae61e1270eeda8c30effc9ed999bf531
|
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
|
['implementation', 'dfs and similar', 'greedy']
|
import math
import sys
def main():
out = 0
n = int(raw_input())
lights = map(int, raw_input().split())
current_nodes = 2**n
current_index = len(lights)
current_index -= current_nodes
current_lights = lights[current_index:]
next_lights = []
for i in range(0, len(current_lights), 2):
a = current_lights[i]
b = current_lights[i + 1]
out += max(a, b) - min(a, b)
next_lights.append(max(a, b))
n -= 1
while n > 0:
current_lights = lights[current_index - 2**n:current_index]
current_index = current_index - 2**n
tmp = []
for i in range(0, len(current_lights), 2):
a = current_lights[i] + next_lights[i]
b = current_lights[i + 1] + next_lights[i + 1]
out += max(a, b) - min(a, b)
tmp.append(max(a, b))
next_lights = tmp
n -= 1
print out
if __name__ == '__main__':
main()
|
Python
|
[
"graphs"
] | 1,532
| 858
| 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,217
|
9044eacc1833c667985c343a71fb4a58
|
You are given n segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.Count the number of distinct points with integer coordinates, which are covered by at least one segment.
|
['number theory', 'geometry', 'fft']
|
from math import gcd
from bisect import *
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, val):
return Point(self.x + val.x, self.y + val.y)
def __sub__(self, val):
return Point(self.x - val.x, self.y - val.y)
def __mul__(self, ratio):
return Point(self.x * ratio, self.y * ratio)
def __truediv__(self, ratio):
return Point(self.x / ratio, self.y / ratio)
@staticmethod
def det(A, B):
return A.x * B.y - A.y * B.x
@staticmethod
def dot(A, B):
return A.x * B.x + A.y * B.y
def onSegment(self, A, B):
if self.det(B-A, self-A) != 0:
return False
if self.dot(B-A, self-A) < 0:
return False
if self.dot(A-B, self-B) < 0:
return False
return True
def intPoints(x1, y1, x2, y2):
dx, dy = abs(x2 - x1), abs(y2 - y1)
return gcd(dx, dy) + 1
def crosspoint(L1, L2):
A, B = Point(L1[0], L1[1]), Point(L1[2], L1[3])
C, D = Point(L2[0], L2[1]), Point(L2[2], L2[3])
S1, S2 = Point.det(C-A, D-A), Point.det(C-D, B-A)
delta = (B - A) * S1
if S2 == 0 or delta.x % S2 != 0 or delta.y % S2 != 0:
return None
delta = delta / S2;
P = A + delta
if not P.onSegment(A, B) or not P.onSegment(C, D):
return None
return (P.x, P.y)
n = int(input())
lines = [ tuple(int(z) for z in input().split()) \
for i in range(n) ]
count = dict()
for i in range(n):
for j in range(i):
P = crosspoint(lines[i], lines[j])
if P != None:
count[P] = count.get(P, 0) + 1
answer = sum(intPoints(*L) for L in lines)
tri = [ x*(x+1)//2 for x in range(n+1) ]
for z in count:
k = bisect_right(tri, count[z])
answer -= k - 1;
print(answer)
|
Python
|
[
"math",
"number theory",
"geometry"
] | 285
| 1,808
| 0
| 1
| 0
| 1
| 1
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 3,858
|
077e0e207d3c530fbf1ba1ac6d3fba6e
|
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A.During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: Delete the first character of S and add it at the front of A. Delete the first character of S and add it at the back of A.Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998\,244\,353.Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S.
|
['dp', 'strings']
|
import sys
range = xrange
input = raw_input
MOD = 998244353
def modder(x):
return x if x < MOD else x - MOD
S = input()
T = input()
n = len(S)
m = len(T)
DP = [[0]*n for _ in range(n + 1)]
c = S[0]
for i in range(n):
DP[1][i] = 2 * (i >= m or c == T[i])
for l in range(1, n):
DPl = DP[l]
DPlp1 = DP[l + 1]
for i in range(n - l + 1):
c = S[l]
if i and (i - 1 >= m or T[i - 1] == c):
DPlp1[i - 1] = modder(DPlp1[i - 1] + DPl[i])
if i + l < n and (i + l >= m or T[i + l] == c):
DPlp1[i] += modder(DPlp1[i] + DPl[i])
print sum(DP[j][0] for j in range(m, n + 1)) % MOD
|
Python
|
[
"strings"
] | 1,357
| 641
| 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
}
| 347
|
3581b3a6bf7b122b49c481535491399d
|
You are given a tree (connected graph without cycles) consisting of n vertices. The tree is unrooted — it is just a connected undirected graph without cycles.In one move, you can choose exactly k leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them with edges incident to them. I.e. you choose such leaves u_1, u_2, \dots, u_k that there are edges (u_1, v), (u_2, v), \dots, (u_k, v) and remove these leaves and these edges.Your task is to find the maximum number of moves you can perform if you remove leaves optimally.You have to answer t independent test cases.
|
['data structures', 'implementation', 'greedy', 'trees']
|
from collections import defaultdict,deque
import sys
input=sys.stdin.readline
t=int(input())
for ii in range(t):
graph=defaultdict(list)
n,k=map(int,input().split())
st=[]
for i in range(n-1):
u,v=map(int,input().split())
graph[u].append(v)
graph[v].append(u)
if k==1:
print(n-1)
else:
leaves=deque()
for i in graph:
if len(graph[i])==1:
leaves.append(i)
#print(leaves)
treecount=[0]*(n+1)
for i in leaves:
treecount[i]=-1
ans=0
#print(graph)
while leaves:
size=len(leaves)
for j in range(size):
vertex=leaves.popleft()
treecount[vertex]=10000000
for i in graph[vertex]:
if treecount[i]!=-1 and treecount[i]<10000000:
treecount[i]+=1
#print(i,treecount,'aa',treecount[i]%k,treecount[i],k)
if treecount[i]%k==0 :
ans+=1
#print(ans,i,'aaa')
if treecount[i]==len(graph[i])-1:
pos=0
for kj in graph[i]:
if treecount[kj]==10000000:
pos+=1
#print(pos,i)
if pos==len(graph[i])-1:
treecount[i]=-1
leaves.append(i)
else:
sys.stdout.write(str(min(ans,n-1))+'\n')
#-1 ->leaves, 0 -> inner nodes, 10000000 -> visited nodes
|
Python
|
[
"trees"
] | 680
| 1,762
| 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,249
|
41d791867f27a57b50eebaad29754520
|
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.
|
['geometry', 'brute force']
|
n = int(raw_input().strip())
ans = [4*4] * n
for i in range(4*n):
if i%4 == 0: coords = [[] for _ in range(4)]
x,y,a,b = map(int, raw_input().strip().split())
coords[i%4] += [complex(x,y)]
for _ in range(3):
x, y = a - (y - b), b + (x - a)
coords[i%4] += [complex(x,y)]
if i%4 == 3:
for b in range(4**4):
cb = [(b / 4**p)%4 for p in range(4)]
verts = []
for j in range(4):
p = coords[j][cb[j]]
if p in verts: continue
verts += [p]
if len(verts) < 4: continue
t = [False] * 4
for k in range(4):
edges = [verts[j] - verts[k] for j in range(4) if j is not k]
lensq = sorted([abs(e*e.conjugate()) for e in edges])
if lensq[0] == 0: continue
if lensq[0] == lensq[1] and lensq[2] == 2*lensq[0]:
t[k] = True
if False not in t:
ans[i//4] = min(ans[i//4], sum(cb))
for i in range(n):
if ans[i] == 16: print -1
else: print ans[i]
|
Python
|
[
"geometry"
] | 760
| 1,102
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,302
|
9cd17c2617b6cde593ef12b2a0a807fb
|
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x1 < x2 < ... < xk where p matches s. More formally, for each xi (1 ≤ i ≤ k) he condition sxisxi + 1... sxi + |p| - 1 = p is fullfilled.Then Malekas wrote down one of subsequences of x1, x2, ... xk (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.Answer can be very large, so Tavas wants you to print the answer modulo 109 + 7.
|
['hashing', 'string suffix structures', 'strings']
|
# -*- coding: utf-8 -*-
def solve():
n, m = map(int, input().split())
p = input()
if m == 0:
return powmod(n)
delta = len(p) - 1
ys = map(int, input().split())
tail = 0
free_chars = 0
for y in ys:
if y > tail:
free_chars += y - tail - 1
elif not is_consistent(p, tail - y + 1):
return 0
tail = y + delta
free_chars += n - tail
return powmod(free_chars)
ok_set = set()
def is_consistent(p, margin):
global ok_set
if margin in ok_set:
return True
elif p[:margin] == p[-margin:]:
ok_set.add(margin)
return True
else:
return False
def powmod(p):
mod = 10**9 + 7
pbin = bin(p)[2:][-1::-1]
result = 26 if pbin[0] == '1' else 1
tmp = 26
for bit in pbin[1:]:
tmp *= tmp
tmp %= mod
if bit == '1':
result *= tmp
result %= mod
return result
print(solve())
# Made By Mostafa_Khaled
|
Python
|
[
"strings"
] | 1,197
| 1,044
| 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,637
|
52863d45ad223687e6975344ab9d3124
|
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
|
['dp', 'divide and conquer', 'trees', 'dfs and similar']
|
import collections
class Graph:
def __init__(self, n, dir):
self.node_cnt = n
self.__directed = dir
self.__adjList = []
for i in range(n): self.__adjList.append([])
def addEdge(self, u, v):
self.__adjList[u].append(v)
if not self.__directed: self.__adjList[v].append(u)
def getDistances(self, start, end=None):
assert (0 <= start and start < self.node_cnt)
dist = [-1] * self.node_cnt
q = collections.deque()
dist[start] = 0
q.append(start)
while len(q) > 0:
z, breakable = q.popleft(), False
if end == z: break
for t in self.__adjList[z]:
if dist[t] == -1:
dist[t] = dist[z] + 1
q.append(t)
if t == end:
breakable = True
break
if breakable: break
return dist
def getAffectedDiameter(graph, affected):
affection = [False for i in range(graph.node_cnt)]
for x in affected: affection[x] = True
dist0 = graph.getDistances(affected[0])
affect_1 = -1
for i in range(n):
if affection[i] and (affect_1 == -1 or dist0[affect_1] < dist0[i]):
affect_1 = i
dist1 = graph.getDistances(affect_1)
affect_2 = -1
for i in range(n):
if affection[i] and (affect_2 == -1 or dist1[affect_2] < dist1[i]):
affect_2 = i
return affect_1, affect_2
n, m, d = map(int, input().split())
p = list(map(lambda s: int(s)-1, input().split()))
g = Graph(n, dir=False)
for i in range(1, n):
a, b = map(lambda s: int(s)-1, input().split())
g.addEdge(a, b)
p1, p2 = getAffectedDiameter(g, p)
d1, d2 = g.getDistances(p1), g.getDistances(p2)
cnt = 0
for i in range(n):
if d1[i] <= d and d2[i] <= d: cnt += 1
print(cnt)
|
Python
|
[
"graphs",
"trees"
] | 1,106
| 1,589
| 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,206
|
21c0e12347d8be7dd19cb9f43a31be85
|
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct: a1 is equivalent to b1, and a2 is equivalent to b2 a1 is equivalent to b2, and a2 is equivalent to b1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!
|
['hashing', 'divide and conquer', 'sortings', 'strings']
|
def checaEquavalencia(a, b, tam):
if a == b:
#print('YES')
return True
elif len(a) % 2 == 1:
return False
elif len(b) % 2 == 1:
return False
elif tam > 1:
tam = tam // 2
a1 = a[ : tam]
a2 = a[tam : ]
b1 = b[ : tam]
b2 = b[tam : ]
#caso1 = checaEquavalencia(a1, b1, tam) and checaEquavalencia(a2, b2, tam)
#caso2 = checaEquavalencia(a1, b2, tam) and checaEquavalencia(a2, b1, tam)
if checaEquavalencia(a1, b2, tam) and checaEquavalencia(a2, b1, tam):
return True
elif checaEquavalencia(a1, b1, tam) and checaEquavalencia(a2, b2, tam):
return True
return False
a = input()
b = input()
resposta = 'NO'
ta = len(a)
tb = len(b)
if(ta != tb):
resposta = 'NO'
elif(a == b):
resposta = 'YES'
elif(ta % 2 == 0):
resp = checaEquavalencia(a , b, ta)
if resp == True:
resposta = 'YES'
print(resposta)
|
Python
|
[
"strings"
] | 627
| 880
| 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,736
|
5dbf91f756fecb004c836a628eb23578
|
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
|
['shortest paths', 'graphs']
|
n = int(input())
mt = [[] for _i in range(n)]
for i in range(n):
mt[i] = list(map(int,input().split()))
# print(mt)
kk = int(input())
for i in range(kk):
a,b,c = map(int,input().split())
a-=1
b-=1
if mt[a][b]>c:
mt[a][b] = c
mt[b][a] = c
for i in range(n):
for j in range(n):
mt[i][j] = min(mt[i][j],mt[i][a]+mt[b][j]+c,mt[i][b]+mt[a][j]+c)
ans = 0
for i in range(n):
ans+= sum(mt[i])
print(ans//2)
|
Python
|
[
"graphs"
] | 868
| 492
| 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,373
|
64700ca85ef3b7408d7d7ad1132f8f81
|
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
|
['greedy', 'constructive algorithms', 'number theory', 'dsu', 'sortings', 'dfs and similar', 'strings']
|
from collections import Counter
def is_prime(x):
if x < 2:
return 0
for i in range(2, x):
if x % i == 0:
return False
return True
def proc(s):
n = len(s)
same = set()
for p in range(2,n+1):
if not is_prime(p):
continue
if p * 2 > n:
continue
for i in range(2, n//p+1):
same.add(p*i)
same.add(p)
counter = Counter(s)
ch, count = counter.most_common(1)[0]
if count < len(same):
print("NO")
return
same = [x-1 for x in same]
w = [x for x in s]
for i in same:
if w[i] == ch:
continue
for j in range(n):
if j not in same and w[j] == ch:
tmp = w[j]
w[j] = w[i]
w[i] = tmp
break
print("YES")
print(''.join(w))
s = input()
proc(s)
|
Python
|
[
"number theory",
"strings",
"graphs"
] | 461
| 906
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
{
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 1,
"trees": 0
}
| 3,580
|
bd519efcfaf5b43bb737337004a1c2c0
|
You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
|
['geometry']
|
n = int(input())
points = [0] * n
D = {}
for i in range(n):
points[i] = tuple(int(x) for x in input().split())
for i in range(n):
for j in range(i+1, n):
x1, y1 = points[i]
x2, y2 = points[j]
u, v = x2 - x1, y2 - y1
if u < 0 or u == 0 and v < 0:
u, v = -u, -v
if (u, v) in D:
D[(u, v)] += 1
else:
D[(u, v)] = 1
S = sum(D[i] * (D[i] - 1) // 2 for i in D)
print(S // 2)
|
Python
|
[
"geometry"
] | 178
| 479
| 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,085
|
d9eb0f6f82bd09ea53a1dbbd7242c497
|
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
|
['sortings', 'geometry']
|
def cw(a, b, c):
return a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) <= 0
def ccw(a, b, c):
return a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) >= 0
def convex_hull(points):
points = sorted(points, key = lambda x: (x[0], x[1]))
up = [points[0]]
down = [points[0]]
for i in range(1, len(points)):
if (i == len(points)-1 or cw(points[0], points[i], points[-1])):
while (len(up) >= 2 and not cw(up[-2], up[-1], points[i])):
up.pop(-1)
up.append(points[i])
if (i == len(points)-1 or ccw(points[0], points[i], points[-1])):
while (len(down) >= 2 and not ccw(down[-2], down[-1], points[i])):
down.pop(-1)
down.append(points[i])
points = up[:] + down[1:-1][::-1]
return points
points = []
n = int(input())
for i in range(n):
x, y = map(int, input().split())
points.append([x, y, 0])
m = int(input())
for i in range(m):
x, y = map(int, input().split())
points.append([x, y, 1])
points = convex_hull(points)
for p in points:
if p[-1] == 1:
print('NO')
break
else:
print('YES')
|
Python
|
[
"geometry"
] | 625
| 1,188
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
{
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
}
| 4,198
|
d3bdb328e4d37de374cb3201c2a86eee
|
After Vitaly was expelled from the university, he became interested in the graph theory.Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w — the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.Two ways to add edges to the graph are considered equal if they have the same sets of added edges.Since Vitaly does not study at the university, he asked you to help him with this task.
|
['combinatorics', 'graphs', 'dfs and similar', 'math']
|
n, m = [int(x) for x in input().split()]
E = {i:[] for i in range(n)}
for i in range(m):
u, v = [int(x)-1 for x in input().split()]
E[v].append(u)
E[u].append(v)
def dfs():
visited = [False for i in range(n)]
colour = [0 for i in range(n)]
ans = 0
for v in range(n):
if visited[v]: continue
stack = [(v, 0)]
part = [0, 0]
while stack:
node, c = stack.pop()
if not visited[node]:
part[c] += 1
visited[node] = True
colour[node] = c
stack.extend((u,c^1) for u in E[node])
elif c != colour[node]:
return (0, 1)
ans += (part[0]*(part[0] - 1) + part[1]*(part[1] - 1)) // 2
return (1, ans)
if m == 0:
print(3, n*(n-1)*(n-2)//6)
elif max(len(E[v]) for v in E) == 1:
print(2, m*(n-2))
else:
ans = dfs()
print(ans[0], ans[1])
|
Python
|
[
"math",
"graphs"
] | 918
| 938
| 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
}
| 310
|
c4016ba22de92d1c7c2e6d13fedc062d
|
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.Help the King to calculate this characteristic for each of his plan.
|
['dp', 'graphs', 'sortings', 'divide and conquer', 'dfs and similar', 'trees']
|
import sys
from collections import deque
def solve():
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
# Euler tour technique
S = []
FS = [0]*N; LS = [0]*N
depth = [0]*N
stk = [-1, 0]
it = [0]*N
while len(stk) > 1:
v = stk[-1]
i = it[v]
if i == 0:
FS[v] = len(S)
depth[v] = len(stk)
if i < len(G[v]) and G[v][i] == stk[-2]:
it[v] += 1
i += 1
if i == len(G[v]):
LS[v] = len(S)
stk.pop()
else:
stk.append(G[v][i])
it[v] += 1
S.append(v)
L = len(S)
lg = [0]*(L+1)
# Sparse Table
for i in range(2, L+1):
lg[i] = lg[i >> 1] + 1
st = [[L]*(L - (1 << i) + 1) for i in range(lg[L]+1)]
st[0][:] = S
b = 1
for i in range(lg[L]):
st0 = st[i]
st1 = st[i+1]
for j in range(L - (b<<1) + 1):
st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
b <<= 1
INF = 10**18
ans = []
Q = int(readline())
G0 = [[]]*N
P = [0]*N
deg = [0]*N
KS = [0]*N
A = [0]*N
B = [0]*N
for t in range(Q):
k, *vs = map(int, readline().split())
for i in range(k):
vs[i] -= 1
KS[vs[i]] = 1
vs.sort(key=FS.__getitem__)
for i in range(k-1):
x = FS[vs[i]]; y = FS[vs[i+1]]
l = lg[y - x + 1]
w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
vs.append(w)
vs.sort(key=FS.__getitem__)
stk = []
prv = -1
for v in vs:
if v == prv:
continue
while stk and LS[stk[-1]] < FS[v]:
stk.pop()
if stk:
G0[stk[-1]].append(v)
G0[v] = []
it[v] = 0
stk.append(v)
prv = v
que = deque()
prv = -1
P[vs[0]] = -1
for v in vs:
if v == prv:
continue
for w in G0[v]:
P[w] = v
deg[v] = len(G0[v])
if deg[v] == 0:
que.append(v)
prv = v
while que:
v = que.popleft()
if KS[v]:
a = 0
for w in G0[v]:
ra = A[w]; rb = B[w]
if depth[v]+1 < depth[w]:
a += min(ra, rb+1)
else:
a += ra
A[v] = INF
B[v] = a
else:
a = 0; b = c = INF
for w in G0[v]:
ra = A[w]; rb = B[w]
a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb))
A[v] = min(a, b+1, c+1)
B[v] = b
p = P[v]
if p != -1:
deg[p] -= 1
if deg[p] == 0:
que.append(p)
v = min(A[vs[0]], B[vs[0]])
if v >= INF:
ans.append("-1\n")
else:
ans.append("%d\n" % v)
for v in vs:
KS[v] = 0
writelines(ans)
solve()
|
Python
|
[
"graphs",
"trees"
] | 1,399
| 3,464
| 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,449
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.