problem_id
stringlengths 3
7
| contestId
stringclasses 660
values | problem_index
stringclasses 27
values | programmingLanguage
stringclasses 3
values | testset
stringclasses 5
values | incorrect_passedTestCount
float64 0
146
| incorrect_timeConsumedMillis
float64 15
4.26k
| incorrect_memoryConsumedBytes
float64 0
271M
| incorrect_submission_id
stringlengths 7
9
| incorrect_source
stringlengths 10
27.7k
| correct_passedTestCount
float64 2
360
| correct_timeConsumedMillis
int64 30
8.06k
| correct_memoryConsumedBytes
int64 0
475M
| correct_submission_id
stringlengths 7
9
| correct_source
stringlengths 28
21.2k
| contest_name
stringclasses 664
values | contest_type
stringclasses 3
values | contest_start_year
int64 2.01k
2.02k
| time_limit
float64 0.5
15
| memory_limit
float64 64
1.02k
| title
stringlengths 2
54
| description
stringlengths 35
3.16k
| input_format
stringlengths 67
1.76k
| output_format
stringlengths 18
1.06k
⌀ | interaction_format
null | note
stringclasses 840
values | examples
stringlengths 34
1.16k
| rating
int64 800
3.4k
⌀ | tags
stringclasses 533
values | testset_size
int64 2
360
| official_tests
stringlengths 44
19.7M
| official_tests_complete
bool 1
class | input_mode
stringclasses 1
value | generated_checker
stringclasses 231
values | executable
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
681/D
|
681
|
D
|
Python 3
|
TESTS
| 0 | 31 | 102,400 |
194010460
|
from collections import defaultdict, deque
# read input
n, m = map(int, input().split())
# build graph
graph = defaultdict(list)
in_degree = [0] * (n+1)
for _ in range(m):
p, q = map(int, input().split())
graph[p].append(q)
in_degree[q] += 1
# read gift wishes
gifts = list(map(int, input().split()))
# perform topological sort
top_order = []
q = deque([i for i in range(1, n+1) if in_degree[i] == 0])
while q:
u = q.popleft()
top_order.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
q.append(v)
# build list of candidates
candidates = []
taken = set()
for u in top_order:
if gifts[u-1] in taken or gifts[u-1] == u:
candidates.append(u)
taken.add(u)
elif gifts[u-1] not in taken:
continue
else:
print("-1")
exit()
# print result
print(len(candidates))
print("\n".join(str(x) for x in candidates))
| 38 | 202 | 18,841,600 |
197407343
|
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def make_graph(n, m):
x, s = [0] * (2 * m), [0] * (n + 3)
for i in range(0, 2 * m, 2):
u, v = map(int, input().split())
s[u + 2] += 1
x[i], x[i + 1] = u, v
for i in range(3, n + 3):
s[i] += s[i - 1]
G = [0] * m
for i in range(0, 2 * m, 2):
j = x[i] + 1
G[s[j]] = x[i ^ 1]
s[j] += 1
return G, s
def bfs(s):
q, k = [s], 0
dist[s] = 0
while len(q) ^ k:
i = q[k]
di = dist[i]
for v in range(s0[i], s0[i + 1]):
j = G[v]
dist[j] = di + 1
q.append(j)
k += 1
return q
n, m = map(int, input().split())
G, s0 = make_graph(n, m)
x = [0] * (n + 1)
for i in G:
x[i] = 1
inf = pow(10, 9) + 1
dist = [inf] * (n + 1)
u = []
for i in range(1, n + 1):
if x[i]:
continue
u0 = bfs(i)
for j in u0:
u.append(j)
a = [0] + list(map(int, input().split()))
b = [0] * (n + 1)
for i in a[1:]:
b[i] = 1
ok = 1
for s in range(1, n + 1):
if not b[s]:
continue
q, k = [s], 0
while len(q) ^ k:
i = q[k]
for v in range(s0[i], s0[i + 1]):
j = G[v]
if not b[j]:
q.append(j)
k += 1
for i in q:
if a[i] ^ s:
ok = 0
break
k = -1 if not ok else sum(b)
print(k)
if k == -1:
exit()
ans = []
for i in u[::-1]:
if b[i]:
ans.append(i)
sys.stdout.write("\n".join(map(str, ans)))
|
Codeforces Round 357 (Div. 2)
|
CF
| 2,016 | 1 | 256 |
Gifts by the List
|
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
- A = B;
- the man number A is the father of the man number B;
- there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A ≠ B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
|
In the first line of the input two integers n and m (0 ≤ m < n ≤ 100 000) are given — the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 ≤ pi, qi ≤ n, pi ≠ qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 ≤ i ≤ n the man numbered ai is an ancestor of the man numbered i.
|
Print an integer k (1 ≤ k ≤ n) — the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n — the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
| null |
The first sample explanation:
- if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
- if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
- if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
- if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1).
|
[{"input": "3 2\n1 2\n2 3\n1 2 1", "output": "-1"}, {"input": "4 2\n1 2\n3 4\n1 2 3 3", "output": "3\n2\n1\n3"}]
| 2,000 |
["constructive algorithms", "dfs and similar", "graphs", "trees"]
| 38 |
[{"input": "3 2\r\n1 2\r\n2 3\r\n1 2 1\r\n", "output": "-1"}, {"input": "4 2\r\n1 2\r\n3 4\r\n1 2 3 3\r\n", "output": "3\r\n2\r\n1\r\n3\r\n"}, {"input": "1 0\r\n1\r\n", "output": "1\r\n1\r\n"}, {"input": "2 1\r\n2 1\r\n2 2\r\n", "output": "1\r\n2\r\n"}, {"input": "2 1\r\n2 1\r\n1 2\r\n", "output": "2\r\n1\r\n2\r\n"}, {"input": "4 3\r\n1 2\r\n2 3\r\n3 4\r\n1 1 3 2\r\n", "output": "-1"}, {"input": "4 3\r\n4 3\r\n3 2\r\n2 1\r\n3 4 4 4\r\n", "output": "-1"}, {"input": "4 3\r\n1 2\r\n2 3\r\n3 4\r\n1 1 1 2\r\n", "output": "-1"}]
| false |
stdio
|
import sys
from sys import stdin
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
submission_path = sys.argv[3]
with open(input_path) as f:
n, m = map(int, f.readline().split())
parent = [0] * (n + 1)
for _ in range(m):
p, q = map(int, f.readline().split())
parent[q] = p
a = list(map(int, f.readline().split()))
a = [0] + a # 1-based
with open(submission_path) as f:
lines = f.read().splitlines()
if not lines:
print(0)
return
if lines[0].strip() == '-1':
# We can't validate this case without solving the problem
# Compare with reference output
with open(output_path) as f_ref:
ref_line = f_ref.readline().strip()
if ref_line == '-1':
print(1)
else:
print(0)
return
# Process list submission
try:
k = int(lines[0])
if k < 1 or k > n:
print(0)
return
lst = list(map(int, lines[1:k+1]))
if len(lst) != k or len(set(lst)) != k or any(x < 1 or x > n for x in lst):
print(0)
return
except:
print(0)
return
# Build ancestor check function
def is_ancestor(x, i):
if x == i:
return True
current = parent[i]
while current != 0:
if current == x:
return True
current = parent[current]
return False
# Check for each i if a_i is first ancestor in list
pos_in_list = {x: idx for idx, x in enumerate(lst)}
for i in range(1, n+1):
ai = a[i]
if ai not in pos_in_list:
print(0)
return
first_ancestor = None
for x in lst:
if x == i or is_ancestor(x, i):
first_ancestor = x
break
if first_ancestor != ai:
print(0)
return
print(1)
if __name__ == '__main__':
main()
| true |
383/D
|
383
|
D
|
Python 3
|
TESTS
| 1 | 30 | 0 |
228198201
|
MOD = 10**9 + 7
n = int(input())
a = list(map(int, input().split()))
total_sum = sum(a)
half_sum = (total_sum + 1) // 2
dp = [[0] * (half_sum + 1) for _ in range(n + 1)]
dp[0][0] = 1
for i in range(1, n + 1):
for j in range(half_sum + 1):
dp[i][j] = dp[i - 1][j]
if j >= a[i - 1]:
dp[i][j] = (dp[i][j] + dp[i - 1][j - a[i - 1]]) % MOD
result = (dp[n][half_sum] * 2) % MOD
print(result)
| 48 | 280 | 83,660,800 |
196824676
|
#from turtle import *
import math
MOD = 1000000007
MAXN = 10000
N = 5000
n = int( input( ) )
a = list( map( int , input( ).split( ) ) )
f = [ [0 for i in range( 0 , MAXN + 2 ) ] for j in range( 0 , n + 2 )]
ans = 0
for i in range( 1 , n + 1 ) :
f[i-1][N] += 1
for j in range( 0 , MAXN + 1 ) :
if j + a[i-1] <= MAXN :
f[i][j] = ( f[i][j] + f[i-1][j+a[i-1]] ) % MOD
if j >= a[i-1] :
f[i][j] = ( f[i][j] + f[i-1][j-a[i-1]] ) % MOD
ans = ( ans + f[i][N] ) % MOD
print( ans )
|
Codeforces Round 225 (Div. 1)
|
CF
| 2,014 | 1 | 256 |
Antimatter
|
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 ≤ i ≤ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).
You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
|
The first line contains an integer n (1 ≤ n ≤ 1000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000).
The sum a1 + a2 + ... + an will be less than or equal to 10000.
|
Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).
| null |
The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.
|
[{"input": "4\n1 1 1 1", "output": "12"}]
| 2,300 |
["dp"]
| 48 |
[{"input": "4\r\n1 1 1 1\r\n", "output": "12\r\n"}, {"input": "10\r\n16 9 9 11 10 12 9 6 10 8\r\n", "output": "86\r\n"}, {"input": "50\r\n2 1 5 2 1 3 1 2 3 2 1 1 5 2 2 2 3 2 1 2 2 2 3 3 1 3 1 1 2 2 2 2 1 2 3 1 2 4 1 1 1 3 2 1 1 1 3 2 1 3\r\n", "output": "115119382\r\n"}, {"input": "100\r\n8 3 3 7 3 6 4 6 9 4 6 5 5 5 4 3 4 2 3 5 3 6 5 3 6 5 6 6 2 6 4 5 5 4 6 4 3 2 8 5 6 6 7 4 4 9 5 6 6 3 7 1 6 2 6 5 9 3 8 6 2 6 3 2 4 4 3 5 4 7 6 5 4 6 3 5 6 8 8 6 3 7 7 1 4 6 8 6 5 3 7 8 4 7 5 3 8 5 4 4\r\n", "output": "450259307\r\n"}, {"input": "250\r\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "533456111\r\n"}, {"input": "250\r\n6 1 4 3 3 7 4 5 3 2 4 4 2 5 4 2 1 7 6 2 4 5 3 3 4 5 3 4 5 4 6 4 6 5 3 3 1 5 4 5 3 4 2 4 2 5 1 4 3 3 3 2 6 6 4 7 2 6 5 3 3 6 5 2 1 3 3 5 2 2 3 7 3 5 6 4 7 3 5 3 4 5 5 4 11 5 1 5 3 3 3 1 4 6 4 4 5 5 5 5 2 5 5 3 2 2 5 6 10 5 4 2 5 4 2 5 5 3 4 2 5 4 3 2 4 4 2 5 4 1 5 3 9 6 4 6 3 5 4 5 3 6 7 4 5 5 3 6 2 6 3 3 4 5 6 3 3 3 5 2 4 4 4 5 4 2 5 4 6 5 3 3 6 3 1 5 6 5 4 6 2 3 4 4 5 2 1 7 4 5 5 5 2 2 7 6 1 5 3 2 7 5 8 2 2 2 3 5 2 4 4 2 2 6 4 6 3 2 8 3 4 7 3 2 7 3 5 5 3 2 2 4 5 3 4 3 5 3 5 4 3 1 2 4 7 4 2 3 3 5\r\n", "output": "377970747\r\n"}, {"input": "250\r\n2 2 2 2 3 2 4 2 3 2 5 1 2 3 4 4 5 3 5 1 2 5 2 3 5 3 2 3 3 3 5 1 5 5 5 4 1 3 2 5 1 2 3 5 3 3 5 2 1 1 3 3 5 1 4 2 3 3 2 2 3 5 5 4 1 4 1 5 1 3 3 4 1 5 2 5 5 3 2 4 4 4 4 3 5 1 3 4 3 4 2 1 4 3 5 1 2 3 4 2 5 5 3 2 5 3 5 4 2 3 2 3 1 1 2 4 2 5 2 3 3 2 4 5 4 2 2 5 5 5 5 4 3 4 5 2 2 3 3 4 5 1 5 5 2 5 1 5 5 4 4 1 4 2 1 2 1 2 2 3 1 4 5 4 2 4 5 1 1 3 2 1 4 1 5 2 3 1 2 3 2 3 3 2 4 2 5 5 2 3 4 2 2 4 2 4 1 5 5 3 1 3 4 5 2 5 5 1 3 1 3 3 2 5 3 5 2 4 3 5 5 3 3 2 3 2 5 3 4 3 5 3 3 4 5 3 1 2 2 5 4 4 5 1 4 1 2 5 2 3\r\n", "output": "257270797\r\n"}, {"input": "1\r\n1\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "2\r\n"}, {"input": "2\r\n1000 1000\r\n", "output": "2\r\n"}, {"input": "2\r\n1 2\r\n", "output": "0\r\n"}, {"input": "3\r\n1 2 4\r\n", "output": "0\r\n"}, {"input": "3\r\n1 2 2\r\n", "output": "2\r\n"}, {"input": "1\r\n1000\r\n", "output": "0\r\n"}, {"input": "3\r\n999 999 999\r\n", "output": "4\r\n"}]
| false |
stdio
| null | true |
351/E
|
351
|
E
|
Python 3
|
TESTS
| 1 | 60 | 0 |
228778988
|
def count_inversions(arr):
inv_count = 0
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
inv_count += 1
return inv_count
n = int(input())
a = list(map(int, input().split()))
original_inversions = count_inversions(a)
flipped_inversions = count_inversions([-x for x in a])
print(min(original_inversions, flipped_inversions))
| 36 | 280 | 3,686,400 |
150804902
|
import sys
input = sys.stdin.buffer.readline
def process(A):
n = len(A)
S = [1 for i in range(n)]
d = {}
for i in range(n):
ai = abs(A[i])
if ai not in d:
d[ai] = []
d[ai].append(i)
L = sorted(d)
answer = 0
while len(L) > 0:
ai = L.pop()
for i in d[ai]:
S[i] = 0
for i in d[ai]:
answer+=min(sum(S[:i]), sum(S[i+1:]))
if sum(S[:i]) < sum(S[i+1:]):
A[i] = -1*ai
else:
A[i] = ai
return answer
n = int(input())
A = [int(x) for x in input().split()]
print(process(A))
|
Codeforces Round 204 (Div. 1)
|
CF
| 2,013 | 2 | 256 |
Jeff and Permutation
|
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality ai > aj holds.
Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
|
The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p1, p2, ..., pn (|pi| ≤ 105). The numbers are separated by spaces.
|
In a single line print the answer to the problem — the minimum number of inversions Jeff can get.
| null | null |
[{"input": "2\n2 1", "output": "0"}, {"input": "9\n-2 0 -1 0 -1 2 1 0 -1", "output": "6"}]
| 2,200 |
["greedy"]
| 36 |
[{"input": "2\r\n2 1\r\n", "output": "0\r\n"}, {"input": "9\r\n-2 0 -1 0 -1 2 1 0 -1\r\n", "output": "6\r\n"}, {"input": "9\r\n0 0 1 1 0 0 1 0 1\r\n", "output": "5\r\n"}, {"input": "8\r\n0 1 2 -1 -2 1 -2 2\r\n", "output": "3\r\n"}, {"input": "24\r\n-1 -1 2 2 0 -2 2 -1 0 0 2 -2 3 0 2 -3 0 -3 -1 1 0 0 -1 -2\r\n", "output": "55\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "31\r\n-2 2 -2 -1 0 0 1 2 1 1 -1 -2 1 -1 -2 2 0 1 -1 -2 -1 -2 -1 2 2 2 2 1 1 0 1\r\n", "output": "74\r\n"}, {"input": "9\r\n1 -1 -1 0 -1 0 1 1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 0 1 -2 1\r\n", "output": "1\r\n"}, {"input": "31\r\n-5 -5 5 3 -1 3 1 -3 -3 -1 -5 -3 -2 -4 -3 3 5 -2 1 0 -1 1 -3 1 -1 1 3 3 2 1 0\r\n", "output": "70\r\n"}, {"input": "53\r\n-3 2 -3 -5 -2 7 0 -2 1 6 -1 2 5 -3 3 -6 -2 -5 -3 -6 4 -4 -2 6 1 -7 -6 -4 0 2 -5 -1 -2 -6 2 2 7 -2 -3 1 0 -4 3 4 -2 7 -3 7 7 3 -5 -5 3\r\n", "output": "289\r\n"}, {"input": "24\r\n-3 -4 3 -3 3 2 -1 -3 -4 0 -4 0 2 3 3 -1 2 1 2 -2 3 -2 1 0\r\n", "output": "46\r\n"}, {"input": "50\r\n-6 1 -3 7 -5 -5 4 0 3 -5 1 2 -1 0 7 0 6 3 -5 4 4 3 -7 -1 4 4 -5 3 7 1 4 2 6 -4 0 3 -3 -2 -3 1 -5 3 -4 2 -2 7 -1 3 -7 4\r\n", "output": "260\r\n"}, {"input": "17\r\n-56007 -97423 -66458 -17041 49374 60662 42188 56222 28689 -4117 -1712 11034 17161 43908 -65064 -76642 -73934\r\n", "output": "13\r\n"}, {"input": "12\r\n0 1 0 1 1 -1 1 -1 0 1 0 -1\r\n", "output": "12\r\n"}]
| false |
stdio
| null | true |
803/F
|
803
|
F
|
Python 3
|
TESTS
| 0 | 608 | 6,451,200 |
84620361
|
N = 10**5+5
MOD = 10**9+7
freq = [0 for i in range(N)]
# Calculating {power(2,i)%MOD} and storing it at ith pos in p2 arr
p2 = [0 for i in range(N)]
p2[0] = 1
for i in range(1,N):
p2[i] = p2[i-1]*2
p2[i]%=MOD
def Calculate_Mobius(N):
arr = [1 for i in range(N+1)]
prime_count = [0 for i in range(N+1)]
mobius_value = [0 for i in range(N+1)]
for i in range(2,N+1):
if prime_count[i]==0:
for j in range(i,N+1,i):
prime_count[j]+=1
arr[j] = arr[j] * i
for i in range(1, N+1):
if arr[i] == i:
if (prime_count[i] & 1) == 0:
mobius_value[i] = 1
else:
mobius_value[i] = -1
else:
mobius_value[i] = 0
return mobius_value
# Caluclating Mobius values for nos' till 10^5
mobius = Calculate_Mobius(N)
b = [int(i) for i in input().split()]
# Storing freq of I/p no.s in array
for i in b:
freq[i]+=1
ans = 0
for i in range(1,N):
# Count no of I/p no's which are divisible by i
cnt = 0
for j in range(i,N,i):
cnt += freq[j]
total_subsequences = p2[cnt] - 1
ans = (ans + (mobius[i] * total_subsequences)%MOD)%MOD
# Dealing if ans is -ve due to MOD
ans += MOD
print(ans%MOD)
| 35 | 202 | 14,950,400 |
199478424
|
# Problem - F - Codeforces
# 題意:
# 給 N 個元素的數列 A。問有幾種不同的非空子序列,其最大公因數不為 1。輸出方案數對 1e9 + 7 取模。
# 制約:
# The first line contains one integer number n (1 ≤ n ≤ 100000).
# The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
# 解法:
# 看起來就很排容。
# 首先計算:
# mcnt[ i ]: i 的倍數的元素數量。
# mans[ i ]: 最大公因數為 i 的倍數的非空子序列數量。
# mans[ i ] = pow( 2, mcnt[ i ] ) - 1
# ans[ i ]: 最大公因數為 i 的非空子序列數量。
# ans[ i ] = mans[ i ] - ( ans[ j ] for all j that j % i == 0 if j > i )
# 非空的部分要特別注意,一開始就要捨掉,因為它沒有因數倍數的概念。
# 時間 / 空間複雜度:
# O( MAXA lg MAXA ) / O( MAXA )
MOD = int( 1e9 ) + 7
N = int( input() )
A = list( map( int, input().split() ) )
pow2 = [ pow( 2, i, MOD ) for i in range( N + 1 ) ]
maxa = max( A )
mcnt = [ 0 for i in range( maxa + 1 ) ]
mans = [ 0 for i in range( maxa + 1 ) ]
for i in range( N ):
mcnt[ A[ i ] ] += 1
for i in range( 1, maxa + 1 ):
for j in range( i + i, maxa + 1, i ):
mcnt[ i ] += mcnt[ j ]
mans[ i ] = pow2[ mcnt[ i ] ] - 1
for i in range( maxa, 0, -1 ):
for j in range( i + i, maxa + 1, i ):
mans[ i ] = ( mans[ i ] - mans[ j ] ) % MOD
print( mans[ 1 ] + ( mans[ 1 ] < 0 ) * MOD )
|
Educational Codeforces Round 20
|
ICPC
| 2,017 | 2 | 256 |
Coprime Subsequences
|
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.
Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.
Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
|
The first line contains one integer number n (1 ≤ n ≤ 100000).
The second line contains n integer numbers a1, a2... an (1 ≤ ai ≤ 100000).
|
Print the number of coprime subsequences of a modulo 109 + 7.
| null |
In the first example coprime subsequences are:
1. 1
2. 1, 2
3. 1, 3
4. 1, 2, 3
5. 2, 3
In the second example all subsequences are coprime.
|
[{"input": "3\n1 2 3", "output": "5"}, {"input": "4\n1 1 1 1", "output": "15"}, {"input": "7\n1 3 5 15 3 105 35", "output": "100"}]
| 2,000 |
["bitmasks", "combinatorics", "number theory"]
| 35 |
[{"input": "3\r\n1 2 3\r\n", "output": "5\r\n"}, {"input": "4\r\n1 1 1 1\r\n", "output": "15\r\n"}, {"input": "7\r\n1 3 5 15 3 105 35\r\n", "output": "100\r\n"}, {"input": "1\r\n1\r\n", "output": "1\r\n"}, {"input": "1\r\n100000\r\n", "output": "0\r\n"}, {"input": "5\r\n10 8 6 4 6\r\n", "output": "0\r\n"}, {"input": "5\r\n5 1 3 5 4\r\n", "output": "26\r\n"}, {"input": "5\r\n5 1 6 6 6\r\n", "output": "23\r\n"}, {"input": "10\r\n9 6 8 5 5 2 8 9 2 2\r\n", "output": "951\r\n"}, {"input": "10\r\n2 2 16 16 14 1 9 12 15 13\r\n", "output": "953\r\n"}, {"input": "50\r\n17 81 20 84 6 86 11 33 19 46 70 79 23 64 40 99 78 70 3 10 32 42 18 73 35 36 69 90 81 81 8 25 87 23 76 100 53 11 36 19 87 89 53 65 97 67 3 65 88 87\r\n", "output": "896338157\r\n"}, {"input": "50\r\n166 126 98 42 179 166 99 192 1 185 114 173 152 187 57 21 132 88 152 55 110 51 1 30 147 153 34 115 59 3 78 16 19 136 188 134 28 48 54 120 97 74 108 54 181 79 143 187 51 4\r\n", "output": "763698643\r\n"}, {"input": "100\r\n154 163 53 13 186 87 143 114 17 111 143 108 102 111 158 171 69 74 67 18 87 43 80 104 63 109 19 113 86 52 119 91 15 154 9 153 140 91 19 19 191 193 76 84 50 128 173 27 120 83 6 59 65 5 135 59 162 121 15 110 146 107 137 99 55 189 2 118 55 27 4 198 23 79 167 125 72 30 74 163 44 184 166 43 198 116 68 5 47 138 121 146 98 103 89 75 137 36 146 195\r\n", "output": "363088732\r\n"}, {"input": "100\r\n881 479 355 759 257 497 690 598 275 446 439 787 257 326 584 713 322 5 253 781 434 307 164 154 241 381 38 942 680 906 240 11 431 478 628 959 346 74 493 964 455 746 950 41 585 549 892 687 264 41 487 676 63 453 861 980 477 901 80 907 285 506 619 748 773 743 56 925 651 685 845 313 419 504 770 324 2 559 405 851 919 128 318 698 820 409 547 43 777 496 925 918 162 725 481 83 220 203 609 617\r\n", "output": "934190491\r\n"}]
| false |
stdio
| null | true |
51/B
|
51
|
B
|
Python 3
|
TESTS
| 0 | 60 | 0 |
231584013
|
n=""
cnt=-1
flag=False
ans=[]
while True:
k=input()
if "<table>" in k: cnt+=1
if "</table>" in k: cnt-=1
if cnt==-1: break
n+=k
n=n[1:len(n)-1].split("><")
for i in n:
if i=="table":
cnt+=1
ans.append(0)
if i=="/table": cnt+=1
if i=="td": ans[cnt]+=1
print(*sorted(ans))
| 19 | 154 | 716,800 |
13939844
|
import fileinput
s = ''
for line in fileinput.input():
s += line.strip()
#print(s)
if s[0] == '<':
s = s[1:]
if s[-1] == '>':
s = s[:-1]
#print(s)
a = s.split('><')
#print(a)
ans = []
b = []
for i in a:
if i == 'table':
b.append(0)
elif i == '/table':
u = 0
ans.append(b[-1])
b.pop()
elif i == 'td':
b[-1] += 1
ans.sort()
print(*ans)
|
Codeforces Beta Round 48
|
CF
| 2,010 | 2 | 256 |
bHTML Tables Analisys
|
In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.
A string is a bHTML table, if it satisfies the grammar:
Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.
As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.
|
For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.
|
Print the sizes of all the tables in the non-decreasing order.
| null | null |
[{"input": "<table><tr><td></td></tr></table>", "output": "1"}, {"input": "<table>\n<tr>\n<td>\n<table><tr><td></td></tr><tr><td></\ntd\n></tr><tr\n><td></td></tr><tr><td></td></tr></table>\n</td>\n</tr>\n</table>", "output": "1 4"}, {"input": "<table><tr><td>\n<table><tr><td>\n<table><tr><td>\n<table><tr><td></td><td></td>\n</tr><tr><td></td></tr></table>\n</td></tr></table>\n</td></tr></table>\n</td></tr></table>", "output": "1 1 1 3"}]
| 1,700 |
["expression parsing"]
| 19 |
[{"input": "<table><tr><td></td></tr></table>\r\n", "output": "1 "}, {"input": "<table>\r\n<tr>\r\n<td>\r\n<table><tr><td></td></tr><tr><td></\r\ntd\r\n></tr><tr\r\n><td></td></tr><tr><td></td></tr></table>\r\n</td>\r\n</tr>\r\n</table>\r\n", "output": "1 4 "}, {"input": "<table><tr><td>\r\n<table><tr><td>\r\n<table><tr><td>\r\n<table><tr><td></td><td></td>\r\n</tr><tr><td></td></tr></table>\r\n</td></tr></table>\r\n</td></tr></table>\r\n</td></tr></table>\r\n", "output": "1 1 1 3 "}, {"input": "<\r\nt\r\na\r\nble><tr><td></td>\r\n</\r\ntr>\r\n</\r\nt\r\nab\r\nle>\r\n", "output": "1 "}, {"input": "<table><tr><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 1 "}, {"input": "<table><tr><td><table><tr><td><table><tr><td></td></tr></table></td></tr></table></td></tr></table>\r\n", "output": "1 1 1 "}, {"input": "<table><tr><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 1 "}, {"input": "<table><tr><td><table><tr><td><table><tr><td></td></tr></table></td></tr></table></td></tr></table>\r\n", "output": "1 1 1 "}, {"input": "<table><tr><td><table><tr><td></td><td></td></tr></table></td><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 2 2 "}, {"input": "<table><tr><td><table><tr><td></td><td></td></tr></table></td><td><table><tr><td></td></tr></table></td></tr></table>\r\n", "output": "1 2 2 "}, {"input": "<table><tr><td><table><tr><td></td></tr></table></td></tr><tr><td><table><tr><td><table><tr><td></td></tr></table></td></tr></table></td></tr></table>\r\n", "output": "1 1 1 2 "}]
| false |
stdio
| null | true |
351/E
|
351
|
E
|
Python 3
|
TESTS
| 1 | 92 | 0 |
228813962
|
n = int(input())
sequence = list(map(int, input().split()))
# Count the number of negative and positive elements
negatives = 0
positives = 0
inversions = 0
for num in sequence:
if num < 0:
negatives += 1
elif num > 0:
positives += 1
# Count the number of inversions by considering elements with the same sign
for i in range(n):
if sequence[i] > 0:
inversions += negatives
elif sequence[i] < 0:
inversions += positives
print(inversions)
| 36 | 280 | 3,686,400 |
150804902
|
import sys
input = sys.stdin.buffer.readline
def process(A):
n = len(A)
S = [1 for i in range(n)]
d = {}
for i in range(n):
ai = abs(A[i])
if ai not in d:
d[ai] = []
d[ai].append(i)
L = sorted(d)
answer = 0
while len(L) > 0:
ai = L.pop()
for i in d[ai]:
S[i] = 0
for i in d[ai]:
answer+=min(sum(S[:i]), sum(S[i+1:]))
if sum(S[:i]) < sum(S[i+1:]):
A[i] = -1*ai
else:
A[i] = ai
return answer
n = int(input())
A = [int(x) for x in input().split()]
print(process(A))
|
Codeforces Round 204 (Div. 1)
|
CF
| 2,013 | 2 | 256 |
Jeff and Permutation
|
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality ai > aj holds.
Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
|
The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p1, p2, ..., pn (|pi| ≤ 105). The numbers are separated by spaces.
|
In a single line print the answer to the problem — the minimum number of inversions Jeff can get.
| null | null |
[{"input": "2\n2 1", "output": "0"}, {"input": "9\n-2 0 -1 0 -1 2 1 0 -1", "output": "6"}]
| 2,200 |
["greedy"]
| 36 |
[{"input": "2\r\n2 1\r\n", "output": "0\r\n"}, {"input": "9\r\n-2 0 -1 0 -1 2 1 0 -1\r\n", "output": "6\r\n"}, {"input": "9\r\n0 0 1 1 0 0 1 0 1\r\n", "output": "5\r\n"}, {"input": "8\r\n0 1 2 -1 -2 1 -2 2\r\n", "output": "3\r\n"}, {"input": "24\r\n-1 -1 2 2 0 -2 2 -1 0 0 2 -2 3 0 2 -3 0 -3 -1 1 0 0 -1 -2\r\n", "output": "55\r\n"}, {"input": "1\r\n0\r\n", "output": "0\r\n"}, {"input": "31\r\n-2 2 -2 -1 0 0 1 2 1 1 -1 -2 1 -1 -2 2 0 1 -1 -2 -1 -2 -1 2 2 2 2 1 1 0 1\r\n", "output": "74\r\n"}, {"input": "9\r\n1 -1 -1 0 -1 0 1 1 1\r\n", "output": "1\r\n"}, {"input": "5\r\n1 0 1 -2 1\r\n", "output": "1\r\n"}, {"input": "31\r\n-5 -5 5 3 -1 3 1 -3 -3 -1 -5 -3 -2 -4 -3 3 5 -2 1 0 -1 1 -3 1 -1 1 3 3 2 1 0\r\n", "output": "70\r\n"}, {"input": "53\r\n-3 2 -3 -5 -2 7 0 -2 1 6 -1 2 5 -3 3 -6 -2 -5 -3 -6 4 -4 -2 6 1 -7 -6 -4 0 2 -5 -1 -2 -6 2 2 7 -2 -3 1 0 -4 3 4 -2 7 -3 7 7 3 -5 -5 3\r\n", "output": "289\r\n"}, {"input": "24\r\n-3 -4 3 -3 3 2 -1 -3 -4 0 -4 0 2 3 3 -1 2 1 2 -2 3 -2 1 0\r\n", "output": "46\r\n"}, {"input": "50\r\n-6 1 -3 7 -5 -5 4 0 3 -5 1 2 -1 0 7 0 6 3 -5 4 4 3 -7 -1 4 4 -5 3 7 1 4 2 6 -4 0 3 -3 -2 -3 1 -5 3 -4 2 -2 7 -1 3 -7 4\r\n", "output": "260\r\n"}, {"input": "17\r\n-56007 -97423 -66458 -17041 49374 60662 42188 56222 28689 -4117 -1712 11034 17161 43908 -65064 -76642 -73934\r\n", "output": "13\r\n"}, {"input": "12\r\n0 1 0 1 1 -1 1 -1 0 1 0 -1\r\n", "output": "12\r\n"}]
| false |
stdio
| null | true |
177/D1
|
177
|
D2
|
PyPy 3-64
|
TESTS2
| 2 | 92 | 614,400 |
158569827
|
import sys, collections, heapq, math
readline = sys.stdin.readline
# [a, a + b, a + b + c]
# [c, b, a]
# [c, b + c, a + b + c]
def solve(A, B, c):
C = B[:]
for i in range(1, len(B)):
B[i] += B[i - 1]
C[i] += C[i - 1]
for i in range(len(A)//2):
A[i] = (A[i] + B[min(i, len(B) - 1)]) % c
j = 0
for i in range(len(A) -1, len(A)//2 - 1, -1):
A[i] = (A[i] + B[min(j, len(C) - 1)]) % c
j += 1
return [val % c for val in A]
n, m, c = list(map(int, readline().split()))
print(*solve(list(map(int, readline().split())), list(map(int, readline().split())), c))
| 12 | 124 | 1,740,800 |
179828902
|
L = lambda : list(map(int, input().split()))
n, m, c = L()
a = L()
b = L()
for i in range(n - m + 1):
for j in range(m):
a[i + j] += b[j]
a[i + j] %= c
a = list(map(str, a))
print(" ".join(a))
|
ABBYY Cup 2.0 - Easy
|
ICPC
| 2,012 | 2 | 256 |
Encrypting Messages
|
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
|
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.
The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key.
The input limitations for getting 30 points are:
- 1 ≤ m ≤ n ≤ 103
- 1 ≤ c ≤ 103
The input limitations for getting 100 points are:
- 1 ≤ m ≤ n ≤ 105
- 1 ≤ c ≤ 103
|
Print n space-separated integers — the result of encrypting the original message.
| null |
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
|
[{"input": "4 3 2\n1 1 1 1\n1 1 1", "output": "0 1 1 0"}, {"input": "3 1 5\n1 2 3\n4", "output": "0 1 2"}]
| 1,200 |
["brute force"]
| 12 |
[{"input": "4 3 2\r\n1 1 1 1\r\n1 1 1\r\n", "output": "0 1 1 0\r\n"}, {"input": "3 1 5\r\n1 2 3\r\n4\r\n", "output": "0 1 2\r\n"}, {"input": "5 2 7\r\n0 0 1 2 4\r\n3 5\r\n", "output": "3 1 2 3 2\r\n"}, {"input": "20 15 17\r\n4 9 14 11 15 16 15 4 0 10 7 12 10 1 8 6 7 14 1 13\r\n6 3 14 8 8 11 16 4 5 9 2 13 6 14 15\r\n", "output": "10 1 3 8 3 15 7 14 1 12 3 10 15 16 16 5 4 15 13 11\r\n"}]
| false |
stdio
| null | true |
437/D
|
437
|
D
|
Python 3
|
TESTS
| 0 | 218 | 25,497,600 |
128303076
|
import sys
inp = sys.stdin.readlines()
first_line = inp.pop(0).replace('\n','').split()
n = int(first_line[0])
m = int(first_line[1])
maximum = 1000005
animals = [0 for i in range(maximum)]
parent = [0 for i in range(maximum)]
size = [0 for i in range(maximum)]
edges = [[-1,-1,-1] for i in range(m+1)]
second_line = inp.pop(0).replace('\n','').split()
for i in range(1,n+1,1):
animals[i] = int(second_line[i-1])
parent[i] = i
size[i] = 1
for i in range(1,m+1):
line = inp[i-1].replace('\n','').split()
a = int(line[0])
b = int(line[1])
edges[i] = [a,b,min(animals[a],animals[b])]
def comp(edge):
return edge[2]
edges.sort(key = comp)
total = 0
answer = 0.0
def get_parent(x):
if parent[x] == x:
return x
else:
parent[x] = get_parent(parent[x])
return parent[x]
def merge(x,y):
fx = get_parent(x)
fy = get_parent(y)
if fx != fy:
if size[fx] < size[fy]:
temp = fy
fy = fx
fx = temp
size[fx] += size[fy]
parent[fy] = fx
for i in range(1,m+1,1):
if total >= n:
break
a = get_parent(edges[i][0])
b = get_parent(edges[i][1])
if a == b:
continue
answer += size[a]*size[b]*edges[i][2]
total+=1
merge(a,b)
print((answer*2)/(n*(n-1)))
| 27 | 607 | 30,720,000 |
128061089
|
import io, os
import math
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
edges = []
for i in range(m):
u, v = map(int, input().split())
smallest = min(a[u-1], a[v-1]);
edges.append((u-1, v-1, smallest))
# Kruskal MST
parent = [i for i in range(n)]
size = [1] * (n)
siblings = [[i] for i in range(n)]
s = 0
def find(x):
if x != parent[x]:
parent[x] = find(parent[x])
return parent[x]
def union(x, y, w):
global s
smaller = find(x)
larger = find(y)
if smaller == larger:
return False
if size[smaller] > size[larger]:
smaller, larger = larger, smaller
parent[smaller] = larger
siblings[larger].extend(siblings[smaller])
s += size[larger] * size[smaller] * w
size[larger] += size[smaller]
return True
# Sort by weight
L = sorted(edges, reverse=True, key=lambda x: x[2])
for edge in L:
u, v, w = edge
union(u, v, w)
s = s << 1
s = s / n / (n - 1)
print(s)
|
Codeforces Round 250 (Div. 2)
|
CF
| 2,014 | 2 | 256 |
The Child and Zoo
|
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.
Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).
After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question?
|
The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each line contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the road between areas xi and yi.
All roads are bidirectional, each pair of areas is connected by at most one road.
|
Output a real number — the value of $$\frac{\sum_{p,q,p\neq q} f(p,q)}{n(n-1)}$$.
The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
| null |
Consider the first sample. There are 12 possible situations:
- p = 1, q = 3, f(p, q) = 10.
- p = 2, q = 3, f(p, q) = 20.
- p = 4, q = 3, f(p, q) = 30.
- p = 1, q = 2, f(p, q) = 10.
- p = 2, q = 4, f(p, q) = 20.
- p = 4, q = 1, f(p, q) = 10.
Another 6 cases are symmetrical to the above. The average is $$(10+20+30+10+20+10)\times 2\over 12 \approx 16.666667$$.
Consider the second sample. There are 6 possible situations:
- p = 1, q = 2, f(p, q) = 10.
- p = 2, q = 3, f(p, q) = 20.
- p = 1, q = 3, f(p, q) = 10.
Another 3 cases are symmetrical to the above. The average is $$(10+20+10)\times2\over6\approx13.333333$$.
|
[{"input": "4 3\n10 20 30 40\n1 3\n2 3\n4 3", "output": "16.666667"}, {"input": "3 3\n10 20 30\n1 2\n2 3\n3 1", "output": "13.333333"}, {"input": "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7", "output": "18.571429"}]
| 1,900 |
["dsu", "sortings"]
| 27 |
[{"input": "4 3\r\n10 20 30 40\r\n1 3\r\n2 3\r\n4 3\r\n", "output": "16.666667\r\n"}, {"input": "3 3\r\n10 20 30\r\n1 2\r\n2 3\r\n3 1\r\n", "output": "13.333333\r\n"}, {"input": "7 8\r\n40 20 10 30 20 50 40\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n1 4\r\n5 7\r\n", "output": "18.571429\r\n"}, {"input": "10 14\r\n594 965 90 327 549 206 514 993 803 635\r\n1 2\r\n1 3\r\n3 4\r\n2 5\r\n5 6\r\n5 7\r\n4 8\r\n4 9\r\n5 10\r\n10 4\r\n7 8\r\n2 6\r\n6 4\r\n5 4\r\n", "output": "326.088889\r\n"}, {"input": "10 19\r\n15704 19758 26631 25050 22778 15041 8487 26418 5136 4199\r\n1 2\r\n1 3\r\n1 4\r\n2 5\r\n1 6\r\n2 7\r\n2 8\r\n7 9\r\n6 10\r\n7 3\r\n4 7\r\n6 4\r\n6 8\r\n5 8\r\n6 9\r\n5 4\r\n1 8\r\n1 9\r\n5 3\r\n", "output": "11616.755556\r\n"}, {"input": "10 14\r\n296 371 507 807 102 558 199 500 553 150\r\n1 2\r\n2 3\r\n3 4\r\n1 5\r\n5 6\r\n3 7\r\n2 8\r\n5 9\r\n8 10\r\n7 2\r\n8 7\r\n4 6\r\n1 7\r\n5 4\r\n", "output": "213.933333\r\n"}, {"input": "10 19\r\n13637 26970 19043 3616 12880 19387 12539 25190 2452 1261\r\n1 2\r\n1 3\r\n1 4\r\n2 5\r\n3 6\r\n6 7\r\n3 8\r\n5 9\r\n3 10\r\n4 10\r\n9 3\r\n2 8\r\n4 3\r\n2 3\r\n7 10\r\n7 8\r\n5 10\r\n5 6\r\n7 4\r\n", "output": "8241.422222\r\n"}, {"input": "2 1\r\n233 2333\r\n1 2\r\n", "output": "233.000000\r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
submission_path = sys.argv[3]
# Read expected output
with open(output_path, 'r') as f:
expected_line = f.read().strip()
try:
expected = float(expected_line)
except:
print(0)
return
# Read submission output
with open(submission_path, 'r') as f:
submission_line = f.read().strip()
try:
actual = float(submission_line)
except:
print(0)
return
# Check absolute error
absolute_diff = abs(expected - actual)
if absolute_diff <= 1e-4:
print(100)
return
# Check relative error if expected is not zero
if expected == 0:
print(0)
return
relative_diff = absolute_diff / abs(expected)
if relative_diff <= 1e-4:
print(100)
else:
print(0)
if __name__ == "__main__":
main()
| true |
177/D1
|
177
|
D1
|
Python 3
|
TESTS1
| 2 | 62 | 0 |
176969598
|
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
n,m,c=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
prefsum=[b[0]]
for j in range(1,m): prefsum.append(prefsum[-1]+b[j])
prev=prefsum[::-1]
ans=[]
for i in range(n):
if i<m and i+m<=n:
ans.append(prefsum[i]+a[i])
elif i>=m and i<n-m+1:
ans.append(prefsum[-1]+a[i])
else:
ans.append(prev[n-1-i]+a[i])
for ele in ans:
print(ele%c,end=" ")
| 12 | 154 | 1,331,200 |
141781115
|
n, m, c = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
k = 0
for i in range(0, (n-m) + 1):
for j in range(0, m):
if(j + k >= n):
break
a[j+k] = (a[j+k] + b[j]) % c
k += 1
a = [str(x) for x in a]
print(' '.join(a))
|
ABBYY Cup 2.0 - Easy
|
ICPC
| 2,012 | 2 | 256 |
Encrypting Messages
|
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
|
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.
The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key.
The input limitations for getting 30 points are:
- 1 ≤ m ≤ n ≤ 103
- 1 ≤ c ≤ 103
The input limitations for getting 100 points are:
- 1 ≤ m ≤ n ≤ 105
- 1 ≤ c ≤ 103
|
Print n space-separated integers — the result of encrypting the original message.
| null |
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
|
[{"input": "4 3 2\n1 1 1 1\n1 1 1", "output": "0 1 1 0"}, {"input": "3 1 5\n1 2 3\n4", "output": "0 1 2"}]
| 1,200 |
["brute force"]
| 12 |
[{"input": "4 3 2\r\n1 1 1 1\r\n1 1 1\r\n", "output": "0 1 1 0\r\n"}, {"input": "3 1 5\r\n1 2 3\r\n4\r\n", "output": "0 1 2\r\n"}, {"input": "5 2 7\r\n0 0 1 2 4\r\n3 5\r\n", "output": "3 1 2 3 2\r\n"}, {"input": "20 15 17\r\n4 9 14 11 15 16 15 4 0 10 7 12 10 1 8 6 7 14 1 13\r\n6 3 14 8 8 11 16 4 5 9 2 13 6 14 15\r\n", "output": "10 1 3 8 3 15 7 14 1 12 3 10 15 16 16 5 4 15 13 11\r\n"}]
| false |
stdio
| null | true |
177/D1
|
177
|
D2
|
Python 3
|
TESTS2
| 2 | 92 | 204,800 |
4855542
|
n, m, c = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = 0
for i in range(n):
if i < m: s += b[i]
if i > n - m: s -= b[i - n + m]
a[i] = (a[i] + s) % c
print(' '.join(str(i) for i in a))
| 12 | 154 | 1,740,800 |
193597553
|
n, m, c = map(int, input().split())
data = list(map(int, input().split()))
keys = tuple(map(int, input().split()))
for i in range(n - m + 1):
for j in range(m):
data[i + j] += keys[j]
data[i + j] %= c
print(*data)
|
ABBYY Cup 2.0 - Easy
|
ICPC
| 2,012 | 2 | 256 |
Encrypting Messages
|
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
|
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.
The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key.
The input limitations for getting 30 points are:
- 1 ≤ m ≤ n ≤ 103
- 1 ≤ c ≤ 103
The input limitations for getting 100 points are:
- 1 ≤ m ≤ n ≤ 105
- 1 ≤ c ≤ 103
|
Print n space-separated integers — the result of encrypting the original message.
| null |
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
|
[{"input": "4 3 2\n1 1 1 1\n1 1 1", "output": "0 1 1 0"}, {"input": "3 1 5\n1 2 3\n4", "output": "0 1 2"}]
| 1,200 |
["brute force"]
| 12 |
[{"input": "4 3 2\r\n1 1 1 1\r\n1 1 1\r\n", "output": "0 1 1 0\r\n"}, {"input": "3 1 5\r\n1 2 3\r\n4\r\n", "output": "0 1 2\r\n"}, {"input": "5 2 7\r\n0 0 1 2 4\r\n3 5\r\n", "output": "3 1 2 3 2\r\n"}, {"input": "20 15 17\r\n4 9 14 11 15 16 15 4 0 10 7 12 10 1 8 6 7 14 1 13\r\n6 3 14 8 8 11 16 4 5 9 2 13 6 14 15\r\n", "output": "10 1 3 8 3 15 7 14 1 12 3 10 15 16 16 5 4 15 13 11\r\n"}]
| false |
stdio
| null | true |
351/B
|
351
|
B
|
Python 3
|
TESTS
| 2 | 62 | 307,200 |
4789312
|
from sys import *
n=int(stdin.readline().strip())
s1=stdin.readline().strip()
a=list(map(int,s1.split()))
x=0
for i in range (n-1):
for j in range (i+1,n):
if a[i]>a[j]:
x+=1
n=x//2
#print(x,n,' !!!')
r=(x)*((0.5)**n)
i=1
bi=3
eps=0.00000001
if x>0:
while (x+2*i)*bi*((0.5)**(n+i))>eps:
r=r+(x+2*i)*bi*(0.5)**(n+i)
#print(r)
bi=(bi*(n+i))//(i+1)
i=i+1
#print(bi,i)
else:
r=0
print("%.7f"%r)
| 25 | 156 | 2,048,000 |
219395895
|
import sys
input = sys.stdin.readline
MOD=10**9+7
if __name__ == '__main__':
n=int(input())
arr=list(map(int, input().split()))
cnt=0
for i in range(n-1):
for j in range(i+1,n):
if arr[j]<arr[i]: cnt +=1
print((cnt*2-(cnt%2))*1.0)
|
Codeforces Round 204 (Div. 1)
|
CF
| 2,013 | 1 | 256 |
Jeff and Furik
|
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.
Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.
You can consider that the coin shows the heads (or tails) with the probability of 50 percent.
|
The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation p. The numbers are separated by spaces.
|
In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
| null |
In the first test the sequence is already sorted, so the answer is 0.
|
[{"input": "2\n1 2", "output": "0.000000"}, {"input": "5\n3 5 2 4 1", "output": "13.000000"}]
| 1,900 |
["combinatorics", "dp", "probabilities"]
| 25 |
[{"input": "2\r\n1 2\r\n", "output": "0.000000\r\n"}, {"input": "5\r\n3 5 2 4 1\r\n", "output": "13.000000\r\n"}, {"input": "16\r\n6 15 3 8 7 11 9 10 2 13 4 14 1 16 5 12\r\n", "output": "108.000000\r\n"}, {"input": "9\r\n1 7 8 5 3 4 6 9 2\r\n", "output": "33.000000\r\n"}, {"input": "5\r\n2 3 4 5 1\r\n", "output": "8.000000\r\n"}, {"input": "9\r\n4 1 8 6 7 5 2 9 3\r\n", "output": "33.000000\r\n"}, {"input": "10\r\n3 4 1 5 7 9 8 10 6 2\r\n", "output": "29.000000\r\n"}, {"input": "13\r\n3 1 11 12 4 5 8 10 13 7 9 2 6\r\n", "output": "69.000000\r\n"}, {"input": "10\r\n8 4 1 7 6 10 9 5 3 2\r\n", "output": "53.000000\r\n"}, {"input": "2\r\n2 1\r\n", "output": "1.000000\r\n"}, {"input": "95\r\n68 56 24 89 79 20 74 69 49 59 85 67 95 66 15 34 2 13 92 25 84 77 70 71 17 93 62 81 1 87 76 38 75 31 63 51 35 33 37 11 36 52 23 10 27 90 12 6 45 32 86 26 60 47 91 65 58 80 78 88 50 9 44 4 28 29 22 8 48 7 19 57 14 54 55 83 5 30 72 18 82 94 43 46 41 3 61 53 73 39 40 16 64 42 21\r\n", "output": "5076.000000\r\n"}]
| false |
stdio
|
import sys
def read_float_from_line(line):
line = line.strip()
try:
return float(line)
except:
return None
def is_acceptable(ref, sub, abs_tol=1e-6, rel_tol=1e-6):
if abs(ref - sub) <= abs_tol:
return True
denom = max(abs(ref), 1e-8)
return abs(ref - sub) / denom <= rel_tol
def main():
input_path = sys.argv[1]
ref_path = sys.argv[2]
sub_path = sys.argv[3]
# Read reference output
with open(ref_path, 'r') as f:
ref_line = f.readline().strip()
ref_val = read_float_from_line(ref_line)
if ref_val is None:
print(0)
return
# Read submission output
with open(sub_path, 'r') as f:
sub_lines = f.readlines()
if not sub_lines:
print(0)
return
sub_line = sub_lines[0].strip()
sub_val = read_float_from_line(sub_line)
if sub_val is None:
print(0)
return
# Check correctness
if is_acceptable(ref_val, sub_val):
print(1)
else:
print(0)
if __name__ == "__main__":
main()
| true |
412/D
|
412
|
D
|
Python 3
|
TESTS
| 2 | 62 | 0 |
6418045
|
n, m = list(map(int, input().split()))
res = [i + 1 for i in range(n)]
no = [0] * m
for i in range(m):
no[i] = list(map(int, input().split()))
for j in range(n - 1):
if res[i:i + 2] == no[i]:
res[i], res[i + 1] = res[i + 1], res[i]
for i in range(n - 1):
if res[i:i + 2] in no:
print(-1)
break
else:
print(" ".join(map(str, res)))
| 33 | 499 | 7,168,000 |
7104128
|
n, m = map(int,input().split())
g = [set() for i in range(n)]
for i in range(m):
a, b = map(int,input().split())
g[a-1].add(b-1)
c = [0] * n
for i in range(n):
c[i] = i
for i in range(n):
j = i
while (j > 0)and(c[j] in g[c[j - 1]]):
c[j], c[j-1] = c[j-1], c[j]
j -= 1
for i in c:
print(i + 1, end = ' ')
|
Coder-Strike 2014 - Round 1
|
CF
| 2,014 | 1 | 256 |
Giving Awards
|
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.
Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.
However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.
|
The first line contains space-separated integers n and m $$(2\leq n\leq3\cdot10^{4};1\leq m\leq min(10^{5},\frac{n(n-1)}{2}))$$ — the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n.
It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.
|
Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on.
If there are multiple correct orders, you are allowed to print any of them.
| null | null |
[{"input": "2 1\n1 2", "output": "2 1"}, {"input": "3 3\n1 2\n2 3\n3 1", "output": "2 1 3"}]
| 2,000 |
["dfs and similar"]
| 33 |
[{"input": "2 1\r\n1 2\r\n", "output": "2 1 \r\n"}, {"input": "3 3\r\n1 2\r\n2 3\r\n3 1\r\n", "output": "2 1 3 \r\n"}, {"input": "10 45\r\n10 5\r\n10 7\r\n6 1\r\n5 8\r\n3 5\r\n6 5\r\n1 2\r\n6 10\r\n2 9\r\n9 5\r\n4 1\r\n7 5\r\n1 8\r\n6 8\r\n10 9\r\n7 2\r\n7 9\r\n4 10\r\n7 3\r\n4 8\r\n10 3\r\n10 8\r\n2 10\r\n8 2\r\n4 2\r\n5 2\r\n9 1\r\n4 5\r\n1 3\r\n9 6\r\n3 8\r\n5 1\r\n6 4\r\n4 7\r\n8 7\r\n7 1\r\n9 3\r\n3 4\r\n6 2\r\n3 2\r\n6 7\r\n6 3\r\n4 9\r\n8 9\r\n1 10\r\n", "output": "2 3 1 5 7 8 4 6 9 10 \r\n"}, {"input": "4 6\r\n3 4\r\n4 1\r\n4 2\r\n2 1\r\n3 2\r\n3 1\r\n", "output": "1 2 4 3 \r\n"}, {"input": "5 10\r\n4 2\r\n4 5\r\n3 1\r\n2 1\r\n3 4\r\n3 2\r\n5 1\r\n5 2\r\n4 1\r\n5 3\r\n", "output": "1 2 4 3 5 \r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
submission_path = sys.argv[3]
# Read input
with open(input_path) as f:
n, m = map(int, f.readline().split())
edges = set()
for _ in range(m):
a, b = map(int, f.readline().split())
edges.add((a, b))
# Read submission output
with open(submission_path) as f:
line = f.readline().strip()
if line == '-1':
# Check if it's actually impossible
# To determine this, we'd need to know if any valid order exists, which is complex.
# However, the problem requires the checker to verify the submission's output.
# Since the submission claims it's impossible, but how can the checker know?
# This suggests that the checker cannot handle the -1 case properly.
# Wait, the problem says if the order does not exist, output -1.
# But how can the checker verify if the submission's -1 is correct?
# This is a problem because the checker would need to solve the problem itself.
# However, the checker can't do that. So for this problem, the checker can't validate a submission that outputs -1.
# Therefore, in the checker code, if the submission outputs -1, we have to check if a valid order exists.
# But that's equivalent to solving the problem. Which is impossible for a checker to do without the correct algorithm.
# Hence, this problem's checker is incomplete. However, given the problem statement, perhaps the checker is expected to handle cases where the submission outputs -1 correctly.
# So, the approach here is that the checker cannot fully validate submissions that output -1. Thus, in practice, such cases would have to be handled by the contest system's test cases, which would have the correct answer (either a permutation or -1).
# However, in the problem statement, the output is either a permutation or -1. So the checker must check two possibilities:
# 1. The submission outputs a valid permutation (so -1 is wrong)
# 2. The submission outputs -1, and no valid permutation exists.
# But how can the checker distinguish between the two? It can't unless it solves the problem.
# Therefore, the checker code here can't handle the -1 case. Thus, the problem may have test cases where the correct answer is -1, and the checker would need to check that the submission's output is -1 and that no valid permutation exists. But how?
# This is a problem. Therefore, perhaps the correct approach is that in this problem, the checker can only check the permutation case. If the submission outputs -1, the checker can't validate it unless it knows whether such a permutation exists (which requires solving the problem).
# Given that the checker's code is supposed to be written without solving the problem, this is impossible. Therefore, the problem is not a 'checker' type but 'diff'? But the problem allows multiple correct outputs, so it's a checker. However, the -1 case complicates things.
# However, according to the problem statement, the correct answer is either -1 or a permutation. So if the submission outputs -1, the checker must check whether the correct answer is -1. But how?
# This is a contradiction. Therefore, in practice, perhaps the test cases where the answer is -1 would be evaluated as 'diff' (exact match), and the rest as 'checker'.
# However, the problem statement's output allows any permutation. So if the reference output is a permutation, then the submission must also be a permutation. If the reference output is -1, then the submission must be -1.
# Therefore, the checker must compare the submission's output with the reference output in the case where the reference output is -1. Otherwise, check the permutation.
# So, the checker must read the reference output. If the reference output is -1, then the submission must also output -1. Else, the submission must output a valid permutation.
# Therefore, the checker logic is:
# Read the reference output. If it's -1, then submission must be -1.
# Otherwise, submission must be a valid permutation.
# So, the code must compare the submission against the reference output in the case where the reference is -1.
# So, the code should proceed as follows:
# 1. Read the reference output (output_path).
with open(output_path) as ref_f:
ref_line = ref_f.readline().strip()
if ref_line == '-1':
# The correct answer is -1; submission must be -1
if line == '-1':
print(1)
return
else:
print(0)
return
else:
# The correct answer is a permutation. The submission must be a valid permutation.
# So proceed with permutation checks.
pass
# If submission is -1 but reference is not, invalid.
if line == '-1':
print(0)
return
# Parse submission's permutation
perm = list(map(int, line.split()))
if len(perm) != n:
print(0)
return
if set(perm) != set(range(1, n+1)):
print(0)
return
# Check consecutive pairs
for i in range(n-1):
x = perm[i]
y = perm[i+1]
if (x, y) in edges:
print(0)
return
print(1)
if __name__ == '__main__':
main()
| true |
986/B
|
986
|
B
|
Python 3
|
TESTS
| 1 | 108 | 0 |
65581546
|
n=int(input())
a=[0] + list(map(int,input().split()))
d={}
for i in range(1,n+1):
d[a[i]]=i
ans=0
for i in range(1,n+1):
if d[i]!=i:
d[a[i]]=d[i]
a[i]=i
ans+=1
# print(a,ans,d)
if (3*n - ans)%2==0:
print("Petr")
else:
print("Um_nik")
| 24 | 296 | 86,425,600 |
216972507
|
n = int(input())
a = [int(x) - 1 for x in input().split()]
ans = 0
for i in range(n):
if a[i] == -1:
continue
ans ^= 1
x = i
while x != -1:
y = a[x]
a[x] = -1
x = y
if ans:
print("Um_nik")
else:
print("Petr")
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
23/B
|
23
|
B
|
Python 3
|
TESTS
| 1 | 1,278 | 0 |
206891934
|
# LUOGU_RID: 111050227
from sys import stdin
input = stdin.readline
def check(num) :
t = n - num
return t >= num - 1
T = int(input())
for _ in range(T) :
n = int(input())
l = 0 ; r = n
while l < r :
mid = l + r + 1 >> 1
if check(mid) : l = mid
else : r = mid - 1
print(n - r)
| 2 | 218 | 9,420,800 |
199473248
|
import sys
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
N = int(input())
print(max(0,N-2))
|
Codeforces Beta Round 23
|
ICPC
| 2,010 | 2 | 256 |
Party
|
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.
What is the maximum amount of people that could stay at the party in the end?
|
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
|
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
| null | null |
[{"input": "1\n3", "output": "1"}]
| 1,600 |
["constructive algorithms", "graphs", "math"]
| 2 |
[{"input": "1\r\n3\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
792/F
|
792
|
F
|
PyPy 3-64
|
TESTS
| 1 | 46 | 0 |
182577807
|
# https://codeforces.com/contest/792/problem/F?f0a28=2
spells = []
def main():
J = 0
n_queries, mana = input().split()
n_queries = int(n_queries)
mana = int(mana)
for i in range(n_queries):
kind, x, y = input().split()
x = ((int(x) + J) % 10**6) + 1
y = ((int(y) + J) % 10**6) + 1
if kind == "1": # spell
spells.append((x, mana / y))
elif kind == "2":
for spell in reversed(spells):
time_to_kill = y / spell[0]
if time_to_kill <= x and time_to_kill <= spell[1]:
print("YES")
break
else:
print("NO")
J = i
if __name__ == "__main__":
import sys
import io
sys.stdin = io.StringIO("""3 100
1 4 9
2 19 49
2 19 49""")
main()
| 36 | 873 | 15,564,800 |
37535361
|
#!/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')
|
Educational Codeforces Round 18
|
ICPC
| 2,017 | 2 | 256 |
Mages and Monsters
|
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.
|
The first line contains two integer numbers q and m (2 ≤ q ≤ 105, 1 ≤ m ≤ 1012) — the number of queries and the amount of mana at the beginning of every fight.
i-th of each next q lines contains three numbers ki, ai and bi (1 ≤ ki ≤ 2, 1 ≤ ai, bi ≤ 106).
Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these).
- If ki = 1, then character learns spell with x = (ai + j) mod 106 + 1, y = (bi + j) mod 106 + 1.
- If ki = 2, then you have to determine if Vova is able to win the fight against monster with t = (ai + j) mod 106 + 1, h = (bi + j) mod 106 + 1.
|
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
| null |
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana.
|
[{"input": "3 100\n1 4 9\n2 19 49\n2 19 49", "output": "YES\nNO"}]
| 3,100 |
["data structures", "geometry"]
| 36 |
[{"input": "3 100\r\n1 4 9\r\n2 19 49\r\n2 19 49\r\n", "output": "YES\r\nNO\r\n"}, {"input": "10 442006988299\r\n2 10 47\r\n1 9 83\r\n1 15 24\r\n2 19 47\r\n2 75 99\r\n2 85 23\r\n2 8 33\r\n2 9 82\r\n1 86 49\r\n2 71 49\r\n", "output": "NO\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\n"}, {"input": "2 424978864039\r\n2 7 3\r\n2 10 8\r\n", "output": "NO\r\nNO\r\n"}, {"input": "2 1000000000000\r\n1 235726 255577\r\n1 959304 206090\r\n", "output": ""}, {"input": "3 10\r\n1 1 1\r\n2 1 1\r\n2 999999 999999\r\n", "output": "YES\r\nYES\r\n"}, {"input": "12 100\r\n1 8 8\r\n2 200 101\r\n2 10 99\r\n1 9 9\r\n2 10 99\r\n2 200 101\r\n1 14 4\r\n2 194 195\r\n2 194 194\r\n2 990 290\r\n2 999991 11\r\n2 999991 10\r\n", "output": "NO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\n"}, {"input": "15 100\r\n1 8 8\r\n2 200 101\r\n2 10 99\r\n1 9 9\r\n2 10 99\r\n2 200 101\r\n1 14 4\r\n2 194 195\r\n2 194 194\r\n2 990 290\r\n1 2 999992\r\n2 6 256\r\n2 7 256\r\n1 2 999988\r\n2 2 252\r\n", "output": "NO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nNO\r\nNO\r\nYES\r\nYES\r\n"}, {"input": "3 12\r\n1 99 9\r\n1 49 1\r\n2 1 149\r\n", "output": "YES\r\n"}]
| false |
stdio
| null | true |
397/B
|
397
|
B
|
PyPy 3
|
TESTS
| 1 | 139 | 0 |
71673582
|
def main():
temp = list(map(int, (input().split())))
n = temp[0]
l = temp[1]
r = temp[2]
i = r
while i >= l:
remain = n % i
if remain >= l and remain < r:
print("Yes")
return 0
i -= 1
print("No")
return
n = int(input())
for i in range(n):
main()
| 6 | 62 | 0 |
5924432
|
t = int(input())
for i in range(0, t) :
n, l, r = [int(s) for s in input().split()]
print('Yes' if n % l <= (r - l) * (n // l) else 'No')
|
Codeforces Round 232 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
On Corruption and Numbers
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
|
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
|
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
| null |
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
[{"input": "2\n5 2 3\n6 4 5", "output": "Yes\nNo"}]
| null |
["constructive algorithms", "implementation", "math"]
| 6 |
[{"input": "2\r\n5 2 3\r\n6 4 5\r\n", "output": "Yes\r\nNo\r\n"}, {"input": "50\r\n69 6 6\r\n22 1 1\r\n23 3 3\r\n60 13 13\r\n13 3 3\r\n7 4 7\r\n6 1 1\r\n49 7 9\r\n68 8 8\r\n20 2 2\r\n34 1 1\r\n79 5 5\r\n22 1 1\r\n77 58 65\r\n10 3 3\r\n72 5 5\r\n47 1 1\r\n82 3 3\r\n92 8 8\r\n34 1 1\r\n42 9 10\r\n63 14 14\r\n10 3 3\r\n38 2 2\r\n80 6 6\r\n79 5 5\r\n53 5 5\r\n44 7 7\r\n85 2 2\r\n24 2 2\r\n57 3 3\r\n95 29 81\r\n77 6 6\r\n24 1 1\r\n33 4 4\r\n93 6 6\r\n55 22 28\r\n91 14 14\r\n7 1 1\r\n16 1 1\r\n20 3 3\r\n43 3 3\r\n53 3 3\r\n49 3 3\r\n52 5 5\r\n2 1 1\r\n60 5 5\r\n76 57 68\r\n67 3 3\r\n61 52 61\r\n", "output": "No\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\n"}]
| false |
stdio
| null | true |
23/B
|
23
|
B
|
Python 3
|
TESTS
| 1 | 1,340 | 2,662,400 |
40262778
|
t = int(input())
a = []
for i in range(0,t):
a.append(int(input())-2)
for i in range(0,t):
print(a[i])
| 2 | 280 | 9,523,200 |
182431083
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
print(max(0, int(input())-2))
|
Codeforces Beta Round 23
|
ICPC
| 2,010 | 2 | 256 |
Party
|
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.
What is the maximum amount of people that could stay at the party in the end?
|
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
|
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
| null | null |
[{"input": "1\n3", "output": "1"}]
| 1,600 |
["constructive algorithms", "graphs", "math"]
| 2 |
[{"input": "1\r\n3\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
23/B
|
23
|
B
|
Python 3
|
TESTS
| 1 | 1,464 | 0 |
172994287
|
N = int(input())
for i in range(N):
b = int(input())
print(b // 2)
| 2 | 342 | 102,400 |
206892050
|
# LUOGU_RID: 111050302
from sys import stdin
input = stdin.readline
T = int(input())
for _ in range(T) :
n = int(input())
print(0 if n <= 2 else n - 2)
|
Codeforces Beta Round 23
|
ICPC
| 2,010 | 2 | 256 |
Party
|
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.
What is the maximum amount of people that could stay at the party in the end?
|
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
|
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
| null | null |
[{"input": "1\n3", "output": "1"}]
| 1,600 |
["constructive algorithms", "graphs", "math"]
| 2 |
[{"input": "1\r\n3\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
23/B
|
23
|
B
|
PyPy 3
|
TESTS
| 1 | 466 | 9,625,600 |
110131849
|
import sys
input=sys.stdin.readline
t=int(input())
for you in range(t):
n=int(input())
print(n-2)
| 2 | 404 | 6,656,000 |
108582736
|
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n=int(input())
if n>2:
sys.stdout.write(str(n-2)+'\n')
else:
sys.stdout.write('0\n')
|
Codeforces Beta Round 23
|
ICPC
| 2,010 | 2 | 256 |
Party
|
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.
What is the maximum amount of people that could stay at the party in the end?
|
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
|
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
| null | null |
[{"input": "1\n3", "output": "1"}]
| 1,600 |
["constructive algorithms", "graphs", "math"]
| 2 |
[{"input": "1\r\n3\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
23/B
|
23
|
B
|
Python 3
|
TESTS
| 1 | 528 | 6,656,000 |
11922651
|
num_tests = int(input())
results = num_tests * [None]
for i in range(num_tests):
n = int(input())
result = (n // 4) * 2
if n % 4 == 3:
result += 1
results[i] = result
print('\n'.join(map(str, results)))
| 2 | 436 | 8,908,800 |
141723547
|
import sys
t = int(sys.stdin.readline())
for _ in range(t):
print(str(max(0, int(sys.stdin.readline()) - 2)))
|
Codeforces Beta Round 23
|
ICPC
| 2,010 | 2 | 256 |
Party
|
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.
What is the maximum amount of people that could stay at the party in the end?
|
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
|
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
| null | null |
[{"input": "1\n3", "output": "1"}]
| 1,600 |
["constructive algorithms", "graphs", "math"]
| 2 |
[{"input": "1\r\n3\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
986/B
|
986
|
B
|
PyPy 3
|
TESTS
| 1 | 77 | 0 |
172326219
|
n = int(input())
a = [int(x) for x in input().split()]
cnt=0
for i in range(len(a)):
if(i+1)==a[i]:
cnt+=1
if cnt:
print("Um_nik")
else:
print("Petr")
| 24 | 390 | 118,886,400 |
191157313
|
n=int(input())
arr=list(map(int,input().split()))
arr=[el-1 for el in arr]
ans=0
for i in range(n):
if arr[i]==-1:
continue
ans^=1
x=i
while x!=-1:
y=arr[x]
arr[x]=-1
x=y
if ans:
print("Um_nik")
else:
print("Petr")
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
208/E
|
208
|
E
|
PyPy 3-64
|
TESTS
| 0 | 92 | 0 |
221094016
|
import sys
input = sys.stdin.readline
def dfs(v, parent, tree, cnt):
cnt[v] = 1
for u in tree[v]:
if u != parent:
cnt[v] += dfs(u, v, tree, cnt)
return cnt[v]
def main():
n = int(input())
parent = list(map(int, input().split()))
tree = [[] for _ in range(n+1)]
for i, p in enumerate(parent, start=1):
if p != 0:
tree[p].append(i)
cnt = [0] * (n+1)
dfs(1, 0, tree, cnt)
height_vertices = [[] for _ in range(n+1)]
for i in range(1, n+1):
height_vertices[cnt[i]].append(i)
m = int(input())
for _ in range(m):
v, p = map(int, input().split())
u = v
while p > 0:
if u == 0:
break
u = parent[u-1]
p -= 1
if u == 0:
print(0, end=' ')
else:
vertices_on_same_height = height_vertices[cnt[u]]
left = 0
right = len(vertices_on_same_height) - 1
while left <= right:
mid = (left + right) // 2
if u <= vertices_on_same_height[mid]:
right = mid - 1
else:
left = mid + 1
descendants_count = right - left + 1
print(descendants_count - 1, end=' ')
if __name__ == "__main__":
main()
| 64 | 1,434 | 108,032,000 |
229646493
|
import sys
import random
input = sys.stdin.readline
rd = random.randint(10 ** 9, 2 * 10 ** 9)
n = int(input())
p = list(map(int, input().split()))
g = [[] for _ in range(n)]
for i in range(n):
if p[i] == 0:
continue
g[p[i] - 1].append(i)
q = int(input())
queries = [[] for _ in range(n)]
queries2 = [[] for _ in range(n)]
ans = [0] * q
for i in range(q):
x, d = map(int, input().split())
queries[x - 1].append((d, i))
from collections import defaultdict
path = []
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(son, depth):
ds = defaultdict(int)
ds[depth] += 1
path.append(son)
for d, i in queries[son]:
if d > depth:
continue
queries2[path[-d - 1]].append((d, i))
for x in g[son]:
dx = yield dfs(x, depth + 1)
if len(dx) > len(ds):
ds, dx = dx, ds
for k, v in dx.items():
ds[k] += v
dx.clear()
for d, i in queries2[son]:
ans[i] = ds[d + depth] - 1
path.pop()
yield ds
for i in range(n):
if p[i] == 0:
dfs(i, 0)
print(*ans)
|
Codeforces Round 130 (Div. 2)
|
CF
| 2,012 | 2 | 256 |
Blood Cousins
|
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.
Let's call person a a 1-ancestor of person b, if a is the parent of b.
Let's call person a a k-ancestor (k > 1) of person b, if person b has a 1-ancestor, and a is a (k - 1)-ancestor of b's 1-ancestor.
Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, x > 0).
Let's call two people x and y (x ≠ y) p-th cousins (p > 0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.
Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.
|
The first input line contains a single integer n (1 ≤ n ≤ 105) — the number of people in the tree. The next line contains n space-separated integers r1, r2, ..., rn, where ri (1 ≤ ri ≤ n) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles.
The third line contains a single number m (1 ≤ m ≤ 105) — the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1 ≤ vi, pi ≤ n).
|
Print m space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.
| null | null |
[{"input": "6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1", "output": "0 0 1 0 0 1 1"}]
| 2,100 |
["binary search", "data structures", "dfs and similar", "trees"]
| 64 |
[{"input": "6\r\n0 1 1 0 4 4\r\n7\r\n1 1\r\n1 2\r\n2 1\r\n2 2\r\n4 1\r\n5 1\r\n6 1\r\n", "output": "0 0 1 0 0 1 1 \r\n"}, {"input": "1\r\n0\r\n20\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n1 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "2\r\n0 1\r\n20\r\n2 1\r\n2 1\r\n2 1\r\n2 1\r\n2 1\r\n2 1\r\n1 1\r\n1 1\r\n1 1\r\n2 1\r\n1 1\r\n2 1\r\n2 1\r\n2 1\r\n1 1\r\n2 1\r\n2 1\r\n1 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "3\r\n0 0 2\r\n20\r\n2 1\r\n1 1\r\n1 1\r\n2 1\r\n2 1\r\n1 1\r\n3 1\r\n1 1\r\n2 1\r\n1 1\r\n3 1\r\n2 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n2 1\r\n3 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "3\r\n0 0 1\r\n20\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n3 1\r\n1 1\r\n2 1\r\n3 1\r\n2 1\r\n3 1\r\n1 1\r\n1 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}, {"input": "4\r\n0 1 1 0\r\n20\r\n3 1\r\n1 1\r\n1 1\r\n3 1\r\n4 1\r\n3 1\r\n3 1\r\n4 1\r\n2 1\r\n1 1\r\n4 1\r\n4 1\r\n2 1\r\n2 1\r\n3 1\r\n4 1\r\n4 1\r\n1 1\r\n2 1\r\n4 1\r\n", "output": "1 0 0 1 0 1 1 0 1 0 0 0 1 1 1 0 0 0 1 0 \r\n"}, {"input": "4\r\n0 0 0 1\r\n20\r\n2 1\r\n2 1\r\n3 1\r\n2 1\r\n4 1\r\n3 1\r\n1 1\r\n3 1\r\n2 1\r\n2 1\r\n3 1\r\n1 1\r\n1 1\r\n1 1\r\n2 1\r\n4 1\r\n4 1\r\n3 1\r\n1 1\r\n2 1\r\n", "output": "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \r\n"}]
| false |
stdio
| null | true |
351/B
|
351
|
B
|
PyPy 3-64
|
TESTS
| 1 | 62 | 0 |
222018915
|
n = int(input())
nums = list(map(int, input().split()))
num_nxd = 0
for i in range(n-1):
for j in range(i+1, n):
if nums[j] < nums[i]:
print(i, j)
num_nxd += 1
if num_nxd == 0: print(0)
elif num_nxd == 1: print(1)
elif num_nxd % 2 == 0: print(2 * num_nxd)
else: print((num_nxd-1) * 2 + 1)
| 25 | 218 | 307,200 |
97900420
|
n=int(input().strip())
p=[0]+list(map(int,input().split()))
c=[0]*(n+1)
def lowbit(x):
return x&(-x)
def add(x,v):
while x<=n:
c[x]+=v
x+=lowbit(x)
def get(x):
ans=0
while x:
ans+=c[x]
x-=lowbit(x)
return ans
ans=0
for i in range(n,0,-1):
ans+=get(p[i])
add(p[i],1)
if ans%2:
print(2*ans-1)
else:
print(2*ans)
|
Codeforces Round 204 (Div. 1)
|
CF
| 2,013 | 1 | 256 |
Jeff and Furik
|
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.
Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.
You can consider that the coin shows the heads (or tails) with the probability of 50 percent.
|
The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation p. The numbers are separated by spaces.
|
In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
| null |
In the first test the sequence is already sorted, so the answer is 0.
|
[{"input": "2\n1 2", "output": "0.000000"}, {"input": "5\n3 5 2 4 1", "output": "13.000000"}]
| 1,900 |
["combinatorics", "dp", "probabilities"]
| 25 |
[{"input": "2\r\n1 2\r\n", "output": "0.000000\r\n"}, {"input": "5\r\n3 5 2 4 1\r\n", "output": "13.000000\r\n"}, {"input": "16\r\n6 15 3 8 7 11 9 10 2 13 4 14 1 16 5 12\r\n", "output": "108.000000\r\n"}, {"input": "9\r\n1 7 8 5 3 4 6 9 2\r\n", "output": "33.000000\r\n"}, {"input": "5\r\n2 3 4 5 1\r\n", "output": "8.000000\r\n"}, {"input": "9\r\n4 1 8 6 7 5 2 9 3\r\n", "output": "33.000000\r\n"}, {"input": "10\r\n3 4 1 5 7 9 8 10 6 2\r\n", "output": "29.000000\r\n"}, {"input": "13\r\n3 1 11 12 4 5 8 10 13 7 9 2 6\r\n", "output": "69.000000\r\n"}, {"input": "10\r\n8 4 1 7 6 10 9 5 3 2\r\n", "output": "53.000000\r\n"}, {"input": "2\r\n2 1\r\n", "output": "1.000000\r\n"}, {"input": "95\r\n68 56 24 89 79 20 74 69 49 59 85 67 95 66 15 34 2 13 92 25 84 77 70 71 17 93 62 81 1 87 76 38 75 31 63 51 35 33 37 11 36 52 23 10 27 90 12 6 45 32 86 26 60 47 91 65 58 80 78 88 50 9 44 4 28 29 22 8 48 7 19 57 14 54 55 83 5 30 72 18 82 94 43 46 41 3 61 53 73 39 40 16 64 42 21\r\n", "output": "5076.000000\r\n"}]
| false |
stdio
|
import sys
def read_float_from_line(line):
line = line.strip()
try:
return float(line)
except:
return None
def is_acceptable(ref, sub, abs_tol=1e-6, rel_tol=1e-6):
if abs(ref - sub) <= abs_tol:
return True
denom = max(abs(ref), 1e-8)
return abs(ref - sub) / denom <= rel_tol
def main():
input_path = sys.argv[1]
ref_path = sys.argv[2]
sub_path = sys.argv[3]
# Read reference output
with open(ref_path, 'r') as f:
ref_line = f.readline().strip()
ref_val = read_float_from_line(ref_line)
if ref_val is None:
print(0)
return
# Read submission output
with open(sub_path, 'r') as f:
sub_lines = f.readlines()
if not sub_lines:
print(0)
return
sub_line = sub_lines[0].strip()
sub_val = read_float_from_line(sub_line)
if sub_val is None:
print(0)
return
# Check correctness
if is_acceptable(ref_val, sub_val):
print(1)
else:
print(0)
if __name__ == "__main__":
main()
| true |
171/C
|
171
|
C
|
PyPy 3
|
TESTS
| 1 | 248 | 0 |
68564637
|
s = [int(i) for i in input().split(" ")]
ans = 0
for i in s[1:]:
ans += i*i
print(ans)
| 41 | 62 | 0 |
207105716
|
p= input ().split()
#pieee
t=0
for i in range (1,int (p [0])+1):
t+=i*eval (p[i])
print (t)
|
April Fools Day Contest
|
ICPC
| 2,012 | 2 | 256 |
A Piece of Cake
|
How to make a cake you'll never eat.
Ingredients.
- 2 carrots
- 0 calories
- 100 g chocolate spread
- 1 pack of flour
- 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
|
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
|
Output a single integer.
| null | null |
[{"input": "4 1 2 3 4", "output": "30"}]
| 2,000 |
["*special", "implementation"]
| 41 |
[{"input": "4 1 2 3 4\r\n", "output": "30\r\n"}, {"input": "4 802 765 992 1\r\n", "output": "5312\r\n"}, {"input": "4 220 380 729 969\r\n", "output": "7043\r\n"}, {"input": "3 887 104 641\r\n", "output": "3018\r\n"}, {"input": "12 378 724 582 387 583 241 294 159 198 653 369 418\r\n", "output": "30198\r\n"}, {"input": "14 36 901 516 623 703 971 304 394 491 525 464 219 183 648\r\n", "output": "49351\r\n"}, {"input": "3 287 979 395\r\n", "output": "3430\r\n"}, {"input": "19 702 667 743 976 908 728 134 106 380 193 214 71 920 114 587 543 817 248 537\r\n", "output": "87024\r\n"}, {"input": "11 739 752 364 649 626 702 444 913 681 529 959\r\n", "output": "45653\r\n"}, {"input": "19 196 392 738 103 119 872 900 189 65 113 260 985 228 537 217 735 785 445 636\r\n", "output": "92576\r\n"}, {"input": "22 196 690 553 822 392 687 425 763 216 73 525 412 155 263 205 965 825 105 153 580 218 103\r\n", "output": "96555\r\n"}, {"input": "10 136 641 472 872 115 607 197 19 494 577\r\n", "output": "22286\r\n"}, {"input": "10 5 659 259 120 421 165 194 637 577 39\r\n", "output": "17712\r\n"}, {"input": "5 472 4 724 577 157\r\n", "output": "5745\r\n"}, {"input": "23 486 261 249 312 592 411 874 397 18 70 417 512 338 679 517 997 938 328 418 793 522 745 59\r\n", "output": "141284\r\n"}, {"input": "17 644 532 255 57 108 413 51 284 364 300 597 646 712 470 42 730 231\r\n", "output": "61016\r\n"}, {"input": "26 932 569 829 138 565 766 466 673 559 678 417 618 930 751 840 184 809 639 287 550 923 341 851 209 987 252\r\n", "output": "207547\r\n"}, {"input": "16 29 672 601 178 603 860 6 431 114 463 588 788 712 956 895 19\r\n", "output": "73502\r\n"}, {"input": "5 336 860 760 835 498\r\n", "output": "10166\r\n"}, {"input": "29 384 110 78 925 320 755 176 690 784 848 981 653 140 840 659 262 954 812 850 431 523 495 16 233 70 352 92 520 877\r\n", "output": "216056\r\n"}, {"input": "21 256 260 390 24 185 400 780 51 89 253 900 760 906 730 599 565 992 243 66 531 364\r\n", "output": "114365\r\n"}, {"input": "19 26 380 823 787 422 605 306 298 885 562 249 965 277 124 365 56 175 144 309\r\n", "output": "67719\r\n"}, {"input": "41 595 215 495 884 470 176 126 536 398 181 816 114 251 328 901 674 933 206 662 507 458 601 162 735 725 217 481 591 51 791 355 646 696 540 530 165 717 346 391 114 527\r\n", "output": "406104\r\n"}, {"input": "20 228 779 225 819 142 849 24 494 45 172 95 207 908 510 424 78 100 166 869 456\r\n", "output": "78186\r\n"}, {"input": "15 254 996 341 109 402 688 501 206 905 398 124 373 313 943 515\r\n", "output": "57959\r\n"}, {"input": "45 657 700 898 830 795 104 427 995 219 505 95 385 64 241 196 318 927 228 428 329 606 619 535 200 707 660 574 19 292 88 872 950 788 769 779 272 563 896 267 782 400 52 857 154 293\r\n", "output": "507143\r\n"}, {"input": "41 473 219 972 591 238 267 209 464 467 916 814 40 625 105 820 496 54 297 264 523 570 828 418 527 299 509 269 156 663 562 900 826 471 561 416 710 828 315 864 985 230\r\n", "output": "463602\r\n"}, {"input": "48 25 856 782 535 41 527 832 306 49 91 824 158 618 122 357 887 969 710 138 868 536 610 118 642 9 946 958 873 931 878 549 646 733 20 180 775 547 11 771 287 103 594 135 411 406 492 989 375\r\n", "output": "597376\r\n"}, {"input": "57 817 933 427 116 51 69 125 687 717 688 307 594 927 643 17 638 823 482 184 525 943 161 318 226 296 419 632 478 97 697 370 915 320 797 30 371 556 847 748 272 224 746 557 151 388 264 789 211 746 663 426 688 825 744 914 811 853\r\n", "output": "900997\r\n"}, {"input": "55 980 951 933 349 865 252 836 585 313 392 431 751 354 656 496 601 497 885 865 976 786 300 638 211 678 152 645 281 654 187 517 633 137 139 672 692 81 507 968 84 589 398 835 944 744 331 234 931 906 99 906 691 89 234 592\r\n", "output": "810147\r\n"}]
| false |
stdio
| null | true |
171/C
|
171
|
C
|
Python 3
|
TESTS
| 1 | 218 | 0 |
58235107
|
a, b, *r, c = input().split()
print((int(b) + int (c)) * eval('*'.join(r)))
| 41 | 92 | 0 |
137353413
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Deean
Date: 2021-11-29 23:34:16
LastEditTime: 2021-11-29 23:36:05
Description: A Piece of Cake
FilePath: CF171C.py
'''
def func():
n, *lst = map(int, input().strip().split())
count = 0
for i in range(n):
count += lst[i] * (i + 1)
print(count)
if __name__ == '__main__':
func()
|
April Fools Day Contest
|
ICPC
| 2,012 | 2 | 256 |
A Piece of Cake
|
How to make a cake you'll never eat.
Ingredients.
- 2 carrots
- 0 calories
- 100 g chocolate spread
- 1 pack of flour
- 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
|
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
|
Output a single integer.
| null | null |
[{"input": "4 1 2 3 4", "output": "30"}]
| 2,000 |
["*special", "implementation"]
| 41 |
[{"input": "4 1 2 3 4\r\n", "output": "30\r\n"}, {"input": "4 802 765 992 1\r\n", "output": "5312\r\n"}, {"input": "4 220 380 729 969\r\n", "output": "7043\r\n"}, {"input": "3 887 104 641\r\n", "output": "3018\r\n"}, {"input": "12 378 724 582 387 583 241 294 159 198 653 369 418\r\n", "output": "30198\r\n"}, {"input": "14 36 901 516 623 703 971 304 394 491 525 464 219 183 648\r\n", "output": "49351\r\n"}, {"input": "3 287 979 395\r\n", "output": "3430\r\n"}, {"input": "19 702 667 743 976 908 728 134 106 380 193 214 71 920 114 587 543 817 248 537\r\n", "output": "87024\r\n"}, {"input": "11 739 752 364 649 626 702 444 913 681 529 959\r\n", "output": "45653\r\n"}, {"input": "19 196 392 738 103 119 872 900 189 65 113 260 985 228 537 217 735 785 445 636\r\n", "output": "92576\r\n"}, {"input": "22 196 690 553 822 392 687 425 763 216 73 525 412 155 263 205 965 825 105 153 580 218 103\r\n", "output": "96555\r\n"}, {"input": "10 136 641 472 872 115 607 197 19 494 577\r\n", "output": "22286\r\n"}, {"input": "10 5 659 259 120 421 165 194 637 577 39\r\n", "output": "17712\r\n"}, {"input": "5 472 4 724 577 157\r\n", "output": "5745\r\n"}, {"input": "23 486 261 249 312 592 411 874 397 18 70 417 512 338 679 517 997 938 328 418 793 522 745 59\r\n", "output": "141284\r\n"}, {"input": "17 644 532 255 57 108 413 51 284 364 300 597 646 712 470 42 730 231\r\n", "output": "61016\r\n"}, {"input": "26 932 569 829 138 565 766 466 673 559 678 417 618 930 751 840 184 809 639 287 550 923 341 851 209 987 252\r\n", "output": "207547\r\n"}, {"input": "16 29 672 601 178 603 860 6 431 114 463 588 788 712 956 895 19\r\n", "output": "73502\r\n"}, {"input": "5 336 860 760 835 498\r\n", "output": "10166\r\n"}, {"input": "29 384 110 78 925 320 755 176 690 784 848 981 653 140 840 659 262 954 812 850 431 523 495 16 233 70 352 92 520 877\r\n", "output": "216056\r\n"}, {"input": "21 256 260 390 24 185 400 780 51 89 253 900 760 906 730 599 565 992 243 66 531 364\r\n", "output": "114365\r\n"}, {"input": "19 26 380 823 787 422 605 306 298 885 562 249 965 277 124 365 56 175 144 309\r\n", "output": "67719\r\n"}, {"input": "41 595 215 495 884 470 176 126 536 398 181 816 114 251 328 901 674 933 206 662 507 458 601 162 735 725 217 481 591 51 791 355 646 696 540 530 165 717 346 391 114 527\r\n", "output": "406104\r\n"}, {"input": "20 228 779 225 819 142 849 24 494 45 172 95 207 908 510 424 78 100 166 869 456\r\n", "output": "78186\r\n"}, {"input": "15 254 996 341 109 402 688 501 206 905 398 124 373 313 943 515\r\n", "output": "57959\r\n"}, {"input": "45 657 700 898 830 795 104 427 995 219 505 95 385 64 241 196 318 927 228 428 329 606 619 535 200 707 660 574 19 292 88 872 950 788 769 779 272 563 896 267 782 400 52 857 154 293\r\n", "output": "507143\r\n"}, {"input": "41 473 219 972 591 238 267 209 464 467 916 814 40 625 105 820 496 54 297 264 523 570 828 418 527 299 509 269 156 663 562 900 826 471 561 416 710 828 315 864 985 230\r\n", "output": "463602\r\n"}, {"input": "48 25 856 782 535 41 527 832 306 49 91 824 158 618 122 357 887 969 710 138 868 536 610 118 642 9 946 958 873 931 878 549 646 733 20 180 775 547 11 771 287 103 594 135 411 406 492 989 375\r\n", "output": "597376\r\n"}, {"input": "57 817 933 427 116 51 69 125 687 717 688 307 594 927 643 17 638 823 482 184 525 943 161 318 226 296 419 632 478 97 697 370 915 320 797 30 371 556 847 748 272 224 746 557 151 388 264 789 211 746 663 426 688 825 744 914 811 853\r\n", "output": "900997\r\n"}, {"input": "55 980 951 933 349 865 252 836 585 313 392 431 751 354 656 496 601 497 885 865 976 786 300 638 211 678 152 645 281 654 187 517 633 137 139 672 692 81 507 968 84 589 398 835 944 744 331 234 931 906 99 906 691 89 234 592\r\n", "output": "810147\r\n"}]
| false |
stdio
| null | true |
474/B
|
474
|
B
|
PyPy 3-64
|
TESTS
| 26 | 967 | 18,329,600 |
193017542
|
n=int(input())
a=list(map(int,input().split()))
m=int(input())
q=list(map(int,input().split()))
l=[]
k,t=0,0
for i in range(n):
k+=a[i]
l.append(k)
for i in range(m):
if q[i]<l[t]:
t=0
elif q[i]==l[t]:
print(t+1)
break
while q[i]>l[t]:
t+=1
print(t+1)
| 38 | 155 | 14,438,400 |
196309371
|
#****************************************************
#***************Shariar Hasan************************
#**************CSE CU Batch 18***********************
#****************************************************
#import os
#import sys
from math import *
#import re
#import random
#sys.set_int_max_str_digits(int(1e9))
def solve():
#for _ in range(int(input())):
for _ in range(1):
n = int(input())
w = [int(x) for x in input().split()]
sum = 0
for i in range(n):
sum+=w[i]
w[i] = sum
m = int(input())
inp = [int(x) for x in input().split()]
ans = 0
for x in inp:
l = -1; r = n
while r - l > 1:
mid = (l+r)//2
if(w[mid] < x):
l = mid
else:
r = mid
print(r+1)
# 2 9 12 16 25
solve()
|
Codeforces Round 271 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
Worms
|
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.
Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.
Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
|
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile.
The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot.
The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
|
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
| null |
For the sample input:
- The worms with labels from [1, 2] are in the first pile.
- The worms with labels from [3, 9] are in the second pile.
- The worms with labels from [10, 12] are in the third pile.
- The worms with labels from [13, 16] are in the fourth pile.
- The worms with labels from [17, 25] are in the fifth pile.
|
[{"input": "5\n2 7 3 4 9\n3\n1 25 11", "output": "1\n5\n3"}]
| 1,200 |
["binary search", "implementation"]
| 38 |
[{"input": "5\r\n2 7 3 4 9\r\n3\r\n1 25 11\r\n", "output": "1\r\n5\r\n3\r\n"}]
| false |
stdio
| null | true |
47/D
|
47
|
D
|
Python 3
|
TESTS
| 0 | 60 | 0 |
212685560
|
def is_consistent(code, responses):
for i, response in enumerate(responses):
count = sum(a == b for a, b in zip(code, response))
if count != responses[i]:
return False
return True
def generate_codes(n, code, index, responses, count_variants):
if index == n:
if is_consistent(code, responses):
count_variants[0] += 1
return count_variants[0]
code[index] = 0
generate_codes(n, code, index + 1, responses, count_variants)
code[index] = 1
generate_codes(n, code, index + 1, responses, count_variants)
n, m = map(int, input().split())
responses = [list(map(int, input().split())) for _ in range(m)]
count_variants = [0]
generate_codes(n, [0] * n, 0, responses, count_variants)
print(count_variants[0])
| 26 | 3,648 | 10,444,800 |
156930466
|
import sys
readline=sys.stdin.readline
def Pop_Count(N):
r=(N&0x5555555555555555)+((N>>1)&0x5555555555555555)
r=(r&0x3333333333333333)+((r>>2)&0x3333333333333333)
r=(r&0x0f0f0f0f0f0f0f0f)+((r>>4)&0x0f0f0f0f0f0f0f0f)
r=(r&0x00ff00ff00ff00ff)+((r>>8)&0x00ff00ff00ff00ff)
r=(r&0x0000ffff0000ffff)+((r>>16)&0x0000ffff0000ffff)
r=(r&0x00000000ffffffff)+((r>>32)&0x00000000ffffffff)
return r
N,M=map(int,readline().split())
S,c=readline().split()
S=sum(1<<i for i in range(N) if S[i]=="1")
c=int(c)
bit=(1<<c)-1
ans_lst=[]
while bit<1<<N:
ans_lst.append(bit^S)
t=bit|bit-1
bit=(t+1)|(~t&-~t)-1>>(bit&-bit).bit_length()
for _ in range(M-1):
S,c=readline().split()
S=sum(1<<i for i in range(N) if S[i]=="1")
c=int(c)
ans_lst=[bit for bit in ans_lst if Pop_Count(bit^S)==c]
ans=len(ans_lst)
print(ans)
|
Codeforces Beta Round 44 (Div. 2)
|
CF
| 2,010 | 5 | 256 |
Safe
|
Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.
|
The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).
|
Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.
| null | null |
[{"input": "6 2\n000000 2\n010100 4", "output": "6"}, {"input": "6 3\n000000 2\n010100 4\n111100 0", "output": "0"}, {"input": "6 3\n000000 2\n010100 4\n111100 2", "output": "1"}]
| 2,200 |
["brute force"]
| 26 |
[{"input": "6 2\r\n000000 2\r\n010100 4\r\n", "output": "6\r\n"}, {"input": "6 3\r\n000000 2\r\n010100 4\r\n111100 0\r\n", "output": "0\r\n"}, {"input": "6 3\r\n000000 2\r\n010100 4\r\n111100 2\r\n", "output": "1\r\n"}, {"input": "6 1\r\n101011 2\r\n", "output": "15\r\n"}, {"input": "7 2\r\n1011111 2\r\n1001111 1\r\n", "output": "6\r\n"}, {"input": "6 4\r\n000110 2\r\n010001 2\r\n001111 2\r\n001100 2\r\n", "output": "1\r\n"}, {"input": "8 3\r\n00111100 5\r\n10100111 2\r\n10110101 2\r\n", "output": "6\r\n"}, {"input": "35 1\r\n00001111001110101000001101100010010 5\r\n", "output": "324632\r\n"}, {"input": "35 2\r\n00101101100111101110111010001101101 3\r\n00111111100101010110111010001101101 3\r\n", "output": "20\r\n"}, {"input": "35 1\r\n11000110100110101001100101001010110 2\r\n", "output": "595\r\n"}, {"input": "35 2\r\n00111111100000111101000110100111101 1\r\n00111111000000111101000010100111101 1\r\n", "output": "2\r\n"}, {"input": "35 6\r\n01100100110000001001100110001100011 5\r\n10000100110000011001110010001100011 5\r\n00101110100000010000100010001110011 4\r\n00110010101000011001100000001110011 5\r\n00100101110000011001101110001110011 4\r\n00110110110000011001101000000100011 5\r\n", "output": "1\r\n"}, {"input": "6 10\r\n110000 5\r\n010011 4\r\n110011 5\r\n110010 4\r\n000001 4\r\n010001 5\r\n110101 5\r\n110011 5\r\n110010 4\r\n011001 4\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
509/C
|
509
|
C
|
Python 3
|
TESTS
| 0 | 93 | 307,200 |
89815762
|
n = int(input())
last=0
for i in range(n):
a = int(input())
s=''
val=0
if i==0:
for j in range(a):
s+='1'
last = int(s)
print(last)
else:
for j in range(a):
s += '1'
val = int(s)
while (val<=last):
val*=10
last = val
print(last)
| 21 | 233 | 2,560,000 |
230063199
|
n = int(input())
def get_sum(x):
result = 0
while x > 0:
d, m = divmod(x, 10)
result += m
x = d
return result
def dec(x):
t = x
mult = 1
while True:
d, m = divmod(x, 10)
if m != 0:
return t + (10 - m) * mult
x = d
mult *= 10
def get_next(prev_x, prev_sum, sum):
t = prev_x
while True:
while prev_sum > sum:
prev_x = dec(prev_x)
prev_sum = get_sum(prev_x)
s = list(str(prev_x))[::-1]
required = sum - prev_sum
i = 0
while required:
try:
a = min(9 - (ord(s[i]) - ord('0')), required)
s[i] = chr(ord(s[i]) + a)
except IndexError:
a = min(9, required)
s += chr(a + ord('0'))
required -= a
i += 1
x = int("".join(reversed(s)))
if x != t:
return x
prev_x = dec(prev_x)
prev_sum = get_sum(prev_x)
a = s = 0
for i in range(n):
b = int(input())
a = get_next(a, s, b)
print(a)
s = b
|
Codeforces Round 289 (Div. 2, ACM ICPC Rules)
|
ICPC
| 2,015 | 2 | 256 |
Sums of Digits
|
Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.
Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.
It is guaranteed that such a sequence always exists.
|
The first line contains a single integer number n (1 ≤ n ≤ 300).
Next n lines contain integer numbers b1, ..., bn — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.
|
Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi.
If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.
| null | null |
[{"input": "3\n1\n2\n3", "output": "1\n2\n3"}, {"input": "3\n3\n2\n1", "output": "3\n11\n100"}]
| 2,000 |
["dp", "greedy", "implementation"]
| 21 |
[{"input": "3\r\n1\r\n2\r\n3\r\n", "output": "1\r\n2\r\n3\r\n"}, {"input": "3\r\n3\r\n2\r\n1\r\n", "output": "3\r\n11\r\n100\r\n"}, {"input": "10\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n1\r\n", "output": "1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n"}, {"input": "10\r\n8\r\n8\r\n5\r\n1\r\n2\r\n7\r\n3\r\n8\r\n9\r\n4\r\n", "output": "8\r\n17\r\n23\r\n100\r\n101\r\n106\r\n111\r\n116\r\n117\r\n121\r\n"}, {"input": "10\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n", "output": "1\r\n10\r\n100\r\n1000\r\n10000\r\n100000\r\n1000000\r\n10000000\r\n100000000\r\n1000000000\r\n"}, {"input": "100\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n1\r\n", "output": "1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19\r\n20\r\n21\r\n22\r\n23\r\n24\r\n25\r\n26\r\n27\r\n28\r\n29\r\n30\r\n31\r\n32\r\n33\r\n34\r\n35\r\n36\r\n37\r\n38\r\n39\r\n40\r\n41\r\n42\r\n43\r\n44\r\n45\r\n46\r\n47\r\n48\r\n49\r\n50\r\n51\r\n52\r\n53\r\n54\r\n55\r\n56\r\n57\r\n58\r\n59\r\n60\r\n61\r\n62\r\n63\r\n64\r\n65\r\n66\r\n67\r\n68\r\n69\r\n70\r\n71\r\n72\r\n73\r\n74\r\n75\r\n76\r\n77\r\n78\r\n79\r\n80\r\n81\r\n82\r\n83\r\n84\r\n85\r\n86\r\n87\r\n88\r\n89\r\n90\r\n91\r\n92\r\n93\r\n94\r\n95\r\n96\r\n97\r\n98\r\n99\r\n100\r\n"}, {"input": "100\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n18\r\n", "output": "99\n189\n198\n279\n288\n297\n369\n378\n387\n396\n459\n468\n477\n486\n495\n549\n558\n567\n576\n585\n594\n639\n648\n657\n666\n675\n684\n693\n729\n738\n747\n756\n765\n774\n783\n792\n819\n828\n837\n846\n855\n864\n873\n882\n891\n909\n918\n927\n936\n945\n954\n963\n972\n981\n990\n1089\n1098\n1179\n1188\n1197\n1269\n1278\n1287\n1296\n1359\n1368\n1377\n1386\n1395\n1449\n1458\n1467\n1476\n1485\n1494\n1539\n1548\n1557\n1566\n1575\n1584\n1593\n1629\n1638\n1647\n1656\n1665\n1674\n1683\n1692\n1719\n1728\n1737\n1746\n1755\n1764\n1773\n1782\n1791\n1809\n"}, {"input": "1\r\n139\r\n", "output": "4999999999999999\r\n"}, {"input": "1\r\n6\r\n", "output": "6\r\n"}]
| false |
stdio
| null | true |
598/E
|
598
|
E
|
PyPy 3-64
|
TESTS
| 1 | 31 | 0 |
201934756
|
# https://codeforces.com/contest/598/problem/E
for _ in range(int(input())):
n, m, k = map(int, input().split())
cout = 0
while k > 0 and n * m != k:
if n > m: n, m = m, n
# n <= m
y_coupe = k // n
if y_coupe > 0:
k -= y_coupe * n
m -= y_coupe
else:
m = k
cout += n * n
print(cout)
| 5 | 482 | 9,113,600 |
175317754
|
from sys import stdin
input=lambda :stdin.readline()[:-1]
dp=[[[10**9]*51 for i in range(31)] for i in range(31)]
for n in range(1,31):
for m in range(1,31):
for k in range(51):
if k==0:
dp[n][m][k]=0
continue
if n*m<k:
continue
if n*m==k:
dp[n][m][k]=0
continue
res=10**9
for i in range(1,n):
for j in range(k+1):
res=min(res,dp[i][m][j]+dp[n-i][m][k-j]+m*m)
for i in range(1,m):
for j in range(k+1):
res=min(res,dp[n][i][j]+dp[n][m-i][k-j]+n*n)
dp[n][m][k]=res
for _ in range(int(input())):
n,m,k=map(int,input().split())
print(dp[n][m][k])
|
Educational Codeforces Round 1
|
ICPC
| 2,015 | 2 | 256 |
Chocolate Bar
|
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
|
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
|
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
| null |
In the first query of the sample one needs to perform two breaks:
- to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),
- to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
|
[{"input": "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4", "output": "5\n5\n4\n0"}]
| 2,000 |
["brute force", "dp"]
| 5 |
[{"input": "4\r\n2 2 1\r\n2 2 3\r\n2 2 2\r\n2 2 4\r\n", "output": "5\r\n5\r\n4\r\n0\r\n"}]
| false |
stdio
| null | true |
29/E
|
29
|
E
|
PyPy 3-64
|
TESTS
| 0 | 124 | 102,400 |
213880873
|
import sys
from collections import deque
readline = sys.stdin.readline
N, M = [int(w) for w in readline().split()]
city = [[] for _ in range(N + 1)]
for _ in range(M):
u, v = [int(w) for w in readline().split()]
city[u].append(v)
city[v].append(u)
seen = {(1, N, 0): (-1, -1, -1)}
que = deque([(1, N, 0)])
target = (N, 1, 0)
while que:
u, v, status = que.popleft()
if status == 0:
for v1 in city[v]:
if (u, v1, 1) in seen:
continue
seen[(u, v1, 1)] = (u, v, status)
que.append((u, v1, 1))
elif status == 1:
for u1 in city[u]:
if u1 == v:
continue
if (u1, v, 0) in seen:
continue
seen[(u1, v, 0)] = (u, v, status)
que.append((u1, v, 0))
if target in seen:
break
result = [[], []]
while target in seen:
if target[-1] == 0:
result[0].append(target[0])
result[1].append(target[1])
target = seen[target]
if result[0]:
print(len(result[0]))
print(*result[1])
print(*result[0])
else:
print(-1)
| 56 | 872 | 71,475,200 |
213890023
|
import sys
from collections import deque
readline = sys.stdin.readline
N, M = [int(w) for w in readline().split()]
city = [[] for _ in range(N + 1)]
edges = []
for _ in range(M):
u, v = [int(w) for w in readline().split()]
city[u].append(v)
city[v].append(u)
edges.append((u, v))
def gen_dists(node: int) -> list:
result = [N + 1] * (N + 1)
dq = deque([node])
result[node] = 1
while dq:
u = dq.popleft()
for v in city[u]:
if result[v] <= result[u] + 1:
continue
result[v] = result[u] + 1
dq.append(v)
return result
dist_alex = gen_dists(1)
dist_bob = gen_dists(N)
if dist_alex[-1] > N:
print(-1)
exit(0)
seen = {(1, N, 0): (-1, -1, -1)}
step_cnt = {(1, N, 0): 0}
que = deque([(1, N, 0, 0)])
target = (N, 1, 0)
while que:
u, v, status, step = que.popleft()
if step >= N:
break
if status == 0:
for v1 in city[v]:
if (u, v1, 1) in seen:
continue
seen[(u, v1, 1)] = (u, v, status)
if dist_alex[v1] < dist_alex[v]:
que.appendleft((u, v1, 1, step))
else:
que.append((u, v1, 1, step))
elif status == 1:
for u1 in city[u]:
if u1 == v:
continue
if (u1, v, 0) in seen:
continue
seen[(u1, v, 0)] = (u, v, status)
if dist_bob[u1] < dist_bob[u]:
que.appendleft((u1, v, 0, step + 1))
else:
que.append((u1, v, 0, step + 1))
if target in seen:
break
if target in seen:
break
result = [[], []]
while target in seen:
if target[-1] == 0:
result[0].append(target[0])
result[1].append(target[1])
target = seen[target]
if result[0]:
print(len(result[0]) - 1)
print(*result[1])
print(*result[0])
else:
print(-1)
|
Codeforces Beta Round 29 (Div. 2, Codeforces format)
|
CF
| 2,010 | 1 | 256 |
Quarrel
|
Friends Alex and Bob live in Bertown. In this town there are n crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number n.
One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads n and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task.
Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving.
The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3.
If the required routes don't exist, your program should output -1.
|
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 10000) — the amount of crossroads and the amount of roads. Each of the following m lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road.
|
If the required routes don't exist, output -1. Otherwise, the first line should contain integer k — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain k + 1 integers — Bob's route, i.e. the numbers of k + 1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them.
| null | null |
[{"input": "2 1\n1 2", "output": "1\n1 2\n2 1"}, {"input": "7 5\n1 2\n2 7\n7 6\n2 3\n3 4", "output": "-1"}, {"input": "7 6\n1 2\n2 7\n7 6\n2 3\n3 4\n1 5", "output": "6\n1 2 3 4 3 2 7\n7 6 7 2 1 5 1"}]
| 2,400 |
["graphs", "shortest paths"]
| 56 |
[{"input": "2 1\r\n1 2\r\n", "output": "1\r\n1 2 \r\n2 1 \r\n"}, {"input": "7 5\r\n1 2\r\n2 7\r\n7 6\r\n2 3\r\n3 4\r\n", "output": "-1\r\n"}, {"input": "7 6\r\n1 2\r\n2 7\r\n7 6\r\n2 3\r\n3 4\r\n1 5\r\n", "output": "6\r\n1 2 3 4 3 2 7 \r\n7 6 7 2 1 5 1 \r\n"}, {"input": "6 10\r\n3 6\r\n3 5\r\n1 3\r\n2 6\r\n5 4\r\n6 4\r\n6 5\r\n5 1\r\n2 3\r\n1 2\r\n", "output": "2\r\n1 3 6 \r\n6 2 1 \r\n"}, {"input": "5 7\r\n5 2\r\n1 3\r\n4 2\r\n3 4\r\n5 3\r\n2 3\r\n4 1\r\n", "output": "3\r\n1 3 2 5 \r\n5 2 4 1 \r\n"}, {"input": "10 7\r\n3 4\r\n8 6\r\n4 8\r\n3 1\r\n9 10\r\n10 6\r\n9 4\r\n", "output": "5\r\n1 3 4 8 6 10 \r\n10 6 8 4 3 1 \r\n"}, {"input": "10 16\r\n9 8\r\n1 2\r\n9 5\r\n5 4\r\n9 2\r\n3 2\r\n1 6\r\n5 10\r\n7 2\r\n8 2\r\n3 7\r\n4 9\r\n5 7\r\n10 3\r\n10 9\r\n7 8\r\n", "output": "3\r\n1 2 9 10 \r\n10 3 2 1 \r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
ref_output_path = sys.argv[2]
sub_output_path = sys.argv[3]
# Read input
with open(input_path) as f:
input_lines = [line.strip() for line in f]
if not input_lines:
print(0)
return
n, m = map(int, input_lines[0].split())
edges = set()
for line in input_lines[1:m+1]:
if not line.strip():
continue
u, v = map(int, line.split())
edges.add(frozenset((u, v)))
# Read reference output
with open(ref_output_path) as f:
ref_lines = [line.strip() for line in f]
if not ref_lines:
print(0)
return
if ref_lines[0] == '-1':
# Check submission is -1
with open(sub_output_path) as f:
sub_lines = [line.strip() for line in f]
if not sub_lines:
print(0)
return
if len(sub_lines) == 1 and sub_lines[0] == '-1':
print(100)
return
else:
print(0)
return
else:
# Reference has a solution
if len(ref_lines) < 3:
print(0)
return
try:
ref_k = int(ref_lines[0])
ref_bob = list(map(int, ref_lines[1].split()))
ref_alex = list(map(int, ref_lines[2].split()))
except:
print(0)
return
# Read submission output
with open(sub_output_path) as f:
sub_lines = [line.strip() for line in f]
if not sub_lines:
print(0)
return
if len(sub_lines) < 3:
if sub_lines[0] == '-1':
print(0)
return
else:
print(0)
return
try:
sub_k = int(sub_lines[0])
sub_bob = list(map(int, sub_lines[1].split()))
sub_alex = list(map(int, sub_lines[2].split()))
except:
print(0)
return
# Check k matches reference
if sub_k != ref_k:
print(0)
return
# Check paths
# Check Bob's path
if len(sub_bob) != sub_k +1:
print(0)
return
if sub_bob[0] != 1 or sub_bob[-1] != n:
print(0)
return
for i in range(sub_k):
u = sub_bob[i]
v = sub_bob[i+1]
if frozenset((u, v)) not in edges:
print(0)
return
# Check Alex's path
if len(sub_alex) != sub_k +1:
print(0)
return
if sub_alex[0] != n or sub_alex[-1] != 1:
print(0)
return
for i in range(sub_k):
u = sub_alex[i]
v = sub_alex[i+1]
if frozenset((u, v)) not in edges:
print(0)
return
# Check positions don't overlap
for i in range(sub_k +1):
if sub_bob[i] == sub_alex[i]:
print(0)
return
# All checks passed
print(100)
return
if __name__ == "__main__":
main()
| true |
29/E
|
29
|
E
|
PyPy 3-64
|
TESTS
| 0 | 92 | 614,400 |
196078778
|
from collections import deque
n, m = map(int, input().split())
edge = [[] for _ in range(n+1)]
for _ in range(m):
u, v = map(int, input().split())
edge[u].append(v)
edge[v].append(u)
pos = [[[-1]*2 for _ in range(n+1)] for _ in range(n+1)]
fromx = [[[-1]*2 for _ in range(n+1)] for _ in range(n+1)]
fromy = [[[-1]*2 for _ in range(n+1)] for _ in range(n+1)]
fromb = [[[-1]*2 for _ in range(n+1)] for _ in range(n+1)]
q = deque()
q.append((1, n, 0))
pos[1][n][0] = 0
while q:
posx, posy, biao = q.popleft()
if biao == 0:
for j in edge[posx]:
if pos[j][posy][biao^1] == -1:
pos[j][posy][biao^1] = pos[posx][posy][biao] + 1
fromx[j][posy][biao^1] = posx
fromy[j][posy][biao^1] = posy
fromb[j][posy][biao^1] = biao
q.append((j, posy, biao^1))
elif biao == 1:
for j in edge[posy]:
if pos[posx][j][biao^1] == -1 and posx != j:
pos[posx][j][biao^1] = pos[posx][posy][biao]
fromx[posx][j][biao^1] = posx
fromy[posx][j][biao^1] = posy
fromb[posx][j][biao^1] = biao
q.append((posx, j, biao^1))
print(pos[n][1][0])
if pos[n][1][0] == -1:
exit(0)
posxx, posyy, biao = n, 1, 0
q1, q2 = [n], [1]
while True:
q2.append(fromy[posxx][posyy][0])
posyy = fromy[posxx][posyy][0]
q1.append(fromx[posxx][posyy][1])
posxx = fromx[posxx][posyy][1]
if posxx == 1 and posyy == n:
break
print(*reversed(q2))
print(*reversed(q1))
| 56 | 872 | 71,475,200 |
213890023
|
import sys
from collections import deque
readline = sys.stdin.readline
N, M = [int(w) for w in readline().split()]
city = [[] for _ in range(N + 1)]
edges = []
for _ in range(M):
u, v = [int(w) for w in readline().split()]
city[u].append(v)
city[v].append(u)
edges.append((u, v))
def gen_dists(node: int) -> list:
result = [N + 1] * (N + 1)
dq = deque([node])
result[node] = 1
while dq:
u = dq.popleft()
for v in city[u]:
if result[v] <= result[u] + 1:
continue
result[v] = result[u] + 1
dq.append(v)
return result
dist_alex = gen_dists(1)
dist_bob = gen_dists(N)
if dist_alex[-1] > N:
print(-1)
exit(0)
seen = {(1, N, 0): (-1, -1, -1)}
step_cnt = {(1, N, 0): 0}
que = deque([(1, N, 0, 0)])
target = (N, 1, 0)
while que:
u, v, status, step = que.popleft()
if step >= N:
break
if status == 0:
for v1 in city[v]:
if (u, v1, 1) in seen:
continue
seen[(u, v1, 1)] = (u, v, status)
if dist_alex[v1] < dist_alex[v]:
que.appendleft((u, v1, 1, step))
else:
que.append((u, v1, 1, step))
elif status == 1:
for u1 in city[u]:
if u1 == v:
continue
if (u1, v, 0) in seen:
continue
seen[(u1, v, 0)] = (u, v, status)
if dist_bob[u1] < dist_bob[u]:
que.appendleft((u1, v, 0, step + 1))
else:
que.append((u1, v, 0, step + 1))
if target in seen:
break
if target in seen:
break
result = [[], []]
while target in seen:
if target[-1] == 0:
result[0].append(target[0])
result[1].append(target[1])
target = seen[target]
if result[0]:
print(len(result[0]) - 1)
print(*result[1])
print(*result[0])
else:
print(-1)
|
Codeforces Beta Round 29 (Div. 2, Codeforces format)
|
CF
| 2,010 | 1 | 256 |
Quarrel
|
Friends Alex and Bob live in Bertown. In this town there are n crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number n.
One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads n and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task.
Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving.
The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3.
If the required routes don't exist, your program should output -1.
|
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 10000) — the amount of crossroads and the amount of roads. Each of the following m lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road.
|
If the required routes don't exist, output -1. Otherwise, the first line should contain integer k — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain k + 1 integers — Bob's route, i.e. the numbers of k + 1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them.
| null | null |
[{"input": "2 1\n1 2", "output": "1\n1 2\n2 1"}, {"input": "7 5\n1 2\n2 7\n7 6\n2 3\n3 4", "output": "-1"}, {"input": "7 6\n1 2\n2 7\n7 6\n2 3\n3 4\n1 5", "output": "6\n1 2 3 4 3 2 7\n7 6 7 2 1 5 1"}]
| 2,400 |
["graphs", "shortest paths"]
| 56 |
[{"input": "2 1\r\n1 2\r\n", "output": "1\r\n1 2 \r\n2 1 \r\n"}, {"input": "7 5\r\n1 2\r\n2 7\r\n7 6\r\n2 3\r\n3 4\r\n", "output": "-1\r\n"}, {"input": "7 6\r\n1 2\r\n2 7\r\n7 6\r\n2 3\r\n3 4\r\n1 5\r\n", "output": "6\r\n1 2 3 4 3 2 7 \r\n7 6 7 2 1 5 1 \r\n"}, {"input": "6 10\r\n3 6\r\n3 5\r\n1 3\r\n2 6\r\n5 4\r\n6 4\r\n6 5\r\n5 1\r\n2 3\r\n1 2\r\n", "output": "2\r\n1 3 6 \r\n6 2 1 \r\n"}, {"input": "5 7\r\n5 2\r\n1 3\r\n4 2\r\n3 4\r\n5 3\r\n2 3\r\n4 1\r\n", "output": "3\r\n1 3 2 5 \r\n5 2 4 1 \r\n"}, {"input": "10 7\r\n3 4\r\n8 6\r\n4 8\r\n3 1\r\n9 10\r\n10 6\r\n9 4\r\n", "output": "5\r\n1 3 4 8 6 10 \r\n10 6 8 4 3 1 \r\n"}, {"input": "10 16\r\n9 8\r\n1 2\r\n9 5\r\n5 4\r\n9 2\r\n3 2\r\n1 6\r\n5 10\r\n7 2\r\n8 2\r\n3 7\r\n4 9\r\n5 7\r\n10 3\r\n10 9\r\n7 8\r\n", "output": "3\r\n1 2 9 10 \r\n10 3 2 1 \r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
ref_output_path = sys.argv[2]
sub_output_path = sys.argv[3]
# Read input
with open(input_path) as f:
input_lines = [line.strip() for line in f]
if not input_lines:
print(0)
return
n, m = map(int, input_lines[0].split())
edges = set()
for line in input_lines[1:m+1]:
if not line.strip():
continue
u, v = map(int, line.split())
edges.add(frozenset((u, v)))
# Read reference output
with open(ref_output_path) as f:
ref_lines = [line.strip() for line in f]
if not ref_lines:
print(0)
return
if ref_lines[0] == '-1':
# Check submission is -1
with open(sub_output_path) as f:
sub_lines = [line.strip() for line in f]
if not sub_lines:
print(0)
return
if len(sub_lines) == 1 and sub_lines[0] == '-1':
print(100)
return
else:
print(0)
return
else:
# Reference has a solution
if len(ref_lines) < 3:
print(0)
return
try:
ref_k = int(ref_lines[0])
ref_bob = list(map(int, ref_lines[1].split()))
ref_alex = list(map(int, ref_lines[2].split()))
except:
print(0)
return
# Read submission output
with open(sub_output_path) as f:
sub_lines = [line.strip() for line in f]
if not sub_lines:
print(0)
return
if len(sub_lines) < 3:
if sub_lines[0] == '-1':
print(0)
return
else:
print(0)
return
try:
sub_k = int(sub_lines[0])
sub_bob = list(map(int, sub_lines[1].split()))
sub_alex = list(map(int, sub_lines[2].split()))
except:
print(0)
return
# Check k matches reference
if sub_k != ref_k:
print(0)
return
# Check paths
# Check Bob's path
if len(sub_bob) != sub_k +1:
print(0)
return
if sub_bob[0] != 1 or sub_bob[-1] != n:
print(0)
return
for i in range(sub_k):
u = sub_bob[i]
v = sub_bob[i+1]
if frozenset((u, v)) not in edges:
print(0)
return
# Check Alex's path
if len(sub_alex) != sub_k +1:
print(0)
return
if sub_alex[0] != n or sub_alex[-1] != 1:
print(0)
return
for i in range(sub_k):
u = sub_alex[i]
v = sub_alex[i+1]
if frozenset((u, v)) not in edges:
print(0)
return
# Check positions don't overlap
for i in range(sub_k +1):
if sub_bob[i] == sub_alex[i]:
print(0)
return
# All checks passed
print(100)
return
if __name__ == "__main__":
main()
| true |
598/E
|
598
|
E
|
PyPy 3-64
|
TESTS
| 1 | 62 | 0 |
194358928
|
t = int(input())
for i in range(t):
n,m,k = map(int,input().split())
ans = 0
if k == n*m:
print(0)
continue
while k != 0:
if n < m:
cnt = k//n
if cnt == 0:
ans += n*n+1
break
ans += n*n
k -= n*cnt
m -= cnt
else:
cnt = k//m
if cnt == 0:
ans += m*m+1
break
ans += m*m
k -= m*cnt
n -= cnt
print(ans)
| 5 | 794 | 30,105,600 |
128888073
|
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# sys.setrecursionlimit(1000000)
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
dp = [[[0 for k in range (51)] for j in range (31)] for i in range (31)]
def calc (n, m, k) :
#print(n,m,k)
if (dp[n][m][k] != 0) or (n*m == k) or (k == 0) :
return dp[n][m][k]
ans = 10**9
for i in range (1,n//2 + 1) :
for j in range (k+1) :
#print(i,j,'a')
if (i*m >= (k-j)) and ((n-i)*m >= j) :
ans = min(ans, m*m + calc(i,m,k-j) + calc(n-i,m,j))
for i in range (1,m//2 + 1) :
for j in range (k+1) :
#print(i,j,'b')
if (i*n >= (k-j)) and ((m-i)*n >= j) :
ans = min(ans, n*n + calc(n,i,k-j) + calc(n,m-i,j))
dp[n][m][k] = ans
return ans
for _ in range (getN()):
N, M, K = getNM()
print(calc(N, M, K))
|
Educational Codeforces Round 1
|
ICPC
| 2,015 | 2 | 256 |
Chocolate Bar
|
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
|
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
|
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
| null |
In the first query of the sample one needs to perform two breaks:
- to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),
- to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
|
[{"input": "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4", "output": "5\n5\n4\n0"}]
| 2,000 |
["brute force", "dp"]
| 5 |
[{"input": "4\r\n2 2 1\r\n2 2 3\r\n2 2 2\r\n2 2 4\r\n", "output": "5\r\n5\r\n4\r\n0\r\n"}]
| false |
stdio
| null | true |
598/E
|
598
|
E
|
PyPy 3-64
|
TESTS
| 1 | 77 | 4,198,400 |
194357463
|
t = int(input())
for i in range(t):
n,m,k = map(int,input().split())
ans = float("inf")
for bit in range(10):
nn,mm = n,m
left = k
tmp = 0
for i in range(10):
if (bit>>i) & 1:
cnt = left // nn
if cnt == mm: break
if cnt != 0:
nn,mm = nn, mm-cnt
left -= nn*cnt
tmp += nn**2
else:
tmp += nn**2 + 1
break
else:
cnt = left // mm
if cnt == nn: break
if cnt != 0:
nn,mm = nn-cnt, mm
left -= mm * cnt
tmp += mm**2
else:
tmp += mm**2 + 1
break
if left == 0: break
ans = min(ans, tmp)
print(ans)
| 5 | 1,778 | 11,878,400 |
218464936
|
def relaxMin(a, b):
return min(a, b)
def Eval(n, m, k):
if n > m:
n, m = m, n
if k == 0:
return 0
if n * m == k:
return 0
if n * m < k:
return float('inf')
if dp[n][m][k] >= 0:
return dp[n][m][k]
val = float('inf')
cost = m ** 2
for tn in range(1, n):
a, b = tn, n - tn
if a > b:
break
for tk in range(k + 1):
val = relaxMin(val, Eval(a, m, tk) +
Eval(b, m, k - tk) +
cost)
val = relaxMin(val, Eval(a, m, k - tk) +
Eval(b, m, tk) +
cost)
cost = n ** 2
for tm in range(1, m):
a, b = tm, m - tm
if a > b:
break
for tk in range(k + 1):
val = relaxMin(val, Eval(n, a, tk) +
Eval(n, b, k - tk) +
cost)
val = relaxMin(val, Eval(n, a, k - tk) +
Eval(n, b, tk) +
cost)
dp[n][m][k] = val
return val
dp = [[[ -1 for _ in range(55)] for _ in range(33)] for _ in range(33)]
q = int(input())
for _ in range(q):
a, b, c = map(int, input().split())
print(Eval(a, b, c))# 1691833418.8259263
|
Educational Codeforces Round 1
|
ICPC
| 2,015 | 2 | 256 |
Chocolate Bar
|
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
|
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
|
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
| null |
In the first query of the sample one needs to perform two breaks:
- to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),
- to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
|
[{"input": "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4", "output": "5\n5\n4\n0"}]
| 2,000 |
["brute force", "dp"]
| 5 |
[{"input": "4\r\n2 2 1\r\n2 2 3\r\n2 2 2\r\n2 2 4\r\n", "output": "5\r\n5\r\n4\r\n0\r\n"}]
| false |
stdio
| null | true |
598/E
|
598
|
E
|
PyPy 3
|
TESTS
| 1 | 93 | 22,118,400 |
128886561
|
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# sys.setrecursionlimit(1000000)
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
T = getN()
for _ in range(T):
N, M, K = getNM()
if N * M == K:
print(0)
continue
ans = float('inf')
# split N
t = K // N
k = K - t * N # 残り
if t == 0:
ans = min(ans, N ** 2 + k)
if k == 0:
ans = min(ans, N ** 2)
if k % (M - t) == 0:
# print('2', N ** 2 + (M - t) ** 2)
ans = min(ans, N ** 2 + (M - t) ** 2)
ans = min(ans, 2 * N ** 2 + k)
t = K // M
k = K - t * M
if t == 0:
ans = min(ans, M ** 2 + k)
if k == 0:
ans = min(ans, M ** 2)
if k % (N - t) == 0:
# print('3', M ** 2 + (N - t) ** 2)
ans = min(ans, M ** 2 + (N - t) ** 2)
ans = min(ans, 2 * M ** 2 + k)
print(ans)
| 5 | 482 | 9,113,600 |
175317754
|
from sys import stdin
input=lambda :stdin.readline()[:-1]
dp=[[[10**9]*51 for i in range(31)] for i in range(31)]
for n in range(1,31):
for m in range(1,31):
for k in range(51):
if k==0:
dp[n][m][k]=0
continue
if n*m<k:
continue
if n*m==k:
dp[n][m][k]=0
continue
res=10**9
for i in range(1,n):
for j in range(k+1):
res=min(res,dp[i][m][j]+dp[n-i][m][k-j]+m*m)
for i in range(1,m):
for j in range(k+1):
res=min(res,dp[n][i][j]+dp[n][m-i][k-j]+n*n)
dp[n][m][k]=res
for _ in range(int(input())):
n,m,k=map(int,input().split())
print(dp[n][m][k])
|
Educational Codeforces Round 1
|
ICPC
| 2,015 | 2 | 256 |
Chocolate Bar
|
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
|
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
|
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
| null |
In the first query of the sample one needs to perform two breaks:
- to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),
- to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
|
[{"input": "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4", "output": "5\n5\n4\n0"}]
| 2,000 |
["brute force", "dp"]
| 5 |
[{"input": "4\r\n2 2 1\r\n2 2 3\r\n2 2 2\r\n2 2 4\r\n", "output": "5\r\n5\r\n4\r\n0\r\n"}]
| false |
stdio
| null | true |
47/D
|
47
|
D
|
Python 3
|
TESTS
| 0 | 60 | 0 |
230675950
|
from itertools import product
n, m = map(int, input().split())
p = set(product('01', repeat=n))
for i in range(m):
s, c = input().split()
c = int(c)
v = set()
for c in p:
cor = sum(s[i] == c[i] for i in range(n))
if cor == c:
v.add(c)
p = v
print(len(p))
| 26 | 466 | 3,686,400 |
181406585
|
from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
pow2 = [1]
for _ in range(20):
pow2.append(2 * pow2[-1])
n1, n2 = n // 2, (n + 1) // 2
x, y, z = [], [], []
for _ in range(m):
s, c = list(input().rstrip().decode().split())
x0, y0 = [], []
for i in range(n1):
x0.append(ord(s[i]) - 48)
for i in range(n1, n):
y0.append(ord(s[i]) - 48)
x.append(x0)
y.append(y0)
z.append(int(c))
cnt = defaultdict(lambda : 0)
u = [0] * n1
for i in range(pow2[n1]):
c = []
for j in range(n1):
u[j] = 1 if i & pow2[j] else 0
for j in range(m):
v = n1
for k, l in zip(u, x[j]):
v -= k ^ l
if v > z[j]:
break
c.append(z[j] - v)
if len(c) == m:
cnt[tuple(c)] += 1
ans = 0
u = [0] * n2
for i in range(pow2[n2]):
c = []
for j in range(n2):
u[j] = 1 if i & pow2[j] else 0
for j in range(m):
v = n2
for k, l in zip(u, y[j]):
v -= k ^ l
if v > z[j]:
break
c.append(v)
if len(c) == m:
c = tuple(c)
if c in cnt:
ans += cnt[c]
print(ans)
|
Codeforces Beta Round 44 (Div. 2)
|
CF
| 2,010 | 5 | 256 |
Safe
|
Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.
|
The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).
|
Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.
| null | null |
[{"input": "6 2\n000000 2\n010100 4", "output": "6"}, {"input": "6 3\n000000 2\n010100 4\n111100 0", "output": "0"}, {"input": "6 3\n000000 2\n010100 4\n111100 2", "output": "1"}]
| 2,200 |
["brute force"]
| 26 |
[{"input": "6 2\r\n000000 2\r\n010100 4\r\n", "output": "6\r\n"}, {"input": "6 3\r\n000000 2\r\n010100 4\r\n111100 0\r\n", "output": "0\r\n"}, {"input": "6 3\r\n000000 2\r\n010100 4\r\n111100 2\r\n", "output": "1\r\n"}, {"input": "6 1\r\n101011 2\r\n", "output": "15\r\n"}, {"input": "7 2\r\n1011111 2\r\n1001111 1\r\n", "output": "6\r\n"}, {"input": "6 4\r\n000110 2\r\n010001 2\r\n001111 2\r\n001100 2\r\n", "output": "1\r\n"}, {"input": "8 3\r\n00111100 5\r\n10100111 2\r\n10110101 2\r\n", "output": "6\r\n"}, {"input": "35 1\r\n00001111001110101000001101100010010 5\r\n", "output": "324632\r\n"}, {"input": "35 2\r\n00101101100111101110111010001101101 3\r\n00111111100101010110111010001101101 3\r\n", "output": "20\r\n"}, {"input": "35 1\r\n11000110100110101001100101001010110 2\r\n", "output": "595\r\n"}, {"input": "35 2\r\n00111111100000111101000110100111101 1\r\n00111111000000111101000010100111101 1\r\n", "output": "2\r\n"}, {"input": "35 6\r\n01100100110000001001100110001100011 5\r\n10000100110000011001110010001100011 5\r\n00101110100000010000100010001110011 4\r\n00110010101000011001100000001110011 5\r\n00100101110000011001101110001110011 4\r\n00110110110000011001101000000100011 5\r\n", "output": "1\r\n"}, {"input": "6 10\r\n110000 5\r\n010011 4\r\n110011 5\r\n110010 4\r\n000001 4\r\n010001 5\r\n110101 5\r\n110011 5\r\n110010 4\r\n011001 4\r\n", "output": "1\r\n"}]
| false |
stdio
| null | true |
149/D
|
149
|
D
|
Python 3
|
TESTS
| 1 | 62 | 0 |
218131269
|
# LUOGU_RID: 120094842
print(12)###
##
##
| 38 | 780 | 38,092,800 |
203670327
|
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from functools import lru_cache
from math import factorial, comb, sqrt, gcd, lcm, log2
from copy import deepcopy
import heapq
from sys import stdin, stdout
input = stdin.readline
# 这道题
# 难点 1:想到用区间dp
# 难点 2:不同状态之间的转移以及计算
def main():
MOD = 10**9 + 7
s = input()[:-1]
left_to_right = dict()
right_to_left = dict()
n = len(s)
stack = []
for i, c in enumerate(s):
if c == "(":
stack.append(i)
else:
cur = stack.pop()
left_to_right[cur] = i
right_to_left[i] = cur
dp = [[Counter() for i in range(n)] for j in range(n)]
# 0 代表不染色 1 代表染红色 2 代表染蓝色
def dfs(i, j):
dic = Counter()
if left_to_right[i] == j:
if j == i + 1:
dic[(0, 1)] = 1
dic[(0, 2)] = 1
dic[(1, 0)] = 1
dic[(2, 0)] = 1
return dic
else:
middle = dfs(i + 1, j - 1)
for status in [(0, 1), (0, 2), (1, 0), (2, 0)]:
# 外层状态
for key, value in middle.items():
if status[0] == key[0] and status[0] > 0:
continue
if status[1] == key[1] and status[1] > 0:
continue
dic[status] = (dic[status] + value) % MOD
return dic
else:
if left_to_right[i] + 1 == right_to_left[j]:
dic1 = dfs(i, left_to_right[i])
dic2 = dfs(right_to_left[j], j)
for key1, value1 in dic1.items():
for key2, value2 in dic2.items():
if key1[1] == key2[0] and key1[1] > 0:
continue
dic[(key1[0], key2[1])] = (dic[(key1[0], key2[1])] + value1 * value2) % MOD
return dic
else:
extra = dfs(left_to_right[i] + 1, right_to_left[j] - 1)
dic1 = dfs(i, left_to_right[i])
dic2 = dfs(right_to_left[j], j)
for key1, value1 in dic1.items():
for key2, value2 in extra.items():
if key1[1] == key2[0] and key1[1] > 0:
continue
for key3, value3 in dic2.items():
if key2[1] == key3[0] and key2[1] > 0:
continue
dic[(key1[0], key3[1])] = (dic[(key1[0], key3[1])] + value1 * value2 * value3) % MOD
return dic
print(sum(dfs(0, n - 1).values()) % MOD)
if __name__ == "__main__":
main()
|
Codeforces Round 106 (Div. 2)
|
CF
| 2,012 | 2 | 256 |
Coloring Brackets
|
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.
You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.
In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.
You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:
- Each bracket is either not colored any color, or is colored red, or is colored blue.
- For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.
- No two neighboring colored brackets have the same color.
Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).
|
The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.
|
Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).
| null |
Let's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below.
The two ways of coloring shown below are incorrect.
|
[{"input": "(())", "output": "12"}, {"input": "(()())", "output": "40"}, {"input": "()", "output": "4"}]
| 1,900 |
["dp"]
| 38 |
[{"input": "(())\r\n", "output": "12\r\n"}, {"input": "(()())\r\n", "output": "40\r\n"}, {"input": "()\r\n", "output": "4\r\n"}, {"input": "((()))\r\n", "output": "36\r\n"}, {"input": "()(())\r\n", "output": "42\r\n"}, {"input": "()()()\r\n", "output": "48\r\n"}, {"input": "(())(())\r\n", "output": "126\r\n"}, {"input": "()()()()()()()()()()()(())\r\n", "output": "9085632\r\n"}, {"input": "()(())()((()))\r\n", "output": "4428\r\n"}, {"input": "()()(())()(())\r\n", "output": "5040\r\n"}, {"input": "()()()()()()()()()()()()()()()()\r\n", "output": "411525376\r\n"}, {"input": "(()()())\r\n", "output": "136\r\n"}, {"input": "()(()())()\r\n", "output": "480\r\n"}, {"input": "(())()(())()\r\n", "output": "1476\r\n"}, {"input": "()()(()())(())()()()\r\n", "output": "195840\r\n"}, {"input": "()()()((((())))())()()()()()((()))()()(())()(((())))()(()())((())())((()())(((((()()()())()()())))))\r\n", "output": "932124942\r\n"}, {"input": "((()(((((()(()(())))()((((((((())))()(((((())()((((())())(()(()(())())((()))()((()))))))))))))))))))))\r\n", "output": "90824888\r\n"}, {"input": "((()))((())())((()()))()(())(()())(())()()()((()(((()())))()())()((((()((()((())))(())(()(())())))((()())()()()((())()))()(())(())))()(((((()())))))))\r\n", "output": "100627207\r\n"}, {"input": "()(((()((((()())))())(())(((((()(()()))))()()))((())))()())((())))(())()((()())())()(()(()())())(()())()(()(((((()))()((()()(())()(())(()((()((()))))()(())()()(()()()((((()())()))))()(((()(((((()()((((())(())))()())(()))(((())((()())(()))())(((()()()(()(())())())(()()()))))())))()((()(()()(()))())((())(()()()(())()))()()(((())))((()))(()((()(((()))((((()())))())(((())()(()((())))))))))))))))))))))\r\n", "output": "306199947\r\n"}, {"input": "(())(((((()()()()())(())))(()()((()(()(((((())(()())))())(()()(()((())()(()()))))))(())()())))()((()()())))()()(()(())())()())()(())(((((()(()()(((()())()))((())((((()()()))())(((())(((())))))))))))))\r\n", "output": "270087235\r\n"}, {"input": "()()()((()))(())(((())()(())(())))()()(((()((()()()))(()()(())(())))(()()((()((())(()()(()(())))))))(((())()((((()())))()(((()()())))()))()())))()(()(()())((()((()))))())(((((()())()((((()))(((((()())()))(((()()()((((((()()(())(()))((()(()(()((()((((()(((()(()()(()()((((()))()()()(()((((()(((())(((()()()(())()))((()()()(()))))())()))))(((((((()))())))(((()(()())(())))())))((((())(())())(((()()()))((()()))())(()))(())((()(()))(()()((()(()((()(())(()))()()))))))))))))))))))))))))))))))))))))))))))\r\n", "output": "461776571\r\n"}, {"input": "()()(((((()((()(())()(()))(()(()(()(()(())(())(())(()(()((())))()))())((()((()(()(((()(()))()(()())(()()()()(((((()(((()))((((())())(((()((((()((((((())())))()))))))))(())())))(((()((()))))((())(()()))()(()(()((()())())()))))((()))))()((())())(()())()())))())())())())()((()((())((()()())()())())()(())()))(()(()))())))(()()()())()())))))))((((()())))((((()()()))())((()(())))))()((()(((())()()()(()()()()()))))(((()())()))()()(((())(()())(()()))))))\r\n", "output": "66338682\r\n"}, {"input": "(()())()()()((((()(()()(())()((())(((()((()()(()))()))()()))))()(()(())(()))))))\r\n", "output": "639345575\r\n"}, {"input": "()((()))((((()((())((()()((((()))()()((())((()(((((()(()))((())()))((((())()(()(()))()))))))))))))))))))\r\n", "output": "391997323\r\n"}, {"input": "(((((()())))))()()()()()(())()()()((()()))()()()()()(((()(())))())(((()())))\r\n", "output": "422789312\r\n"}, {"input": "((()((()))()((()(()))())))()((()())())()(()())((()))(()())(())()(())()(())(())((()()))((()))()()()()(())()\r\n", "output": "140121189\r\n"}, {"input": "()()\r\n", "output": "14\r\n"}]
| false |
stdio
| null | true |
908/G
|
908
|
G
|
Python 3
|
PRETESTS
| 1 | 1,122 | 5,529,600 |
33790693
|
n = int(input())
s = 0
for i in range(1,n+1):
x = list(str(i))
# print(x)
l = sorted(x)
n = int(''.join(map(str,l)))
s += n
print(s)
| 20 | 77 | 0 |
113281106
|
# Problem G
num = input()
num_list = []
for i in range(len(num)):
num_list.append(int(num[i]))
myMod = (10 ** 9) + 7
length = len(num_list)
f = [0] * (length + 1)
t = [1] * (length + 1)
for i in range(length):
f[i+1] = (f[i] * 10 + 1) % myMod
t[i+1] = (t[i] * 10) % myMod
ans = 0
for i in range(1, 10):
dp = [0] * (length + 1)
for j in range(length):
dp[j+1] = (dp[j] * i + (10 - i) * (dp[j] * 10 + t[j])) % myMod
c = 0
ctr = 0
for k in num_list:
z = min(i, k)
o = k - z
ans += o * (dp[length-1-ctr] * t[c+1] + f[c+1] * t[length-1-ctr]) % myMod
ans += z * (dp[length-1-ctr] * t[c] + f[c] * t[length-1-ctr]) % myMod
ans %= myMod
c += k >= i
ctr += 1
ans += f[c]
if ans >= myMod:
ans -= myMod
print(ans)
|
Good Bye 2017
|
CF
| 2,017 | 2 | 256 |
New Year and Original Order
|
Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555.
Given a number X, compute $$\sum_{1 \leq k \leq X} S(k)$$ modulo 109 + 7.
|
The first line of input will contain the integer X (1 ≤ X ≤ 10700).
|
Print a single integer, the answer to the question.
| null |
The first few values of S are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 12. The sum of these values is 195.
|
[{"input": "21", "output": "195"}, {"input": "345342", "output": "390548434"}]
| 2,800 |
["dp", "math"]
| 20 |
[{"input": "21\r\n", "output": "195\r\n"}, {"input": "345342\r\n", "output": "390548434\r\n"}, {"input": "9438174368\r\n", "output": "419438859\r\n"}, {"input": "33340691714056185860211260984431382156326935244157\r\n", "output": "683387308\r\n"}, {"input": "60659389952427965488066632743799525603106037644498358605868947137979908494800892265261453803791510334840960342863677552781925982028425181448855359993703120262947850907075964314040305228976226486729250\r\n", "output": "654963480\r\n"}, {"input": "44649014054971081213608137817466046254652492627741860478258558206397113198232823859870363821007188476405951611069347299689170240023979048198711745011542774268179055311013054073075176122755643483380248999657649211459997766221072399103579977409770898200358240970169892326442892826731631357561876251276209119521202062222947560634301788787748428236988789594458520867663257476744168528121470923031438015546006185059454402637036376247785881323277542968298682307854655591317046086531554595892680980142608410\r\n", "output": "382433601\r\n"}, {"input": "87180\r\n", "output": "273914491\r\n"}, {"input": "404075833601771942667259010375375556744823902383758960785823552761999143572376325949809260679742124753881851158698439457386070260861271136645763680151691355801985707548363664714643023957647369701126324673656050885747545042127147214166479318245077239696802674619402305982303576335159698484641718860881491887951521487208762\r\n", "output": "770789762\r\n"}]
| false |
stdio
| null | true |
171/C
|
171
|
C
|
Python 3
|
TESTS
| 1 | 186 | 0 |
74875321
|
a,b,c,d,e=map(int,input().split())
print(a*2+b*1+c*4+d*3+e*1)
| 41 | 92 | 0 |
173781945
|
a=list(map(int,input().split()))
ans=0
for num in range(0,len(a)):
ans=ans+a[num]*num
print(ans)
|
April Fools Day Contest
|
ICPC
| 2,012 | 2 | 256 |
A Piece of Cake
|
How to make a cake you'll never eat.
Ingredients.
- 2 carrots
- 0 calories
- 100 g chocolate spread
- 1 pack of flour
- 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
|
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
|
Output a single integer.
| null | null |
[{"input": "4 1 2 3 4", "output": "30"}]
| 2,000 |
["*special", "implementation"]
| 41 |
[{"input": "4 1 2 3 4\r\n", "output": "30\r\n"}, {"input": "4 802 765 992 1\r\n", "output": "5312\r\n"}, {"input": "4 220 380 729 969\r\n", "output": "7043\r\n"}, {"input": "3 887 104 641\r\n", "output": "3018\r\n"}, {"input": "12 378 724 582 387 583 241 294 159 198 653 369 418\r\n", "output": "30198\r\n"}, {"input": "14 36 901 516 623 703 971 304 394 491 525 464 219 183 648\r\n", "output": "49351\r\n"}, {"input": "3 287 979 395\r\n", "output": "3430\r\n"}, {"input": "19 702 667 743 976 908 728 134 106 380 193 214 71 920 114 587 543 817 248 537\r\n", "output": "87024\r\n"}, {"input": "11 739 752 364 649 626 702 444 913 681 529 959\r\n", "output": "45653\r\n"}, {"input": "19 196 392 738 103 119 872 900 189 65 113 260 985 228 537 217 735 785 445 636\r\n", "output": "92576\r\n"}, {"input": "22 196 690 553 822 392 687 425 763 216 73 525 412 155 263 205 965 825 105 153 580 218 103\r\n", "output": "96555\r\n"}, {"input": "10 136 641 472 872 115 607 197 19 494 577\r\n", "output": "22286\r\n"}, {"input": "10 5 659 259 120 421 165 194 637 577 39\r\n", "output": "17712\r\n"}, {"input": "5 472 4 724 577 157\r\n", "output": "5745\r\n"}, {"input": "23 486 261 249 312 592 411 874 397 18 70 417 512 338 679 517 997 938 328 418 793 522 745 59\r\n", "output": "141284\r\n"}, {"input": "17 644 532 255 57 108 413 51 284 364 300 597 646 712 470 42 730 231\r\n", "output": "61016\r\n"}, {"input": "26 932 569 829 138 565 766 466 673 559 678 417 618 930 751 840 184 809 639 287 550 923 341 851 209 987 252\r\n", "output": "207547\r\n"}, {"input": "16 29 672 601 178 603 860 6 431 114 463 588 788 712 956 895 19\r\n", "output": "73502\r\n"}, {"input": "5 336 860 760 835 498\r\n", "output": "10166\r\n"}, {"input": "29 384 110 78 925 320 755 176 690 784 848 981 653 140 840 659 262 954 812 850 431 523 495 16 233 70 352 92 520 877\r\n", "output": "216056\r\n"}, {"input": "21 256 260 390 24 185 400 780 51 89 253 900 760 906 730 599 565 992 243 66 531 364\r\n", "output": "114365\r\n"}, {"input": "19 26 380 823 787 422 605 306 298 885 562 249 965 277 124 365 56 175 144 309\r\n", "output": "67719\r\n"}, {"input": "41 595 215 495 884 470 176 126 536 398 181 816 114 251 328 901 674 933 206 662 507 458 601 162 735 725 217 481 591 51 791 355 646 696 540 530 165 717 346 391 114 527\r\n", "output": "406104\r\n"}, {"input": "20 228 779 225 819 142 849 24 494 45 172 95 207 908 510 424 78 100 166 869 456\r\n", "output": "78186\r\n"}, {"input": "15 254 996 341 109 402 688 501 206 905 398 124 373 313 943 515\r\n", "output": "57959\r\n"}, {"input": "45 657 700 898 830 795 104 427 995 219 505 95 385 64 241 196 318 927 228 428 329 606 619 535 200 707 660 574 19 292 88 872 950 788 769 779 272 563 896 267 782 400 52 857 154 293\r\n", "output": "507143\r\n"}, {"input": "41 473 219 972 591 238 267 209 464 467 916 814 40 625 105 820 496 54 297 264 523 570 828 418 527 299 509 269 156 663 562 900 826 471 561 416 710 828 315 864 985 230\r\n", "output": "463602\r\n"}, {"input": "48 25 856 782 535 41 527 832 306 49 91 824 158 618 122 357 887 969 710 138 868 536 610 118 642 9 946 958 873 931 878 549 646 733 20 180 775 547 11 771 287 103 594 135 411 406 492 989 375\r\n", "output": "597376\r\n"}, {"input": "57 817 933 427 116 51 69 125 687 717 688 307 594 927 643 17 638 823 482 184 525 943 161 318 226 296 419 632 478 97 697 370 915 320 797 30 371 556 847 748 272 224 746 557 151 388 264 789 211 746 663 426 688 825 744 914 811 853\r\n", "output": "900997\r\n"}, {"input": "55 980 951 933 349 865 252 836 585 313 392 431 751 354 656 496 601 497 885 865 976 786 300 638 211 678 152 645 281 654 187 517 633 137 139 672 692 81 507 968 84 589 398 835 944 744 331 234 931 906 99 906 691 89 234 592\r\n", "output": "810147\r\n"}]
| false |
stdio
| null | true |
171/C
|
171
|
C
|
PyPy 3
|
TESTS
| 1 | 186 | 0 |
111647518
|
cases=list(map(int,input().split()))
cnt=0
for i in cases[1:]:
cnt+=i*i
print(cnt)
| 41 | 92 | 0 |
205826256
|
a = list(map(int, input().split()))
ans = 0
for i in range(1, len(a)) :
ans += i*a[i]
print(ans)
|
April Fools Day Contest
|
ICPC
| 2,012 | 2 | 256 |
A Piece of Cake
|
How to make a cake you'll never eat.
Ingredients.
- 2 carrots
- 0 calories
- 100 g chocolate spread
- 1 pack of flour
- 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
|
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
|
Output a single integer.
| null | null |
[{"input": "4 1 2 3 4", "output": "30"}]
| 2,000 |
["*special", "implementation"]
| 41 |
[{"input": "4 1 2 3 4\r\n", "output": "30\r\n"}, {"input": "4 802 765 992 1\r\n", "output": "5312\r\n"}, {"input": "4 220 380 729 969\r\n", "output": "7043\r\n"}, {"input": "3 887 104 641\r\n", "output": "3018\r\n"}, {"input": "12 378 724 582 387 583 241 294 159 198 653 369 418\r\n", "output": "30198\r\n"}, {"input": "14 36 901 516 623 703 971 304 394 491 525 464 219 183 648\r\n", "output": "49351\r\n"}, {"input": "3 287 979 395\r\n", "output": "3430\r\n"}, {"input": "19 702 667 743 976 908 728 134 106 380 193 214 71 920 114 587 543 817 248 537\r\n", "output": "87024\r\n"}, {"input": "11 739 752 364 649 626 702 444 913 681 529 959\r\n", "output": "45653\r\n"}, {"input": "19 196 392 738 103 119 872 900 189 65 113 260 985 228 537 217 735 785 445 636\r\n", "output": "92576\r\n"}, {"input": "22 196 690 553 822 392 687 425 763 216 73 525 412 155 263 205 965 825 105 153 580 218 103\r\n", "output": "96555\r\n"}, {"input": "10 136 641 472 872 115 607 197 19 494 577\r\n", "output": "22286\r\n"}, {"input": "10 5 659 259 120 421 165 194 637 577 39\r\n", "output": "17712\r\n"}, {"input": "5 472 4 724 577 157\r\n", "output": "5745\r\n"}, {"input": "23 486 261 249 312 592 411 874 397 18 70 417 512 338 679 517 997 938 328 418 793 522 745 59\r\n", "output": "141284\r\n"}, {"input": "17 644 532 255 57 108 413 51 284 364 300 597 646 712 470 42 730 231\r\n", "output": "61016\r\n"}, {"input": "26 932 569 829 138 565 766 466 673 559 678 417 618 930 751 840 184 809 639 287 550 923 341 851 209 987 252\r\n", "output": "207547\r\n"}, {"input": "16 29 672 601 178 603 860 6 431 114 463 588 788 712 956 895 19\r\n", "output": "73502\r\n"}, {"input": "5 336 860 760 835 498\r\n", "output": "10166\r\n"}, {"input": "29 384 110 78 925 320 755 176 690 784 848 981 653 140 840 659 262 954 812 850 431 523 495 16 233 70 352 92 520 877\r\n", "output": "216056\r\n"}, {"input": "21 256 260 390 24 185 400 780 51 89 253 900 760 906 730 599 565 992 243 66 531 364\r\n", "output": "114365\r\n"}, {"input": "19 26 380 823 787 422 605 306 298 885 562 249 965 277 124 365 56 175 144 309\r\n", "output": "67719\r\n"}, {"input": "41 595 215 495 884 470 176 126 536 398 181 816 114 251 328 901 674 933 206 662 507 458 601 162 735 725 217 481 591 51 791 355 646 696 540 530 165 717 346 391 114 527\r\n", "output": "406104\r\n"}, {"input": "20 228 779 225 819 142 849 24 494 45 172 95 207 908 510 424 78 100 166 869 456\r\n", "output": "78186\r\n"}, {"input": "15 254 996 341 109 402 688 501 206 905 398 124 373 313 943 515\r\n", "output": "57959\r\n"}, {"input": "45 657 700 898 830 795 104 427 995 219 505 95 385 64 241 196 318 927 228 428 329 606 619 535 200 707 660 574 19 292 88 872 950 788 769 779 272 563 896 267 782 400 52 857 154 293\r\n", "output": "507143\r\n"}, {"input": "41 473 219 972 591 238 267 209 464 467 916 814 40 625 105 820 496 54 297 264 523 570 828 418 527 299 509 269 156 663 562 900 826 471 561 416 710 828 315 864 985 230\r\n", "output": "463602\r\n"}, {"input": "48 25 856 782 535 41 527 832 306 49 91 824 158 618 122 357 887 969 710 138 868 536 610 118 642 9 946 958 873 931 878 549 646 733 20 180 775 547 11 771 287 103 594 135 411 406 492 989 375\r\n", "output": "597376\r\n"}, {"input": "57 817 933 427 116 51 69 125 687 717 688 307 594 927 643 17 638 823 482 184 525 943 161 318 226 296 419 632 478 97 697 370 915 320 797 30 371 556 847 748 272 224 746 557 151 388 264 789 211 746 663 426 688 825 744 914 811 853\r\n", "output": "900997\r\n"}, {"input": "55 980 951 933 349 865 252 836 585 313 392 431 751 354 656 496 601 497 885 865 976 786 300 638 211 678 152 645 281 654 187 517 633 137 139 672 692 81 507 968 84 589 398 835 944 744 331 234 931 906 99 906 691 89 234 592\r\n", "output": "810147\r\n"}]
| false |
stdio
| null | true |
171/C
|
171
|
C
|
Python 3
|
TESTS
| 1 | 92 | 4,608,000 |
25945668
|
a = list(map(int,input().split()))
print(2*(sum(a)+1))
| 41 | 92 | 0 |
206951318
|
# /**
# * author: brownfox2k6
# * created: 23/05/2023 20:41:01 Hanoi, Vietnam
# **/
print(sum(i*j for i,j in enumerate(map(int, input().split()), 0)))
|
April Fools Day Contest
|
ICPC
| 2,012 | 2 | 256 |
A Piece of Cake
|
How to make a cake you'll never eat.
Ingredients.
- 2 carrots
- 0 calories
- 100 g chocolate spread
- 1 pack of flour
- 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
|
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
|
Output a single integer.
| null | null |
[{"input": "4 1 2 3 4", "output": "30"}]
| 2,000 |
["*special", "implementation"]
| 41 |
[{"input": "4 1 2 3 4\r\n", "output": "30\r\n"}, {"input": "4 802 765 992 1\r\n", "output": "5312\r\n"}, {"input": "4 220 380 729 969\r\n", "output": "7043\r\n"}, {"input": "3 887 104 641\r\n", "output": "3018\r\n"}, {"input": "12 378 724 582 387 583 241 294 159 198 653 369 418\r\n", "output": "30198\r\n"}, {"input": "14 36 901 516 623 703 971 304 394 491 525 464 219 183 648\r\n", "output": "49351\r\n"}, {"input": "3 287 979 395\r\n", "output": "3430\r\n"}, {"input": "19 702 667 743 976 908 728 134 106 380 193 214 71 920 114 587 543 817 248 537\r\n", "output": "87024\r\n"}, {"input": "11 739 752 364 649 626 702 444 913 681 529 959\r\n", "output": "45653\r\n"}, {"input": "19 196 392 738 103 119 872 900 189 65 113 260 985 228 537 217 735 785 445 636\r\n", "output": "92576\r\n"}, {"input": "22 196 690 553 822 392 687 425 763 216 73 525 412 155 263 205 965 825 105 153 580 218 103\r\n", "output": "96555\r\n"}, {"input": "10 136 641 472 872 115 607 197 19 494 577\r\n", "output": "22286\r\n"}, {"input": "10 5 659 259 120 421 165 194 637 577 39\r\n", "output": "17712\r\n"}, {"input": "5 472 4 724 577 157\r\n", "output": "5745\r\n"}, {"input": "23 486 261 249 312 592 411 874 397 18 70 417 512 338 679 517 997 938 328 418 793 522 745 59\r\n", "output": "141284\r\n"}, {"input": "17 644 532 255 57 108 413 51 284 364 300 597 646 712 470 42 730 231\r\n", "output": "61016\r\n"}, {"input": "26 932 569 829 138 565 766 466 673 559 678 417 618 930 751 840 184 809 639 287 550 923 341 851 209 987 252\r\n", "output": "207547\r\n"}, {"input": "16 29 672 601 178 603 860 6 431 114 463 588 788 712 956 895 19\r\n", "output": "73502\r\n"}, {"input": "5 336 860 760 835 498\r\n", "output": "10166\r\n"}, {"input": "29 384 110 78 925 320 755 176 690 784 848 981 653 140 840 659 262 954 812 850 431 523 495 16 233 70 352 92 520 877\r\n", "output": "216056\r\n"}, {"input": "21 256 260 390 24 185 400 780 51 89 253 900 760 906 730 599 565 992 243 66 531 364\r\n", "output": "114365\r\n"}, {"input": "19 26 380 823 787 422 605 306 298 885 562 249 965 277 124 365 56 175 144 309\r\n", "output": "67719\r\n"}, {"input": "41 595 215 495 884 470 176 126 536 398 181 816 114 251 328 901 674 933 206 662 507 458 601 162 735 725 217 481 591 51 791 355 646 696 540 530 165 717 346 391 114 527\r\n", "output": "406104\r\n"}, {"input": "20 228 779 225 819 142 849 24 494 45 172 95 207 908 510 424 78 100 166 869 456\r\n", "output": "78186\r\n"}, {"input": "15 254 996 341 109 402 688 501 206 905 398 124 373 313 943 515\r\n", "output": "57959\r\n"}, {"input": "45 657 700 898 830 795 104 427 995 219 505 95 385 64 241 196 318 927 228 428 329 606 619 535 200 707 660 574 19 292 88 872 950 788 769 779 272 563 896 267 782 400 52 857 154 293\r\n", "output": "507143\r\n"}, {"input": "41 473 219 972 591 238 267 209 464 467 916 814 40 625 105 820 496 54 297 264 523 570 828 418 527 299 509 269 156 663 562 900 826 471 561 416 710 828 315 864 985 230\r\n", "output": "463602\r\n"}, {"input": "48 25 856 782 535 41 527 832 306 49 91 824 158 618 122 357 887 969 710 138 868 536 610 118 642 9 946 958 873 931 878 549 646 733 20 180 775 547 11 771 287 103 594 135 411 406 492 989 375\r\n", "output": "597376\r\n"}, {"input": "57 817 933 427 116 51 69 125 687 717 688 307 594 927 643 17 638 823 482 184 525 943 161 318 226 296 419 632 478 97 697 370 915 320 797 30 371 556 847 748 272 224 746 557 151 388 264 789 211 746 663 426 688 825 744 914 811 853\r\n", "output": "900997\r\n"}, {"input": "55 980 951 933 349 865 252 836 585 313 392 431 751 354 656 496 601 497 885 865 976 786 300 638 211 678 152 645 281 654 187 517 633 137 139 672 692 81 507 968 84 589 398 835 944 744 331 234 931 906 99 906 691 89 234 592\r\n", "output": "810147\r\n"}]
| false |
stdio
| null | true |
598/E
|
598
|
E
|
Python 3
|
TESTS
| 1 | 15 | 0 |
202355620
|
for _ in range(int(input())):
n,m,k=map(int,input().split())
if k%2!=0:
print(min(n*n+1,m*m+1))
else:
z=min(n*n+1,m*m+1)
for i in range(1,k+1):
if k%i==0:
x=k//i
y=i
if y!=n and x!=m:
z=min(z,m*m+y*y,n*n+x*x)
elif y==n and x!=m:
z=min(z,n*n)
elif y!=n and x==m:
z=min(z,m*m)
else:
z=0
break
print(z)
| 5 | 794 | 30,105,600 |
128888073
|
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# sys.setrecursionlimit(1000000)
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
dp = [[[0 for k in range (51)] for j in range (31)] for i in range (31)]
def calc (n, m, k) :
#print(n,m,k)
if (dp[n][m][k] != 0) or (n*m == k) or (k == 0) :
return dp[n][m][k]
ans = 10**9
for i in range (1,n//2 + 1) :
for j in range (k+1) :
#print(i,j,'a')
if (i*m >= (k-j)) and ((n-i)*m >= j) :
ans = min(ans, m*m + calc(i,m,k-j) + calc(n-i,m,j))
for i in range (1,m//2 + 1) :
for j in range (k+1) :
#print(i,j,'b')
if (i*n >= (k-j)) and ((m-i)*n >= j) :
ans = min(ans, n*n + calc(n,i,k-j) + calc(n,m-i,j))
dp[n][m][k] = ans
return ans
for _ in range (getN()):
N, M, K = getNM()
print(calc(N, M, K))
|
Educational Codeforces Round 1
|
ICPC
| 2,015 | 2 | 256 |
Chocolate Bar
|
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
|
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
|
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
| null |
In the first query of the sample one needs to perform two breaks:
- to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),
- to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
|
[{"input": "4\n2 2 1\n2 2 3\n2 2 2\n2 2 4", "output": "5\n5\n4\n0"}]
| 2,000 |
["brute force", "dp"]
| 5 |
[{"input": "4\r\n2 2 1\r\n2 2 3\r\n2 2 2\r\n2 2 4\r\n", "output": "5\r\n5\r\n4\r\n0\r\n"}]
| false |
stdio
| null | true |
677/C
|
677
|
C
|
Python 3
|
TESTS
| 0 | 15 | 0 |
232376718
|
MOD = 10**9 + 7
def convert_to_num(char):
if char.isdigit():
return int(char)
elif char.isupper():
return ord(char) - ord('A') + 10
elif char.islower():
return ord(char) - ord('a') + 36
elif char == '-':
return 62
elif char == '_':
return 63
def count_pairs(s):
num_representation = [convert_to_num(char) for char in s]
occurrences = [0] * 64
for num in num_representation:
occurrences[num] += 1
total_pairs = 1
for count in occurrences:
# Calculate the number of pairs for each digit
total_pairs = (total_pairs * (count * (count - 1) // 2 + 1)) % MOD
return total_pairs
if __name__ == "__main__":
s = input().strip()
result = count_pairs(s)
print(result)
| 46 | 93 | 5,120,000 |
18198069
|
def count(num):
string = bin(num)[2:]
return string.count('0') + 6 - len(string)
key = [3 ** count(x) for x in range(64)]
dic = {}
for i in range(10):
dic[chr(ord('0') + i)] = key[i]
for i in range(26):
dic[chr(ord('A') + i)] = key[i + 10]
for i in range(26):
dic[chr(ord('a') + i)] = key[i + 36]
dic['-'] = key[62]
dic['_'] = key[63]
mod = int(1e9) + 7
string = input()
ans = 1
for x in string:
ans = (ans * dic[x]) % mod
print(ans)
|
Codeforces Round 355 (Div. 2)
|
CF
| 2,016 | 1 | 256 |
Vanya and Label
|
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7.
To represent the string as a number in numeral system with base 64 Vanya uses the following rules:
- digits from '0' to '9' correspond to integers from 0 to 9;
- letters from 'A' to 'Z' correspond to integers from 10 to 35;
- letters from 'a' to 'z' correspond to integers from 36 to 61;
- letter '-' correspond to integer 62;
- letter '_' correspond to integer 63.
|
The only line of the input contains a single word s (1 ≤ |s| ≤ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.
|
Print a single integer — the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7.
| null |
For a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.
In the first sample, there are 3 possible solutions:
1. z&_ = 61&63 = 61 = z
2. _&z = 63&61 = 61 = z
3. z&z = 61&61 = 61 = z
|
[{"input": "z", "output": "3"}, {"input": "V_V", "output": "9"}, {"input": "Codeforces", "output": "130653412"}]
| 1,500 |
["bitmasks", "combinatorics", "implementation", "strings"]
| 46 |
[{"input": "z\r\n", "output": "3\r\n"}, {"input": "V_V\r\n", "output": "9\r\n"}, {"input": "Codeforces\r\n", "output": "130653412\r\n"}, {"input": "zHsIINYjVtU71kmM9E\r\n", "output": "130312847\r\n"}, {"input": "fRRNAdMvLFTX21T0FG5gyn7NG0SaIvzGG_g_SO\r\n", "output": "547121709\r\n"}, {"input": "Lb1T3sA4BcTx4KAgLIsl-dNOGDvimpxZOxJfMz6VC3nQkB3Y780qqX_1dnjjb59H9X\r\n", "output": "680590434\r\n"}, {"input": "2kdYy5-G2-TL5dtLRKcp0ScPGQMrEjwsXuxJHZb4EOd7g7NSQYiAuX2O40PKVyMGEQ1WzW6TvQqbrM1O6e3TdduRsk\r\n", "output": "39961202\r\n"}, {"input": "kuCerLoRuMSm6wa_YM\r\n", "output": "172815616\r\n"}, {"input": "_\r\n", "output": "1\r\n"}, {"input": "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_\r\n", "output": "803556829\r\n"}, {"input": "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_\r\n", "output": "188799173\r\n"}, {"input": "__________\r\n", "output": "1\r\n"}, {"input": "___________________________________________________________________X________________________________\r\n", "output": "81\r\n"}, {"input": "Bq\r\n", "output": "729\r\n"}, {"input": "UhXl\r\n", "output": "19683\r\n"}, {"input": "oXyg5\r\n", "output": "43046721\r\n"}, {"input": "6\r\n", "output": "81\r\n"}]
| false |
stdio
| null | true |
811/E
|
811
|
E
|
Python 3
|
TESTS
| 1 | 46 | 204,800 |
27584672
|
#!/usr/bin/python3
import sys
def get_str_deb():
yield list(int(x) for x in "4 5 4".split())
yield list(int(x) for x in "1 1 1 1 1".split())
yield list(int(x) for x in "1 2 2 3 3".split())
yield list(int(x) for x in "1 1 1 2 5".split())
yield list(int(x) for x in "4 4 5 5 5".split())
yield list(int(x) for x in "1 5".split())
yield list(int(x) for x in "2 5".split())
yield list(int(x) for x in "1 2".split())
yield list(int(x) for x in "4 5".split())
deb = get_str_deb()
def get_str():
if False:
return (int(x) for x in sys.stdin.readline().split())
else:
return next(deb)
def main():
n, m, q = get_str()
matr = [None] * n
for i in range(n):
matr[i] = list(get_str())
for i in range(q):
l, r = get_str()
l = l - 1
r = r - 1
x, y = [l, 0]
regions = 0
checked = [[False for i in range(m)] for j in range(n)]
while True:
regions = regions + 1
chain = []
while True:
checked[y][x] = True
if x > l and matr[y][x - 1] == matr[y][x] and not(checked[y][x - 1]):
chain.append((x, y))
x = x - 1
continue
elif x < r and matr[y][x + 1] == matr[y][x] and not(checked[y][x + 1]):
chain.append((x, y))
x = x + 1
continue
elif y > 0 and matr[y - 1][x] == matr[y][x] and not(checked[y - 1][x]):
chain.append((x, y))
y = y - 1
continue
elif y < n - 1 and matr[y + 1][x] == matr[y][x] and not(checked[y + 1][x]):
chain.append((x, y))
y = y + 1
continue
elif len(chain) == 0:
break
x, y = chain.pop()
x = None
y = None
for newx in range(l, r + 1):
for newy in range(n):
if not(checked[newy][newx]):
x = newx
y = newy
stop = True
break
if x is not None:
break
if x is None:
break
print(regions)
if __name__ == "__main__":
main()
| 120 | 1,653 | 111,513,600 |
221893861
|
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v):
return u * n + v
def get_root(s):
v = []
while not s == root[s]:
v.append(s)
s = root[s]
for i in v:
root[i] = s
return s
def unite(s, t):
s, t = get_root(s), get_root(t)
if s == t:
return
if rank[s] < rank[t]:
s, t = t, s
if rank[s] == rank[t]:
rank[s] += 1
root[t] = s
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def get_segment(s, t):
s, t = s + l1, t + l1
u, v = [], []
while s <= t:
if s & 1:
u.append(s)
s += 1
s >>= 1
if not t & 1:
v.append(t)
t -= 1
t >>= 1
return u + v[::-1]
n, m, q = map(int, input().split())
l1 = pow(2, (m + 1).bit_length())
l2 = 2 * l1
a = [0] * (n * l2)
for i in range(n):
a0 = list(map(int, input().split()))
for j in range(m):
a[f(j, i)] = a0[j]
root = [i for i in range(n * l1)]
rank = [1 for _ in range(n * l1)]
l0, r0 = [0] * l2, [0] * l2
ll, rr = [0] * (n * l2), [0] * (n * l2)
cnt = [0] * l2
for i in range(l1):
c = n
for j in range(n - 1):
u, v = f(i, j), f(i, j + 1)
if a[u] == a[v] and not same(u, v):
unite(u, v)
c -= 1
for j in range(n):
u, v = f(i + l1, j), get_root(f(i, j))
ll[u], rr[u] = v, v
l0[i + l1], r0[i + l1] = i, i
cnt[i + l1] = c
for i in range(l1 - 1, 0, -1):
c = cnt[2 * i] + cnt[2 * i + 1]
l, r = r0[2 * i], l0[2 * i + 1]
for j in range(n):
u, v = f(l, j), f(r, j)
if a[u] == a[v] and not same(u, v):
unite(u, v)
c -= 1
l, r = l0[2 * i], r0[2 * i + 1]
for j in range(n):
u = f(i, j)
ll[u], rr[u] = get_root(f(l, j)), get_root(f(r, j))
l0[i], r0[i] = l, r
cnt[i] = c
ans = [0] * q
root = [i for i in range(n * l1)]
rank = [1 for _ in range(n * l1)]
for q0 in range(q):
l, r = map(int, input().split())
x = get_segment(l - 1, r - 1)
ans0 = cnt[x[0]]
for i in range(len(x) - 1):
l, r = x[i], x[i + 1]
ans0 += cnt[r]
for j in range(n):
u, v = rr[f(l, j)], ll[f(r, j)]
if a[u] == a[v] and not same(u, v):
unite(u, v)
ans0 -= 1
ans[q0] = ans0
for i in x:
for j in range(n):
u, v = ll[f(i, j)], rr[f(i, j)]
root[u], root[v] = u, v
rank[u], rank[v] = 1, 1
sys.stdout.write("\n".join(map(str, ans)))
|
Codeforces Round 416 (Div. 2)
|
CF
| 2,017 | 2 | 256 |
Vladik and Entertaining Flags
|
In his spare time Vladik estimates beauty of the flags.
Every flag could be represented as the matrix n × m which consists of positive integers.
Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components:
But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≤ l ≤ r ≤ m are satisfied.
Help Vladik to calculate the beauty for some segments of the given flag.
|
First line contains three space-separated integers n, m, q (1 ≤ n ≤ 10, 1 ≤ m, q ≤ 105) — dimensions of flag matrix and number of segments respectively.
Each of next n lines contains m space-separated integers — description of flag matrix. All elements of flag matrix is positive integers not exceeding 106.
Each of next q lines contains two space-separated integers l, r (1 ≤ l ≤ r ≤ m) — borders of segment which beauty Vladik wants to know.
|
For each segment print the result on the corresponding line.
| null |
Partitioning on components for every segment from first test case:
|
[{"input": "4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5", "output": "6\n7\n3\n4"}]
| 2,600 |
["data structures", "dsu", "graphs"]
| 120 |
[{"input": "4 5 4\r\n1 1 1 1 1\r\n1 2 2 3 3\r\n1 1 1 2 5\r\n4 4 5 5 5\r\n1 5\r\n2 5\r\n1 2\r\n4 5\r\n", "output": "6\r\n7\r\n3\r\n4\r\n"}, {"input": "5 2 9\r\n6 1\r\n6 6\r\n6 6\r\n6 6\r\n5 6\r\n1 2\r\n1 1\r\n1 2\r\n1 2\r\n1 2\r\n1 1\r\n1 1\r\n1 2\r\n1 1\r\n", "output": "3\r\n2\r\n3\r\n3\r\n3\r\n2\r\n2\r\n3\r\n2\r\n"}, {"input": "5 4 10\r\n5 5 5 5\r\n5 5 5 5\r\n5 5 5 5\r\n5 5 5 5\r\n5 5 5 5\r\n2 4\r\n2 2\r\n1 2\r\n1 4\r\n1 1\r\n1 3\r\n2 4\r\n2 3\r\n1 3\r\n3 3\r\n", "output": "1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n1\r\n"}, {"input": "8 4 12\r\n7 20 20 29\r\n29 7 29 29\r\n29 20 20 29\r\n29 20 20 29\r\n29 8 29 29\r\n20 29 29 29\r\n29 29 32 29\r\n29 29 29 29\r\n2 4\r\n1 4\r\n2 3\r\n2 3\r\n1 4\r\n2 4\r\n1 1\r\n3 3\r\n3 3\r\n2 3\r\n3 4\r\n1 2\r\n", "output": "6\r\n9\r\n7\r\n7\r\n9\r\n6\r\n4\r\n6\r\n6\r\n7\r\n4\r\n8\r\n"}, {"input": "7 8 14\r\n8 8 36 8 36 36 5 36\r\n25 36 36 8 36 25 36 36\r\n36 36 36 8 36 36 36 36\r\n36 36 36 36 36 36 8 55\r\n8 8 36 36 36 36 36 36\r\n49 36 36 36 8 36 36 36\r\n36 36 5 44 5 36 36 48\r\n2 3\r\n1 4\r\n6 8\r\n1 2\r\n5 8\r\n2 8\r\n1 5\r\n5 8\r\n6 7\r\n1 3\r\n2 6\r\n1 6\r\n3 6\r\n2 4\r\n", "output": "4\r\n8\r\n7\r\n6\r\n8\r\n13\r\n10\r\n8\r\n5\r\n6\r\n9\r\n11\r\n7\r\n6\r\n"}, {"input": "1 6 9\r\n1 2 3 4 5 6\r\n2 6\r\n4 5\r\n3 4\r\n3 5\r\n6 6\r\n3 6\r\n4 6\r\n2 3\r\n1 6\r\n", "output": "5\r\n2\r\n2\r\n3\r\n1\r\n4\r\n3\r\n2\r\n6\r\n"}, {"input": "4 8 6\r\n23 23 23 23 23 13 23 23\r\n23 23 23 23 23 23 23 23\r\n23 23 23 23 13 23 23 23\r\n23 23 26 23 23 23 23 23\r\n5 8\r\n2 8\r\n6 8\r\n5 5\r\n7 7\r\n2 4\r\n", "output": "3\r\n4\r\n2\r\n3\r\n1\r\n2\r\n"}, {"input": "2 10 7\r\n8 13 13 8 8 8 8 8 8 8\r\n8 8 8 8 8 8 8 8 8 8\r\n4 9\r\n1 7\r\n6 6\r\n7 8\r\n4 4\r\n1 8\r\n2 10\r\n", "output": "1\r\n2\r\n1\r\n1\r\n1\r\n2\r\n2\r\n"}, {"input": "5 12 6\r\n25 24 24 53 53 53 53 53 5 20 53 53\r\n24 53 24 53 53 3 5 53 53 53 53 53\r\n24 53 53 5 53 5 53 53 53 17 53 60\r\n49 53 53 24 53 53 53 53 53 53 53 35\r\n53 53 5 53 53 53 53 53 53 53 53 53\r\n6 8\r\n8 10\r\n4 11\r\n4 8\r\n6 12\r\n8 9\r\n", "output": "4\r\n4\r\n9\r\n6\r\n9\r\n2\r\n"}, {"input": "4 14 4\r\n8 8 8 8 46 46 48 8 8 8 8 13 24 40\r\n8 46 46 46 8 8 46 8 8 8 8 24 24 24\r\n8 46 46 8 8 8 23 23 8 8 8 8 8 8\r\n8 8 8 8 8 8 8 8 8 8 8 8 8 55\r\n10 10\r\n10 14\r\n3 5\r\n10 12\r\n", "output": "1\r\n5\r\n4\r\n3\r\n"}, {"input": "1 16 10\r\n2 2 2 2 6 2 8 2 2 12 10 9 9 2 16 2\r\n9 9\r\n5 5\r\n6 9\r\n6 8\r\n7 11\r\n6 16\r\n4 7\r\n6 15\r\n7 9\r\n11 11\r\n", "output": "1\r\n1\r\n3\r\n3\r\n4\r\n9\r\n4\r\n8\r\n2\r\n1\r\n"}, {"input": "7 12 11\r\n73 14 4 73 42 42 73 73 73 67 73 24\r\n73 73 73 73 73 73 72 73 73 73 73 11\r\n73 73 4 72 73 73 73 73 73 73 67 72\r\n73 74 73 72 73 73 73 73 73 73 73 73\r\n4 73 73 73 73 73 73 73 73 57 73 73\r\n72 73 73 4 73 73 73 73 33 73 73 73\r\n73 73 73 15 42 72 67 67 33 67 73 73\r\n9 12\r\n6 6\r\n10 11\r\n8 10\r\n1 9\r\n6 9\r\n3 5\r\n2 4\r\n2 4\r\n7 11\r\n1 12\r\n", "output": "9\r\n3\r\n5\r\n7\r\n16\r\n6\r\n8\r\n9\r\n9\r\n8\r\n23\r\n"}, {"input": "5 16 10\r\n32 4 4 4 4 4 4 52 4 4 4 4 29 30 4 4\r\n4 4 67 52 4 4 4 67 4 4 4 4 4 4 4 4\r\n4 52 52 52 4 4 4 67 67 52 32 4 4 4 4 52\r\n4 52 4 4 4 4 4 4 67 52 49 4 4 4 4 62\r\n49 4 4 4 4 72 55 4 4 52 49 52 4 62 4 62\r\n5 16\r\n9 13\r\n2 12\r\n3 13\r\n8 14\r\n7 7\r\n3 9\r\n1 4\r\n1 5\r\n7 7\r\n", "output": "15\r\n8\r\n12\r\n13\r\n11\r\n2\r\n8\r\n6\r\n5\r\n2\r\n"}]
| false |
stdio
| null | true |
247/D
|
250
|
D
|
Python 3
|
TESTS
| 1 | 92 | 0 |
11597490
|
import sys
from itertools import *
from math import *
def solve():
n,m,leftbank,rightbank = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
l = list(map(int, input().split()))
dist = rightbank - leftbank
smallx = leftbank
leftbest, rightbest, distbest = -1, -1, 100000000
for righty, bcord, length in zip(count(), b, l):
wanty = bcord * smallx / dist
ll , rr = 0, n - 1
while ll < rr:
mm = (ll + rr) // 2
if a[mm] > wanty: rr = mm - 1
else: ll = mm + 1
for pos in range(ll - 1, ll + 2):
if pos > 0 and pos < n:
first = sqrt(smallx * smallx + a[pos] * a[pos])
second = sqrt((dist - smallx)*(dist - smallx) + (righty - a[pos])*(righty - a[pos]))
totaldist = first + second + length
if totaldist < distbest:
distbest = totaldist
leftbest = pos
rightbest = righty
print(leftbest + 1, rightbest + 1)
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
| 33 | 1,122 | 11,878,400 |
13858446
|
from math import sqrt,fabs
def dist(x1, y1, x2, y2):
return sqrt(pow(abs(x1 - x2), 2) + pow(abs(y1 - y2), 2))
def calcOptimumRightPoint(startX, startY):
l = float("inf")
idx = -1
for i in range(len(B)):
d = dist(startX, startY, b, B[i]) + L[i]
if d <= l:
l = d
idx = i
return idx
n,m,a,b = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
L = [int(x) for x in input().split()]
optimumRightPoint = calcOptimumRightPoint(0,0)
intersectLeft = (a * B[optimumRightPoint]) / b
l = float("inf")
optimumLeftPoint = -1
for i in range(len(A)):
if fabs(intersectLeft-A[i]) < l:
l = fabs(intersectLeft-A[i])
optimumLeftPoint = i
optimumRightPoint = calcOptimumRightPoint(a, A[optimumLeftPoint])
print(optimumLeftPoint + 1, optimumRightPoint + 1)
|
CROC-MBTU 2012, Final Round
|
CF
| 2,012 | 1 | 256 |
Building Bridge
|
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.
The river banks can be assumed to be vertical straight lines x = a and x = b (0 < a < b).
The west village lies in a steppe at point O = (0, 0). There are n pathways leading from the village to the river, they end at points Ai = (a, yi). The villagers there are plain and simple, so their pathways are straight segments as well.
The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are m twisted paths leading from this village to the river and ending at points Bi = (b, y'i). The lengths of all these paths are known, the length of the path that leads from the eastern village to point Bi, equals li.
The villagers want to choose exactly one point on the left bank of river Ai, exactly one point on the right bank Bj and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |OAi| + |AiBj| + lj, where |XY| is the Euclidean distance between points X and Y) were minimum. The Euclidean distance between points (x1, y1) and (x2, y2) equals $$\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}$$.
Help them and find the required pair of points.
|
The first line contains integers n, m, a, b (1 ≤ n, m ≤ 105, 0 < a < b < 106).
The second line contains n integers in the ascending order: the i-th integer determines the coordinate of point Ai and equals yi (|yi| ≤ 106).
The third line contains m integers in the ascending order: the i-th integer determines the coordinate of point Bi and equals y'i (|y'i| ≤ 106).
The fourth line contains m more integers: the i-th of them determines the length of the path that connects the eastern village and point Bi, and equals li (1 ≤ li ≤ 106).
It is guaranteed, that there is such a point C with abscissa at least b, that |BiC| ≤ li for all i (1 ≤ i ≤ m). It is guaranteed that no two points Ai coincide. It is guaranteed that no two points Bi coincide.
|
Print two integers — the numbers of points on the left (west) and right (east) banks, respectively, between which you need to build a bridge. You can assume that the points on the west bank are numbered from 1 to n, in the order in which they are given in the input. Similarly, the points on the east bank are numbered from 1 to m in the order in which they are given in the input.
If there are multiple solutions, print any of them. The solution will be accepted if the final length of the path will differ from the answer of the jury by no more than 10 - 6 in absolute or relative value.
| null | null |
[{"input": "3 2 3 5\n-2 -1 4\n-1 2\n7 3", "output": "2 2"}]
| 1,900 |
[]
| 33 |
[{"input": "3 2 3 5\r\n-2 -1 4\r\n-1 2\r\n7 3\r\n", "output": "2 2"}, {"input": "1 1 10 20\r\n5\r\n-5\r\n1\r\n", "output": "1 1"}, {"input": "2 2 1 2\r\n-1 10\r\n8 9\r\n3 7\r\n", "output": "1 1"}, {"input": "10 20 50 60\r\n-96 -75 32 37 42 43 44 57 61 65\r\n-95 -90 -86 -79 -65 -62 -47 -11 -8 -6 1 8 23 25 32 51 73 88 94 100\r\n138 75 132 116 49 43 96 166 96 161 146 112 195 192 201 186 251 254 220 227\r\n", "output": "2 6"}]
| false |
stdio
| null | true |
678/E
|
678
|
E
|
PyPy 3
|
TESTS
| 0 | 576 | 147,865,600 |
148038367
|
n = int(input())
a = [[0]*(n+1) for i in range(n+1)]
for i in range(n):
j = 0
for v in map(float, input().split()):
a[i][j] = v
j += 1
f = [[0]*20 for i in range(1<<20)]
f[1][1] = 1
for k in range(1, 1<<n):
for i in range(n):
if (1<<i) & k != 0:
for j in range(n):
if (1<<j) & k != 0:
f[k][i] = max(f[k][i], f[k-(1<<i)][i]*a[i][j], f[k-(1>>j)][j]*a[j][i])
ans = 0
for i in range(n):
ans = max(ans, f[(1<<n)-1][i])
print(ans)
| 41 | 1,419 | 80,793,600 |
126740185
|
from decimal import *
ar = [list(map(float, input().split())) for i in range(int(input()))]
dp = [[0 for i in range(1 << 18)] for j in range(18)]
n, ans = len(ar), 0
dp[0][(1 << n) - 1] = 1
for i in range((1 << n) - 1, 0, -1):
for j in range(n):
if i & (1 << j) == 0:
continue
for k in range(n):
if i & (1 << k) != 0 or j == k:
continue
dp[j][i] = max(dp[j][i], dp[k][i ^ (1 << k)] * ar[k][j] + dp[j][i ^ (1 << k)] * ar[j][k])
for i in range(n):
ans = max(ans, dp[i][1 << i])
print('{:.6f}'.format(ans))
|
Educational Codeforces Round 13
|
ICPC
| 2,016 | 2.5 | 256 |
Another Sith Tournament
|
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.
Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.
|
The first line contains a single integer n (1 ≤ n ≤ 18) — the number of participants of the Sith Tournament.
Each of the next n lines contains n real numbers, which form a matrix pij (0 ≤ pij ≤ 1). Each its element pij is the probability that the i-th participant defeats the j-th in a duel.
The elements on the main diagonal pii are equal to zero. For all different i, j the equality pij + pji = 1 holds. All probabilities are given with no more than six decimal places.
Jedi Ivan is the number 1 in the list of the participants.
|
Output a real number — the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10 - 6.
| null | null |
[{"input": "3\n0.0 0.5 0.8\n0.5 0.0 0.4\n0.2 0.6 0.0", "output": "0.680000000000000"}]
| 2,200 |
["bitmasks", "dp", "math", "probabilities"]
| 41 |
[{"input": "3\r\n0.0 0.5 0.8\r\n0.5 0.0 0.4\r\n0.2 0.6 0.0\r\n", "output": "0.680000000000000\n"}, {"input": "1\r\n0.0\r\n", "output": "1.000000000000000\n"}, {"input": "2\r\n0.00 0.75\r\n0.25 0.00\r\n", "output": "0.750000000000000\n"}, {"input": "4\r\n0.0 0.6 0.5 0.4\r\n0.4 0.0 0.3 0.8\r\n0.5 0.7 0.0 0.5\r\n0.6 0.2 0.5 0.0\r\n", "output": "0.545000000000000\n"}, {"input": "4\r\n0.0 0.3 0.5 0.6\r\n0.7 0.0 0.1 0.4\r\n0.5 0.9 0.0 0.6\r\n0.4 0.6 0.4 0.0\r\n", "output": "0.534000000000000\n"}, {"input": "2\r\n0.0 0.0\r\n1.0 0.0\r\n", "output": "0.000000000000000\n"}, {"input": "2\r\n0.0 1.0\r\n0.0 0.0\r\n", "output": "1.000000000000000\n"}, {"input": "5\r\n0.0 0.3 0.4 0.5 0.6\r\n0.7 0.0 0.2 0.6 0.8\r\n0.6 0.8 0.0 0.6 0.3\r\n0.5 0.4 0.4 0.0 0.5\r\n0.4 0.2 0.7 0.5 0.0\r\n", "output": "0.522400000000000\n"}, {"input": "6\r\n0.00 0.15 0.25 0.35 0.45 0.55\r\n0.85 0.00 0.35 0.45 0.55 0.65\r\n0.75 0.65 0.00 0.75 0.85 0.15\r\n0.65 0.55 0.25 0.00 0.40 0.35\r\n0.55 0.45 0.15 0.60 0.00 0.70\r\n0.45 0.35 0.85 0.65 0.30 0.00\r\n", "output": "0.483003750000000\n"}, {"input": "4\r\n0.0 1.0 1.0 1.0\r\n0.0 0.0 0.0 1.0\r\n0.0 1.0 0.0 0.0\r\n0.0 0.0 1.0 0.0\r\n", "output": "1.000000000000000\n"}, {"input": "4\r\n0.0 1.0 1.0 1.0\r\n0.0 0.0 0.0 0.0\r\n0.0 1.0 0.0 0.0\r\n0.0 1.0 1.0 0.0\r\n", "output": "1.000000000000000\n"}, {"input": "4\r\n0.0 1.0 1.0 0.0\r\n0.0 0.0 0.9 0.2\r\n0.0 0.1 0.0 1.0\r\n1.0 0.8 0.0 0.0\r\n", "output": "1.000000000000000\n"}, {"input": "5\r\n0.0 0.0 0.0 0.0 0.0\r\n1.0 0.0 0.5 0.5 0.5\r\n1.0 0.5 0.0 0.5 0.5\r\n1.0 0.5 0.5 0.0 0.5\r\n1.0 0.5 0.5 0.5 0.0\r\n", "output": "0.000000000000000\n"}, {"input": "2\r\n0.000000 0.032576\r\n0.967424 0.000000\r\n", "output": "0.032576000000000\n"}, {"input": "3\r\n0.000000 0.910648 0.542843\r\n0.089352 0.000000 0.537125\r\n0.457157 0.462875 0.000000\r\n", "output": "0.740400260625000\n"}, {"input": "4\r\n0.000000 0.751720 0.572344 0.569387\r\n0.248280 0.000000 0.893618 0.259864\r\n0.427656 0.106382 0.000000 0.618783\r\n0.430613 0.740136 0.381217 0.000000\r\n", "output": "0.688466450920859\n"}, {"input": "5\r\n0.000000 0.629791 0.564846 0.602334 0.362179\r\n0.370209 0.000000 0.467868 0.924988 0.903018\r\n0.435154 0.532132 0.000000 0.868573 0.209581\r\n0.397666 0.075012 0.131427 0.000000 0.222645\r\n0.637821 0.096982 0.790419 0.777355 0.000000\r\n", "output": "0.607133963373199\n"}, {"input": "6\r\n0.000000 0.433864 0.631347 0.597596 0.794426 0.713555\r\n0.566136 0.000000 0.231193 0.396458 0.723050 0.146212\r\n0.368653 0.768807 0.000000 0.465978 0.546227 0.309438\r\n0.402404 0.603542 0.534022 0.000000 0.887926 0.456734\r\n0.205574 0.276950 0.453773 0.112074 0.000000 0.410517\r\n0.286445 0.853788 0.690562 0.543266 0.589483 0.000000\r\n", "output": "0.717680454673393\n"}, {"input": "7\r\n0.000000 0.311935 0.623164 0.667542 0.225988 0.921559 0.575083\r\n0.688065 0.000000 0.889215 0.651525 0.119843 0.635314 0.564710\r\n0.376836 0.110785 0.000000 0.583317 0.175043 0.795995 0.836790\r\n0.332458 0.348475 0.416683 0.000000 0.263615 0.469602 0.883191\r\n0.774012 0.880157 0.824957 0.736385 0.000000 0.886308 0.162544\r\n0.078441 0.364686 0.204005 0.530398 0.113692 0.000000 0.023692\r\n0.424917 0.435290 0.163210 0.116809 0.837456 0.976308 0.000000\r\n", "output": "0.721455539644280\n"}, {"input": "2\r\n0 0.233\r\n0.767 0\r\n", "output": "0.233000000000000\n"}]
| false |
stdio
|
import sys
def read_value(path):
with open(path, 'r') as f:
lines = [line.strip() for line in f.readlines() if line.strip()]
if len(lines) != 1:
return None
try:
return float(lines[0])
except:
return None
def main():
input_path = sys.argv[1]
correct_output_path = sys.argv[2]
submission_output_path = sys.argv[3]
correct = read_value(correct_output_path)
sub = read_value(submission_output_path)
if correct is None or sub is None:
print(0)
return
a, b = correct, sub
if a == b:
print(1)
return
abs_err = abs(a - b)
if abs_err <= 1e-6:
print(1)
return
max_abs = max(abs(a), abs(b))
rel_err = abs_err / max_abs if max_abs != 0 else 0
if rel_err <= 1e-6:
print(1)
return
print(0)
if __name__ == "__main__":
main()
| true |
145/C
|
145
|
C
|
PyPy 3
|
TESTS
| 0 | 122 | 20,172,800 |
123056951
|
import math
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
# A = [4,4,4,4,7,7,7,44,44,44,44,1,1,1,1,1,1,1,1,1,1,123,123,123,123,123,123,123,12,3,12,3,12,1,13,123,123,123,123,123,123,12,3,12,3,12,1,1,2,12,1]
# k = 24
Ocurrencias = []
print( Calcular(a,k))
Ocurrencias = []
def Fac(n):
temp = 1
for i in range(1, n + 1):
temp = temp * i
return temp
def Combinatoria(k, A):
if (A == 0 or k == 0): return 0
return Fac(A) / (Fac(A - k) * Fac(k))
def IsLucky(n):
count = len(str(n))
for i in range(0, count):
if n % 10 != 7 and n % 10 != 4: return False
n =int(n / 10)
return True
def AddOcurrencias(a:int):
if IsLucky(a) == False: return
for i in range(0, len(Ocurrencias)):
if a == Ocurrencias[i][0]:
Ocurrencias[i] = [a, Ocurrencias[i][1] + 1]
return
Ocurrencias.append([a,1])
def LimpiarOcurrencias():
for i in range(0, len(Ocurrencias)):
if Ocurrencias[i][1] == 1:
Ocurrencias.remove(Ocurrencias[i])
i -= 1
def Calcular(A: list, k):
if k == 1: return len(A)
Ocurrencias
CombinacioesMaximas = Combinatoria(k, len(A))
for i in range(0, len(A)):
AddOcurrencias(int(A[i]))
LimpiarOcurrencias()
if len(Ocurrencias) == 0: return CombinacioesMaximas
if k == 2: return CombinacioesMaximas - CasoK2()
CombinacionesInvalidas = 0
for i in range(0, len(Ocurrencias)):
if i == 0:
CombinacionesInvalidas += CombinacionesInvalidasParaPos(i, k, len(A))
else:
CombinacionesInvalidas += CombinacionesTurbiasInvalidasParaPos(i, k, len(A))
result = CombinacioesMaximas - CombinacionesInvalidas
return result % 1000000007
def CombinacionesInvalidasParaPos(pos, k, a):
result = 0
cota = min(Ocurrencias[pos][1], k)
for i in range(2, cota + 1):
temp = Combinatoria(k - i, a - Ocurrencias[pos][1])
comb = Combinatoria(i, Ocurrencias[pos][1])
result += temp * comb
if k <= Ocurrencias[pos][1]:
result += Combinatoria(k, Ocurrencias[pos][1])
return result
def CombinacionesTurbiasInvalidasParaPos(pos, k, a):
result = 0
cota = min(Ocurrencias[pos][1], k)
o = OcurrenciasHastaN(pos)
for i in range(2, cota + 1):
temp = Combinatoria(k - i, a - Ocurrencias[pos][1] - o)
comb = Combinatoria(i, Ocurrencias[pos][1])
result += temp * comb
if k <= Ocurrencias[pos][1]:
result += Combinatoria(k, Ocurrencias[pos][1])
for i in range(2, cota + 1):
for j in range(0, k + 1):
k_0 = k - i - j
if (k_0 <= 0): continue
Derecha = Combinatoria(j, a - Ocurrencias[pos][1] - o)
comb = Combinatoria(i, Ocurrencias[pos][1])
izquierda = CombinatoriaComunHastaPos(pos, k_0)
if (j != 0):
result += izquierda * Derecha * comb
else:
result += izquierda * comb
return result
def CombinatoriaComunHastaPos(pos, k):
temporal=[]
for i in range(0, pos):
temporal.append(Ocurrencias[i][1])
return CombinatoriaComun(temporal, k)
valorComb = [0]
def CombinatoriaComun( A: list, k):
valorComb[0] = 0
CombinatoriaComun2(A, k, 0, 1, 0)
return valorComb[0]
def CombinatoriaComun2(A: list, k, j, mul, cont):
if cont == k:
valorComb[0] += mul
for i in range(j, len(A)):
if cont < k:
CombinatoriaComun2(A, k, i + 1, A[i] * mul, cont + 1)
def CasoK2():
result = 0
for i in range(0, len(Ocurrencias)):
result += Combinatoria(2, Ocurrencias[i][1])
return result
def OcurrenciasHastaN(n):
count = 0
for i in range(0, n):
count += Ocurrencias[i][1]
return count
if __name__ == '__main__':
main()
| 58 | 872 | 22,937,600 |
70819857
|
import sys
MOD = 10 ** 9 + 7
def is_lucky(n):
n = str(n)
return n.count('4') + n.count('7') == len(n)
def get_inv(n):
return pow(n, MOD - 2, MOD)
def c(n, k):
if n < k or k < 0:
return 0
global fact, rfact
return (fact[n] * rfact[k] * rfact[n - k]) % MOD
fact = [1]
rfact = [1]
for i in range(1, 100500):
fact.append((i * fact[-1]) % MOD)
rfact.append((get_inv(i) * rfact[-1]) % MOD)
n, k = map(int,sys.stdin.readline().split())
a = list(map(int,sys.stdin.readline().split()))
d = dict()
for x in a:
if is_lucky(x):
d[x] = d.get(x, 0) + 1
dp = [0]*(len(d)+2)
dp[0] = 1
for x in d:
for i in range(len(dp) - 1, 0, -1):
dp[i] += dp[i - 1] * d[x]
dp[i] %= MOD
unlucky = n - sum(d.values())
ans = 0
for i in range(len(dp)):
if k >= i:
ans += dp[i] * c(unlucky, k - i)
print(ans % MOD)
|
Codeforces Round 104 (Div. 1)
|
CF
| 2,012 | 2 | 256 |
Lucky Subsequence
|
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has sequence a consisting of n integers.
The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements.
Two sequences are considered different if index sets of numbers included in them are different. That is, the values of the elements do not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence).
A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).
Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109 + 7).
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105). The next line contains n integers ai (1 ≤ ai ≤ 109) — the sequence a.
|
On the single line print the single number — the answer to the problem modulo prime number 1000000007 (109 + 7).
| null |
In the first sample all 3 subsequences of the needed length are considered lucky.
In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1, 3}, {1, 4}, {2, 3} and {2, 4}.
|
[{"input": "3 2\n10 10 10", "output": "3"}, {"input": "4 2\n4 4 7 7", "output": "4"}]
| 2,100 |
["combinatorics", "dp", "math"]
| 58 |
[{"input": "3 2\r\n10 10 10\r\n", "output": "3\r\n"}, {"input": "4 2\r\n4 4 7 7\r\n", "output": "4\r\n"}, {"input": "7 4\r\n1 2 3 4 5 6 7\r\n", "output": "35\r\n"}, {"input": "7 4\r\n7 7 7 7 7 7 7\r\n", "output": "0\r\n"}, {"input": "10 1\r\n1 2 3 4 5 6 7 8 9 10\r\n", "output": "10\r\n"}, {"input": "10 7\r\n1 2 3 4 5 6 7 8 9 10\r\n", "output": "120\r\n"}, {"input": "20 7\r\n1 4 5 8 47 777777777 1 5 4 8 5 9 5 4 7 4 5 7 7 44474\r\n", "output": "29172\r\n"}, {"input": "5 2\r\n47 47 47 47 47\r\n", "output": "0\r\n"}, {"input": "13 5\r\n44 44 44 44 44 44 44 44 77 55 66 99 55\r\n", "output": "41\r\n"}, {"input": "3 2\r\n1 47 47\r\n", "output": "2\r\n"}, {"input": "2 2\r\n47 47\r\n", "output": "0\r\n"}, {"input": "2 2\r\n44 44\r\n", "output": "0\r\n"}]
| false |
stdio
| null | true |
149/D
|
149
|
D
|
Python 3
|
TESTS
| 0 | 60 | 0 |
219448747
|
# LUOGU_RID: 121658616
print("4")
| 38 | 1,090 | 111,513,600 |
181683625
|
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(l, r, c1, c2):
return 9 * n * l + 9 * r + 3 * c1 + c2
def sparse_table(a):
mi = []
s0, l = list(a), 1
mi.append(s0)
while 2 * l <= len(a):
s = [min(s0[i], s0[i + l]) for i in range(len(s0) - l)]
mi.append(list(s))
s0 = s
l *= 2
return mi
def get_min(l, r, mi):
d = (r - l + 1).bit_length() - 1
ans = min(mi[d][l], mi[d][r - pow2[d] + 1])
return ans
s = list(input().rstrip())
mod = pow(10, 9) + 7
u = [0]
for i in s:
u.append(u[-1] + (1 if not i & 1 else -1))
mi = sparse_table(u)
pow2 = [1]
for _ in range(20):
pow2.append(2 * pow2[-1])
n = len(s) + 1
m = 9 * n * n
dp = [0] * m
la = [0] * n
x = [(1, 0), (2, 0), (0, 1), (0, 2)]
for i in range(n - 2):
if u[i] < u[i + 1] > u[i + 2]:
for c1, c2 in x:
dp[f(i, i + 2, c1, c2)] = 1
la[i] = 2
for i in range(4, n, 2):
for l in range(n - i):
r = l + i
if not get_min(l, r, mi) == u[l] == u[r]:
continue
if la[l]:
c = la[l] + l
for c1 in range(3):
for c2 in range(3):
dpl = dp[f(l, c, c1, c2)]
for c3 in range(3):
if c2 == c3 > 0:
continue
for c4 in range(3):
dpr = dp[f(c, r, c3, c4)]
j = f(l, r, c1, c4)
dp[j] += dpl * dpr % mod
dp[j] %= mod
else:
for c1, c2 in x:
j = f(l, r, c1, c2)
for c3 in range(3):
if c1 == c3 > 0:
continue
for c4 in range(3):
if c2 == c4 > 0:
continue
dp[j] += dp[f(l + 1, r - 1, c3, c4)]
dp[j] %= mod
la[l] = i
ans = 0
for c1 in range(3):
for c2 in range(3):
ans += dp[f(0, n - 1, c1, c2)]
ans %= mod
print(ans)
|
Codeforces Round 106 (Div. 2)
|
CF
| 2,012 | 2 | 256 |
Coloring Brackets
|
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.
You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.
In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.
You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:
- Each bracket is either not colored any color, or is colored red, or is colored blue.
- For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.
- No two neighboring colored brackets have the same color.
Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).
|
The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.
|
Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).
| null |
Let's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below.
The two ways of coloring shown below are incorrect.
|
[{"input": "(())", "output": "12"}, {"input": "(()())", "output": "40"}, {"input": "()", "output": "4"}]
| 1,900 |
["dp"]
| 38 |
[{"input": "(())\r\n", "output": "12\r\n"}, {"input": "(()())\r\n", "output": "40\r\n"}, {"input": "()\r\n", "output": "4\r\n"}, {"input": "((()))\r\n", "output": "36\r\n"}, {"input": "()(())\r\n", "output": "42\r\n"}, {"input": "()()()\r\n", "output": "48\r\n"}, {"input": "(())(())\r\n", "output": "126\r\n"}, {"input": "()()()()()()()()()()()(())\r\n", "output": "9085632\r\n"}, {"input": "()(())()((()))\r\n", "output": "4428\r\n"}, {"input": "()()(())()(())\r\n", "output": "5040\r\n"}, {"input": "()()()()()()()()()()()()()()()()\r\n", "output": "411525376\r\n"}, {"input": "(()()())\r\n", "output": "136\r\n"}, {"input": "()(()())()\r\n", "output": "480\r\n"}, {"input": "(())()(())()\r\n", "output": "1476\r\n"}, {"input": "()()(()())(())()()()\r\n", "output": "195840\r\n"}, {"input": "()()()((((())))())()()()()()((()))()()(())()(((())))()(()())((())())((()())(((((()()()())()()())))))\r\n", "output": "932124942\r\n"}, {"input": "((()(((((()(()(())))()((((((((())))()(((((())()((((())())(()(()(())())((()))()((()))))))))))))))))))))\r\n", "output": "90824888\r\n"}, {"input": "((()))((())())((()()))()(())(()())(())()()()((()(((()())))()())()((((()((()((())))(())(()(())())))((()())()()()((())()))()(())(())))()(((((()())))))))\r\n", "output": "100627207\r\n"}, {"input": "()(((()((((()())))())(())(((((()(()()))))()()))((())))()())((())))(())()((()())())()(()(()())())(()())()(()(((((()))()((()()(())()(())(()((()((()))))()(())()()(()()()((((()())()))))()(((()(((((()()((((())(())))()())(()))(((())((()())(()))())(((()()()(()(())())())(()()()))))())))()((()(()()(()))())((())(()()()(())()))()()(((())))((()))(()((()(((()))((((()())))())(((())()(()((())))))))))))))))))))))\r\n", "output": "306199947\r\n"}, {"input": "(())(((((()()()()())(())))(()()((()(()(((((())(()())))())(()()(()((())()(()()))))))(())()())))()((()()())))()()(()(())())()())()(())(((((()(()()(((()())()))((())((((()()()))())(((())(((())))))))))))))\r\n", "output": "270087235\r\n"}, {"input": "()()()((()))(())(((())()(())(())))()()(((()((()()()))(()()(())(())))(()()((()((())(()()(()(())))))))(((())()((((()())))()(((()()())))()))()())))()(()(()())((()((()))))())(((((()())()((((()))(((((()())()))(((()()()((((((()()(())(()))((()(()(()((()((((()(((()(()()(()()((((()))()()()(()((((()(((())(((()()()(())()))((()()()(()))))())()))))(((((((()))())))(((()(()())(())))())))((((())(())())(((()()()))((()()))())(()))(())((()(()))(()()((()(()((()(())(()))()()))))))))))))))))))))))))))))))))))))))))))\r\n", "output": "461776571\r\n"}, {"input": "()()(((((()((()(())()(()))(()(()(()(()(())(())(())(()(()((())))()))())((()((()(()(((()(()))()(()())(()()()()(((((()(((()))((((())())(((()((((()((((((())())))()))))))))(())())))(((()((()))))((())(()()))()(()(()((()())())()))))((()))))()((())())(()())()())))())())())())()((()((())((()()())()())())()(())()))(()(()))())))(()()()())()())))))))((((()())))((((()()()))())((()(())))))()((()(((())()()()(()()()()()))))(((()())()))()()(((())(()())(()()))))))\r\n", "output": "66338682\r\n"}, {"input": "(()())()()()((((()(()()(())()((())(((()((()()(()))()))()()))))()(()(())(()))))))\r\n", "output": "639345575\r\n"}, {"input": "()((()))((((()((())((()()((((()))()()((())((()(((((()(()))((())()))((((())()(()(()))()))))))))))))))))))\r\n", "output": "391997323\r\n"}, {"input": "(((((()())))))()()()()()(())()()()((()()))()()()()()(((()(())))())(((()())))\r\n", "output": "422789312\r\n"}, {"input": "((()((()))()((()(()))())))()((()())())()(()())((()))(()())(())()(())()(())(())((()()))((()))()()()()(())()\r\n", "output": "140121189\r\n"}, {"input": "()()\r\n", "output": "14\r\n"}]
| false |
stdio
| null | true |
149/D
|
149
|
D
|
Python 3
|
TESTS
| 0 | 60 | 0 |
226513509
|
# LUOGU_RID: 127442379
print("4")
| 38 | 92 | 307,200 |
183796920
|
# LUOGU_RID: 96524724
def dp(left, right):
color = {(i,j):0 for i in range(3) for j in range(3)} # 用字典代替二维列表表示九种方案,初始值均为0
if right-left == 1: # 只有一对括号的情况
for x in [(0,1), (0,2), (1,0), (2,0)]: # 一对配对的括号只有这四种合法的上色方案,下同
color[x] = 1 # 合法方案为1
elif bracket[left] == right: # 左右括号配对成功
inner = dp(left+1,right-1) # 递归计算内部“(...)”的方案
for x,y in [(0,1), (0,2), (1,0), (2,0)]:
for i in range(3):
for j in range(3):
if y==0 and i!=x or x==0 and j!=y: # 相邻颜色不能相同
color[(x,y)] += inner[(i,j)]
else: # 左右括号配对不成功
l = dp(left, bracket[left]) # 递归计算左边“(...)”的方案
r = dp(bracket[left]+1, right) # 递归计算右边“(...)”的方案
for x,y in color.keys():
for i in range(3):
for j in range(3):
if i==0 or i!=j: # 相邻要么都不上色,要么颜色不能相同
color[(x,y)] += l[(x,i)]*r[(j,y)]
return color # 返回包含九种方案个数的字典
s = input()
bracket = dict()
stack = [] # 查找配对括号的栈操作
for i in range(len(s)):
if s[i] == "(":
stack.append(i)
else:
bracket[stack.pop()] = i
result = sum(dp(0,len(s)-1).values()) # 要计算的结果就是把九种方案各自的个数加在一起,因为使用的是字典,所以直接对字典的值进行求和即可
print(result%1000000007)
|
Codeforces Round 106 (Div. 2)
|
CF
| 2,012 | 2 | 256 |
Coloring Brackets
|
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.
You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.
In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.
You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:
- Each bracket is either not colored any color, or is colored red, or is colored blue.
- For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.
- No two neighboring colored brackets have the same color.
Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).
|
The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.
|
Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).
| null |
Let's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below.
The two ways of coloring shown below are incorrect.
|
[{"input": "(())", "output": "12"}, {"input": "(()())", "output": "40"}, {"input": "()", "output": "4"}]
| 1,900 |
["dp"]
| 38 |
[{"input": "(())\r\n", "output": "12\r\n"}, {"input": "(()())\r\n", "output": "40\r\n"}, {"input": "()\r\n", "output": "4\r\n"}, {"input": "((()))\r\n", "output": "36\r\n"}, {"input": "()(())\r\n", "output": "42\r\n"}, {"input": "()()()\r\n", "output": "48\r\n"}, {"input": "(())(())\r\n", "output": "126\r\n"}, {"input": "()()()()()()()()()()()(())\r\n", "output": "9085632\r\n"}, {"input": "()(())()((()))\r\n", "output": "4428\r\n"}, {"input": "()()(())()(())\r\n", "output": "5040\r\n"}, {"input": "()()()()()()()()()()()()()()()()\r\n", "output": "411525376\r\n"}, {"input": "(()()())\r\n", "output": "136\r\n"}, {"input": "()(()())()\r\n", "output": "480\r\n"}, {"input": "(())()(())()\r\n", "output": "1476\r\n"}, {"input": "()()(()())(())()()()\r\n", "output": "195840\r\n"}, {"input": "()()()((((())))())()()()()()((()))()()(())()(((())))()(()())((())())((()())(((((()()()())()()())))))\r\n", "output": "932124942\r\n"}, {"input": "((()(((((()(()(())))()((((((((())))()(((((())()((((())())(()(()(())())((()))()((()))))))))))))))))))))\r\n", "output": "90824888\r\n"}, {"input": "((()))((())())((()()))()(())(()())(())()()()((()(((()())))()())()((((()((()((())))(())(()(())())))((()())()()()((())()))()(())(())))()(((((()())))))))\r\n", "output": "100627207\r\n"}, {"input": "()(((()((((()())))())(())(((((()(()()))))()()))((())))()())((())))(())()((()())())()(()(()())())(()())()(()(((((()))()((()()(())()(())(()((()((()))))()(())()()(()()()((((()())()))))()(((()(((((()()((((())(())))()())(()))(((())((()())(()))())(((()()()(()(())())())(()()()))))())))()((()(()()(()))())((())(()()()(())()))()()(((())))((()))(()((()(((()))((((()())))())(((())()(()((())))))))))))))))))))))\r\n", "output": "306199947\r\n"}, {"input": "(())(((((()()()()())(())))(()()((()(()(((((())(()())))())(()()(()((())()(()()))))))(())()())))()((()()())))()()(()(())())()())()(())(((((()(()()(((()())()))((())((((()()()))())(((())(((())))))))))))))\r\n", "output": "270087235\r\n"}, {"input": "()()()((()))(())(((())()(())(())))()()(((()((()()()))(()()(())(())))(()()((()((())(()()(()(())))))))(((())()((((()())))()(((()()())))()))()())))()(()(()())((()((()))))())(((((()())()((((()))(((((()())()))(((()()()((((((()()(())(()))((()(()(()((()((((()(((()(()()(()()((((()))()()()(()((((()(((())(((()()()(())()))((()()()(()))))())()))))(((((((()))())))(((()(()())(())))())))((((())(())())(((()()()))((()()))())(()))(())((()(()))(()()((()(()((()(())(()))()()))))))))))))))))))))))))))))))))))))))))))\r\n", "output": "461776571\r\n"}, {"input": "()()(((((()((()(())()(()))(()(()(()(()(())(())(())(()(()((())))()))())((()((()(()(((()(()))()(()())(()()()()(((((()(((()))((((())())(((()((((()((((((())())))()))))))))(())())))(((()((()))))((())(()()))()(()(()((()())())()))))((()))))()((())())(()())()())))())())())())()((()((())((()()())()())())()(())()))(()(()))())))(()()()())()())))))))((((()())))((((()()()))())((()(())))))()((()(((())()()()(()()()()()))))(((()())()))()()(((())(()())(()()))))))\r\n", "output": "66338682\r\n"}, {"input": "(()())()()()((((()(()()(())()((())(((()((()()(()))()))()()))))()(()(())(()))))))\r\n", "output": "639345575\r\n"}, {"input": "()((()))((((()((())((()()((((()))()()((())((()(((((()(()))((())()))((((())()(()(()))()))))))))))))))))))\r\n", "output": "391997323\r\n"}, {"input": "(((((()())))))()()()()()(())()()()((()()))()()()()()(((()(())))())(((()())))\r\n", "output": "422789312\r\n"}, {"input": "((()((()))()((()(()))())))()((()())())()(()())((()))(()())(())()(())()(())(())((()()))((()))()()()()(())()\r\n", "output": "140121189\r\n"}, {"input": "()()\r\n", "output": "14\r\n"}]
| false |
stdio
| null | true |
848/B
|
848
|
B
|
Python 3
|
TESTS
| 0 | 46 | 5,529,600 |
33455772
|
n, w, h = map(int, input().split(" "))
x = []
y = []
for _ in range(n):
g, p, t = map(int, input().split(" "))
if g == 1:
x.append([p,t])
else:
y.append([p,t])
xf = []
yf = []
for i in x:
for j in y:
p1 = i[0]
t1 = i[1]
p2 = j[0]
t2 = j[1]
if (p1+t1 == p2+t2):
y.append(x.remove(i))
x.append(y.remove(j))
else:
continue
for i in x:
print(i[0], h)
for i in y:
print(w, i[0])
| 23 | 779 | 75,673,600 |
130213364
|
import sys
input = sys.stdin.buffer.readline
def process(A, w, h):
d = {}
n = len(A)
for i in range(n):
gi, pi, ti = A[i]
if gi==1:
xi = pi
if (xi-ti) not in d:
d[(xi-ti)] = {'x': [], 'y': []}
d[(xi-ti)]['x'].append(i+1)
else:
yi = pi
if (yi-ti) not in d:
d[(yi-ti)] = {'x': [], 'y': []}
d[(yi-ti)]['y'].append(i+1)
answer = []
for x in d:
if len(d[x]['x']) > 0 and len(d[x]['y']) > 0:
d[x]['x'] = sorted(d[x]['x'], key=lambda a:A[a-1][1])
d[x]['y'] = sorted(d[x]['y'], key=lambda a:A[a-1][1], reverse=True)
original = []
for i1 in d[x]['y']:
original.append(i1)
for i1 in d[x]['x']:
original.append(i1)
#original = A B C | D E
m = len(d[x]['x'])
m2 = len(d[x]['y'])
for i in range(m):
i2 = d[x]['x'][i]
i1 = original[i]
answer.append([i1, A[i2-1][1], h])
for i in range(m2):
i2 = d[x]['y'][i]
i1 = original[m+i]
answer.append([i1, w, A[i2-1][1]])
else:
for i in d[x]['x']:
x1 = A[i-1][1]
answer.append([i, x1, h])
for i in d[x]['y']:
y = A[i-1][1]
answer.append([i, w, y])
answer = sorted(answer)
answer = [[x[1], x[2]] for x in answer]
return answer
n, w, h = [int(x) for x in input().split()]
A = []
for i in range(n):
a, b, c = [int(x) for x in input().split()]
A.append([a, b, c])
answer = process(A, w, h)
for x, y in answer:
print(f'{x} {y}')
|
Codeforces Round 431 (Div. 1)
|
CF
| 2,017 | 2 | 256 |
Rooter's Song
|
Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.
On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups:
- Vertical: stands at (xi, 0), moves in positive y direction (upwards);
- Horizontal: stands at (0, yi), moves in positive x direction (rightwards).
According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.
Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.
|
The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively.
The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
|
Output n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input.
| null |
The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure.
In the second example, no dancers collide.
|
[{"input": "8 10 8\n1 1 10\n1 4 13\n1 7 1\n1 8 2\n2 2 0\n2 5 14\n2 6 0\n2 6 1", "output": "4 8\n10 5\n8 8\n10 6\n10 2\n1 8\n7 8\n10 6"}, {"input": "3 2 3\n1 1 2\n2 1 1\n1 1 5", "output": "1 3\n2 1\n1 3"}]
| 1,900 |
["constructive algorithms", "data structures", "geometry", "implementation", "sortings", "two pointers"]
| 23 |
[{"input": "8 10 8\r\n1 1 10\r\n1 4 13\r\n1 7 1\r\n1 8 2\r\n2 2 0\r\n2 5 14\r\n2 6 0\r\n2 6 1\r\n", "output": "4 8\r\n10 5\r\n8 8\r\n10 6\r\n10 2\r\n1 8\r\n7 8\r\n10 6\r\n"}, {"input": "3 2 3\r\n1 1 2\r\n2 1 1\r\n1 1 5\r\n", "output": "1 3\r\n2 1\r\n1 3\r\n"}, {"input": "1 10 10\r\n1 8 1\r\n", "output": "8 10\r\n"}, {"input": "3 4 5\r\n1 3 9\r\n2 1 9\r\n1 2 8\r\n", "output": "3 5\r\n4 1\r\n2 5\r\n"}, {"input": "10 500 500\r\n2 88 59\r\n2 470 441\r\n1 340 500\r\n2 326 297\r\n1 74 45\r\n1 302 273\r\n1 132 103\r\n2 388 359\r\n1 97 68\r\n2 494 465\r\n", "output": "500 494\r\n97 500\r\n340 500\r\n302 500\r\n500 470\r\n500 88\r\n500 326\r\n132 500\r\n500 388\r\n74 500\r\n"}, {"input": "20 50000 50000\r\n2 45955 55488\r\n1 19804 29337\r\n2 3767 90811\r\n2 24025 33558\r\n1 46985 56518\r\n2 21094 30627\r\n2 5787 15320\r\n1 4262 91306\r\n2 37231 46764\r\n1 18125 27658\r\n1 36532 12317\r\n1 31330 40863\r\n1 18992 28525\r\n1 29387 38920\r\n1 44654 54187\r\n2 45485 55018\r\n2 36850 46383\r\n1 44649 54182\r\n1 40922 50455\r\n2 12781 99825\r\n", "output": "18125 50000\r\n50000 45955\r\n50000 12781\r\n31330 50000\r\n50000 5787\r\n40922 50000\r\n44649 50000\r\n50000 3767\r\n19804 50000\r\n44654 50000\r\n36532 50000\r\n50000 37231\r\n46985 50000\r\n50000 45485\r\n50000 21094\r\n18992 50000\r\n29387 50000\r\n50000 24025\r\n50000 36850\r\n4262 50000\r\n"}, {"input": "20 15 15\r\n2 7 100000\r\n1 2 100000\r\n2 1 100000\r\n1 9 100000\r\n2 4 100000\r\n2 3 100000\r\n2 14 100000\r\n1 6 100000\r\n1 10 100000\r\n2 5 100000\r\n2 13 100000\r\n1 8 100000\r\n1 13 100000\r\n1 14 100000\r\n2 10 100000\r\n1 5 100000\r\n1 11 100000\r\n1 12 100000\r\n1 1 100000\r\n2 2 100000\r\n", "output": "15 7\r\n15 2\r\n1 15\r\n9 15\r\n15 4\r\n15 3\r\n14 15\r\n6 15\r\n15 10\r\n5 15\r\n13 15\r\n8 15\r\n15 13\r\n15 14\r\n10 15\r\n15 5\r\n11 15\r\n12 15\r\n15 1\r\n2 15\r\n"}, {"input": "5 20 20\r\n1 15 3\r\n2 15 3\r\n2 3 1\r\n2 1 0\r\n1 16 4\r\n", "output": "16 20\r\n15 20\r\n20 3\r\n20 1\r\n20 15\r\n"}, {"input": "15 80 80\r\n2 36 4\r\n2 65 5\r\n1 31 2\r\n2 3 1\r\n2 62 0\r\n2 37 5\r\n1 16 4\r\n2 47 2\r\n1 17 5\r\n1 9 5\r\n2 2 0\r\n2 62 5\r\n2 34 2\r\n1 33 1\r\n2 69 3\r\n", "output": "80 37\r\n80 65\r\n31 80\r\n80 3\r\n80 62\r\n33 80\r\n16 80\r\n80 47\r\n17 80\r\n9 80\r\n80 2\r\n80 62\r\n80 36\r\n80 34\r\n80 69\r\n"}, {"input": "15 15 15\r\n1 10 1\r\n2 11 0\r\n2 6 4\r\n1 1 0\r\n1 7 5\r\n1 14 3\r\n1 3 1\r\n1 4 2\r\n1 9 0\r\n2 10 1\r\n1 12 1\r\n2 2 0\r\n1 5 3\r\n2 3 0\r\n2 4 2\r\n", "output": "15 10\r\n12 15\r\n3 15\r\n1 15\r\n15 2\r\n15 11\r\n7 15\r\n15 6\r\n10 15\r\n9 15\r\n14 15\r\n5 15\r\n15 4\r\n15 3\r\n4 15\r\n"}, {"input": "5 5 5\r\n1 1 0\r\n2 1 0\r\n2 2 1\r\n1 2 1\r\n2 4 3\r\n", "output": "5 2\r\n5 4\r\n2 5\r\n5 1\r\n1 5\r\n"}]
| false |
stdio
| null | true |
839/D
|
839
|
D
|
PyPy 3
|
TESTS
| 1 | 171 | 13,414,400 |
103996864
|
visited=[0]*(10**6+1)
lastfactor=[-1]*(10**6+1)
for j in range(2,10**6+1):
for k in range(2*j,10**6+1,j):
lastfactor[k]=j
n=int(input())
count=[0]*(10**6+1)
a=list(map(int,input().split()))
for i in range(n):
r=a[i]
curr=1
while curr*curr<=r:
if r%curr==0:
count[curr]+=1
count[r//curr]+=1
curr+=1
if (curr-1)*(curr-1)==r:
count[curr-1]-=1
ans=0
MOD=10**9+7
for i in range(10**6,1,-1):
t=count[i]
if t==0:
continue
ans=(ans+i*t*pow(2,t-1,MOD))%MOD
curr=1
while curr*curr<i:
if i%curr==0:
count[curr]-=t
count[i//curr]-=t
curr+=1
if curr*curr==i:
count[curr]-=t
print(ans)
| 47 | 1,106 | 51,404,800 |
70405101
|
import sys
useless = sys.stdin.readline()
a = list(map(int,sys.stdin.readline().split()))
n = 1000001
mod = 1000000007
cnt = [0]*n
for i in a:
cnt[i]+=1
arr = [0]*n
ans = 0
for i in range(n-1,1,-1):
j = sum(cnt[i::i])
if j > 0:
arr[i]= (j*pow(2,j-1,mod)-sum(arr[i::i]))%mod
ans=(ans+i*arr[i])%mod
sys.stdout.write(str(ans))
|
Codeforces Round 428 (Div. 2)
|
CF
| 2,017 | 3 | 256 |
Winter is here
|
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.
He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan if i1 < i2 < i3 < ... < ik and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan k·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans.
Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7).
Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.
|
The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his soldiers.
|
Print one integer — the strength of John Snow's army modulo 1000000007 (109 + 7).
| null |
In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12
|
[{"input": "3\n3 3 1", "output": "12"}, {"input": "4\n2 3 4 6", "output": "39"}]
| 2,200 |
["combinatorics", "dp", "math", "number theory"]
| 47 |
[{"input": "3\r\n3 3 1\r\n", "output": "12\r\n"}, {"input": "4\r\n2 3 4 6\r\n", "output": "39\r\n"}]
| false |
stdio
| null | true |
316/E1
|
316
|
E1
|
PyPy 3
|
TESTS1
| 0 | 122 | 819,200 |
106242658
|
import sys
f = [-1] * 200000
def fib(n):
if f[n] == -1:
k = n//2
while k > 0 and f[k] == -1:
k = k/2
for i in range(k, n):
f[i+1] = f[i] + f[i-1];
return f[n]
def solve(numbers, t, l, r, d):
if t == 1:
numbers[l-1] = r
elif t == 2:
total = 0
for j in range(l-1, r):
total = total + numbers[j] * fib(j)
print(total)
else:
for j in range(l-1, r):
numbers[j] = numbers[j] + d
n, m = sys.stdin.readline().rstrip().split()
n = int(n)
m = int(m)
numbers = list(map(lambda x: int (x), sys.stdin.readline().rstrip().split()))
f[0] = f[1] = 1
for i in range(m):
line = sys.stdin.readline().rstrip().split()
t = int(line[0])
d = 0
if t == 1:
l = int(line[1])
r = int(line[2])
elif t == 2:
l = int(line[1])
r = int(line[2])
else:
l = int(line[1])
r = int(line[2])
d = int(line[3])
solve(numbers, t, l, r, d)
| 19 | 904 | 307,200 |
104278377
|
from sys import *
from math import *
mod = 1000000000
f = [0 for i in range(200)]
f[0] = f[1] = 1
for i in range(2, 200):
f[i] = f[i - 1] + f[i - 2]
n, m = stdin.readline().split()
n = int(n)
m = int(m)
a = list(map(int, stdin.readline().split()))
for i in range(m):
tp, x, y = stdin.readline().split()
tp = int(tp)
x = int(x)
y = int(y)
if tp == 1:
x -= 1
a[x] = y
else:
s = 0
x -= 1
y -= 1
for p in range(y - x + 1):
s += f[p] * a[x + p]
print(s % mod)
|
ABBYY Cup 3.0
|
ICPC
| 2,013 | 3 | 256 |
Summer Homework
|
By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:
You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:
1. For given numbers xi and vi assign value vi to element axi.
2. For given numbers li and ri you've got to calculate sum $$\sum_{x=0}^{r_i-l_i} (f_x \cdot a_{l_i+x})$$, where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2.
3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri).
Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
|
The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type:
- if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105);
- if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n);
- if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105).
The input limits for scoring 30 points are (subproblem E1):
- It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.
The input limits for scoring 70 points are (subproblems E1+E2):
- It is guaranteed that there will be queries of the 1-st and 2-nd type only.
The input limits for scoring 100 points are (subproblems E1+E2+E3):
- No extra limitations.
|
For each query print the calculated sum modulo 1000000000 (109).
| null | null |
[{"input": "5 5\n1 3 1 2 4\n2 1 4\n2 1 5\n2 2 4\n1 3 10\n2 1 5", "output": "12\n32\n8\n50"}, {"input": "5 4\n1 3 1 2 4\n3 1 4 1\n2 2 4\n1 2 10\n2 1 5", "output": "12\n45"}]
| 1,500 |
["brute force", "data structures"]
| 19 |
[{"input": "5 5\r\n1 3 1 2 4\r\n2 1 4\r\n2 1 5\r\n2 2 4\r\n1 3 10\r\n2 1 5\r\n", "output": "12\r\n32\r\n8\r\n50\r\n"}, {"input": "1 3\r\n2\r\n2 1 1\r\n1 1 3\r\n2 1 1\r\n", "output": "2\r\n3\r\n"}, {"input": "11 11\r\n6 1 9 0 2 9 1 6 2 8 0\r\n2 9 9\r\n1 9 0\r\n1 1 8\r\n2 2 5\r\n2 7 11\r\n2 2 8\r\n1 3 2\r\n1 10 0\r\n2 1 8\r\n2 9 11\r\n1 9 7\r\n", "output": "2\r\n16\r\n31\r\n147\r\n234\r\n0\r\n"}, {"input": "11 18\r\n14 13 18 17 14 17 13 3 0 3 21\r\n2 6 9\r\n2 1 6\r\n2 5 7\r\n2 1 3\r\n2 1 9\r\n2 3 9\r\n2 2 5\r\n2 7 10\r\n2 1 5\r\n2 4 6\r\n2 10 11\r\n2 4 5\r\n2 2 8\r\n2 3 9\r\n2 1 5\r\n2 2 3\r\n2 2 6\r\n1 4 19\r\n", "output": "36\r\n320\r\n57\r\n63\r\n552\r\n203\r\n107\r\n25\r\n184\r\n65\r\n24\r\n31\r\n335\r\n203\r\n184\r\n31\r\n192\r\n"}, {"input": "12 26\r\n18 5 13 38 33 11 30 24 6 34 11 30\r\n2 1 12\r\n2 1 12\r\n2 1 11\r\n1 3 15\r\n1 11 5\r\n2 1 11\r\n2 2 10\r\n2 3 12\r\n2 2 11\r\n2 3 11\r\n2 3 10\r\n2 3 11\r\n1 9 37\r\n1 2 37\r\n2 1 11\r\n1 3 30\r\n2 2 12\r\n1 4 42\r\n2 3 10\r\n2 1 11\r\n1 11 26\r\n1 7 37\r\n2 3 11\r\n1 7 30\r\n1 6 40\r\n1 7 13\r\n", "output": "8683\r\n8683\r\n4363\r\n3833\r\n2084\r\n3106\r\n2359\r\n1456\r\n1286\r\n1456\r\n4919\r\n5727\r\n1708\r\n4961\r\n2627\r\n"}]
| false |
stdio
| null | true |
863/D
|
863
|
D
|
PyPy 3
|
TESTS
| 1 | 156 | 102,400 |
81022183
|
import sys
import math
from collections import defaultdict,deque
def get(ind ,arr):
n = len(arr)
for i in range(n):
t,l,r = arr[i]
if t == 1:
if l <= ind <= r:
if ind == l:
ind = r
else:
ind -= 1
continue
if t == 2:
if l <=ind <= r:
ind = (r - ind + l)
continue
return ind
n,q,m = map(int,sys.stdin.readline().split())
arr = list(map(int,sys.stdin.readline().split()))
l = []
for i in range(q):
a,b,c = map(int,sys.stdin.readline().split())
l.append([a,b,c])
l.reverse()
b = list(map(int,sys.stdin.readline().split()))
ans = []
for i in range(m):
x = get(b[i],l)
ans.append(x)
print(*ans)
| 23 | 670 | 27,238,400 |
161145571
|
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, q, m = map(int, input().split())
A = list(map(int, input().split()))
Q = []
for i in range(q):
t, l, r = map(int, input().split())
l, r = l-1, r-1
Q.append((t, l, r))
B = list(map(int, input().split()))
B = [b-1 for b in B]
Q.reverse()
ans = []
for i, b in enumerate(B):
for t, l, r in Q:
if l <= b <= r:
if t == 1:
if b != l:
b -= 1
else:
b = r
else:
b = r-(b-l)
ans.append(A[b])
print(*ans)
|
Educational Codeforces Round 29
|
ICPC
| 2,017 | 2 | 256 |
Yet Another Array Queries Problem
|
You are given an array a of size n, and q queries to it. There are queries of two types:
- 1 li ri — perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li ≤ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari;
- 2 li ri — reverse the segment [li, ri].
There are m important indices in the array b1, b2, ..., bm. For each i such that 1 ≤ i ≤ m you have to output the number that will have index bi in the array after all queries are performed.
|
The first line contains three integer numbers n, q and m (1 ≤ n, q ≤ 2·105, 1 ≤ m ≤ 100).
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109).
Then q lines follow. i-th of them contains three integer numbers ti, li, ri, where ti is the type of i-th query, and [li, ri] is the segment where this query is performed (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n).
The last line contains m integer numbers b1, b2, ..., bm (1 ≤ bi ≤ n) — important indices of the array.
|
Print m numbers, i-th of which is equal to the number at index bi after all queries are done.
| null | null |
[{"input": "6 3 5\n1 2 3 4 5 6\n2 1 3\n2 3 6\n1 1 6\n2 2 1 5 3", "output": "3 3 1 5 2"}]
| 1,800 |
["data structures", "implementation"]
| 23 |
[{"input": "6 3 5\r\n1 2 3 4 5 6\r\n2 1 3\r\n2 3 6\r\n1 1 6\r\n2 2 1 5 3\r\n", "output": "3 3 1 5 2 \r\n"}, {"input": "5 2 5\r\n64 3 4 665 2\r\n1 1 3\r\n2 1 5\r\n1 2 3 4 5\r\n", "output": "2 665 3 64 4 \r\n"}, {"input": "1 1 1\r\n474812122\r\n2 1 1\r\n1\r\n", "output": "474812122 \r\n"}]
| false |
stdio
| null | true |
852/G
|
852
|
G
|
Python 3
|
TESTS
| 1 | 46 | 204,800 |
30031423
|
n,m=map(int,input().split(" "))
word=[]
pattern=[]
count=0
for i in range (0,n):
word.append(input())
for i in range (0,m):
pattern.append(input())
for i in range (0,m):
for j in range (0,n):
flag=1
if(len(word[j])==len(pattern[i])):
for k in range(len(word[j])):
if(word[j][k] != pattern[i][k] and pattern[i][k]!='?' ):
flag=0
if(flag==1):
count=count+1
#print(pattern[i])
else:
if(len(pattern[i])>len(word[j]) and (len(pattern[i])-len(word[j]))<=3):
for p in range(0,len(pattern[i])):
if(pattern[i][p]=='?'):
w1=pattern[i].replace(pattern[i][p],"")
if(word[j] ==w1):
count=count+1
print(count)
| 15 | 872 | 31,846,400 |
105100981
|
import sys
from itertools import product
from collections import defaultdict
r=sys.stdin.readline
N,M=map(int,r().split())
words=defaultdict(int)
tb=['a','b','c','d','e']
st=set()
cnt=0
res=""
def dfs(u):
global res,cnt
if u==l:
if res in st:
return
if words[res]>0: cnt+=words[res]
st.add(res)
return
if pattern[u]=='?':
for i in range(6):
if i!=5:res+=tb[i]
dfs(u+1)
if i!=5:res=res[:-1]
else:
res+=pattern[u]
dfs(u+1)
res=res[:-1]
for _ in range(N):
word=r().strip()
words[word]+=1
for _ in range(M):
cnt=0
st.clear()
pattern=r().strip()
l=len(pattern)
res=""
dfs(0)
print(cnt)
|
Bubble Cup X - Finals [Online Mirror]
|
ICPC
| 2,017 | 2 | 256 |
Bathroom terminal
|
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:
"Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle.
You are given N strings which represent words. Each word is of the maximum length L and consists of characters 'a'-'e'. You are also given M strings which represent patterns. Pattern is a string of length ≤ L and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin."
Help Smith escape.
|
The first line of input contains two integers N and M (1 ≤ N ≤ 100 000, 1 ≤ M ≤ 5000), representing the number of words and patterns respectively.
The next N lines represent each word, and after those N lines, following M lines represent each pattern. Each word and each pattern has a maximum length L (1 ≤ L ≤ 50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.
|
Output contains M lines and each line consists of one integer, representing the number of words that match the corresponding pattern.
| null |
If we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively.
|
[{"input": "3 1\nabc\naec\nac\na?c", "output": "3"}]
| 1,700 |
["implementation"]
| 15 |
[{"input": "3 1\r\nabc\r\naec\r\nac\r\na?c\r\n", "output": "3\r\n"}, {"input": "22 2\r\naaaab\r\naaabb\r\naabab\r\naabbb\r\nabaab\r\nababb\r\nabbab\r\nabbbb\r\naaab\r\naabb\r\nabab\r\nabbb\r\naab\r\nabb\r\nab\r\ncccd\r\nccdd\r\ncdcd\r\ncddd\r\nccd\r\ncdd\r\ncd\r\na???b\r\nc??d\r\n", "output": "15\r\n7\r\n"}, {"input": "15 6\r\naaa\r\naaabbb\r\naaabb\r\naaaaa\r\naaaaaa\r\naaaa\r\naaabbbb\r\naaaaa\r\naaaaaa\r\naaaa\r\naaabbbb\r\naabbbb\r\naa\r\naa\r\naab\r\na\r\n?a?\r\n??\r\n?aa?bb?\r\n?aa?aa?\r\n??aaa?\r\n", "output": "0\r\n4\r\n2\r\n5\r\n6\r\n7\r\n"}]
| false |
stdio
| null | true |
975/E
|
975
|
E
|
Python 3
|
TESTS
| 1 | 77 | 7,065,600 |
38005912
|
n, q = map(int, input().split())
polygon = []
for _ in range(n):
polygon.append([int(x) for x in input().split()])
#print(polygon)
requests = []
for _ in range(q):
requests.append([int(x) for x in input().split()])
#print(requests)
time = len(requests)
#print(time)
# формула центроида:
# xc = (x1 + x2 + ... + xn) / n
# yc = (y1 + y2 + ... +yn) / n
print('3.4142135624 -1.4142135624')
print('2.0000000000 0.0000000000')
print('0.5857864376 -1.4142135624')
| 31 | 2,136 | 23,449,600 |
38080955
|
#!/usr/bin/env python3
from math import hypot
[n, q] = map(int, input().strip().split())
xys = [tuple(map(int, input().strip().split())) for _ in range(n)]
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
dxys = [(xys[(i + 1) % n][0] - xys[i][0], xys[(i + 1) % n][1] - xys[i][1]) for i in range(n)]
S = 3 * sum((x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))
Sx = sum((dx + 2*x) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))
Sy = sum((dy + 2*y) * (x*dy - y*dx) for (x, y), (dx, dy) in zip(xys, dxys))
#Sy = sum((2*dx*dy + 3*x*dx + 3*x*dy + 6*x*y)*dy for (x, y), (dx, dy) in zip(xys, dxys))
for p in [2, 3]:
while S % p == Sx % p == Sy % p == 0:
S //= p
Sx //= p
Sy //= p
xyms = [(S*x - Sx, S*y - Sy) for x, y in xys]
hs = [hypot(x, y) for x, y in xyms]
def to_coord(x, y):
return (x + Sx) / S, (y + Sy) / S
hangs = (0, 1)
hang_on = None
cx, cy = 0.0, 0.0
# hang on u
def get_v(v):
if hang_on is None:
return xyms[v]
else:
ux, uy = xyms[hang_on]
vx, vy = xyms[v]
h = hs[hang_on]
return ((uy * vx - ux * vy) / h, (ux * vx + uy * vy) / h)
#def ss(v1, v2):
# return tuple(vi + vj for vi, vj in zip(v1, v2))
#def disp():
# print ('hangs on', hang_on, 'of', hangs)
# print ('center', to_coord(cx, cy))
# print ({i: to_coord(*ss(get_v(i), (cx, cy))) for i in range(n)})
#disp()
for qi in qis:
if qi[0] == 1:
_, f, t = qi # 1-indexation
s = hangs[1 - hangs.index(f - 1)]
dx, dy = get_v(s)
cx += dx
cy += dy - hs[s]
hang_on = s
hangs = (s, t - 1)
# print ('{} --> {}'.format(f - 1, t - 1))
# disp()
else:
_, v = qi # 1-indexation
dx, dy = get_v(v - 1)
print (*to_coord(cx + dx, cy + dy))
|
Codeforces Round 478 (Div. 2)
|
CF
| 2,018 | 3 | 256 |
Hag's Khashba
|
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.
|
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$3\leq n \leq 10\,000$$$, $$$1 \leq q \leq 200000$$$) — the number of vertices in the polygon and the number of queries.
The next $$$n$$$ lines describe the wooden polygon, the $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$|x_i|, |y_i|\leq 10^8$$$) — the coordinates of the $$$i$$$-th vertex of the polygon. It is guaranteed that polygon is strictly convex and the vertices are given in the counter-clockwise order and all vertices are distinct.
The next $$$q$$$ lines describe the queries, one per line. Each query starts with its type $$$1$$$ or $$$2$$$. Each query of the first type continues with two integers $$$f$$$ and $$$t$$$ ($$$1 \le f, t \le n$$$) — the vertex the pin is taken from, and the vertex the pin is put to and the polygon finishes rotating. It is guaranteed that the vertex $$$f$$$ contains a pin. Each query of the second type continues with a single integer $$$v$$$ ($$$1 \le v \le n$$$) — the vertex the coordinates of which Hag should tell his father.
It is guaranteed that there is at least one query of the second type.
|
The output should contain the answer to each query of second type — two numbers in a separate line. Your answer is considered correct, if its absolute or relative error does not exceed $$$10^{-4}$$$.
Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}$$$
| null |
In the first test note the initial and the final state of the wooden polygon.
Red Triangle is the initial state and the green one is the triangle after rotation around $$$(2,0)$$$.
In the second sample note that the polygon rotates $$$180$$$ degrees counter-clockwise or clockwise direction (it does not matter), because Hag's father makes sure that the polygon is stable and his son does not trick him.
|
[{"input": "3 4\n0 0\n2 0\n2 2\n1 1 2\n2 1\n2 2\n2 3", "output": "3.4142135624 -1.4142135624\n2.0000000000 0.0000000000\n0.5857864376 -1.4142135624"}, {"input": "3 2\n-1 1\n0 0\n1 1\n1 1 2\n2 1", "output": "1.0000000000 -1.0000000000"}]
| 2,600 |
["geometry"]
| 31 |
[{"input": "3 4\r\n0 0\r\n2 0\r\n2 2\r\n1 1 2\r\n2 1\r\n2 2\r\n2 3\r\n", "output": "3.4142135624 -1.4142135624\r\n2.0000000000 0.0000000000\r\n0.5857864376 -1.4142135624\r\n"}, {"input": "3 2\r\n-1 1\r\n0 0\r\n1 1\r\n1 1 2\r\n2 1\r\n", "output": "1.0000000000 -1.0000000000\r\n"}, {"input": "10 10\r\n0 -100000000\r\n1 -100000000\r\n1566 -99999999\r\n2088 -99999997\r\n2610 -99999994\r\n3132 -99999990\r\n3654 -99999985\r\n4176 -99999979\r\n4698 -99999972\r\n5220 -99999964\r\n1 2 5\r\n2 1\r\n1 1 7\r\n2 5\r\n1 5 4\r\n1 4 2\r\n2 8\r\n1 7 9\r\n2 1\r\n1 2 10\r\n", "output": "0.0000000000 -100000000.0000000000\r\n-7.3726558373 -100002609.9964835122\r\n-129.8654413032 -100003125.4302210321\r\n-114.4079442212 -100007299.4544525659\r\n"}, {"input": "4 10\r\n0 0\r\n2 0\r\n2 2\r\n0 2\r\n2 3\r\n2 1\r\n2 1\r\n1 1 1\r\n2 3\r\n1 2 4\r\n1 4 4\r\n2 4\r\n1 1 3\r\n2 3\r\n", "output": "2.0000000000 2.0000000000\r\n0.0000000000 0.0000000000\r\n0.0000000000 0.0000000000\r\n0.5857864376 -1.4142135624\r\n4.8284271247 -2.8284271247\r\n6.2426406871 -4.2426406871\r\n"}, {"input": "3 2\r\n0 0\r\n1 0\r\n1566 1\r\n1 2 1\r\n2 3\r\n", "output": "0.0006381620 -1566.0003192846\r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
submission_path = sys.argv[3]
# Read input to count type 2 queries
with open(input_path, 'r') as f:
n, q = map(int, f.readline().split())
for _ in range(n):
f.readline() # skip vertices
type2_count = 0
for _ in range(q):
parts = f.readline().split()
if parts[0] == '2':
type2_count += 1
# Read correct and submission outputs
with open(output_path, 'r') as f:
correct = [line.strip() for line in f]
with open(submission_path, 'r') as f:
submission = [line.strip() for line in f]
# Check line count
if len(correct) != len(submission) or len(correct) != type2_count:
print(0)
return
# Check each line
for c_line, s_line in zip(correct, submission):
try:
c_x, c_y = map(float, c_line.split())
s_x, s_y = map(float, s_line.split())
except:
print(0)
return
# Check x
dx = abs(s_x - c_x)
max_x = max(1.0, abs(c_x))
if dx > 1e-4 * max_x:
print(0)
return
# Check y
dy = abs(s_y - c_y)
max_y = max(1.0, abs(c_y))
if dy > 1e-4 * max_y:
print(0)
return
# All checks passed
print(1)
if __name__ == "__main__":
main()
| true |
898/C
|
898
|
C
|
PyPy 3
|
TESTS
| 1 | 155 | 409,600 |
62421625
|
n=int(input())
#s=input().split()
from collections import defaultdict
d=defaultdict(list)
for i in range(n):
s=input().split()
a=s[0]
b=s[1:]
for x in b:
if x not in d[a]:
d[a].append(x)
#d[a].append(b)
for i in d:
curr=d[i]
ans=curr [:]
curr.sort(key=lambda x:-len(x))
le=len(curr)
for x in range(le-1,-1,-1):
for j in range(0,x):
# print(curr[j],curr[x])
if curr[j].endswith(curr[x]):
try:
ans.remove(curr[x])
except:
pass
#print('hi')
d[i]=ans
print(len(d))
for i in d:
print(i,end=' ')
print(*d[i])
| 59 | 62 | 5,632,000 |
33294470
|
n = int(input())
d = dict()
for i in range(n):
a = input().split()
if a[0] not in d:
d[a[0]] = []
for j in range(2, len(a)):
a[j] = a[j][::-1]
d[a[0]] += a[2:]
print(len(d))
for x in d:
a = d[x]
a.sort(reverse = True)
##print(a)
b = [a[0]]
for i in range(1, len(a)):
if a[i - 1][:len(a[i])] != a[i]:
b += [a[i]]
for i in range(len(b)):
b[i] = b[i][::-1]
print(x, len(b), *b)
|
Codeforces Round 451 (Div. 2)
|
CF
| 2,017 | 2 | 256 |
Phone Numbers
|
Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.
Vasya decided to organize information about the phone numbers of friends. You will be given n strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.
Vasya also believes that if the phone number a is a suffix of the phone number b (that is, the number b ends up with a), and both numbers are written by Vasya as the phone numbers of the same person, then a is recorded without the city code and it should not be taken into account.
The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers x and y, and x is a suffix of y (that is, y ends in x), then you shouldn't print number x. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.
Read the examples to understand statement and format of the output better.
|
First line contains the integer n (1 ≤ n ≤ 20) — number of entries in Vasya's phone books.
The following n lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros.
|
Print out the ordered information about the phone numbers of Vasya's friends. First output m — number of friends that are found in Vasya's phone books.
The following m lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend.
Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order.
| null | null |
[{"input": "2\nivan 1 00123\nmasha 1 00123", "output": "2\nmasha 1 00123\nivan 1 00123"}, {"input": "3\nkarl 2 612 12\npetr 1 12\nkatya 1 612", "output": "3\nkatya 1 612\npetr 1 12\nkarl 1 612"}, {"input": "4\nivan 3 123 123 456\nivan 2 456 456\nivan 8 789 3 23 6 56 9 89 2\ndasha 2 23 789", "output": "2\ndasha 2 23 789\nivan 4 789 123 2 456"}]
| 1,400 |
["implementation", "strings"]
| 59 |
[{"input": "2\r\nivan 1 00123\r\nmasha 1 00123\r\n", "output": "2\r\nmasha 1 00123 \r\nivan 1 00123 \r\n"}, {"input": "3\r\nkarl 2 612 12\r\npetr 1 12\r\nkatya 1 612\r\n", "output": "3\r\nkatya 1 612 \r\npetr 1 12 \r\nkarl 1 612 \r\n"}, {"input": "4\r\nivan 3 123 123 456\r\nivan 2 456 456\r\nivan 8 789 3 23 6 56 9 89 2\r\ndasha 2 23 789\r\n", "output": "2\r\ndasha 2 789 23 \r\nivan 4 789 123 456 2 \r\n"}, {"input": "20\r\nnxj 6 7 6 6 7 7 7\r\nnxj 10 8 5 1 7 6 1 0 7 0 6\r\nnxj 2 6 5\r\nnxj 10 6 7 6 6 5 8 3 6 6 8\r\nnxj 10 6 1 7 6 7 1 8 7 8 6\r\nnxj 10 8 5 8 6 5 6 1 9 6 3\r\nnxj 10 8 1 6 4 8 0 4 6 0 1\r\nnxj 9 2 6 6 8 1 1 3 6 6\r\nnxj 10 8 9 0 9 1 3 2 3 2 3\r\nnxj 6 6 7 0 8 1 2\r\nnxj 7 7 7 8 1 3 6 9\r\nnxj 10 2 7 0 1 5 1 9 1 2 6\r\nnxj 6 9 6 9 6 3 7\r\nnxj 9 0 1 7 8 2 6 6 5 6\r\nnxj 4 0 2 3 7\r\nnxj 10 0 4 0 6 1 1 8 8 4 7\r\nnxj 8 4 6 2 6 6 1 2 7\r\nnxj 10 5 3 4 2 1 0 7 0 7 6\r\nnxj 10 9 6 0 6 1 6 2 1 9 6\r\nnxj 4 2 9 0 1\r\n", "output": "1\r\nnxj 10 0 3 2 1 4 7 8 5 9 6 \r\n"}, {"input": "20\r\nl 6 02 02 2 02 02 2\r\nl 8 8 8 8 2 62 13 31 3\r\ne 9 0 91 0 0 60 91 60 2 44\r\ne 9 69 2 1 44 2 91 66 1 70\r\nl 9 7 27 27 3 1 3 7 80 81\r\nl 9 2 1 13 7 2 10 02 3 92\r\ne 9 0 15 3 5 5 15 91 09 44\r\nl 7 2 50 4 5 98 31 98\r\nl 3 26 7 3\r\ne 6 7 5 0 62 65 91\r\nl 8 80 0 4 0 2 2 0 13\r\nl 9 19 13 02 2 1 4 19 26 02\r\nl 10 7 39 7 9 22 22 26 2 90 4\r\ne 7 65 2 36 0 34 57 9\r\ne 8 13 02 09 91 73 5 36 62\r\nl 9 75 0 10 8 76 7 82 8 34\r\nl 7 34 0 19 80 6 4 7\r\ne 5 4 2 5 7 2\r\ne 7 4 02 69 7 07 20 2\r\nl 4 8 2 1 63\r\n", "output": "2\r\ne 18 15 62 07 70 91 57 02 66 65 69 09 13 20 44 73 34 60 36 \r\nl 21 27 50 22 63 75 19 26 90 02 92 62 31 10 76 82 80 98 81 39 34 13 \r\n"}, {"input": "20\r\no 10 6 6 97 45 6 6 6 6 5 6\r\nl 8 5 5 5 19 59 5 8 5\r\nj 9 2 30 58 2 2 1 0 30 4\r\nc 10 1 1 7 51 7 7 51 1 1 1\r\no 9 7 97 87 70 2 19 2 14 6\r\ne 6 26 6 6 6 26 5\r\ng 9 3 3 3 3 3 78 69 8 9\r\nl 8 8 01 1 5 8 41 72 3\r\nz 10 1 2 2 2 9 1 9 1 6 7\r\ng 8 7 78 05 36 7 3 67 9\r\no 5 6 9 9 7 7\r\ne 10 30 2 1 1 2 5 04 0 6 6\r\ne 9 30 30 2 2 0 26 30 79 8\r\nt 10 2 2 9 29 7 7 7 9 2 9\r\nc 7 7 51 1 31 2 7 4\r\nc 9 83 1 6 78 94 74 54 8 32\r\ng 8 4 1 01 9 39 28 6 6\r\nt 7 9 2 01 4 4 9 58\r\nj 5 0 1 58 02 4\r\nw 10 80 0 91 91 06 91 9 9 27 7\r\n", "output": "9\r\nw 5 91 27 06 9 80 \r\nt 6 7 58 4 29 2 01 \r\ne 8 8 79 5 30 2 26 04 1 \r\nl 8 72 3 19 59 41 01 5 8 \r\nj 5 4 30 58 1 02 \r\nz 5 6 1 9 2 7 \r\ng 10 05 39 4 3 36 01 67 69 28 78 \r\no 8 14 87 97 6 19 70 45 2 \r\nc 10 83 51 31 54 74 32 7 94 78 6 \r\n"}, {"input": "1\r\negew 5 3 123 23 1234 134\r\n", "output": "1\r\negew 3 123 134 1234 \r\n"}]
| false |
stdio
|
import sys
from collections import defaultdict
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
submission_path = sys.argv[3]
# Read input and build friends data
friends = defaultdict(set)
with open(input_path, 'r') as f:
n = int(f.readline())
for _ in range(n):
parts = f.readline().strip().split()
name = parts[0]
numbers = parts[2:]
friends[name].update(numbers) # Add all numbers, duplicates in same line are handled via set
# Read submission output
submission_friends = set()
try:
with open(submission_path, 'r') as f:
lines = f.read().splitlines()
except:
print(0)
return
if not lines:
print(0)
return
# Check m line
try:
m_line = lines[0]
m = int(m_line)
except:
print(0)
return
if m != len(friends):
print(0)
return
submission_lines = lines[1:]
if len(submission_lines) != m:
print(0)
return
for line in submission_lines:
parts = line.strip().split()
if len(parts) < 2:
print(0)
return
name = parts[0]
if name not in friends:
print(0)
return
submission_friends.add(name)
try:
k = int(parts[1])
except:
print(0)
return
numbers = parts[2:]
if len(numbers) != k:
print(0)
return
# Check for duplicates in submission's numbers
if len(set(numbers)) != k:
print(0)
return
# Check all numbers are present in friends' merged set
merged_numbers = friends[name]
for num in numbers:
if num not in merged_numbers:
print(0)
return
# Check no two numbers in submission are suffix of each other
for i in range(len(numbers)):
for j in range(i+1, len(numbers)):
a = numbers[i]
b = numbers[j]
if (len(a) >= len(b) and a.endswith(b)) or (len(b) >= len(a) and b.endswith(a)):
print(0)
return
# Check every merged number is either in submission or is a suffix of some submission number
for merged_num in merged_numbers:
if merged_num in numbers:
continue
found = False
for num in numbers:
if len(merged_num) <= len(num) and num.endswith(merged_num):
found = True
break
if not found:
print(0)
return
# Check all friends are present in submission
if submission_friends != set(friends.keys()):
print(0)
return
# All checks passed
print(100)
if __name__ == "__main__":
main()
| true |
986/B
|
986
|
B
|
PyPy 3
|
TESTS
| 3 | 140 | 1,433,600 |
99558388
|
class BIT():
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
def to_sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= (i & -i)
return s
def add(self, i, x):
while i <= self.n:
self.data[i] += x
i += (i & -i)
def get(self, i, j):
return self.to_sum(j)-self.to_sum(i-1)
n = int(input())
a = list(map(int, input().split()))
b = [(v, i + 1) for i, v in enumerate(a)]
b.sort()
bit = BIT(n + 10)
inversion = 0
for value, index in b:
inversion += bit.get(1, index)
bit.add(index, 1)
if n % 2 == 0:
if inversion % 2 == 0:
print("Petr")
else:
print("Um_nik")
else:
if inversion % 2 != 0:
print("Petr")
else:
print("Um_nik")
| 24 | 498 | 60,825,600 |
176109577
|
n=int(input())
a=list(map(int,input().split()))
if sum(a[i]==i+1 for i in range(n))>=n//1000:print("Petr")
else:print("Um_nik")
# Made By Mostafa_Khaled
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
986/B
|
986
|
B
|
PyPy 3-64
|
TESTS
| 2 | 46 | 0 |
232298157
|
import sys
input = sys.stdin.buffer.readline
def process(A):
n = len(A)
cycle = [0 for i in range(n+1)]
answer = 0
for i in range(1, n+1):
if cycle[i]==0:
my_cycle = [i]
cycle[i] = 1
while True:
x = my_cycle[-1]
y = A[x-1]
if cycle[y]==1:
break
cycle[y] = 1
my_cycle.append(y)
# print(my_cycle)
answer+=(len(my_cycle)-1)
if answer % 2==n % 2:
print('Petr')
else:
print('Um_Nik')
n = int(input())
A = [int(x) for x in input().split()]
process(A)
| 24 | 654 | 61,030,400 |
38739617
|
import math
n = int(input())
a = list(map(int, input().split()))
if n < 10: print('Petr')
else: print(['Petr', 'Um_nik'][sum(a[i] == i + 1 for i in range(n)) < math.log(n) / 3])
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
986/B
|
986
|
B
|
PyPy 3
|
TESTS
| 2 | 92 | 20,172,800 |
115365991
|
n = int(input())
p = list(map(lambda x: int(x) - 1, input().split()))
vis = [False] * n
odd = 0
for x in range(n):
if vis[x]:
continue
sz = 0
while not vis[x]:
sz += 1
vis[x] = True
x = p[x]
odd ^= (sz - 1) % 2
print('Petr' if (3 * n + odd) % 2 == 0 else 'Alex')
| 24 | 670 | 61,337,600 |
40105676
|
import random
n = int(input())
a = list(map(int,input().split(' ')))
c = 0
for i in range(1,n+1):
if a[i-1]==i:
c += 1
if c >= n//1000:
print("Petr")
else:
print("Um_nik")
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
813/F
|
813
|
F
|
Python 3
|
TESTS
| 1 | 31 | 4,915,200 |
27952713
|
class DoubleGraf:
def __init__(self, n):
self.points = [set() for i in range(n)]
self.n = n
def add(self, a, b):
self.points[a].add(b)
self.points[b].add(a)
def rem(self, a, b):
self.points[a].discard(b)
self.points[b].discard(a)
def line(self, a, b):
return a in self.points[b]
def look(self):
def rec(cur, point):
for subpoint in point:
if self.colors[subpoint] is None:
self.colors[subpoint] = cur
rec(not cur, self.points[subpoint])
elif self.colors[subpoint] != cur:
return False
cur = not cur
return True
self.colors = [None for i in range(self.n)]
self.colors[0] = False
cur = True
return rec(cur, self.points[0])
def __repr__(self):
return str(self.points)
def __init__(a, b):
if g.line(a, b):
g.rem(a, b)
else:
g.add(a, b)
return g.look()
if __name__ == '__main__':
__test__ = 0
if __test__:
tests = []
for i in range(len(tests)):
print(i + 1, end="\t")
print(tests[i][0] == __init__(*tests[i][1]), end="\t")
print(tests[i][0], "<<", __init__(*tests[i][1]))
exit()
n, q = map(int, input().split())
g = DoubleGraf(n)
for i in range(q):
print("YES" if __init__(*map(lambda x: int(x)-1, input().split())) else "NO")
| 25 | 1,185 | 83,660,800 |
215838651
|
from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def f(u, v, w):
return (u * n2 + v) * n2 + w
def g(u, v):
return u * n2 + v
def get_root(s):
while s ^ root[s]:
s = root[s]
return s
def unite(s, t, i):
s, t = get_root(s), get_root(t)
if s == t:
return
if rank[s] < rank[t]:
s, t = t, s
c1, c2, c3, c4 = s, t, 0, root[t]
if rank[s] == rank[t]:
rank[s] += 1
c3 = 1
root[t] = s
st1.append(f(c1, c2, c3))
st2.append(g(i, c4))
return
def same(s, t):
return True if get_root(s) == get_root(t) else False
def undo(x, y):
s, z = divmod(x, n2 * n2)
t, c = divmod(z, n2)
rt = y % n2
rank[s] -= c
root[t] = rt
return
n, q = map(int, input().split())
d = defaultdict(lambda : -1)
u, v = [], []
x, y = [0] * q, [0] * q
for i in range(q):
x0, y0 = map(int, input().split())
if x0 > y0:
x0, y0 = y0, x0
x[i], y[i] = x0, y0
if d[(x0, y0)] == -1:
d[(x0, y0)] = i
else:
u.append(d[(x0, y0)])
v.append(i - 1)
d[(x0, y0)] = -1
for i in d.values():
if i ^ -1:
u.append(i)
v.append(q - 1)
l1 = pow(2, (q + 1).bit_length())
l2 = 2 * l1
s0 = [0] * l2
for u0, v0 in zip(u, v):
l0 = u0 + l1
r0 = v0 + l1
while l0 <= r0:
if l0 & 1:
s0[l0] += 1
l0 += 1
l0 >>= 1
if not r0 & 1 and l0 <= r0:
s0[r0] += 1
r0 -= 1
r0 >>= 1
for i in range(1, l2):
s0[i] += s0[i - 1]
now = [0] + list(s0)
tree = [-1] * now[l2]
m = len(u)
for i in range(m):
l0 = u[i] + l1
r0 = v[i] + l1
while l0 <= r0:
if l0 & 1:
tree[now[l0]] = u[i]
now[l0] += 1
l0 += 1
l0 >>= 1
if not r0 & 1 and l0 <= r0:
tree[now[r0]] = u[i]
now[r0] += 1
r0 -= 1
r0 >>= 1
n += 5
n2 = 2 * n
root = [i for i in range(n2)]
rank = [1 for _ in range(n2)]
s0 = [0] + s0
st1, st2 = [], []
now = 1
ng = 0
for i in range(s0[1], s0[2]):
j = tree[i]
u0, v0 = get_root(x[j]), get_root(y[j])
u1, v1 = get_root(x[j] + n), get_root(y[j] + n)
if u0 == v0 and u0 == v1:
continue
if u0 == u1:
ng -= 1
if v0 == v1:
ng -= 1
unite(u0, v1, 1)
unite(u1, v0, 1)
if same(u0, u1):
ng += 1
visit = [0] * l2
cnt = [0] * l2
cnt[1] = ng
ans = []
while len(ans) ^ q:
if now >= l1:
ans.append("YES" if not ng else "NO")
if now >= l1 or visit[now << 1 ^ 1]:
visit[now] = 1
while st1 and st2[-1] // n2 == now:
undo(st1.pop(), st2.pop())
now >>= 1
ng = cnt[now]
continue
now = now << 1 if not visit[now << 1] else now << 1 ^ 1
for i in range(s0[now], s0[now + 1]):
j = tree[i]
u0, v0 = get_root(x[j]), get_root(y[j])
u1, v1 = get_root(x[j] + n), get_root(y[j] + n)
if u0 == v0 and u0 == v1:
continue
if u0 == u1:
ng -= 1
if v0 == v1:
ng -= 1
unite(u0, v1, now)
unite(u1, v0, now)
if same(u0, u1):
ng += 1
cnt[now] = ng
sys.stdout.write("\n".join(map(str, ans)))
|
Educational Codeforces Round 22
|
ICPC
| 2,017 | 6 | 256 |
Bipartite Checking
|
You are given an undirected graph consisting of n vertices. Initially there are no edges in the graph. Also you are given q queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color).
|
The first line contains two integers n and q (2 ≤ n, q ≤ 100000).
Then q lines follow. ith line contains two numbers xi and yi (1 ≤ xi < yi ≤ n). These numbers describe ith query: if there is an edge between vertices xi and yi, then remove it, otherwise add it.
|
Print q lines. ith line must contain YES if the graph is bipartite after ith query, and NO otherwise.
| null | null |
[{"input": "3 5\n2 3\n1 3\n1 2\n1 2\n1 2", "output": "YES\nYES\nNO\nYES\nNO"}]
| 2,500 |
["data structures", "dsu", "graphs"]
| 25 |
[{"input": "3 5\r\n2 3\r\n1 3\r\n1 2\r\n1 2\r\n1 2\r\n", "output": "YES\r\nYES\r\nNO\r\nYES\r\nNO\r\n"}, {"input": "5 10\r\n1 5\r\n2 5\r\n2 4\r\n1 4\r\n4 5\r\n2 4\r\n2 5\r\n1 4\r\n2 3\r\n1 2\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nYES\r\nYES\r\nYES\r\n"}, {"input": "10 20\r\n1 10\r\n5 7\r\n1 2\r\n3 5\r\n3 6\r\n4 9\r\n3 4\r\n6 9\r\n4 8\r\n6 9\r\n7 8\r\n3 8\r\n7 10\r\n2 7\r\n3 7\r\n5 9\r\n6 7\r\n4 6\r\n2 10\r\n8 10\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\n"}, {"input": "10 30\r\n5 6\r\n5 9\r\n4 9\r\n6 7\r\n7 9\r\n3 10\r\n5 6\r\n5 7\r\n6 10\r\n2 4\r\n2 6\r\n2 5\r\n3 7\r\n1 8\r\n8 9\r\n3 4\r\n3 5\r\n1 9\r\n6 7\r\n4 8\r\n4 5\r\n1 5\r\n2 3\r\n4 10\r\n1 7\r\n2 8\r\n3 10\r\n1 7\r\n1 7\r\n3 8\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\n"}, {"input": "10 40\r\n6 9\r\n1 5\r\n2 6\r\n2 5\r\n7 9\r\n7 9\r\n5 6\r\n5 8\r\n6 9\r\n1 7\r\n5 6\r\n1 7\r\n1 9\r\n4 5\r\n4 6\r\n6 8\r\n7 8\r\n1 8\r\n5 7\r\n1 7\r\n8 9\r\n5 6\r\n6 7\r\n1 4\r\n3 7\r\n9 10\r\n1 7\r\n4 7\r\n4 10\r\n3 8\r\n7 10\r\n3 6\r\n1 10\r\n6 10\r\n8 9\r\n8 10\r\n7 10\r\n2 5\r\n1 9\r\n3 6\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nNO\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\n"}, {"input": "30 40\r\n5 15\r\n13 16\r\n12 17\r\n19 23\r\n1 27\r\n16 25\r\n20 21\r\n6 18\r\n10 17\r\n7 13\r\n20 24\r\n4 17\r\n8 12\r\n12 25\r\n25 29\r\n4 7\r\n1 14\r\n2 21\r\n4 26\r\n2 13\r\n20 24\r\n23 24\r\n8 16\r\n16 18\r\n8 10\r\n25 28\r\n4 22\r\n11 25\r\n13 24\r\n19 22\r\n18 20\r\n22 30\r\n4 13\r\n28 29\r\n6 13\r\n18 22\r\n18 28\r\n4 20\r\n14 21\r\n5 6\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\n"}, {"input": "50 60\r\n7 36\r\n43 45\r\n12 17\r\n10 40\r\n30 47\r\n18 30\r\n3 9\r\n5 6\r\n13 49\r\n5 26\r\n4 20\r\n5 50\r\n27 41\r\n3 21\r\n15 43\r\n24 41\r\n6 30\r\n40 50\r\n8 13\r\n9 21\r\n2 47\r\n23 26\r\n21 22\r\n15 31\r\n28 38\r\n1 50\r\n24 35\r\n2 13\r\n4 33\r\n14 42\r\n10 28\r\n3 5\r\n18 19\r\n9 40\r\n11 21\r\n22 36\r\n6 11\r\n36 44\r\n20 35\r\n7 38\r\n9 33\r\n29 31\r\n6 14\r\n22 32\r\n27 48\r\n19 31\r\n39 47\r\n12 50\r\n8 38\r\n35 36\r\n1 43\r\n7 49\r\n10 25\r\n10 21\r\n14 15\r\n1 44\r\n8 32\r\n17 50\r\n42 45\r\n13 44\r\n", "output": "YES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nYES\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\nNO\r\n"}]
| false |
stdio
| null | true |
908/G
|
908
|
G
|
Python 3
|
TESTS
| 1 | 997 | 0 |
57311629
|
n=int(input())
sum=0
for i in range(1,n+1):
t=str(i)
m=sorted(t)
g=[str(j) for j in m]
j=int("".join(g))
sum=sum+j
print(sum)
| 20 | 77 | 0 |
113281106
|
# Problem G
num = input()
num_list = []
for i in range(len(num)):
num_list.append(int(num[i]))
myMod = (10 ** 9) + 7
length = len(num_list)
f = [0] * (length + 1)
t = [1] * (length + 1)
for i in range(length):
f[i+1] = (f[i] * 10 + 1) % myMod
t[i+1] = (t[i] * 10) % myMod
ans = 0
for i in range(1, 10):
dp = [0] * (length + 1)
for j in range(length):
dp[j+1] = (dp[j] * i + (10 - i) * (dp[j] * 10 + t[j])) % myMod
c = 0
ctr = 0
for k in num_list:
z = min(i, k)
o = k - z
ans += o * (dp[length-1-ctr] * t[c+1] + f[c+1] * t[length-1-ctr]) % myMod
ans += z * (dp[length-1-ctr] * t[c] + f[c] * t[length-1-ctr]) % myMod
ans %= myMod
c += k >= i
ctr += 1
ans += f[c]
if ans >= myMod:
ans -= myMod
print(ans)
|
Good Bye 2017
|
CF
| 2,017 | 2 | 256 |
New Year and Original Order
|
Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555.
Given a number X, compute $$\sum_{1 \leq k \leq X} S(k)$$ modulo 109 + 7.
|
The first line of input will contain the integer X (1 ≤ X ≤ 10700).
|
Print a single integer, the answer to the question.
| null |
The first few values of S are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 12. The sum of these values is 195.
|
[{"input": "21", "output": "195"}, {"input": "345342", "output": "390548434"}]
| 2,800 |
["dp", "math"]
| 20 |
[{"input": "21\r\n", "output": "195\r\n"}, {"input": "345342\r\n", "output": "390548434\r\n"}, {"input": "9438174368\r\n", "output": "419438859\r\n"}, {"input": "33340691714056185860211260984431382156326935244157\r\n", "output": "683387308\r\n"}, {"input": "60659389952427965488066632743799525603106037644498358605868947137979908494800892265261453803791510334840960342863677552781925982028425181448855359993703120262947850907075964314040305228976226486729250\r\n", "output": "654963480\r\n"}, {"input": "44649014054971081213608137817466046254652492627741860478258558206397113198232823859870363821007188476405951611069347299689170240023979048198711745011542774268179055311013054073075176122755643483380248999657649211459997766221072399103579977409770898200358240970169892326442892826731631357561876251276209119521202062222947560634301788787748428236988789594458520867663257476744168528121470923031438015546006185059454402637036376247785881323277542968298682307854655591317046086531554595892680980142608410\r\n", "output": "382433601\r\n"}, {"input": "87180\r\n", "output": "273914491\r\n"}, {"input": "404075833601771942667259010375375556744823902383758960785823552761999143572376325949809260679742124753881851158698439457386070260861271136645763680151691355801985707548363664714643023957647369701126324673656050885747545042127147214166479318245077239696802674619402305982303576335159698484641718860881491887951521487208762\r\n", "output": "770789762\r\n"}]
| false |
stdio
| null | true |
171/C
|
171
|
C
|
Python 3
|
TESTS
| 1 | 186 | 0 |
52143309
|
a = list(map(int, input().split()))
print(3*sum(a[1:]))
| 41 | 92 | 0 |
206952329
|
a=input().split()
s=0
for i in range(1,int(a[0])+1):
s+=i*eval(a[i])
print(s)
|
April Fools Day Contest
|
ICPC
| 2,012 | 2 | 256 |
A Piece of Cake
|
How to make a cake you'll never eat.
Ingredients.
- 2 carrots
- 0 calories
- 100 g chocolate spread
- 1 pack of flour
- 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
|
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
|
Output a single integer.
| null | null |
[{"input": "4 1 2 3 4", "output": "30"}]
| 2,000 |
["*special", "implementation"]
| 41 |
[{"input": "4 1 2 3 4\r\n", "output": "30\r\n"}, {"input": "4 802 765 992 1\r\n", "output": "5312\r\n"}, {"input": "4 220 380 729 969\r\n", "output": "7043\r\n"}, {"input": "3 887 104 641\r\n", "output": "3018\r\n"}, {"input": "12 378 724 582 387 583 241 294 159 198 653 369 418\r\n", "output": "30198\r\n"}, {"input": "14 36 901 516 623 703 971 304 394 491 525 464 219 183 648\r\n", "output": "49351\r\n"}, {"input": "3 287 979 395\r\n", "output": "3430\r\n"}, {"input": "19 702 667 743 976 908 728 134 106 380 193 214 71 920 114 587 543 817 248 537\r\n", "output": "87024\r\n"}, {"input": "11 739 752 364 649 626 702 444 913 681 529 959\r\n", "output": "45653\r\n"}, {"input": "19 196 392 738 103 119 872 900 189 65 113 260 985 228 537 217 735 785 445 636\r\n", "output": "92576\r\n"}, {"input": "22 196 690 553 822 392 687 425 763 216 73 525 412 155 263 205 965 825 105 153 580 218 103\r\n", "output": "96555\r\n"}, {"input": "10 136 641 472 872 115 607 197 19 494 577\r\n", "output": "22286\r\n"}, {"input": "10 5 659 259 120 421 165 194 637 577 39\r\n", "output": "17712\r\n"}, {"input": "5 472 4 724 577 157\r\n", "output": "5745\r\n"}, {"input": "23 486 261 249 312 592 411 874 397 18 70 417 512 338 679 517 997 938 328 418 793 522 745 59\r\n", "output": "141284\r\n"}, {"input": "17 644 532 255 57 108 413 51 284 364 300 597 646 712 470 42 730 231\r\n", "output": "61016\r\n"}, {"input": "26 932 569 829 138 565 766 466 673 559 678 417 618 930 751 840 184 809 639 287 550 923 341 851 209 987 252\r\n", "output": "207547\r\n"}, {"input": "16 29 672 601 178 603 860 6 431 114 463 588 788 712 956 895 19\r\n", "output": "73502\r\n"}, {"input": "5 336 860 760 835 498\r\n", "output": "10166\r\n"}, {"input": "29 384 110 78 925 320 755 176 690 784 848 981 653 140 840 659 262 954 812 850 431 523 495 16 233 70 352 92 520 877\r\n", "output": "216056\r\n"}, {"input": "21 256 260 390 24 185 400 780 51 89 253 900 760 906 730 599 565 992 243 66 531 364\r\n", "output": "114365\r\n"}, {"input": "19 26 380 823 787 422 605 306 298 885 562 249 965 277 124 365 56 175 144 309\r\n", "output": "67719\r\n"}, {"input": "41 595 215 495 884 470 176 126 536 398 181 816 114 251 328 901 674 933 206 662 507 458 601 162 735 725 217 481 591 51 791 355 646 696 540 530 165 717 346 391 114 527\r\n", "output": "406104\r\n"}, {"input": "20 228 779 225 819 142 849 24 494 45 172 95 207 908 510 424 78 100 166 869 456\r\n", "output": "78186\r\n"}, {"input": "15 254 996 341 109 402 688 501 206 905 398 124 373 313 943 515\r\n", "output": "57959\r\n"}, {"input": "45 657 700 898 830 795 104 427 995 219 505 95 385 64 241 196 318 927 228 428 329 606 619 535 200 707 660 574 19 292 88 872 950 788 769 779 272 563 896 267 782 400 52 857 154 293\r\n", "output": "507143\r\n"}, {"input": "41 473 219 972 591 238 267 209 464 467 916 814 40 625 105 820 496 54 297 264 523 570 828 418 527 299 509 269 156 663 562 900 826 471 561 416 710 828 315 864 985 230\r\n", "output": "463602\r\n"}, {"input": "48 25 856 782 535 41 527 832 306 49 91 824 158 618 122 357 887 969 710 138 868 536 610 118 642 9 946 958 873 931 878 549 646 733 20 180 775 547 11 771 287 103 594 135 411 406 492 989 375\r\n", "output": "597376\r\n"}, {"input": "57 817 933 427 116 51 69 125 687 717 688 307 594 927 643 17 638 823 482 184 525 943 161 318 226 296 419 632 478 97 697 370 915 320 797 30 371 556 847 748 272 224 746 557 151 388 264 789 211 746 663 426 688 825 744 914 811 853\r\n", "output": "900997\r\n"}, {"input": "55 980 951 933 349 865 252 836 585 313 392 431 751 354 656 496 601 497 885 865 976 786 300 638 211 678 152 645 281 654 187 517 633 137 139 672 692 81 507 968 84 589 398 835 944 744 331 234 931 906 99 906 691 89 234 592\r\n", "output": "810147\r\n"}]
| false |
stdio
| null | true |
839/D
|
839
|
D
|
PyPy 3-64
|
TESTS
| 1 | 421 | 19,865,600 |
231993374
|
M=10**9+7
n=int(input())
a=[int(e) for e in input().split()]
R=10**6
c=[0]*(R+1)
for i in range(n):
j=1
while j*j<=a[i]:
if a[i]%j==0:
c[j]+=1
J=a[i]//j
if J!=j:
c[J]+=1
j+=1
F=[0]*(R+1)
for i in range(R,0,-1):
F[i]=c[i]*pow(2,c[i]-1,M)
j=2*i
while j<=R:
#F[i]-=F[j]
j+=i
print(sum(i*F[i] for i in range(2,R+1))%M)
| 47 | 1,434 | 35,942,400 |
186589212
|
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
mod = pow(10, 9) + 7
a = list(map(int, input().split()))
l = max(a) + 5
cnt = [0] * l
for i in a:
cnt[i] += 1
dp = [0] * l
pow2 = [1]
for _ in range(n + 5):
pow2.append(2 * pow2[-1] % mod)
ans = 0
for i in range(l - 1, 1, -1):
s = 0
for j in range(i, l, i):
s += cnt[j]
if not s:
continue
dpi = s * pow2[s - 1] % mod
for j in range(2 * i, l, i):
dpi = (dpi - dp[j]) % mod
ans += dpi * i % mod
ans %= mod
dp[i] = dpi
print(ans)
|
Codeforces Round 428 (Div. 2)
|
CF
| 2,017 | 3 | 256 |
Winter is here
|
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.
He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan if i1 < i2 < i3 < ... < ik and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan k·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans.
Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7).
Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.
|
The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his soldiers.
|
Print one integer — the strength of John Snow's army modulo 1000000007 (109 + 7).
| null |
In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12
|
[{"input": "3\n3 3 1", "output": "12"}, {"input": "4\n2 3 4 6", "output": "39"}]
| 2,200 |
["combinatorics", "dp", "math", "number theory"]
| 47 |
[{"input": "3\r\n3 3 1\r\n", "output": "12\r\n"}, {"input": "4\r\n2 3 4 6\r\n", "output": "39\r\n"}]
| false |
stdio
| null | true |
986/B
|
986
|
B
|
PyPy 3
|
TESTS
| 4 | 77 | 0 |
172417015
|
n = int(input())
l = [int(x) for x in input().split()]
if n%5==0:
print("Petr")
else:
print("Um_nik")
| 24 | 748 | 47,308,800 |
164539860
|
print(('Um_nik', 'Petr')[int(input()) // 1000 <= sum(i == x for i, x in enumerate(map(int, input().split()), 1))])
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
379/B
|
379
|
B
|
PyPy 3
|
TESTS
| 0 | 77 | 0 |
216445885
|
n = int(input())
arr = list(map(int,input().split()))
ans = 'PRL' * arr[0]
for i in range(1,n):
ans += 'R' +' PLR' * arr[i]
print(ans)
| 15 | 46 | 1,024,000 |
5574523
|
n=int(input())
A=list(map(int,input().split()))
import sys
ans=""
x=0
ind=0
for i in range(n):
if(i!=0):
ans+="R"
if(i!=n-1):
ans+="PRL"*A[i]
else:
ans+="PLR"*A[i]
sys.stdout.write(ans)
|
Good Bye 2013
|
CF
| 2,013 | 1 | 256 |
New Year Present
|
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.
Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left.
Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row.
Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.
|
The first line contains integer n (2 ≤ n ≤ 300) — the number of wallets. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 300).
It is guaranteed that at least one ai is positive.
|
Print the sequence that consists of k (1 ≤ k ≤ 106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet n.
As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.
| null | null |
[{"input": "2\n1 2", "output": "PRPLRP"}, {"input": "4\n0 2 0 2", "output": "RPRRPLLPLRRRP"}]
| 1,200 |
["constructive algorithms", "implementation"]
| 15 |
[{"input": "2\r\n1 2\r\n", "output": "PRPLRP"}, {"input": "4\r\n0 2 0 2\r\n", "output": "RPRRPLLPLRRRP"}, {"input": "10\r\n2 3 4 0 0 1 1 3 4 2\r\n", "output": "PRPRPRRRPRPRPRPRPLPLPLLLLLPLPLPRPRPRRRRRPRPRPLPLLLLLLPLL"}, {"input": "10\r\n0 0 0 0 0 0 0 0 1 0\r\n", "output": "RRRRRRRRPR"}, {"input": "5\r\n2 2 2 2 2\r\n", "output": "PRPRPRPRPLPLPLPLPRRRRP"}, {"input": "2\r\n6 0\r\n", "output": "PRLPRLPRLPRLPRLP"}]
| false |
stdio
|
import sys
def main(input_path, output_path, sub_output_path):
with open(input_path) as f:
n = int(f.readline())
a = list(map(int, f.readline().split()))
with open(sub_output_path) as f:
s = f.read().strip()
if len(s) < 1 or len(s) > 10**6:
print(0)
return
valid_chars = {'L', 'R', 'P'}
for c in s:
if c not in valid_chars:
print(0)
return
coins = [0] * n
current_pos = 1 # 1-based position
prev_was_p = False
for c in s:
if c == 'P':
if prev_was_p:
print(0)
return
coins[current_pos - 1] += 1
prev_was_p = True
else:
if c == 'L':
if current_pos == 1:
print(0)
return
current_pos -= 1
else: # 'R'
if current_pos == n:
print(0)
return
current_pos += 1
prev_was_p = False
if coins == a:
print(1)
else:
print(0)
if __name__ == "__main__":
input_path = sys.argv[1]
output_path = sys.argv[2]
sub_output_path = sys.argv[3]
main(input_path, output_path, sub_output_path)
| true |
852/E
|
852
|
E
|
PyPy 3
|
TESTS
| 1 | 93 | 307,200 |
30117160
|
print(4+0+0)
| 12 | 420 | 15,155,200 |
34109480
|
n = int(input())
cnt = [[] for _ in range(n)]
for i in range (n - 1):
fr, to = map(int, input().split())
cnt[fr - 1].append(to - 1);
cnt[to - 1].append(fr - 1);
l = 0
for i in range(n):
if (len(cnt[i]) == 1):
l += 1
ans = (n - l) * pow(2, n - l, 10 ** 9 + 7)
ans += l * pow(2, n - l + 1, 10 ** 9 + 7)
print (ans % (10 ** 9 + 7))
|
Bubble Cup X - Finals [Online Mirror]
|
ICPC
| 2,017 | 1 | 256 |
Casinos and travel
|
John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N.
John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules.
To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey.
He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey.
In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7.
|
In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities.
In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road.
|
Output one number, the answer to the problem modulo 109 + 7.
| null |
Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4.
Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
|
[{"input": "2\n1 2", "output": "4"}, {"input": "3\n1 2\n2 3", "output": "10"}]
| 2,100 |
["dp"]
| 12 |
[{"input": "2\r\n1 2\r\n", "output": "4\r\n"}, {"input": "3\r\n1 2\r\n2 3\r\n", "output": "10\r\n"}, {"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "24\r\n"}]
| false |
stdio
| null | true |
852/G
|
852
|
G
|
Python 3
|
TESTS
| 1 | 46 | 0 |
30338778
|
import sys, itertools
n, m = map(int, sys.stdin.readline().split())
lines = []
for _ in range(n):
lines.append(sys.stdin.readline().strip())
for _ in range(m):
c = 0
p = sys.stdin.readline().strip().split('?')
s = [(p[0],)]
o = ('a','b','c','d','e','')
for d in p[1:]:
s.append(o)
s.append((d,))
s = map(lambda x: ''.join(x),itertools.product(*s))
for l in lines:
if l in s:
c += 1
print(c)
| 15 | 872 | 31,846,400 |
105100981
|
import sys
from itertools import product
from collections import defaultdict
r=sys.stdin.readline
N,M=map(int,r().split())
words=defaultdict(int)
tb=['a','b','c','d','e']
st=set()
cnt=0
res=""
def dfs(u):
global res,cnt
if u==l:
if res in st:
return
if words[res]>0: cnt+=words[res]
st.add(res)
return
if pattern[u]=='?':
for i in range(6):
if i!=5:res+=tb[i]
dfs(u+1)
if i!=5:res=res[:-1]
else:
res+=pattern[u]
dfs(u+1)
res=res[:-1]
for _ in range(N):
word=r().strip()
words[word]+=1
for _ in range(M):
cnt=0
st.clear()
pattern=r().strip()
l=len(pattern)
res=""
dfs(0)
print(cnt)
|
Bubble Cup X - Finals [Online Mirror]
|
ICPC
| 2,017 | 2 | 256 |
Bathroom terminal
|
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:
"Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle.
You are given N strings which represent words. Each word is of the maximum length L and consists of characters 'a'-'e'. You are also given M strings which represent patterns. Pattern is a string of length ≤ L and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin."
Help Smith escape.
|
The first line of input contains two integers N and M (1 ≤ N ≤ 100 000, 1 ≤ M ≤ 5000), representing the number of words and patterns respectively.
The next N lines represent each word, and after those N lines, following M lines represent each pattern. Each word and each pattern has a maximum length L (1 ≤ L ≤ 50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.
|
Output contains M lines and each line consists of one integer, representing the number of words that match the corresponding pattern.
| null |
If we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively.
|
[{"input": "3 1\nabc\naec\nac\na?c", "output": "3"}]
| 1,700 |
["implementation"]
| 15 |
[{"input": "3 1\r\nabc\r\naec\r\nac\r\na?c\r\n", "output": "3\r\n"}, {"input": "22 2\r\naaaab\r\naaabb\r\naabab\r\naabbb\r\nabaab\r\nababb\r\nabbab\r\nabbbb\r\naaab\r\naabb\r\nabab\r\nabbb\r\naab\r\nabb\r\nab\r\ncccd\r\nccdd\r\ncdcd\r\ncddd\r\nccd\r\ncdd\r\ncd\r\na???b\r\nc??d\r\n", "output": "15\r\n7\r\n"}, {"input": "15 6\r\naaa\r\naaabbb\r\naaabb\r\naaaaa\r\naaaaaa\r\naaaa\r\naaabbbb\r\naaaaa\r\naaaaaa\r\naaaa\r\naaabbbb\r\naabbbb\r\naa\r\naa\r\naab\r\na\r\n?a?\r\n??\r\n?aa?bb?\r\n?aa?aa?\r\n??aaa?\r\n", "output": "0\r\n4\r\n2\r\n5\r\n6\r\n7\r\n"}]
| false |
stdio
| null | true |
852/C
|
852
|
C
|
PyPy 3
|
TESTS
| 1 | 93 | 0 |
30117081
|
print("0 2 1")
| 29 | 155 | 12,083,200 |
217501588
|
n = int(input())
a = input().split()
for i in range(n):
a[i] = int(a[i])
b = []
for i in range(0, n-1):
b.append((a[i]-(n-a[i+1]), i))
b.append((a[n-1]-(n-a[0]), n-1))
b = sorted(b)
ans = n*[0]
for i in range(n):
# the line segment at index b[i][1]
ans[b[i][1]] = i
for i in range(n):
print(ans[i], end = ' ')
|
Bubble Cup X - Finals [Online Mirror]
|
ICPC
| 2,017 | 0.5 | 256 |
Property
|
Bill is a famous mathematician in BubbleLand. Thanks to his revolutionary math discoveries he was able to make enough money to build a beautiful house. Unfortunately, for not paying property tax on time, court decided to punish Bill by making him lose a part of his property.
Bill’s property can be observed as a convex regular 2n-sided polygon A0 A1... A2n - 1 A2n, A2n = A0, with sides of the exactly 1 meter in length.
Court rules for removing part of his property are as follows:
- Split every edge Ak Ak + 1, k = 0... 2n - 1 in n equal parts of size 1 / n with points P0, P1, ..., Pn - 1
- On every edge A2k A2k + 1, k = 0... n - 1 court will choose one point B2k = Pi for some i = 0, ..., n - 1 such that $$\bigcup_{i=0}^{n-1} B_{2i} = \bigcup_{i=0}^{n-1} P_i$$
- On every edge A2k + 1A2k + 2, k = 0...n - 1 Bill will choose one point B2k + 1 = Pi for some i = 0, ..., n - 1 such that $$\bigcup_{i=0}^{n-1} B_{2i+1} = \bigcup_{i=0}^{n-1} P_i$$
- Bill gets to keep property inside of 2n-sided polygon B0 B1... B2n - 1
Luckily, Bill found out which B2k points the court chose. Even though he is a great mathematician, his house is very big and he has a hard time calculating. Therefore, he is asking you to help him choose points so he maximizes area of property he can keep.
|
The first line contains one integer number n (2 ≤ n ≤ 50000), representing number of edges of 2n-sided polygon.
The second line contains n distinct integer numbers B2k (0 ≤ B2k ≤ n - 1, k = 0... n - 1) separated by a single space, representing points the court chose. If B2k = i, the court chose point Pi on side A2k A2k + 1.
|
Output contains n distinct integers separated by a single space representing points B1, B3, ..., B2n - 1 Bill should choose in order to maximize the property area. If there are multiple solutions that maximize the area, return any of them.
| null |
To maximize area Bill should choose points: B1 = P0, B3 = P2, B5 = P1
|
[{"input": "3\n0 1 2", "output": "0 2 1"}]
| 2,100 |
["greedy", "sortings"]
| 29 |
[{"input": "3\r\n0 1 2\r\n", "output": "0 2 1\r\n"}, {"input": "10\r\n0 1 2 3 4 5 6 7 8 9\r\n", "output": "0 1 2 3 5 6 7 8 9 4\r\n"}, {"input": "10\r\n1 7 3 6 8 2 4 5 0 9\r\n", "output": "2 6 5 9 7 1 4 0 3 8\r\n"}, {"input": "10\r\n4 9 7 2 3 5 6 1 8 0\r\n", "output": "8 9 6 1 4 7 2 5 3 0\r\n"}, {"input": "5\r\n1 2 3 0 4\r\n", "output": "1 3 0 2 4\r\n"}, {"input": "5\r\n3 0 2 1 4\r\n", "output": "2 0 1 3 4\r\n"}, {"input": "5\r\n2 4 3 0 1\r\n", "output": "3 4 2 0 1\r\n"}, {"input": "17\r\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\r\n", "output": "0 1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 8\r\n"}, {"input": "17\r\n5 13 12 8 4 7 15 6 0 1 2 10 9 14 3 16 11\r\n", "output": "8 15 11 5 3 13 12 2 0 1 4 9 14 7 10 16 6\r\n"}, {"input": "17\r\n7 10 12 11 13 0 9 6 4 2 15 3 5 8 14 16 1\r\n", "output": "8 12 14 15 6 3 7 4 0 9 11 2 5 13 16 10 1\r\n"}, {"input": "50\r\n15 14 37 47 44 7 1 0 39 18 26 25 24 48 4 41 33 12 31 45 43 5 16 23 8 49 34 35 29 2 9 40 36 11 27 46 17 38 19 6 28 21 32 13 22 42 10 20 30 3\r\n", "output": "6 27 47 49 28 1 0 15 34 17 29 25 41 30 20 43 19 16 44 48 22 4 14 9 35 46 40 38 8 2 24 45 21 13 42 37 33 36 5 11 23 32 18 12 39 31 7 26 10 3\r\n"}, {"input": "50\r\n28 37 42 14 19 23 35 25 22 30 36 12 4 46 38 29 41 2 24 43 7 21 11 13 32 48 0 6 1 40 49 16 15 8 20 10 9 34 45 31 17 5 47 26 33 44 27 18 3 39\r\n", "output": "34 45 30 14 17 31 33 22 28 36 25 2 26 48 37 40 19 8 38 27 10 13 7 21 47 24 0 1 15 49 35 12 6 9 11 3 18 46 43 23 5 29 42 32 44 41 20 4 16 39\r\n"}, {"input": "50\r\n48 24 13 25 40 2 41 17 35 0 28 29 37 10 6 5 36 12 46 21 23 33 15 45 18 16 47 19 20 22 8 30 7 1 31 49 27 4 43 14 11 38 39 34 9 44 32 3 26 42\r\n", "output": "43 13 15 38 19 21 33 28 11 4 31 39 24 2 1 17 26 34 41 22 30 25 35 36 9 37 40 16 18 6 14 12 0 8 48 45 7 23 32 3 27 47 44 20 29 46 10 5 42 49\r\n"}, {"input": "100\r\n54 93 37 83 59 66 74 19 6 75 76 81 41 97 22 86 80 13 55 3 32 40 18 96 95 44 33 53 79 88 28 70 63 35 25 38 85 36 58 98 87 12 52 0 16 61 17 72 46 62 31 20 43 34 4 7 60 15 73 1 78 48 69 30 8 14 94 84 91 27 2 64 57 42 71 51 29 89 5 11 26 90 99 77 68 82 24 65 23 21 67 92 47 10 56 49 9 45 39 50\r\n", "output": "86 77 69 84 75 83 46 4 35 88 90 72 80 68 57 92 45 25 17 6 26 16 61 99 81 31 37 78 93 62 50 79 49 18 20 74 70 48 89 97 53 21 12 2 30 32 43 65 58 44 11 19 29 9 0 24 28 40 27 33 76 64 52 8 3 59 96 94 66 5 23 71 51 60 73 34 67 47 1 7 63 98 95 85 87 56 42 39 10 38 91 82 14 22 55 15 13 36 41 54\r\n"}, {"input": "100\r\n10 35 37 66 56 68 22 41 52 36 3 90 32 20 0 43 75 59 40 25 97 94 8 91 33 26 79 69 78 49 72 53 61 15 65 82 76 58 4 17 73 99 92 31 95 85 96 98 27 62 74 51 21 14 63 80 11 16 64 57 84 30 86 42 2 60 29 19 81 23 83 87 71 38 54 13 5 48 39 55 6 24 18 9 12 46 89 1 77 28 50 45 88 67 93 70 47 7 44 34\r\n", "output": "13 28 53 66 70 42 24 46 37 8 45 67 16 1 10 63 79 50 25 68 97 52 49 71 20 55 87 85 76 64 72 59 29 35 86 89 80 23 3 41 94 98 69 75 95 96 99 73 39 82 74 27 7 30 84 43 5 34 65 83 60 61 77 12 22 38 14 51 54 57 93 90 58 44 26 0 17 36 47 21 6 9 4 2 19 81 40 33 56 32 48 78 88 91 92 62 18 15 31 11\r\n"}, {"input": "100\r\n60 61 7 27 72 82 46 3 65 67 29 90 68 37 36 31 38 80 79 15 19 47 42 70 54 33 83 30 35 69 59 78 18 17 40 62 20 5 57 26 2 98 9 63 16 81 6 86 77 91 92 32 28 94 52 45 21 71 73 76 74 50 34 4 23 25 1 39 41 95 48 84 51 85 58 43 99 97 56 8 88 75 96 11 55 13 10 53 87 0 44 12 24 14 66 22 89 49 93 64\r\n", "output": "65 28 6 51 90 71 14 27 73 48 64 92 56 31 25 29 63 93 45 5 24 42 60 67 40 62 61 21 55 72 78 47 7 16 54 35 1 18 36 4 52 57 30 32 50 39 44 94 96 98 68 17 66 86 49 23 43 85 87 88 69 37 10 3 13 2 11 34 76 83 74 75 77 84 53 81 99 89 20 46 95 97 58 22 26 0 19 80 38 12 15 8 9 33 41 59 79 82 91 70\r\n"}, {"input": "100\r\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99\r\n", "output": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 49\r\n"}, {"input": "2\r\n1 0\r\n", "output": "1 0\r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
submission_path = sys.argv[3]
with open(input_path, 'r') as f:
n = int(f.readline().strip())
court = list(map(int, f.readline().split()))
with open(submission_path, 'r') as f:
submission = list(map(int, f.readline().split()))
if len(submission) != n:
print(0)
return
seen = set()
valid = True
for num in submission:
if num < 0 or num >= n or num in seen:
valid = False
break
seen.add(num)
print(1 if valid else 0)
if __name__ == "__main__":
main()
| true |
852/G
|
852
|
G
|
Python 3
|
TESTS
| 1 | 46 | 0 |
30212008
|
n,m = map(int , input().split())
str1 = []
shabl1 = []
answ = 0
for i in range(n):
str1.append(input())
d = 0
for i in range(m):
shabl1.append(input())
shabl1[i]+=str("000")
for shabl in shabl1:
answ = 0
for i in str1:
for j in range(len(i)):
if shabl[j]!=i[j] and shabl[j]!="?" and shabl[j+1] != i[j]:
d+=1
if d==0:
answ+=1
print(answ)
| 15 | 872 | 31,846,400 |
105100981
|
import sys
from itertools import product
from collections import defaultdict
r=sys.stdin.readline
N,M=map(int,r().split())
words=defaultdict(int)
tb=['a','b','c','d','e']
st=set()
cnt=0
res=""
def dfs(u):
global res,cnt
if u==l:
if res in st:
return
if words[res]>0: cnt+=words[res]
st.add(res)
return
if pattern[u]=='?':
for i in range(6):
if i!=5:res+=tb[i]
dfs(u+1)
if i!=5:res=res[:-1]
else:
res+=pattern[u]
dfs(u+1)
res=res[:-1]
for _ in range(N):
word=r().strip()
words[word]+=1
for _ in range(M):
cnt=0
st.clear()
pattern=r().strip()
l=len(pattern)
res=""
dfs(0)
print(cnt)
|
Bubble Cup X - Finals [Online Mirror]
|
ICPC
| 2,017 | 2 | 256 |
Bathroom terminal
|
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is connected to the terminal next to him. After pressing a Play button a rough voice starts playing from the tape:
"Listen up Smith. As you can see, you are in pretty tough situation and in order to escape, you have to solve a puzzle.
You are given N strings which represent words. Each word is of the maximum length L and consists of characters 'a'-'e'. You are also given M strings which represent patterns. Pattern is a string of length ≤ L and consists of characters 'a'-'e' as well as the maximum 3 characters '?'. Character '?' is an unknown character, meaning it can be equal to any character 'a'-'e', or even an empty character. For each pattern find the number of words that matches with the given pattern. After solving it and typing the result in the terminal, the key will drop from the ceiling and you may escape. Let the game begin."
Help Smith escape.
|
The first line of input contains two integers N and M (1 ≤ N ≤ 100 000, 1 ≤ M ≤ 5000), representing the number of words and patterns respectively.
The next N lines represent each word, and after those N lines, following M lines represent each pattern. Each word and each pattern has a maximum length L (1 ≤ L ≤ 50). Each pattern has no more that three characters '?'. All other characters in words and patters are lowercase English letters from 'a' to 'e'.
|
Output contains M lines and each line consists of one integer, representing the number of words that match the corresponding pattern.
| null |
If we switch '?' with 'b', 'e' and with empty character, we get 'abc', 'aec' and 'ac' respectively.
|
[{"input": "3 1\nabc\naec\nac\na?c", "output": "3"}]
| 1,700 |
["implementation"]
| 15 |
[{"input": "3 1\r\nabc\r\naec\r\nac\r\na?c\r\n", "output": "3\r\n"}, {"input": "22 2\r\naaaab\r\naaabb\r\naabab\r\naabbb\r\nabaab\r\nababb\r\nabbab\r\nabbbb\r\naaab\r\naabb\r\nabab\r\nabbb\r\naab\r\nabb\r\nab\r\ncccd\r\nccdd\r\ncdcd\r\ncddd\r\nccd\r\ncdd\r\ncd\r\na???b\r\nc??d\r\n", "output": "15\r\n7\r\n"}, {"input": "15 6\r\naaa\r\naaabbb\r\naaabb\r\naaaaa\r\naaaaaa\r\naaaa\r\naaabbbb\r\naaaaa\r\naaaaaa\r\naaaa\r\naaabbbb\r\naabbbb\r\naa\r\naa\r\naab\r\na\r\n?a?\r\n??\r\n?aa?bb?\r\n?aa?aa?\r\n??aaa?\r\n", "output": "0\r\n4\r\n2\r\n5\r\n6\r\n7\r\n"}]
| false |
stdio
| null | true |
383/D
|
383
|
D
|
Python 3
|
TESTS
| 1 | 30 | 0 |
228198474
|
MOD = 10**9 + 7
n = int(input())
a = list(map(int, input().split()))
total_sum = sum(a)
half_sum = (total_sum + 1) // 2
dp = [0] * (half_sum + 1)
dp[0] = 1
for i in range(n):
for j in range(half_sum, a[i] - 1, -1):
dp[j] = (dp[j] + dp[j - a[i]]) % MOD
# Calculate the number of ways for the target sum
result = (2 * dp[half_sum] - (n % 2)) % MOD
print(result)
| 48 | 327 | 159,948,800 |
123422157
|
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))
n = int(input())
a = list(map(int, input().split()))
m = sum(a)
M = 10**9+7
dp = [0]*(2*m+1)
ans = 0
dp[m] = 1
val = 0
for i in range(n):
v = a[i]
ndp = [0]*(2*m+1)
for j in range(m-val, m+val+1):
if j-v>=0:
ndp[j-v] += dp[j]
if ndp[j-v]>M:
ndp[j-v] -= M
if j+v<=2*m:
ndp[j+v] += dp[j]
if ndp[j+v]>M:
ndp[j+v] -= M
dp = ndp
ans += dp[m]
ans %= M
dp[m] += 1
val += v
print(ans%M)
|
Codeforces Round 225 (Div. 1)
|
CF
| 2,014 | 1 | 256 |
Antimatter
|
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 ≤ i ≤ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).
You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
|
The first line contains an integer n (1 ≤ n ≤ 1000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000).
The sum a1 + a2 + ... + an will be less than or equal to 10000.
|
Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).
| null |
The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.
|
[{"input": "4\n1 1 1 1", "output": "12"}]
| 2,300 |
["dp"]
| 48 |
[{"input": "4\r\n1 1 1 1\r\n", "output": "12\r\n"}, {"input": "10\r\n16 9 9 11 10 12 9 6 10 8\r\n", "output": "86\r\n"}, {"input": "50\r\n2 1 5 2 1 3 1 2 3 2 1 1 5 2 2 2 3 2 1 2 2 2 3 3 1 3 1 1 2 2 2 2 1 2 3 1 2 4 1 1 1 3 2 1 1 1 3 2 1 3\r\n", "output": "115119382\r\n"}, {"input": "100\r\n8 3 3 7 3 6 4 6 9 4 6 5 5 5 4 3 4 2 3 5 3 6 5 3 6 5 6 6 2 6 4 5 5 4 6 4 3 2 8 5 6 6 7 4 4 9 5 6 6 3 7 1 6 2 6 5 9 3 8 6 2 6 3 2 4 4 3 5 4 7 6 5 4 6 3 5 6 8 8 6 3 7 7 1 4 6 8 6 5 3 7 8 4 7 5 3 8 5 4 4\r\n", "output": "450259307\r\n"}, {"input": "250\r\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\r\n", "output": "533456111\r\n"}, {"input": "250\r\n6 1 4 3 3 7 4 5 3 2 4 4 2 5 4 2 1 7 6 2 4 5 3 3 4 5 3 4 5 4 6 4 6 5 3 3 1 5 4 5 3 4 2 4 2 5 1 4 3 3 3 2 6 6 4 7 2 6 5 3 3 6 5 2 1 3 3 5 2 2 3 7 3 5 6 4 7 3 5 3 4 5 5 4 11 5 1 5 3 3 3 1 4 6 4 4 5 5 5 5 2 5 5 3 2 2 5 6 10 5 4 2 5 4 2 5 5 3 4 2 5 4 3 2 4 4 2 5 4 1 5 3 9 6 4 6 3 5 4 5 3 6 7 4 5 5 3 6 2 6 3 3 4 5 6 3 3 3 5 2 4 4 4 5 4 2 5 4 6 5 3 3 6 3 1 5 6 5 4 6 2 3 4 4 5 2 1 7 4 5 5 5 2 2 7 6 1 5 3 2 7 5 8 2 2 2 3 5 2 4 4 2 2 6 4 6 3 2 8 3 4 7 3 2 7 3 5 5 3 2 2 4 5 3 4 3 5 3 5 4 3 1 2 4 7 4 2 3 3 5\r\n", "output": "377970747\r\n"}, {"input": "250\r\n2 2 2 2 3 2 4 2 3 2 5 1 2 3 4 4 5 3 5 1 2 5 2 3 5 3 2 3 3 3 5 1 5 5 5 4 1 3 2 5 1 2 3 5 3 3 5 2 1 1 3 3 5 1 4 2 3 3 2 2 3 5 5 4 1 4 1 5 1 3 3 4 1 5 2 5 5 3 2 4 4 4 4 3 5 1 3 4 3 4 2 1 4 3 5 1 2 3 4 2 5 5 3 2 5 3 5 4 2 3 2 3 1 1 2 4 2 5 2 3 3 2 4 5 4 2 2 5 5 5 5 4 3 4 5 2 2 3 3 4 5 1 5 5 2 5 1 5 5 4 4 1 4 2 1 2 1 2 2 3 1 4 5 4 2 4 5 1 1 3 2 1 4 1 5 2 3 1 2 3 2 3 3 2 4 2 5 5 2 3 4 2 2 4 2 4 1 5 5 3 1 3 4 5 2 5 5 1 3 1 3 3 2 5 3 5 2 4 3 5 5 3 3 2 3 2 5 3 4 3 5 3 3 4 5 3 1 2 2 5 4 4 5 1 4 1 2 5 2 3\r\n", "output": "257270797\r\n"}, {"input": "1\r\n1\r\n", "output": "0\r\n"}, {"input": "2\r\n1 1\r\n", "output": "2\r\n"}, {"input": "2\r\n1000 1000\r\n", "output": "2\r\n"}, {"input": "2\r\n1 2\r\n", "output": "0\r\n"}, {"input": "3\r\n1 2 4\r\n", "output": "0\r\n"}, {"input": "3\r\n1 2 2\r\n", "output": "2\r\n"}, {"input": "1\r\n1000\r\n", "output": "0\r\n"}, {"input": "3\r\n999 999 999\r\n", "output": "4\r\n"}]
| false |
stdio
| null | true |
158/C
|
158
|
C
|
Python 3
|
TESTS
| 0 | 62 | 0 |
226886524
|
n = int(input()) # Read the number of commands
current_directory = "/" # Initialize the current directory as the root "/"
for _ in range(n):
command = input().split() # Read the command and its parameter
if command[0] == "cd":
path = command[1]
if path.startswith("/"):
# Absolute path
current_directory = "/"
path = path[1:] # Remove leading "/"
# Split the path into directory names
directories = path.split("/")
for directory in directories:
if directory == "..":
# Move up to the parent directory
current_directory = current_directory.rstrip("/").rsplit("/", 1)[0] + "/"
else:
# Change to the specified directory
current_directory += directory + "/"
elif command[0] == "pwd":
# Print the current directory (remove the trailing "/" for formatting)
print(current_directory.rstrip("/"))
| 29 | 124 | 0 |
18858108
|
class Shell:
def __init__(self):
self.wd = ['']
def cd(self, where: str):
glob = where.startswith('/')
directories = where.split('/')
if directories and not directories[0]:
directories.pop(0)
if glob:
self._reset()
for d in directories:
self._cd_one_dir(d)
def pwd(self):
if len(self.wd) == 1:
print('/')
else:
print('/', '/'.join(self.wd[1:]), '/', sep='')
def _reset(self):
self.wd = ['']
def _cd_one_dir(self, d):
if d == '..':
self.wd.pop()
else:
self.wd.append(d)
n = int(input())
sh = Shell()
for _ in range(n):
cmd = input()
if cmd.startswith('cd'):
sh.cd(cmd.split()[-1])
else:
sh.pwd()
|
VK Cup 2012 Qualification Round 1
|
CF
| 2,012 | 3 | 256 |
Cd and pwd commands
|
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
|
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
|
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
| null | null |
[{"input": "7\npwd\ncd /home/vasya\npwd\ncd ..\npwd\ncd vasya/../petya\npwd", "output": "/\n/home/vasya/\n/home/\n/home/petya/"}, {"input": "4\ncd /a/b\npwd\ncd ../a/b\npwd", "output": "/a/b/\n/a/a/b/"}]
| 1,400 |
["*special", "data structures", "implementation"]
| 29 |
[{"input": "7\r\npwd\r\ncd /home/vasya\r\npwd\r\ncd ..\r\npwd\r\ncd vasya/../petya\r\npwd\r\n", "output": "/\r\n/home/vasya/\r\n/home/\r\n/home/petya/\r\n"}, {"input": "4\r\ncd /a/b\r\npwd\r\ncd ../a/b\r\npwd\r\n", "output": "/a/b/\r\n/a/a/b/\r\n"}, {"input": "1\r\npwd\r\n", "output": "/\r\n"}, {"input": "2\r\ncd /test/../test/../test/../test/../a/b/c/..\r\npwd\r\n", "output": "/a/b/\r\n"}, {"input": "9\r\ncd test\r\npwd\r\ncd ..\r\ncd /test\r\npwd\r\ncd ..\r\npwd\r\ncd test/test\r\npwd\r\n", "output": "/test/\r\n/test/\r\n/\r\n/test/test/\r\n"}, {"input": "6\r\ncd a/a/b/b\r\npwd\r\ncd ../..\r\npwd\r\ncd ..\r\npwd\r\n", "output": "/a/a/b/b/\r\n/a/a/\r\n/a/\r\n"}, {"input": "5\r\npwd\r\ncd /xgztbykka\r\npwd\r\ncd /gia/kxfls\r\npwd\r\n", "output": "/\r\n/xgztbykka/\r\n/gia/kxfls/\r\n"}, {"input": "17\r\npwd\r\ncd denwxe/../jhj/rxit/ie\r\npwd\r\ncd /tmyuylvul/qev/ezqit\r\npwd\r\ncd ../gxsfgyuspg/irleht\r\npwd\r\ncd wq/pqyz/tjotsmdzja\r\npwd\r\ncd ia/hs/../u/nemol/ffhf\r\npwd\r\ncd /lrdm/mvwxwb/llib\r\npwd\r\ncd /lmhu/wloover/rqd\r\npwd\r\ncd lkwabdw/../wrqn/x/../ien\r\npwd\r\n", "output": "/\r\n/jhj/rxit/ie/\r\n/tmyuylvul/qev/ezqit/\r\n/tmyuylvul/qev/gxsfgyuspg/irleht/\r\n/tmyuylvul/qev/gxsfgyuspg/irleht/wq/pqyz/tjotsmdzja/\r\n/tmyuylvul/qev/gxsfgyuspg/irleht/wq/pqyz/tjotsmdzja/ia/u/nemol/ffhf/\r\n/lrdm/mvwxwb/llib/\r\n/lmhu/wloover/rqd/\r\n/lmhu/wloover/rqd/wrqn/ien/\r\n"}, {"input": "5\r\ncd /xgztbykka\r\ncd /gia/kxfls\r\ncd /kiaxt/hcx\r\ncd /ufzoiv\r\npwd\r\n", "output": "/ufzoiv/\r\n"}, {"input": "17\r\ncd denwxe/../jhj/rxit/ie\r\ncd /tmyuylvul/qev/ezqit\r\ncd ../gxsfgyuspg/irleht\r\ncd wq/pqyz/tjotsmdzja\r\ncd ia/hs/../u/nemol/ffhf\r\ncd /lrdm/mvwxwb/llib\r\ncd /lmhu/wloover/rqd\r\ncd lkwabdw/../wrqn/x/../ien\r\ncd /rqljh/qyovqhiry/q\r\ncd /d/aargbeotxm/ovv\r\ncd /jaagwy/../xry/w/zdvx\r\ncd /nblqgcua/s/s/c/dgg\r\ncd /jktwitbkgj/ee/../../q\r\ncd wkx/jyphtd/h/../ygwc\r\ncd areyd/regf/ogvklan\r\ncd /wrbi/vbxefrd/jimis\r\npwd\r\n", "output": "/wrbi/vbxefrd/jimis/\r\n"}, {"input": "5\r\npwd\r\ncd ztb/kag\r\npwd\r\npwd\r\npwd\r\n", "output": "/\r\n/ztb/kag/\r\n/ztb/kag/\r\n/ztb/kag/\r\n"}, {"input": "17\r\ncd en/ebhjhjzlrx/pmieg\r\ncd uylvulohqe/wezq/oarx\r\npwd\r\ncd yus/fsi/ehtrs/../vjpq\r\ncd tjotsmdzja/diand/dqb\r\ncd emolqs/hff/rdmy/vw\r\ncd ../llibd/mhuos/oove\r\ncd /rqdqj/kwabd/nj/qng\r\npwd\r\ncd /yie/lrq/hmxq/vqhi\r\ncd qma/../aargbeotxm/ov\r\ncd /jaagwy/../xry/w/zdvx\r\npwd\r\ncd ../gcuagas/s/c/dggmz\r\npwd\r\npwd\r\ncd bkgjifee/../../../vfwkxjoj\r\n", "output": "/en/ebhjhjzlrx/pmieg/uylvulohqe/wezq/oarx/\r\n/rqdqj/kwabd/nj/qng/\r\n/xry/w/zdvx/\r\n/xry/w/gcuagas/s/c/dggmz/\r\n/xry/w/gcuagas/s/c/dggmz/\r\n"}, {"input": "50\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\npwd\r\n", "output": "/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n/\r\n"}, {"input": "1\r\ncd /\r\n", "output": ""}, {"input": "11\r\npwd\r\ncd /home/vasya\r\npwd\r\ncd ..\r\npwd\r\ncd vasya/../../petya\r\npwd\r\ncd /a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a\r\npwd\r\ncd ..\r\npwd\r\n", "output": "/\r\n/home/vasya/\r\n/home/\r\n/petya/\r\n/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/\r\n/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/\r\n"}]
| false |
stdio
| null | true |
342/E
|
342
|
E
|
PyPy 3
|
TESTS
| 2 | 140 | 0 |
99283930
|
n,m=map(int,input().split())
tr=[set() for i in range(n+1)]
trr=[[] for i in range(n+1)]
for _ in range(n-1):
a,b=map(int,input().split())
trr[a].append(b);trr[b].append(a)
tr[a].add(b);tr[b].add(a)
euler=[]
disc=[-1 for i in range(n+1)]
hei=[-1 for i in range(n+1)]
def eulerr():
q=[1]
pa={1:-1}
hei[1]=0
while q:
x=q.pop()
if disc[x]==-1:disc[x]=len(euler)
euler.append(x)
if len(trr[x])==0:
if pa[x]!=-1:q.append(pa[x])
elif trr[x][-1]==pa[x]:
trr[x].pop(-1)
q.append(x)
euler.pop()
else:
y=trr[x].pop(-1)
pa[y]=x
hei[y]=hei[x]+1
q.append(y)
eulerr()
st=[-1 for i in range(2*len(euler))]
for i in range(len(euler)):
st[i+len(euler)]=euler[i]
for i in range(len(euler)-1,0,-1):
if disc[st[i<<1]]<disc[st[i<<1|1]]:
st[i]=st[i<<1]
else:
st[i]=st[i<<1|1]
def dist(a,b):
i=disc[a];j=disc[b]
if i>j:i,j=j,i
i+=len(euler);j+=len(euler)+1
ans=st[i]
while i<j:
if i&1:
if disc[st[i]]<disc[ans]:ans=st[i]
i+=1
if j&1:
j-=1
if disc[st[j]]<disc[ans]:ans=st[j]
i>>=1
j>>=1
return(hei[a]+hei[b]-2*hei[ans])
size=[0 for i in range(n+1)]
def siz(i):
pa={i:-1}
q=[i]
w=[]
while q:
x=q.pop()
w.append(x)
size[x]=1
for y in tr[x]:
if y==pa[x]:continue
pa[y]=x
q.append(y)
for j in range(len(w)-1,0,-1):
x=w[j]
size[pa[x]]+=size[x]
return(size[i])
def centroid(i,nn):
pa={i:-1}
q=[i]
while q:
x=q.pop()
for y in tr[x]:
if y!=pa[x] and size[y]>nn//2:
q.append(y)
pa[y]=x
break
else:return(x)
ct=[-1 for i in range(n+1)]
def build():
q=[1]
while q:
x=q.pop()
nn=siz(x)
j=centroid(x,nn)
ct[j]=ct[x]
for y in tr[j]:
tr[y].discard(j)
ct[y]=j
q.append(y)
tr[j].clear()
build()
ps=[float("INF") for i in range(n+1)]
ps[1]=0
x=1
while ct[x]!=-1:
ps[ct[x]]=min(ct[x],dist(1,ct[x]))
x=ct[x]
for _ in range(m):
t,x=map(int,input().split())
if t==1:
ps[x]=0
v=x
while ct[x]!=-1:
ps[ct[x]]=min(ct[x],dist(v,ct[x]))
x=ct[x]
else:
ans=ps[x]
v=x
while ct[x]!=-1:
ans=min(ans,ps[ct[x]]+dist(v,ct[x]))
x=ct[x]
print(ans)
| 23 | 997 | 27,648,000 |
109826106
|
class CentroidDecomposition():
def __init__(self, g):
self.g = g
self.n = len(g)
self.parent = [-1]*self.n
self.size = [1]*self.n
self.cdparent = [-1]*self.n
self.cddepth = [0]*self.n
self.cdorder = [-1]*self.n
self.cdused = [0]*self.n
cnt = 0
stack = [0]
while stack:
v = stack.pop()
p = self.cdparent[v]
c = self.get_centroid(v)
self.cdused[c] = True
self.cdparent[c] = p
self.cddepth[c] = self.cddepth[v]
self.cdorder[c] = cnt
cnt += 1
for u in self.g[c]:
if self.cdused[u]:
continue
self.cdparent[u] = c
self.cddepth[u] = self.cddepth[c]+1
stack.append(u)
def get_centroid(self, root):
self.parent[root] = -1
self.size[root] = 1
stack = [root]
order = []
while stack:
v = stack.pop()
order.append(v)
for u in g[v]:
if self.parent[v] == u or self.cdused[u]:
continue
self.size[u] = 1
self.parent[u] = v
stack.append(u)
if len(order) <= 2:
return root
for v in reversed(order):
if self.parent[v] == -1:
continue
self.size[self.parent[v]] += self.size[v]
total = self.size[root]
v = root
while True:
for u in self.g[v]:
if self.parent[v] == u or self.cdused[u]:
continue
if self.size[u] > total//2:
v = u
break
else:
return v
class HLD:
def __init__(self, g):
self.g = g
self.n = len(g)
self.parent = [-1]*self.n
self.size = [1]*self.n
self.head = [0]*self.n
self.preorder = [0]*self.n
self.k = 0
self.depth = [0]*self.n
for v in range(self.n):
if self.parent[v] == -1:
self.dfs_pre(v)
self.dfs_hld(v)
def dfs_pre(self, v):
g = self.g
stack = [v]
order = [v]
while stack:
v = stack.pop()
for u in g[v]:
if self.parent[v] == u:
continue
self.parent[u] = v
self.depth[u] = self.depth[v]+1
stack.append(u)
order.append(u)
# 隣接リストの左端: heavyな頂点への辺
# 隣接リストの右端: 親への辺
while order:
v = order.pop()
child_v = g[v]
if len(child_v) and child_v[0] == self.parent[v]:
child_v[0], child_v[-1] = child_v[-1], child_v[0]
for i, u in enumerate(child_v):
if u == self.parent[v]:
continue
self.size[v] += self.size[u]
if self.size[u] > self.size[child_v[0]]:
child_v[i], child_v[0] = child_v[0], child_v[i]
def dfs_hld(self, v):
stack = [v]
while stack:
v = stack.pop()
self.preorder[v] = self.k
self.k += 1
top = self.g[v][0]
# 隣接リストを逆順に見ていく(親 > lightな頂点への辺 > heavyな頂点 (top))
# 連結成分が連続するようにならべる
for u in reversed(self.g[v]):
if u == self.parent[v]:
continue
if u == top:
self.head[u] = self.head[v]
else:
self.head[u] = u
stack.append(u)
def for_each(self, u, v):
# [u, v]上の頂点集合の区間を列挙
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
l = max(self.preorder[self.head[v]], self.preorder[u])
r = self.preorder[v]
yield l, r # [l, r]
if self.head[u] != self.head[v]:
v = self.parent[self.head[v]]
else:
return
def for_each_edge(self, u, v):
# [u, v]上の辺集合の区間列挙
# 辺の情報は子の頂点に
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
if self.head[u] != self.head[v]:
yield self.preorder[self.head[v]], self.preorder[v]
v = self.parent[self.head[v]]
else:
if u != v:
yield self.preorder[u]+1, self.preorder[v]
break
def subtree(self, v):
# 頂点vの部分木の頂点集合の区間 [l, r)
l = self.preorder[v]
r = self.preorder[v]+self.size[v]
return l, r
def lca(self, u, v):
# 頂点u, vのLCA
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
if self.head[u] == self.head[v]:
return u
v = self.parent[self.head[v]]
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
g = [[] for i in range(n)]
for i in range(n-1):
a, b = map(int, input().split())
a, b = a-1, b-1
g[a].append(b)
g[b].append(a)
cd = CentroidDecomposition(g)
hld = HLD(g)
#print(cd.cdparent)
min_dist = [0]*n
for i in range(n):
min_dist[i] = hld.depth[i]
#print(min_dist)
for i in range(m):
t, v = map(int, input().split())
v -= 1
if t == 1:
cur = v
while cur != -1:
l = hld.lca(cur, v)
d = hld.depth[cur]+hld.depth[v]-2*hld.depth[l]
min_dist[cur] = min(min_dist[cur], d)
cur = cd.cdparent[cur]
else:
ans = n
cur = v
while cur != -1:
l = hld.lca(cur, v)
d = hld.depth[cur]+hld.depth[v]-2*hld.depth[l]
ans = min(ans, d+min_dist[cur])
cur = cd.cdparent[cur]
print(ans)
|
Codeforces Round 199 (Div. 2)
|
CF
| 2,013 | 5 | 256 |
Xenia and Tree
|
Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.
Xenia needs to learn how to quickly execute queries of two types:
1. paint a specified blue node in red;
2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node.
Your task is to write a program which will execute the described queries.
|
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree.
Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi.
It is guaranteed that the given graph is a tree and that all queries are correct.
|
For each second type query print the reply in a single line.
| null | null |
[{"input": "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 5\n1 2\n2 5", "output": "0\n3\n2"}]
| 2,400 |
["data structures", "divide and conquer", "trees"]
| 23 |
[{"input": "5 4\r\n1 2\r\n2 3\r\n2 4\r\n4 5\r\n2 1\r\n2 5\r\n1 2\r\n2 5\r\n", "output": "0\r\n3\r\n2\r\n"}]
| false |
stdio
| null | true |
342/E
|
342
|
E
|
PyPy 3
|
TESTS
| 2 | 93 | 20,684,800 |
128984780
|
import os
import sys
from io import BytesIO, IOBase
_print = print
BUFSIZE = 8192
def dbg(*args, **kwargs):
_print('\33[95m', end='')
_print(*args, **kwargs)
_print('\33[0m', end='')
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
PARENT_LIST = [] # get_parent_list
def get_parent_list(tree):
global PARENT_LIST
PARENT_LIST = list(range(len(tree)))
for parent, children in enumerate(tree):
for child in children:
PARENT_LIST[child] = parent
def to_tree(graph, root=0):
"""
graph: [{child, ...}, ...] (undirected)
:return directed graph that parent -> children
"""
stack = [[root]]
while stack:
if not stack[-1]:
del stack[-1]
continue
parent = stack[-1].pop()
for child in graph[parent]:
graph[child].discard(parent)
stack.append(list(graph[parent]))
def tree_bfs(tree, flat=True, root=0) -> list:
stack = [root]
result = []
while stack:
new_stack = []
if flat:
result.extend(stack)
else:
result.append(stack)
for node in stack:
new_stack.extend(tree[node])
stack = new_stack
return result
def level_list(tree, root=0):
"""
:return: a list of the level for each node
root is level 0
"""
result = [0] * len(tree)
for level, nodes in enumerate(tree_bfs(tree, False, root)):
for node in nodes:
result[node] = level
return result
# 2020/12/6
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def __call__(self, begin, end):
depth = (end - begin).bit_length() - 1
return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)])
def __getitem__(self, idx):
return self._data[0][idx]
class LCA:
def __init__(self, graph, root):
self._time = [-1] * len(graph)
self._path = [-1] * len(graph)
P = [-1] * len(graph)
t = -1
dfs = [root]
while dfs:
node = dfs.pop()
self._path[t] = P[node]
self._time[node] = t = t + 1
for nei in graph[node]:
if self._time[nei] == -1:
P[nei] = node
dfs.append(nei)
self._rmq = RangeQuery(self._time[node] for node in self._path)
def __call__(self, a, b):
if a == b:
return a
a = self._time[a]
b = self._time[b]
if a > b:
a, b = b, a
return self._path[self._rmq(a, b)]
class TreeLCA:
def __init__(self, tree, root=0):
self.ROOT = root
self._LCA = LCA(tree, root)
self.LEVELS = level_list(tree, root)
def __call__(self, u, v):
return self._LCA(u, v)
def distance(self, u, v) -> int:
return self.LEVELS[u] + self.LEVELS[v] - self.LEVELS[self(u, v)] * 2
def path(self, u, v) -> list:
""":return the path in O(len(path)), path: (u, v]"""
path1, path2 = [], []
lca_lv = self.LEVELS[self(u, v)]
for _ in range(self.LEVELS[u] - lca_lv):
u = PARENT_LIST[u]
path1.append(u)
for _ in range(self.LEVELS[v] - lca_lv):
path2.append(v)
v = PARENT_LIST[v]
return path1 + path2[::-1]
# ############################## main
# 先砸可以O(1)求樹上任兩點距的lca
# 以及設d[u]=當前離u最近的紅點的距離
# 將每sqrt(m)個操作分塊
# 塗色時將該點加進 dq
# 詢問時用lca暴力問過所有dq中的紅點距
# 以及跟d[u]去比誰最小
# 該塊處理完畢後將所有dq中的紅點 用多源bfs更新所有節點的d[u]
# 當某點 u 與某紅點的距離 > d[u] 時,則不需再做擴展,所以可以 O(n)
# 並清空dq
from collections import deque
def main():
n, m = mpint()
tree = [set() for _ in range(n)]
for _ in range(n - 1):
u, v = mpint()
u, v = u - 1, v - 1
tree[u].add(v)
tree[v].add(u)
to_tree(tree)
get_parent_list(tree)
lca = TreeLCA(tree)
d = [n] * n
d[0] = 0
sqrt = int(m ** 0.5)
dq = deque([(0, 0)])
for i in range(1, m + 1):
t, u = mpint()
u -= 1
if t == 1:
dq.append((u, 0))
else:
ans = d[u]
for red, _ in dq:
ans = min(ans, lca.distance(u, red))
print(ans)
if not i % sqrt:
# multiple start points bfs update all nodes
while dq:
node, dis = dq.popleft()
if dis >= d[node]:
continue
d[node] = min(d[node], dis)
dis += 1
dq.extend([(child, dis) for child in tree[node]])
dq.append((PARENT_LIST[node], dis))
DEBUG = 0
URL = 'https://codeforces.com/contest/342/problem/E'
if __name__ == '__main__':
# 0: normal, 1: runner, 2: debug, 3: interactive
if DEBUG == 1:
import requests
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
if DEBUG != 2:
dbg = lambda *args, **kwargs: ...
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if DEBUG == 3:
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
main()
# Please check!
| 23 | 1,153 | 46,694,400 |
103009002
|
class Tree():
def __init__(self, n):
self.n = n
self.tree = [[] for _ in range(n)]
self.root = None
def add_edge(self, u, v):
self.tree[u].append(v)
self.tree[v].append(u)
def set_root(self, r=0):
self.root = r
self.par = [None] * self.n
self.dep = [0] * self.n
self.height = [0] * self.n
self.size = [1] * self.n
self.ord = [r]
stack = [r]
while stack:
v = stack.pop()
for adj in self.tree[v]:
if self.par[v] == adj: continue
self.par[adj] = v
self.dep[adj] = self.dep[v] + 1
self.ord.append(adj)
stack.append(adj)
for v in self.ord[1:][::-1]:
self.size[self.par[v]] += self.size[v]
self.height[self.par[v]] = max(self.height[self.par[v]], self.height[v] + 1)
def rerooting(self, op, e, merge, id):
if self.root is None: self.set_root()
dp = [e] * self.n
lt = [id] * self.n
rt = [id] * self.n
inv = [id] * self.n
for v in self.ord[::-1]:
tl = tr = e
for adj in self.tree[v]:
if self.par[v] == adj: continue
lt[adj] = tl
tl = op(tl, dp[adj])
for adj in self.tree[v][::-1]:
if self.par[v] == adj: continue
rt[adj] = tr
tr = op(tr, dp[adj])
dp[v] = tr
for v in self.ord:
if v == self.root: continue
p = self.par[v]
inv[v] = op(merge(lt[v], rt[v]), inv[p])
dp[v] = op(dp[v], inv[v])
return dp
def euler_tour(self):
if self.root is None: self.set_root()
self.tour = []
self.etin = [None for _ in range(self.n)]
self.etout = [None for _ in range(self.n)]
used = [0 for _ in range(self.n)]
used[self.root] = 1
stack = [self.root]
while stack:
v = stack.pop()
if v >= 0:
self.tour.append(v)
stack.append(~v)
if self.etin[v] is None:
self.etin[v] = len(self.tour) - 1
for adj in self.tree[v]:
if used[adj]: continue
used[adj] = 1
stack.append(adj)
else:
self.etout[~v] = len(self.tour)
if ~v != self.root:
self.tour.append(self.par[~v])
def heavylight_decomposition(self):
if self.root is None: self.set_root()
self.hldid = [None] * self.n
self.hldtop = [None] * self.n
self.hldtop[self.root] = self.root
self.hldnxt = [None] * self.n
self.hldrev = [None] * self.n
stack = [self.root]
cnt = 0
while stack:
v = stack.pop()
self.hldid[v] = cnt
self.hldrev[cnt] = v
cnt += 1
maxs = 0
for adj in self.tree[v]:
if self.par[v] == adj: continue
if maxs < self.size[adj]:
maxs = self.size[adj]
self.hldnxt[v] = adj
for adj in self.tree[v]:
if self.par[v] == adj or self.hldnxt[v] == adj: continue
self.hldtop[adj] = adj
stack.append(adj)
if self.hldnxt[v] is not None:
self.hldtop[self.hldnxt[v]] = self.hldtop[v]
stack.append(self.hldnxt[v])
def lca(self, u, v):
while True:
if self.hldid[u] > self.hldid[v]: u, v = v, u
if self.hldtop[u] != self.hldtop[v]:
v = self.par[self.hldtop[v]]
else:
return u
def dist(self, u, v):
lca = self.lca(u, v)
return self.dep[u] + self.dep[v] - 2 * self.dep[lca]
def range_query(self, u, v, edge_query=False):
while True:
if self.hldid[u] > self.hldid[v]: u, v = v, u
if self.hldtop[u] != self.hldtop[v]:
yield self.hldid[self.hldtop[v]], self.hldid[v] + 1
v = self.par[self.hldtop[v]]
else:
yield self.hldid[u] + edge_query, self.hldid[v] + 1
return
def subtree_query(self, u):
return self.hldid[u], self.hldid[u] + self.size[u]
def _get_centroid_(self, r):
self._par_[r] = None
self._size_[r] = 1
ord = [r]
stack = [r]
while stack:
v = stack.pop()
for adj in self.tree[v]:
if self._par_[v] == adj or self.cdused[adj]: continue
self._size_[adj] = 1
self._par_[adj] = v
ord.append(adj)
stack.append(adj)
if len(ord) <= 2: return r
for v in ord[1:][::-1]:
self._size_[self._par_[v]] += self._size_[v]
sr = self._size_[r] // 2
v = r
while True:
for adj in self.tree[v]:
if self._par_[v] == adj or self.cdused[adj]: continue
if self._size_[adj] > sr:
v = adj
break
else:
return v
def centroid_decomposition(self):
self._par_ = [None] * self.n
self._size_ = [1] * self.n
self.cdpar = [None] * self.n
self.cddep = [0] * self.n
self.cdord = [None] * self.n
self.cdused = [0] * self.n
cnt = 0
stack = [0]
while stack:
v = stack.pop()
p = self.cdpar[v]
c = self._get_centroid_(v)
self.cdused[c] = True
self.cdpar[c] = p
self.cddep[c] = self.cddep[v]
self.cdord[c] = cnt
cnt += 1
for adj in self.tree[c]:
if self.cdused[adj]: continue
self.cdpar[adj] = c
self.cddep[adj] = self.cddep[c] + 1
stack.append(adj)
def centroid(self):
if self.root is None: self.set_root()
sr = self.size[self.root] // 2
v = self.root
while True:
for adj in self.tree[v]:
if self.par[v] == adj: continue
if self.size[adj] > sr:
v = adj
break
else:
return v
def diam(self):
if self.root is None: self.set_root()
u = self.dep.index(max(self.dep))
self.set_root(u)
v = self.dep.index(max(self.dep))
return u, v
def get_path(self, u, v):
if self.root != u: self.set_root(u)
path = []
while v != None:
path.append(v)
v = self.par[v]
return path
def longest_path_decomposition(self, make_ladder=True):
assert self.root is not None
self.lpdnxt = [None] * self.n
self.lpdtop = [None] * self.n
self.lpdtop[self.root] = self.root
stack = [self.root]
while stack:
v = stack.pop()
for adj in self.tree[v]:
if self.par[v] == adj: continue
if self.height[v] == self.height[adj] + 1:
self.lpdnxt[v] = adj
for adj in self.tree[v]:
if self.par[v] == adj or self.lpdnxt[v] == adj: continue
self.lpdtop[adj] = adj
stack.append(adj)
if self.lpdnxt[v] is not None:
self.lpdtop[self.lpdnxt[v]] = self.lpdtop[v]
stack.append(self.lpdnxt[v])
if make_ladder: self._make_ladder_()
def _make_ladder_(self):
self.ladder = [[] for _ in range(self.n)]
for v in range(self.n):
if self.lpdtop[v] != v: continue
to = v
path = []
while to is not None:
path.append(to)
to = self.lpdnxt[to]
p = self.par[v]
self.ladder[v] = path[::-1]
for i in range(len(path)):
self.ladder[v].append(p)
if p is None: break
p = self.par[p]
def level_ancestor(self, v, k):
while v is not None:
id = self.height[v]
h = self.lpdtop[v]
if len(self.ladder[h]) > k + id:
return self.ladder[h][k + id]
v = self.ladder[h][-1]
k -= len(self.ladder[h]) - id - 1
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, Q = map(int, input().split())
t = Tree(N)
for _ in range(N - 1):
u, v = map(int, input().split())
t.add_edge(u - 1, v - 1)
t.heavylight_decomposition()
t.centroid_decomposition()
min_dist = [N] * N
res = []
def query_1(v):
cur = v
while cur is not None:
min_dist[cur] = min(min_dist[cur], t.dist(cur, v))
cur = t.cdpar[cur]
def query_2(v):
ret = N
cur = v
while cur is not None:
ret = min(ret, t.dist(cur, v) + min_dist[cur])
cur = t.cdpar[cur]
return ret
query_1(0)
for _ in range(Q):
q, v = map(int, input().split())
if q == 1:
query_1(v - 1)
else:
res.append((query_2(v - 1)))
print('\n'.join(map(str, res)))
|
Codeforces Round 199 (Div. 2)
|
CF
| 2,013 | 5 | 256 |
Xenia and Tree
|
Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.
Xenia needs to learn how to quickly execute queries of two types:
1. paint a specified blue node in red;
2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node.
Your task is to write a program which will execute the described queries.
|
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree.
Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi.
It is guaranteed that the given graph is a tree and that all queries are correct.
|
For each second type query print the reply in a single line.
| null | null |
[{"input": "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 5\n1 2\n2 5", "output": "0\n3\n2"}]
| 2,400 |
["data structures", "divide and conquer", "trees"]
| 23 |
[{"input": "5 4\r\n1 2\r\n2 3\r\n2 4\r\n4 5\r\n2 1\r\n2 5\r\n1 2\r\n2 5\r\n", "output": "0\r\n3\r\n2\r\n"}]
| false |
stdio
| null | true |
802/M
|
802
|
M
|
Python 3
|
TESTS
| 0 | 30 | 0 |
120657957
|
input()
input()
print(1)
| 14 | 46 | 102,400 |
224698431
|
x,y=map(int,input().split())
n=list(map(int,input().split()))
n=sorted(n)
ans=0
for num in range(y):
ans=ans+n[num]
print(ans)
|
Helvetic Coding Contest 2017 online mirror (teams allowed, unrated)
|
ICPC
| 2,017 | 2 | 256 |
April Fools' Problem (easy)
|
The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.
However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!
|
The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).
|
Output one number.
| null | null |
[{"input": "8 5\n1 1 1 1 1 1 1 1", "output": "5"}, {"input": "10 3\n16 8 2 4 512 256 32 128 64 1", "output": "7"}, {"input": "5 1\n20 10 50 30 46", "output": "10"}, {"input": "6 6\n6 6 6 6 6 6", "output": "36"}, {"input": "1 1\n100", "output": "100"}]
| 1,200 |
["greedy", "sortings"]
| 14 |
[{"input": "8 5\r\n1 1 1 1 1 1 1 1\r\n", "output": "5"}, {"input": "10 3\r\n16 8 2 4 512 256 32 128 64 1\r\n", "output": "7"}, {"input": "5 1\r\n20 10 50 30 46\r\n", "output": "10"}, {"input": "6 6\r\n6 6 6 6 6 6\r\n", "output": "36"}, {"input": "1 1\r\n100\r\n", "output": "100"}, {"input": "1 1\r\n1\r\n", "output": "1"}, {"input": "10 5\r\n147 1917 5539 7159 5763 416 711 1412 6733 4402\r\n", "output": "4603"}, {"input": "100 60\r\n1443 3849 6174 8249 696 8715 3461 9159 4468 2496 3044 2301 2437 7559 7235 7956 8959 2036 4399 9595 8664 9743 7688 3730 3705 1203 9332 7088 8563 3823 2794 8014 6951 1160 8616 970 9885 2421 6510 4885 5246 6146 8849 5141 8602 9486 7257 3300 8323 4797 4082 7135 80 9622 4543 6567 2747 5013 4626 9091 9028 9851 1654 7021 6843 3209 5350 3809 4697 4617 4450 81 5208 1877 2897 6115 3191 2878 9258 2849 8103 6678 8714 8024 80 9894 321 8074 6797 457 1348 8652 811 7215 4381 5000 7406 7899 9974 844\r\n", "output": "206735"}]
| false |
stdio
| null | true |
159/E
|
159
|
E
|
Python 3
|
TESTS
| 0 | 46 | 307,200 |
15156452
|
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
[n]=get()
p = {}
for i in range(n):
[a,b] = get()
if a not in p:
p[a]=[]
p[a].append([b,i+1])
h=[]
for i in p:
s=0
for j in p[i]:
s+=j[0]
h.append([s,i])
h.sort()
print(h[-1][0] + h[-2][0])
print(len(p[h[-1][1]]) + len(p[h[-2][1]]))
for i in p[h[-1][1]]:
print(i[1],end=' ')
for i in p[h[-2][1]]:
print(i[1],end=' ')
if mode=="file":f.close()
if __name__=="__main__":
main()
| 35 | 1,200 | 31,129,600 |
144123105
|
from collections import defaultdict
n=int(input())
g=defaultdict(list)
for i in range(n):
c,s=map(int,input().strip().split())
g[c].append((s,i+1))
pref=defaultdict(list)
for i in g:
g[i].sort(key=lambda s:s[0],reverse=True)
pre=g[i][0][0]
sz=1
pref[sz].append((pre,i))
for id in range(1,len(g[i])):
sz+=1
pre+=g[i][id][0]
pref[sz].append((pre,i))
ans=0
pair=None
# print(pref)
[pref[i].sort(reverse=True) for i in pref]
for i in pref:
if len(pref[i])>=2:
if pref[i][0][0]+pref[i][1][0]>ans:
ans=pref[i][0][0]+pref[i][1][0]
pair=((pref[i][0][1],i),(pref[i][1][1],i)) #id, size of pref taken
if i==1:
continue
i2=i-1
if pref[i2][0][1]==pref[i][0][1]:
if len(pref[i2])>=2:
if pref[i2][1][0]+pref[i][0][0]>ans:
ans=pref[i2][1][0]+pref[i][0][0]
pair=((pref[i2][1][1],i2),(pref[i][0][1],i))
if len(pref[i])>=2:
if pref[i2][0][0] + pref[i][1][0] > ans:
ans = pref[i2][0][0] + pref[i][1][0]
pair = ((pref[i2][0][1], i2), (pref[i][1][1], i))
else:
if pref[i2][0][0] + pref[i][0][0] > ans:
ans = pref[i2][0][0] + pref[i][0][0]
pair = ((pref[i2][0][1], i2), (pref[i][0][1], i))
print(ans)
gen=[]
for col,sz in pair:
gen1=[id for wt,id in g[col][:sz]]
gen.append(gen1)
a,b=sorted(gen,key=len,reverse=True)
print(len(a)+len(b))
while a :
print(a.pop(0),end=" ")
if b:
print(b.pop(0),end=" ")
|
VK Cup 2012 Qualification Round 2
|
CF
| 2,012 | 1.5 | 256 |
Zebra Tower
|
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower.
A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
|
The first line contains an integer n (2 ≤ n ≤ 105) — the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 ≤ ci, si ≤ 109) — the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
|
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input.
If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
| null | null |
[{"input": "4\n1 2\n1 3\n2 4\n3 3", "output": "9\n3\n2 3 1"}, {"input": "2\n1 1\n2 1", "output": "2\n2\n2 1"}]
| 1,700 |
["*special", "data structures", "greedy", "sortings"]
| 35 |
[{"input": "4\r\n1 2\r\n1 3\r\n2 4\r\n3 3\r\n", "output": "9\r\n3\r\n2 3 1 \r\n"}, {"input": "2\r\n1 1\r\n2 1\r\n", "output": "2\r\n2\r\n2 1 \r\n"}, {"input": "3\r\n1 2\r\n2 2\r\n2 1\r\n", "output": "5\r\n3\r\n2 1 3 \r\n"}, {"input": "4\r\n2 1\r\n2 1\r\n1 1\r\n1 2\r\n", "output": "5\r\n4\r\n4 2 3 1 \r\n"}, {"input": "6\r\n1 1\r\n1 1\r\n2 2\r\n1 2\r\n1 2\r\n2 2\r\n", "output": "9\r\n5\r\n5 6 4 3 2 \r\n"}, {"input": "20\r\n1 2\r\n3 2\r\n4 2\r\n2 2\r\n5 2\r\n2 5\r\n3 2\r\n3 4\r\n4 4\r\n5 3\r\n2 1\r\n5 2\r\n5 3\r\n2 1\r\n5 5\r\n2 3\r\n1 5\r\n5 2\r\n3 4\r\n3 3\r\n", "output": "32\r\n11\r\n15 19 13 8 10 20 18 7 12 2 5 \r\n"}, {"input": "12\r\n1 3\r\n2 4\r\n2 1\r\n2 1\r\n3 1\r\n3 1\r\n3 1\r\n3 1\r\n3 1\r\n3 1\r\n3 1\r\n3 1\r\n", "output": "10\r\n7\r\n12 2 11 4 10 3 9 \r\n"}, {"input": "4\r\n2 1000000000\r\n2 1000000000\r\n2 1000000000\r\n1 1\r\n", "output": "2000000001\r\n3\r\n3 4 2 \r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
submission_path = sys.argv[3]
# Read input
with open(input_path) as f:
n = int(f.readline())
cubes = []
for i in range(n):
c, s = map(int, f.readline().split())
cubes.append((c, s))
# Read reference output to get H_ref
with open(output_path) as f:
try:
H_ref = int(f.readline().strip())
except:
H_ref = 0
# Read submission output
with open(submission_path) as f:
lines = [line.strip() for line in f.readlines()]
if len(lines) != 3:
print(0)
return
try:
H_sub = int(lines[0])
k = int(lines[1])
indices = list(map(int, lines[2].split()))
except:
print(0)
return
# Check height matches reference
if H_sub != H_ref:
print(0)
return
# Validate indices
if k < 2 or len(indices) != k:
print(0)
return
seen = set()
for idx in indices:
if not (1 <= idx <= n) or idx in seen:
print(0)
return
seen.add(idx)
# Check color alternation and two colors
if len(indices) < 2:
print(0)
return
colors = [cubes[idx-1][0] for idx in indices]
color1, color2 = colors[0], colors[1]
if color1 == color2:
print(0)
return
for i in range(2, len(colors)):
expected = color1 if (i % 2 == 0) else color2
if colors[i] != expected:
print(0)
return
# Ensure all colors are from the two
for c in colors:
if c not in (color1, color2):
print(0)
return
# Check sum matches reported height
total = sum(cubes[idx-1][1] for idx in indices)
if total != H_sub:
print(0)
return
# All checks passed
print(1)
if __name__ == "__main__":
main()
| true |
397/B
|
397
|
B
|
Python 3
|
TESTS
| 1 | 93 | 0 |
62337644
|
for i in range(int(input())):
n,l,r = map(int,input().split())
i = n%r
while i>0 and l<r:
if i%l !=0: l+=1
else:i = 0
print('Yes') if i==0 else print('No')
| 6 | 62 | 0 |
5946952
|
T=int(input())
while T>0:
T-=1
n,l,r=map(int,input().split())
t = n//l
if t*r>=n:
print("Yes")
else:
print("No")
|
Codeforces Round 232 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
On Corruption and Numbers
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
|
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
|
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
| null |
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
[{"input": "2\n5 2 3\n6 4 5", "output": "Yes\nNo"}]
| null |
["constructive algorithms", "implementation", "math"]
| 6 |
[{"input": "2\r\n5 2 3\r\n6 4 5\r\n", "output": "Yes\r\nNo\r\n"}, {"input": "50\r\n69 6 6\r\n22 1 1\r\n23 3 3\r\n60 13 13\r\n13 3 3\r\n7 4 7\r\n6 1 1\r\n49 7 9\r\n68 8 8\r\n20 2 2\r\n34 1 1\r\n79 5 5\r\n22 1 1\r\n77 58 65\r\n10 3 3\r\n72 5 5\r\n47 1 1\r\n82 3 3\r\n92 8 8\r\n34 1 1\r\n42 9 10\r\n63 14 14\r\n10 3 3\r\n38 2 2\r\n80 6 6\r\n79 5 5\r\n53 5 5\r\n44 7 7\r\n85 2 2\r\n24 2 2\r\n57 3 3\r\n95 29 81\r\n77 6 6\r\n24 1 1\r\n33 4 4\r\n93 6 6\r\n55 22 28\r\n91 14 14\r\n7 1 1\r\n16 1 1\r\n20 3 3\r\n43 3 3\r\n53 3 3\r\n49 3 3\r\n52 5 5\r\n2 1 1\r\n60 5 5\r\n76 57 68\r\n67 3 3\r\n61 52 61\r\n", "output": "No\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\n"}]
| false |
stdio
| null | true |
397/B
|
397
|
B
|
Python 3
|
TESTS
| 1 | 78 | 307,200 |
72907387
|
class CodeforcesTask397BSolution:
def __init__(self):
self.result = ''
self.t = 0
self.queries = []
def read_input(self):
self.t = int(input())
for _ in range(self.t):
self.queries.append([int(x) for x in input().split(" ")])
def process_task(self):
res = []
for query in self.queries:
res.append("Yes" if (query[0] % query[2]) >= query[1] else "No")
self.result = "\n".join(res)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask397BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
| 6 | 62 | 0 |
29595548
|
for i in range(int(input())):
n, l, r = map(int, input().split())
print('No' if (n // l) * r < n else 'Yes')
|
Codeforces Round 232 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
On Corruption and Numbers
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
|
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
|
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
| null |
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
[{"input": "2\n5 2 3\n6 4 5", "output": "Yes\nNo"}]
| null |
["constructive algorithms", "implementation", "math"]
| 6 |
[{"input": "2\r\n5 2 3\r\n6 4 5\r\n", "output": "Yes\r\nNo\r\n"}, {"input": "50\r\n69 6 6\r\n22 1 1\r\n23 3 3\r\n60 13 13\r\n13 3 3\r\n7 4 7\r\n6 1 1\r\n49 7 9\r\n68 8 8\r\n20 2 2\r\n34 1 1\r\n79 5 5\r\n22 1 1\r\n77 58 65\r\n10 3 3\r\n72 5 5\r\n47 1 1\r\n82 3 3\r\n92 8 8\r\n34 1 1\r\n42 9 10\r\n63 14 14\r\n10 3 3\r\n38 2 2\r\n80 6 6\r\n79 5 5\r\n53 5 5\r\n44 7 7\r\n85 2 2\r\n24 2 2\r\n57 3 3\r\n95 29 81\r\n77 6 6\r\n24 1 1\r\n33 4 4\r\n93 6 6\r\n55 22 28\r\n91 14 14\r\n7 1 1\r\n16 1 1\r\n20 3 3\r\n43 3 3\r\n53 3 3\r\n49 3 3\r\n52 5 5\r\n2 1 1\r\n60 5 5\r\n76 57 68\r\n67 3 3\r\n61 52 61\r\n", "output": "No\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\n"}]
| false |
stdio
| null | true |
342/E
|
342
|
E
|
PyPy 3-64
|
TESTS
| 3 | 2,948 | 60,928,000 |
190924318
|
import os, sys
from io import BytesIO, IOBase
from array import array
from itertools import accumulate
import bisect
import math
from collections import deque
# from functools import cache
# cache cf需要自己提交 pypy3.9!
from copy import deepcopy
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, 8192))
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, 8192))
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().strip()
ints = lambda: list(map(int, input().split()))
Int = lambda: int(input())
def queryInteractive(a, b, c):
print('? {} {} {}'.format(a, b, c))
sys.stdout.flush()
return int(input())
def answerInteractive(x1, x2):
print('! {} {}'.format(x1, x2))
sys.stdout.flush()
inf = float('inf')
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class LCA:
"""<O(n), O(log(n))>"""
def __init__(self, G, root, parents):
from collections import deque
self.n = len(G)
self.tour = [0] * (2 * self.n - 1)
self.depth_list = [0] * (2 * self.n - 1)
self.id = [-1] * self.n
self.dfs(G, root, parents)
self._rmq_init(self.depth_list)
def _rmq_init(self, arr):
n = self.mod = len(arr)
self.seg_len = 1 << (n - 1).bit_length()
self.seg = [self.n * n] * (2 * self.seg_len)
seg = self.seg
for i, e in enumerate(arr):
seg[self.seg_len + i] = n * e + i
for i in range(self.seg_len - 1, 0, -1):
seg[i] = min(seg[2 * i], seg[2 * i + 1])
def _rmq_query(self, l, r):
l += self.seg_len
r += self.seg_len
res = self.n * self.mod
seg = self.seg
while l < r:
if r & 1:
r -= 1
res = min(res, seg[r])
if l & 1:
res = min(res, seg[l])
l += 1
l >>= 1
r >>= 1
return res % self.mod
def dfs(self, G, root, parents):
id = self.id
tour = self.tour
depth_list = self.depth_list
v = root
it = [0] * self.n
visit_id = 0
depth = 0
while v != -1:
if id[v] == -1:
id[v] = visit_id
tour[visit_id] = v
depth_list[visit_id] = depth
visit_id += 1
g = G[v]
if it[v] == len(g):
v = parents[v]
depth -= 1
continue
if g[it[v]] == parents[v]:
it[v] += 1
if it[v] == len(g):
v = parents[v]
depth -= 1
continue
else:
child = g[it[v]]
it[v] += 1
v = child
depth += 1
else:
child = g[it[v]]
it[v] += 1
v = child
depth += 1
def lca(self, u: int, v: int) -> int:
l, r = self.id[u], self.id[v]
if r < l:
l, r = r, l
q = self._rmq_query(l, r + 1)
return self.tour[q]
def dist(self, u: int, v: int) -> int:
lca = self.lca(u, v)
depth_u = self.depth_list[self.id[u]]
depth_v = self.depth_list[self.id[v]]
depth_lca = self.depth_list[self.id[lca]]
return depth_u + depth_v - 2 * depth_lca
n,m = ints()
g = [[] for _ in range(n)]
for _ in range(n-1):
u,v = ints()
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
par = [-1]*n
dis = [float('inf')]*n
@bootstrap
def dfs(x,p,d):
dis[x] = d
par[x] = p
for y in g[x]:
if y == p:
continue
yield dfs(y,x,d+1)
yield None
dfs(0,-1,0)
lca = LCA(g,0,par)
LIM = math.sqrt(m)
buck = [0]
def qry(x):
ans = dis[x]
for y in buck:
ans = min(ans,lca.dist(y,x))
#print(y,x,lca.dist(y,x))
return ans
def multi_bfs():
q = deque(buck)
cnt = 0
while q:
l = len(q)
for _ in range(l):
x = q.popleft()
dis[x] = cnt
for y in g[x]:
if dis[y] > dis[x] + 1:
dis[y] = dis[x] + 1
q.append(y)
cnt += 1
return
for i in range(m):
t,v = ints()
v -= 1
if t == 1:
buck.append(v)
if t == 2:
print(qry(v))
if len(buck) >= LIM:
multi_bfs()
buck = []
| 23 | 1,356 | 62,566,400 |
211268601
|
class Tree():
def __init__(self, n):
self.n = n
self.tree = [[] for _ in range(n)]
self.root = None
def addEdge(self, u, v):
self.tree[u].append(v)
self.tree[v].append(u)
def setRoot(self, r=0):
self.root = r
self.par = [None] * self.n
self.dep = [0] * self.n
self.height = [0] * self.n
self.size = [1] * self.n
self.order = [r]
stack = [r]
while stack:
v = stack.pop()
for adj in self.tree[v]:
if self.par[v] == adj: continue
self.par[adj] = v
self.dep[adj] = self.dep[v] + 1
self.order.append(adj)
stack.append(adj)
for v in self.order[1:][::-1]:
self.size[self.par[v]] += self.size[v]
self.height[self.par[v]] = max(self.height[self.par[v]], self.height[v] + 1)
def rerooting(self, op, e, merge, timer):
if self.root is None: self.setRoot()
dp = [e] * self.n
lt = [timer] * self.n
rt = [timer] * self.n
inv = [timer] * self.n
for v in self.order[::-1]:
tl = tr = e
for adj in self.tree[v]:
if self.par[v] == adj: continue
lt[adj] = tl
tl = op(tl, dp[adj])
for adj in self.tree[v][::-1]:
if self.par[v] == adj: continue
rt[adj] = tr
tr = op(tr, dp[adj])
dp[v] = tr
for v in self.order:
if v == self.root: continue
p = self.par[v]
inv[v] = op(merge(lt[v], rt[v]), inv[p])
dp[v] = op(dp[v], inv[v])
return dp
def eulerTour(self):
if self.root is None: self.setRoot()
self.tour = []
self.etin = [None for _ in range(self.n)]
self.etout = [None for _ in range(self.n)]
used = [0 for _ in range(self.n)]
used[self.root] = 1
stack = [self.root]
while stack:
v = stack.pop()
if v >= 0:
self.tour.append(v)
stack.append(~v)
if self.etin[v] is None:
self.etin[v] = len(self.tour) - 1
for adj in self.tree[v]:
if used[adj]: continue
used[adj] = 1
stack.append(adj)
else:
self.etout[~v] = len(self.tour)
if ~v != self.root:
self.tour.append(self.par[~v])
def heavyLightDecompostion(self):
if self.root is None: self.setRoot()
self.hldtimer = [None] * self.n
self.hldtop = [None] * self.n
self.hldtop[self.root] = self.root
self.hldnxt = [None] * self.n
self.hldrev = [None] * self.n
stack = [self.root]
cnt = 0
while stack:
v = stack.pop()
self.hldtimer[v] = cnt
self.hldrev[cnt] = v
cnt += 1
maxs = 0
for adj in self.tree[v]:
if self.par[v] == adj: continue
if maxs < self.size[adj]:
maxs = self.size[adj]
self.hldnxt[v] = adj
for adj in self.tree[v]:
if self.par[v] == adj or self.hldnxt[v] == adj: continue
self.hldtop[adj] = adj
stack.append(adj)
if self.hldnxt[v] is not None:
self.hldtop[self.hldnxt[v]] = self.hldtop[v]
stack.append(self.hldnxt[v])
def lca(self, u, v):
while True:
if self.hldtimer[u] > self.hldtimer[v]: u, v = v, u
if self.hldtop[u] != self.hldtop[v]:
v = self.par[self.hldtop[v]]
else:
return u
def dist(self, u, v):
lca = self.lca(u, v)
return self.dep[u] + self.dep[v] - 2 * self.dep[lca]
def getCentoridTimer(self, r):
self.parent[r] = None
self.size[r] = 1
order = [r]
stack = [r]
while stack:
v = stack.pop()
for adj in self.tree[v]:
if self.parent[v] == adj or self.cdused[adj]: continue
self.size[adj] = 1
self.parent[adj] = v
order.append(adj)
stack.append(adj)
if len(order) <= 2: return r
for v in order[1:][::-1]:
self.size[self.parent[v]] += self.size[v]
sr = self.size[r] // 2
v = r
while True:
for adj in self.tree[v]:
if self.parent[v] == adj or self.cdused[adj]: continue
if self.size[adj] > sr:
v = adj
break
else:
return v
def centroidDecomposition(self):
self.parent = [None] * self.n
self.size = [1] * self.n
self.cdpar = [None] * self.n
self.cddep = [0] * self.n
self.cdorder = [None] * self.n
self.cdused = [0] * self.n
cnt = 0
stack = [0]
while stack:
v = stack.pop()
p = self.cdpar[v]
c = self.getCentoridTimer(v)
self.cdused[c] = True
self.cdpar[c] = p
self.cddep[c] = self.cddep[v]
self.cdorder[c] = cnt
cnt += 1
for adj in self.tree[c]:
if self.cdused[adj]: continue
self.cdpar[adj] = c
self.cddep[adj] = self.cddep[c] + 1
stack.append(adj)
import sys
def rd(): return sys.stdin.readline().strip()
def rdl(typ,sep=" "): return list(map(typ, rd().split(sep)))
def wt(x,sep="\n") : sys.stdout.write(str(x) + sep) # string / num
N, Q = rdl(int)
tree = Tree(N)
for _ in range(N - 1):
u, v = rdl(int)
tree.addEdge(u - 1, v - 1)
tree.heavyLightDecompostion()
tree.centroidDecomposition()
minDist = [N] * N
res = []
def centroidUpdate(v):
curr = v
while curr is not None:
minDist[curr] = min(minDist[curr], tree.dist(curr, v))
curr = tree.cdpar[curr]
def centroidQuery(v):
ret = N
curr = v
while curr is not None:
ret = min(ret, tree.dist(curr, v) + minDist[curr])
curr = tree.cdpar[curr]
return ret
centroidUpdate(0)
for _ in range(Q):
q, v = rdl(int)
if q == 1:
centroidUpdate(v - 1)
else:
wt((centroidQuery(v - 1)))
|
Codeforces Round 199 (Div. 2)
|
CF
| 2,013 | 5 | 256 |
Xenia and Tree
|
Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.
Xenia needs to learn how to quickly execute queries of two types:
1. paint a specified blue node in red;
2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node.
Your task is to write a program which will execute the described queries.
|
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree.
Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi.
It is guaranteed that the given graph is a tree and that all queries are correct.
|
For each second type query print the reply in a single line.
| null | null |
[{"input": "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 5\n1 2\n2 5", "output": "0\n3\n2"}]
| 2,400 |
["data structures", "divide and conquer", "trees"]
| 23 |
[{"input": "5 4\r\n1 2\r\n2 3\r\n2 4\r\n4 5\r\n2 1\r\n2 5\r\n1 2\r\n2 5\r\n", "output": "0\r\n3\r\n2\r\n"}]
| false |
stdio
| null | true |
342/E
|
342
|
E
|
Python 3
|
TESTS
| 3 | 1,886 | 16,588,800 |
69301594
|
def dfs(neighbours, queue, distances):
t = 0
while(t < len(queue)):
for x in neighbours[queue[t]]:
if distances[x] > distances[queue[t]] + 1:
distances[x] = distances[queue[t]] + 1
queue.append(x)
t += 1
return 0
l = input().split()
n = int(l[0])
m = int(l[1])
neighbours = {}
distances = [100000001]*n
for i in range(n):
neighbours[i] = []
for _ in range(n-1):
l = input().split()
a = int(l[0]) - 1
b = int(l[1]) - 1
neighbours[a].append(b)
neighbours[b].append(a)
distances[0] = 0
queue = []
queue.append(0)
for j in range(m):
l = input().split()
a = int(l[0])
b = int(l[1])
if a == 1:
distances[b-1] = 0
queue = [b-1]
else:
dfs(neighbours, queue, distances)
queue = []
print(distances[b-1])
| 23 | 2,480 | 64,307,200 |
190927214
|
import os, sys
from io import BytesIO, IOBase
from array import array
from itertools import accumulate
import bisect
import math
from collections import deque
# from functools import cache
# cache cf需要自己提交 pypy3.9!
from copy import deepcopy
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, 8192))
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, 8192))
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().strip()
ints = lambda: list(map(int, input().split()))
Int = lambda: int(input())
def queryInteractive(a, b, c):
print('? {} {} {}'.format(a, b, c))
sys.stdout.flush()
return int(input())
def answerInteractive(x1, x2):
print('! {} {}'.format(x1, x2))
sys.stdout.flush()
INF = 1000000000
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class LCA:
"""<O(n), O(log(n))>"""
def __init__(self, G, root, parents):
from collections import deque
self.n = len(G)
self.tour = [0] * (2 * self.n - 1)
self.depth_list = [0] * (2 * self.n - 1)
self.id = [-1] * self.n
self.dfs(G, root, parents)
self._rmq_init(self.depth_list)
def _rmq_init(self, arr):
n = self.mod = len(arr)
self.seg_len = 1 << (n - 1).bit_length()
self.seg = [self.n * n] * (2 * self.seg_len)
seg = self.seg
for i, e in enumerate(arr):
seg[self.seg_len + i] = n * e + i
for i in range(self.seg_len - 1, 0, -1):
seg[i] = min(seg[2 * i], seg[2 * i + 1])
def _rmq_query(self, l, r):
l += self.seg_len
r += self.seg_len
res = self.n * self.mod
seg = self.seg
while l < r:
if r & 1:
r -= 1
res = min(res, seg[r])
if l & 1:
res = min(res, seg[l])
l += 1
l >>= 1
r >>= 1
return res % self.mod
def dfs(self, G, root, parents):
id = self.id
tour = self.tour
depth_list = self.depth_list
v = root
it = [0] * self.n
visit_id = 0
depth = 0
while v != -1:
if id[v] == -1:
id[v] = visit_id
tour[visit_id] = v
depth_list[visit_id] = depth
visit_id += 1
g = G[v]
if it[v] == len(g):
v = parents[v]
depth -= 1
continue
if g[it[v]] == parents[v]:
it[v] += 1
if it[v] == len(g):
v = parents[v]
depth -= 1
continue
else:
child = g[it[v]]
it[v] += 1
v = child
depth += 1
else:
child = g[it[v]]
it[v] += 1
v = child
depth += 1
def lca(self, u: int, v: int) -> int:
l, r = self.id[u], self.id[v]
if r < l:
l, r = r, l
q = self._rmq_query(l, r + 1)
return self.tour[q]
def dist(self, u: int, v: int) -> int:
lca = self.lca(u, v)
depth_u = self.depth_list[self.id[u]]
depth_v = self.depth_list[self.id[v]]
depth_lca = self.depth_list[self.id[lca]]
return depth_u + depth_v - 2 * depth_lca
class Graph:
def __init__(self, n):
self.n = n
self.dis = [INF] * n
self.g = [[] for _ in range(n)]
self.root_dis = [INF] * n
self.lca_nodes = []
self.first_occur = [0] * n
self.MAX_LOG = 18
self.rmq = [array('l',[INF]*(2*n)) for _ in range(self.MAX_LOG)]
def input(self):
for _ in range(self.n-1):
u, v = map(int, input().split())
u -= 1
v -= 1
self.g[u].append(v)
self.g[v].append(u)
self.update_distance([0])
self.root_dis[0] = 0
self.dfs_plus(0)
# print(len(self.lca_nodes), self.lca_nodes)
for j in range(self.MAX_LOG):
step = 2**(j-1)
length = len(self.lca_nodes)
for i in range(length):
u = self.lca_nodes[i]
if j == 0:
self.rmq[j][i] = self.root_dis[u]
else:
self.rmq[j][i] = self.rmq[j-1][i]
if i + step < length:
self.rmq[j][i] = min(self.rmq[j][i], self.rmq[j-1][i+step])
def dfs_plus(self, start):
Q = deque([(start,0,-1)])
while Q:
u, nxt, last = Q.pop()
if nxt == 0:
self.first_occur[u] = len(self.lca_nodes)
self.lca_nodes.append(u)
is_add_back = False
for i in range(nxt, len(self.g[u])):
v = self.g[u][i]
if v != last:
self.root_dis[v] = self.root_dis[u] + 1
Q.append((u, i+1, last))
Q.append((v, 0, u))
is_add_back = True
break
if last != -1 and not is_add_back:
self.lca_nodes.append(last)
def dfs(self, u, last):
self.first_occur[u] = len(self.lca_nodes)
self.lca_nodes.append(u)
for v in self.g[u]:
if v != last:
self.root_dis[v] = self.root_dis[u] + 1
self.dfs(v,u)
self.lca_nodes.append(u)
def update_distance(self, l):
# nodes in l are changed to distance 0, update others
for u in l:
self.dis[u] = 0
Q = deque(l)
while Q:
u = Q.popleft()
for v in self.g[u]:
if self.dis[v] > self.dis[u] + 1:
self.dis[v] = self.dis[u] + 1
Q.append(v)
def get_distance(self, u):
return self.dis[u]
def get_pair_distance(self, u, v):
return self.root_dis[u] + self.root_dis[v] \
- 2 * self.get_lca_root_distance(u,v)
def get_lca_root_distance(self, u, v):
fu, fv = self.first_occur[u], self.first_occur[v]
if fu > fv:
fu, fv = fv, fu
length = fv - fu + 1
j, step = 0, 1
while step*2 < length:
j += 1
step <<= 1
return min(self.rmq[j][fu], self.rmq[j][fv - step + 1])
n,m = ints()
g = Graph(n)
g.input()
LIM = int(math.sqrt(m))
buck = [0]
def qry(x):
ans = g.dis[x]
for y in buck:
ans = min(ans,g.get_pair_distance(y,x))
return ans
for i in range(m):
t,v = ints()
v -= 1
if t == 1:
buck.append(v)
else:
print(qry(v))
if len(buck) >= LIM:
g.update_distance(buck)
buck = []
|
Codeforces Round 199 (Div. 2)
|
CF
| 2,013 | 5 | 256 |
Xenia and Tree
|
Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.
Xenia needs to learn how to quickly execute queries of two types:
1. paint a specified blue node in red;
2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node.
Your task is to write a program which will execute the described queries.
|
The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree.
Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi.
It is guaranteed that the given graph is a tree and that all queries are correct.
|
For each second type query print the reply in a single line.
| null | null |
[{"input": "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 5\n1 2\n2 5", "output": "0\n3\n2"}]
| 2,400 |
["data structures", "divide and conquer", "trees"]
| 23 |
[{"input": "5 4\r\n1 2\r\n2 3\r\n2 4\r\n4 5\r\n2 1\r\n2 5\r\n1 2\r\n2 5\r\n", "output": "0\r\n3\r\n2\r\n"}]
| false |
stdio
| null | true |
37/D
|
37
|
D
|
PyPy 3-64
|
TESTS
| 0 | 46 | 614,400 |
215318826
|
import sys
from functools import cache
MOD = 10**9 + 7
def make_comb_matrix(n: int) -> list:
comb = [[1] * (n + 1) for i in range(n + 1)]
for i in range(2, n + 1):
for j in range(1, i):
comb[i][j] = (comb[i - 1][j] + comb[i - 1][j -1]) % MOD
return comb
readline = sys.stdin.readline
M = int(readline())
xs = [int(w) for w in readline().split()]
ys = [int(w) for w in readline().split()]
N = sum(xs)
rests = ys[:]
for i in range(M - 1, 0, -1):
rests[i - 1] += rests[i]
comb = make_comb_matrix(N)
@cache
def dfs(idx: int, prev: int) -> int:
if idx == M - 1:
return int(prev + xs[idx] <= rests[idx])
if prev + xs[idx] > rests[idx]:
return 0
# xs[idx]
result = 0
nprev = rests[idx + 1] - xs[idx + 1]
for i in range(nprev, xs[idx] + prev + 1): # 留 i 个
if i > ys[idx]:
break
nxt = dfs(idx + 1, prev + xs[idx] - i)
if nxt == 0:
continue
result += comb[xs[idx] + prev][i] * nxt
# print('dfs', idx, prev, result)
return result % MOD
result = 1
total = N
for i in range(M):
result *= comb[total][xs[i]]
total -= xs[i]
result %= MOD
# print(result)
# print(xs, ys, rests)
print(result * dfs(0, 0) % MOD)
| 76 | 124 | 11,673,600 |
215322269
|
import sys
from functools import cache
MOD = 10**9 + 7
def make_comb_matrix(n: int) -> list:
comb = [[1] * (n + 1) for i in range(n + 1)]
for i in range(2, n + 1):
for j in range(1, i):
comb[i][j] = (comb[i - 1][j] + comb[i - 1][j -1]) % MOD
return comb
readline = sys.stdin.readline
M = int(readline())
xs = [int(w) for w in readline().split()]
ys = [int(w) for w in readline().split()]
N = sum(xs)
comb = make_comb_matrix(N)
result = 1
total = N
for i in range(M):
result *= comb[total][xs[i]]
total -= xs[i]
result %= MOD
# second
pre = 0
dp = [0] * (N+1)
dp[0] = 1
for i in range(M) :
ndp = [0] * (N + 1)
for j in range(pre + 1) :
res = pre + xs[i] - j
for k in range(min(res + 1, ys[i] + 1)) :
ndp[j + k] += dp[j] * comb[res][k]
ndp[j + k] %= MOD
pre += xs[i]
dp = ndp
print(result * dp[-1] % MOD)
|
Codeforces Beta Round 37
|
CF
| 2,010 | 1 | 256 |
Lesson Timetable
|
When Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with M classrooms numbered from 1 to M, situated along it.
All the students of Petya’s year are divided into N groups. Petya has noticed recently that these groups’ timetable has the following peculiarity: the number of the classroom where the first lesson of a group takes place does not exceed the number of the classroom where the second lesson of this group takes place.
Once Petya decided to count the number of ways in which one can make a lesson timetable for all these groups. The timetable is a set of 2N numbers: for each group the number of the rooms where the first and the second lessons take place. Unfortunately, he quickly lost the track of his calculations and decided to count only the timetables that satisfy the following conditions:
1) On the first lesson in classroom i exactly Xi groups must be present.
2) In classroom i no more than Yi groups may be placed.
Help Petya count the number of timetables satisfying all those conditionsю As there can be a lot of such timetables, output modulo 109 + 7.
|
The first line contains one integer M (1 ≤ M ≤ 100) — the number of classrooms.
The second line contains M space-separated integers — Xi (0 ≤ Xi ≤ 100) the amount of groups present in classroom i during the first lesson.
The third line contains M space-separated integers — Yi (0 ≤ Yi ≤ 100) the maximal amount of groups that can be present in classroom i at the same time.
It is guaranteed that all the Xi ≤ Yi, and that the sum of all the Xi is positive and does not exceed 1000.
|
In the single line output the answer to the problem modulo 109 + 7.
| null |
In the second sample test the first and the second lessons of each group must take place in the same classroom, that’s why the timetables will only be different in the rearrangement of the classrooms’ numbers for each group, e.g. 3! = 6.
|
[{"input": "3\n1 1 1\n1 2 3", "output": "36"}, {"input": "3\n1 1 1\n1 1 1", "output": "6"}]
| 2,300 |
["combinatorics", "dp", "math"]
| 76 |
[{"input": "3\r\n1 1 1\r\n1 2 3\r\n", "output": "36\r\n"}, {"input": "3\r\n1 1 1\r\n1 1 1\r\n", "output": "6\r\n"}, {"input": "3\r\n2 1 1\r\n5 1 2\r\n", "output": "72\r\n"}, {"input": "5\r\n2 1 1 1 1\r\n5 3 1 1 3\r\n", "output": "49320\r\n"}, {"input": "5\r\n1 3 15 3 18\r\n2 6 18 5 19\r\n", "output": "921487545\r\n"}, {"input": "6\r\n3 8 2 6 18 2\r\n6 20 9 6 19 3\r\n", "output": "693504502\r\n"}, {"input": "7\r\n3 4 7 8 6 5 2\r\n6 12 19 16 15 7 5\r\n", "output": "913992323\r\n"}, {"input": "9\r\n1 1 1 3 6 1 4 2 1\r\n1 14 1 6 15 2 14 5 2\r\n", "output": "853357529\r\n"}, {"input": "9\r\n7 1 4 7 8 4 5 7 1\r\n12 10 6 15 13 7 5 17 1\r\n", "output": "71929769\r\n"}, {"input": "11\r\n4 12 2 1 2 9 13 1 12 9 1\r\n16 19 11 8 5 14 19 17 17 14 4\r\n", "output": "737972006\r\n"}, {"input": "12\r\n1 5 1 1 4 3 1 1 1 1 1 1\r\n11 13 7 3 20 9 13 18 8 8 9 4\r\n", "output": "14752815\r\n"}, {"input": "12\r\n2 8 18 8 1 8 3 4 2 3 4 13\r\n5 14 20 16 12 14 14 19 7 19 5 16\r\n", "output": "825613060\r\n"}, {"input": "13\r\n3 4 1 2 14 3 5 4 4 2 3 1 1\r\n4 6 10 5 20 11 10 8 15 6 11 1 1\r\n", "output": "326076016\r\n"}, {"input": "15\r\n3 5 2 10 1 3 5 11 3 1 1 4 2 3 2\r\n8 16 5 14 7 9 10 15 8 18 5 17 3 8 13\r\n", "output": "13869964\r\n"}, {"input": "31\r\n1 6 1 13 41 6 1 2 9 23 30 34 11 6 10 14 7 2 2 6 14 8 12 7 4 5 22 6 22 3 14\r\n4 9 3 27 45 22 3 11 9 32 36 34 43 43 35 44 20 12 25 7 14 8 22 31 24 5 36 9 23 4 49\r\n", "output": "402278182\r\n"}, {"input": "33\r\n3 27 7 10 1 1 17 15 2 7 1 10 1 1 9 1 10 4 2 24 10 3 8 21 13 3 8 19 6 22 10 9 19\r\n5 46 9 40 7 2 39 40 4 26 32 22 4 6 42 2 15 7 24 38 22 45 14 35 35 26 38 33 10 49 49 48 33\r\n", "output": "702251119\r\n"}, {"input": "34\r\n4 17 3 9 12 3 13 1 1 13 22 8 1 3 14 5 3 13 2 4 8 3 5 7 5 3 32 12 6 4 3 19 13 1\r\n22 50 4 25 35 13 24 23 12 24 35 15 5 5 26 30 32 38 3 21 16 5 13 34 22 28 43 36 23 25 27 26 46 3\r\n", "output": "529866511\r\n"}, {"input": "36\r\n1 9 20 9 9 1 4 1 11 5 14 1 5 8 7 5 8 10 1 1 2 1 4 15 4 6 9 11 17 4 1 8 1 12 15 18\r\n3 30 41 21 35 19 20 10 25 18 40 3 33 30 34 15 25 31 10 1 5 27 43 49 12 12 38 27 46 9 17 17 19 25 46 41\r\n", "output": "862453940\r\n"}, {"input": "39\r\n23 4 6 2 11 1 2 17 36 1 13 9 14 9 4 6 2 20 3 2 31 6 16 1 3 11 36 3 2 15 3 3 27 20 5 9 17 26 20\r\n27 20 8 2 27 3 2 34 45 8 39 29 34 28 7 26 11 20 29 3 47 8 30 1 33 25 50 3 4 16 9 4 34 46 25 48 25 27 31\r\n", "output": "533737639\r\n"}, {"input": "41\r\n1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1\r\n4 34 4 9 28 16 37 3 16 4 9 9 25 14 26 43 35 23 28 44 23 42 29 15 34 19 22 40 2 13 44 32 23 37 22 33 38 25 4 1 47\r\n", "output": "641814964\r\n"}, {"input": "43\r\n5 6 28 30 15 34 18 2 5 8 8 5 9 16 10 9 9 18 2 13 2 16 4 7 2 19 9 1 11 32 32 27 20 12 24 3 8 6 24 1 6 25 32\r\n46 26 44 31 16 50 29 19 18 9 19 8 21 29 48 21 35 29 3 29 6 35 5 18 2 25 14 1 38 44 33 32 25 33 43 50 8 19 43 31 30 43 47\r\n", "output": "495674257\r\n"}, {"input": "44\r\n21 21 2 6 12 15 1 10 35 3 5 2 7 4 1 10 1 2 6 21 11 3 10 24 27 1 35 10 18 17 5 30 9 9 26 1 20 2 20 5 9 27 6 14\r\n49 25 10 16 32 39 1 27 44 24 21 5 34 4 1 24 1 2 11 28 13 5 17 28 47 12 44 40 32 29 6 38 14 24 35 37 26 26 47 30 30 43 27 21\r\n", "output": "566172318\r\n"}, {"input": "46\r\n20 27 5 4 2 23 7 38 2 1 2 23 1 34 3 3 11 31 3 11 2 10 22 6 11 43 9 4 16 20 3 22 16 20 6 12 6 30 26 17 1 16 3 13 9 27\r\n27 41 33 4 2 30 18 39 26 3 6 27 1 44 6 3 28 38 42 15 2 29 37 17 35 46 45 49 41 36 7 47 22 45 7 14 23 33 43 50 1 20 5 36 9 32\r\n", "output": "584532065\r\n"}, {"input": "50\r\n5 1 2 1 1 1 1 1 1 1 2 2 3 2 1 3 1 2 6 1 1 4 3 1 1 4 1 3 1 1 1 3 1 6 3 1 6 1 1 2 4 2 1 1 2 7 7 3 1 2\r\n40 4 48 29 6 31 5 13 8 14 19 28 31 44 15 21 13 24 39 2 17 42 50 6 20 26 12 29 12 21 50 40 8 42 26 28 42 22 22 18 36 41 15 12 30 45 47 44 19 24\r\n", "output": "710102803\r\n"}]
| false |
stdio
| null | true |
986/B
|
986
|
B
|
PyPy 3
|
TESTS
| 2 | 171 | 4,812,800 |
160459989
|
from bisect import *
from collections import *
import sys
import io, os
import math
import random
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
def ceil(a, b):
a = -a
k = a // b
k = -k
return k
# arr=list(map(int, input().split()))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def strinp(testcases):
k = 5
if (testcases == -1 or testcases == 1):
k = 1
f = str(input())
f = f[2:len(f) - k]
return f
def minSwaps(arr):
n = len(arr)
# Create two arrays and use
# as pairs where first array
# is element and second array
# is position of first element
arrpos = [*enumerate(arr)]
# Sort the array by array element
# values to get right position of
# every element as the elements
# of second array.
arrpos.sort(key = lambda it : it[1])
# To keep track of visited elements.
# Initialize all elements as not
# visited or false.
vis = {k : False for k in range(n)}
# Initialize result
ans = 0
for i in range(n):
# already swapped or
# already present at
# correct position
if vis[i] or arrpos[i][0] == i:
continue
# find number of nodes
# in this cycle and
# add it to ans
cycle_size = 0
j = i
while not vis[j]:
# mark node as visited
vis[j] = True
# move to next node
j = arrpos[j][0]
cycle_size += 1
# update answer by adding
# current cycle
if cycle_size > 0:
ans += (cycle_size - 1)
# return answer
return ans
def main():
t=1
for _ in range(t):
n=int(input())
arr=list(map(int, input().split()))
na=[0]*(n)
for i in range(n):
na[arr[i]-1]=i
g=minSwaps(na)
if(g>3*n):
print("Um_nik")
else:
print('Petr')
main()
| 24 | 748 | 75,059,200 |
39037427
|
n=int(input())
a=[0]+list(map(int,input().split()))
ans=0
for i in range(1,len(a)):
if a[i]==-1:
continue
j=i
while a[j]!=-1:
prev=j
j=a[j]
a[prev]=-1
ans+=1
if n%2==0:
#n even ans also even even number of swaps required
#3*n
if ans%2==0:
print("Petr")
else:
print("Um_nik")
else:
#n us odd ans is even odd number of swaps required
if ans%2==0:
print("Petr")
else:
print("Um_nik")
|
Codeforces Round 485 (Div. 1)
|
CF
| 2,018 | 2 | 256 |
Petr and Permutations
|
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
|
In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$).
In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
|
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
| null |
Please note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
|
[{"input": "5\n2 4 5 1 3", "output": "Petr"}]
| 1,800 |
["combinatorics", "math"]
| 24 |
[{"input": "5\r\n2 4 5 1 3\r\n", "output": "Petr\r\n"}]
| false |
stdio
| null | true |
177/D1
|
177
|
D2
|
Python 3
|
TESTS2
| 0 | 60 | 0 |
142746309
|
line = input().split(' ')
n, m, c = int(line[0]), int(line[1]), int(line[2])
arr = input().split(' ')
for i in range(len(arr)):
arr[i] = int(arr[i])
enc = input().split(' ')
for i in range(len(enc)):
enc[i] = int(enc[i])
dif = [0] * (n + 2)
for i in range(m):
dif[i + 1] += enc[i]
if n - m + i + 2 < n:
dif[n - m + i + 2] -= enc[i]
for i in range(1, len(dif)):
dif[i] += dif[i - 1]
for i in range(1, len(dif) - 1):
arr[i - 1] += dif[i]
arr[i - 1] = (arr[i - 1] % c)
for i in range(len(arr)):
print(str(arr[i]), end = ' ')
| 12 | 184 | 2,048,000 |
197629446
|
L = lambda: list(map(int, input().split()))
n, m, c = L()
A, B = L(), L()
for i in range(n-m+1):
for j in range(i, i+m):
A[j] += B[j-i]
A[j] %= c
print(*A)
|
ABBYY Cup 2.0 - Easy
|
ICPC
| 2,012 | 2 | 256 |
Encrypting Messages
|
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
|
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.
The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key.
The input limitations for getting 30 points are:
- 1 ≤ m ≤ n ≤ 103
- 1 ≤ c ≤ 103
The input limitations for getting 100 points are:
- 1 ≤ m ≤ n ≤ 105
- 1 ≤ c ≤ 103
|
Print n space-separated integers — the result of encrypting the original message.
| null |
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
|
[{"input": "4 3 2\n1 1 1 1\n1 1 1", "output": "0 1 1 0"}, {"input": "3 1 5\n1 2 3\n4", "output": "0 1 2"}]
| 1,200 |
["brute force"]
| 12 |
[{"input": "4 3 2\r\n1 1 1 1\r\n1 1 1\r\n", "output": "0 1 1 0\r\n"}, {"input": "3 1 5\r\n1 2 3\r\n4\r\n", "output": "0 1 2\r\n"}, {"input": "5 2 7\r\n0 0 1 2 4\r\n3 5\r\n", "output": "3 1 2 3 2\r\n"}, {"input": "20 15 17\r\n4 9 14 11 15 16 15 4 0 10 7 12 10 1 8 6 7 14 1 13\r\n6 3 14 8 8 11 16 4 5 9 2 13 6 14 15\r\n", "output": "10 1 3 8 3 15 7 14 1 12 3 10 15 16 16 5 4 15 13 11\r\n"}]
| false |
stdio
| null | true |
451/C
|
451
|
C
|
PyPy 3-64
|
TESTS
| 1 | 1,013 | 9,011,200 |
214655604
|
t = int(input())
for _ in range(t):
n, k, d1, d2 = list(map(int, input().split()))
if (n % 3 != 0):
print("no")
continue
x1 = (2 * d1 + d2 + k) // 3
x2 = x1 - d1
x3 = x2 - d2
if not (x1 <= n // 3 and x2 <= n // 3 and x3 <= n // 3):
print("no")
continue
r = n - k
t = int(n // 3)
rx1, rx2, rx3 = (t - x1), (t - x2), (t - x3)
if (rx1 + rx2 + rx3 == r): print("yes")
else: print("no")
| 36 | 529 | 11,776,000 |
212078103
|
from sys import stdin ,stdout
input=stdin.readline
inp = lambda : map(int,input().split())
def print(*args, end='\n', sep=' ') -> None:
stdout.write(sep.join(map(str, args)) + end)
def check() :
global ans , arr , n , k
for i in arr :
if i<0 : return 0
ans += max(arr ) - i
if ans== n -k : return 1
elif n-k - ans > 0 and (n-k - ans )%3==0: return 1
return 0
def summ() :
global arr
z= 0
for i in arr :
z+=abs(i)
return z
for _ in range(int(input())) :
n , k , d1 , d2 = inp()
if (k-d1-d2 ) % 3 == 0 :
b= (k - d1-d2)//3 ; a= b+d1 ; c = b+d2 ; arr=[a,b,c] ; ans=0
if check() : print("yes") ; continue
if (k- (d1 -d2)) %3==0 :
b= (k-(d1-d2))//3 ; a= b+d1 ; c = b-d2 ; arr=[a,b,c] ; ans=0
if check() : print("yes") ; continue
if (k-(d2-d1)) %3==0 :
b= (k-(d2-d1))//3 ; a= b-d1 ; c = b+d2 ; arr=[a,b,c] ; ans=0
if check() : print("yes") ; continue
if (k-(-d2-d1)) %3==0 :
b= (k-(-d2-d1))//3 ; a= b-d1 ; c = b-d2 ; arr=[a,b,c] ; ans=0
if check() : print("yes") ; continue
print("no")
|
Codeforces Round 258 (Div. 2)
|
CF
| 2,014 | 2 | 256 |
Predict Outcome of the Game
|
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.
You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.
You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?
Note that outcome of a match can not be a draw, it has to be either win or loss.
|
The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 105).
Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — data for the current test case.
|
For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).
| null |
Sample 1. There has not been any match up to now (k = 0, d1 = 0, d2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.
Sample 2. You missed all the games (k = 3). As d1 = 0 and d2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".
Sample 3. You missed 4 matches, and d1 = 1, d2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).
|
[{"input": "5\n3 0 0 0\n3 3 0 0\n6 4 1 0\n6 3 3 0\n3 3 3 2", "output": "yes\nyes\nyes\nno\nno"}]
| 1,700 |
["brute force", "implementation", "math"]
| 36 |
[{"input": "5\r\n3 0 0 0\r\n3 3 0 0\r\n6 4 1 0\r\n6 3 3 0\r\n3 3 3 2\r\n", "output": "yes\r\nyes\r\nyes\r\nno\r\nno\r\n"}]
| false |
stdio
| null | true |
689/E
|
689
|
E
|
Python 3
|
PRETESTS
| 0 | 46 | 0 |
18935365
|
N, K = map(int,input().split())
L = [list(map(int,input().split())) for x in range(N)]
a = [L[x][0] for x in range(N)]
b = [L[x][1] for x in range(N)]
s = 0
a.sort()
b.sort()
a = a[K-1:] + [a[-1]]*(K-1)
b = [b[0]]*(K-1) + b[:K-1]
print(sum(a)+sum(b))
| 69 | 1,513 | 48,128,000 |
228758837
|
from collections import defaultdict
mod=10**9+7
MAXN=300001
def power(a,b):
res=1
while b>0:
if b&1:
res=(res*a)%mod
b>>=1
a=(a*a)%mod
return res
fact=[1 for _ in range(MAXN)]
inv_fact=[1 for _ in range(MAXN)]
for i in range(2,MAXN):
fact[i]=(fact[i-1]*i)%mod
inv_fact[i]=power(fact[i],mod-2)
def ncr(n,r):
if n<r:
return 0
return (((fact[n]*inv_fact[r])%mod)*inv_fact[n-r])%mod
n,k=map(int,input().split())
mp=defaultdict(int)
end_points=[]
for _ in range(n):
l,r=map(int,input().split())
mp[l]+=1
mp[r+1]-=1
end_points=list(mp.keys())
end_points.sort()
ans=0
curr=0
for i in range(len(end_points)-1):
curr+=mp[end_points[i]]
ans+=(end_points[i+1]-end_points[i])*ncr(curr,k)
if ans>=mod:
ans%=mod
print(ans)
|
Codeforces Round 361 (Div. 2)
|
CF
| 2,016 | 3 | 256 |
Mike and Geometry Problem
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that $$f(\varnothing) = 0$$). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find:
$$\sum_{1 \leq i_1 < i_2 < \ldots < i_k \leq n} f([l_{i_1}, r_{i_1}] \cap [l_{i_2}, r_{i_2}] \cap \ldots \cap [l_{i_k}, r_{i_k}])$$
In other words, you should find the sum of the number of integer points in the intersection of any k of the segments.
As the answer may be very large, output it modulo 1000000007 (109 + 7).
Mike can't solve this problem so he needs your help. You will help him, won't you?
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively.
Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
|
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
| null |
In the first example:
$$f([1,2]\cap[1,3])=f([1,2])=2$$;
$$f([1,2]\cap[2,3])=f([2,2])=1$$;
$$f([1,3]\cap[2,3])=f([2,3])=2$$.
So the answer is 2 + 1 + 2 = 5.
|
[{"input": "3 2\n1 2\n1 3\n2 3", "output": "5"}, {"input": "3 3\n1 3\n1 3\n1 3", "output": "3"}, {"input": "3 1\n1 2\n2 3\n3 4", "output": "6"}]
| 2,000 |
["combinatorics", "data structures", "dp", "geometry", "implementation"]
| 69 |
[{"input": "3 2\r\n1 2\r\n1 3\r\n2 3\r\n", "output": "5\r\n"}, {"input": "3 3\r\n1 3\r\n1 3\r\n1 3\r\n", "output": "3\r\n"}, {"input": "3 1\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "6\r\n"}, {"input": "1 1\r\n45 70\r\n", "output": "26\r\n"}, {"input": "1 1\r\n-35 -8\r\n", "output": "28\r\n"}, {"input": "1 1\r\n-79 -51\r\n", "output": "29\r\n"}, {"input": "2 2\r\n26 99\r\n-56 40\r\n", "output": "15\r\n"}, {"input": "9 6\r\n-44 -29\r\n-11 85\r\n11 84\r\n-63 1\r\n75 89\r\n-37 61\r\n14 73\r\n78 88\r\n-22 -18\r\n", "output": "0\r\n"}, {"input": "2 2\r\n-93 -22\r\n12 72\r\n", "output": "0\r\n"}]
| false |
stdio
| null | true |
451/C
|
451
|
C
|
PyPy 3-64
|
TESTS
| 1 | 1,075 | 10,547,200 |
214707025
|
t = int(input())
for _ in range(t):
n, k, d1, d2 = list(map(int, input().split()))
if (n % 3 != 0):
print("no")
continue
v = False
for sign1 in range(-1, 2):
for sign2 in range(-1, 2):
if (sign1 == 0 or sign2 == 0): continue
d1 = d1 * sign1
d2 = d2 * sign2
x1 = (2 * d1 + d2 + k) // 3
if ((2 * d1 + d2 + k) % 3) != 0:continue
if ( 0 <= x1 and x1 <= k):
x2 = x1 - d1
x3 = x2 - d2
if (x1 >= 0 and x1 <= k and x3 >= 0 and x3 <= k):
if (x1 <= n // 3 and x2 <= n // 3 and x3 <= n // 3):
if (abs(x1 - x2) == d1 and abs(x2 - x3) == d2):
v = True
if (v):
break
if (v): break
if (not v): print("no")
else: print("yes")
| 36 | 1,232 | 512,000 |
7228790
|
import itertools
import sys
'''
w1 - w2 = d1
w2 - w3 = d2
w1 + w2 + w3 = k
w1 = w2 + d1
w3 = w2 - d2
w2 + d1 + w2 + w2 - d2 = k
w2 = (k - d1 + d2) / 3
w1 = w2 + d1
w3 = w2 - d2
'''
for _ in range(int(input())):
n, k, d1, d2 = map(int, str.split(sys.stdin.readline()))
for s1, s2 in itertools.product((1, -1), repeat=2):
cd1, cd2 = d1 * s1, d2 * s2
w2 = k - cd1 + cd2
if w2 % 3 != 0:
continue
w2 //= 3
w1 = w2 + cd1
w3 = w2 - cd2
if w1 >= 0 and w2 >= 0 and w3 >= 0:
d = n - k
mw = max((w1, w2, w3))
nw = 3 * mw - w1 - w2 - w3
if d >= nw and (d - nw) % 3 == 0:
print("yes")
break
else:
print("no")
|
Codeforces Round 258 (Div. 2)
|
CF
| 2,014 | 2 | 256 |
Predict Outcome of the Game
|
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.
You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.
You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?
Note that outcome of a match can not be a draw, it has to be either win or loss.
|
The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 105).
Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — data for the current test case.
|
For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).
| null |
Sample 1. There has not been any match up to now (k = 0, d1 = 0, d2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.
Sample 2. You missed all the games (k = 3). As d1 = 0 and d2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".
Sample 3. You missed 4 matches, and d1 = 1, d2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).
|
[{"input": "5\n3 0 0 0\n3 3 0 0\n6 4 1 0\n6 3 3 0\n3 3 3 2", "output": "yes\nyes\nyes\nno\nno"}]
| 1,700 |
["brute force", "implementation", "math"]
| 36 |
[{"input": "5\r\n3 0 0 0\r\n3 3 0 0\r\n6 4 1 0\r\n6 3 3 0\r\n3 3 3 2\r\n", "output": "yes\r\nyes\r\nyes\r\nno\r\nno\r\n"}]
| false |
stdio
| null | true |
852/E
|
852
|
E
|
PyPy 3
|
TESTS
| 1 | 78 | 0 |
30117158
|
print(4+0)
| 12 | 577 | 8,089,600 |
175629065
|
'''
john以好心情开始、在n个“由n-1条双向边连通”的城市间旅行,每个城市呆一天,然后选择相邻未访问的城市,
到达有赌场的城市时john一定会试下身手,并且赌博会改变心情,即由好变坏、或反之,
求使得john总是会以好心情结束旅程的“选择起始城市和设赌场的”方案数。
dfs计数,超时。
描述问题:在树上任意选择根节点并将每个节点描为红或黑色,
求满足“从根节点到任意叶节点的路径上包含偶数个黑节点”的方案数。
考虑如何使“路径上包含偶数个黑节点”,……答案是其他节点任意设颜色、由叶节点来修正
做完这题给人带来的直觉是,关于奇偶性的问题,解法可以是简单的。
'''
I=input;n=int(I());d=[0]*n
for _ in range(n-1):
for u in I().split():d[int(u)-1]+=1
l=d.count(1);print((l*2**(n-l+1)+(n-l)*2**(n-l))%(10**9+7))
|
Bubble Cup X - Finals [Online Mirror]
|
ICPC
| 2,017 | 1 | 256 |
Casinos and travel
|
John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N.
John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules.
To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey.
He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey.
In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109 + 7.
|
In the first line, a positive integer N (1 ≤ N ≤ 100000), the number of cities.
In the next N - 1 lines, two numbers a, b (1 ≤ a, b ≤ N) separated by a single space meaning that cities a and b are connected by a bidirectional road.
|
Output one number, the answer to the problem modulo 109 + 7.
| null |
Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4.
Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
|
[{"input": "2\n1 2", "output": "4"}, {"input": "3\n1 2\n2 3", "output": "10"}]
| 2,100 |
["dp"]
| 12 |
[{"input": "2\r\n1 2\r\n", "output": "4\r\n"}, {"input": "3\r\n1 2\r\n2 3\r\n", "output": "10\r\n"}, {"input": "4\r\n1 2\r\n2 3\r\n3 4\r\n", "output": "24\r\n"}]
| false |
stdio
| null | true |
545/A
|
545
|
A
|
Python 3
|
TESTS
| 3 | 31 | 0 |
181555683
|
size = int(input())
matrix = [[int(x) for x in input().split(" ")] for y in range(size)]
sols = []
for irow in range(size):
sols.append(irow)
for icol in range(size):
if matrix[irow][icol] == 3 or matrix[irow][icol] == 1:
if len(sols) > 0:
sols.pop(len(sols)-1)
print(len(sols))
for x in sols:
print(x+1, end=" ")
print()
| 35 | 46 | 0 |
188007982
|
n = int(input())
i = 0
data = []
while i < n:
data.append([int(x) for x in input().split()])
i += 1
i = 0
bad_cars = set()
while i < n:
j = 0
while j < n:
if data[i][j] == 1:
bad_cars.add(i + 1)
elif data[i][j] == 2:
bad_cars.add(j + 1)
elif data[i][j] == 3:
bad_cars.add(i + 1)
bad_cars.add(j + 1)
j += 1
i += 1
good_cars = []
i = 1
while i < n + 1:
if i not in bad_cars:
good_cars.append(str(i))
i += 1
print(n - len(bad_cars))
if n - len(bad_cars) != 0:
print(' '.join(good_cars))
|
Codeforces Round 303 (Div. 2)
|
CF
| 2,015 | 1 | 256 |
Toy Cars
|
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car:
- - 1: if this pair of cars never collided. - 1 occurs only on the main diagonal of the matrix.
- 0: if no car turned over during the collision.
- 1: if only the i-th car turned over during the collision.
- 2: if only the j-th car turned over during the collision.
- 3: if both cars turned over during the collision.
Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?
|
The first line contains integer n (1 ≤ n ≤ 100) — the number of cars.
Each of the next n lines contains n space-separated integers that determine matrix A.
It is guaranteed that on the main diagonal there are - 1, and - 1 doesn't appear anywhere else in the matrix.
It is guaranteed that the input is correct, that is, if Aij = 1, then Aji = 2, if Aij = 3, then Aji = 3, and if Aij = 0, then Aji = 0.
|
Print the number of good cars and in the next line print their space-separated indices in the increasing order.
| null | null |
[{"input": "3\n-1 0 0\n0 -1 1\n0 2 -1", "output": "2\n1 3"}, {"input": "4\n-1 3 3 3\n3 -1 3 3\n3 3 -1 3\n3 3 3 -1", "output": "0"}]
| 900 |
["implementation"]
| 35 |
[{"input": "3\r\n-1 0 0\r\n0 -1 1\r\n0 2 -1\r\n", "output": "2\r\n1 3 "}, {"input": "4\r\n-1 3 3 3\r\n3 -1 3 3\r\n3 3 -1 3\r\n3 3 3 -1\r\n", "output": "0\r\n"}, {"input": "1\r\n-1\r\n", "output": "1\r\n1 "}, {"input": "2\r\n-1 0\r\n0 -1\r\n", "output": "2\r\n1 2 "}, {"input": "2\r\n-1 1\r\n2 -1\r\n", "output": "1\r\n2 "}, {"input": "2\r\n-1 2\r\n1 -1\r\n", "output": "1\r\n1 "}, {"input": "2\r\n-1 3\r\n3 -1\r\n", "output": "0\r\n"}]
| false |
stdio
| null | true |
451/C
|
451
|
C
|
PyPy 3-64
|
TESTS
| 1 | 1,060 | 10,444,800 |
208580733
|
def is_possible(n, k, d1, d2):
# Check for the case where no games have been played yet
if k == 0:
if (d1 + d2) % 3 == 0:
return "yes"
else:
return "no"
# Check if it is possible to have a valid tournament using the remaining games
remaining_games = n - k
if (d1 + d2) % 3 == 0:
if remaining_games % 2 == 0:
return "yes"
else:
return "no"
else:
if k % 2 == 0:
x = (remaining_games + d1 - d2) // 2
y = (remaining_games - d1 + d2) // 2
z = (remaining_games - d1 - d2) // 2
if x >= 0 and y >= 0 and z >= 0 and x + d1 >= y and y >= 0 and z + d2 >= y and y >= 0:
return "yes"
else:
return "no"
else:
return "no"
# Read input and process each test case
t = int(input())
for i in range(t):
n, k, d1, d2 = map(int, input().split())
print(is_possible(n, k, d1, d2))
| 36 | 1,996 | 0 |
18778723
|
read = lambda: map(int, input().split())
f = lambda x, y, a, b: x > a or y > b or (a - x) % 3 or (b - y) % 3
g = lambda x, y, a, b: f(x, y, a, b) and f(x, y, b, a)
t = int(input())
for i in range(t):
n, k, d1, d2 = read()
r = n - k
d = d1 + d2
p = 2 * d2 - d1 if d2 > d1 else 2 * d1 - d2
print('no' if g(d, p, k, r) and g(d + d1, d + d2, k, r) else 'yes')
|
Codeforces Round 258 (Div. 2)
|
CF
| 2,014 | 2 | 256 |
Predict Outcome of the Game
|
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.
You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.
You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?
Note that outcome of a match can not be a draw, it has to be either win or loss.
|
The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 105).
Each of the next t lines will contain four space-separated integers n, k, d1, d2 (1 ≤ n ≤ 1012; 0 ≤ k ≤ n; 0 ≤ d1, d2 ≤ k) — data for the current test case.
|
For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).
| null |
Sample 1. There has not been any match up to now (k = 0, d1 = 0, d2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.
Sample 2. You missed all the games (k = 3). As d1 = 0 and d2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".
Sample 3. You missed 4 matches, and d1 = 1, d2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).
|
[{"input": "5\n3 0 0 0\n3 3 0 0\n6 4 1 0\n6 3 3 0\n3 3 3 2", "output": "yes\nyes\nyes\nno\nno"}]
| 1,700 |
["brute force", "implementation", "math"]
| 36 |
[{"input": "5\r\n3 0 0 0\r\n3 3 0 0\r\n6 4 1 0\r\n6 3 3 0\r\n3 3 3 2\r\n", "output": "yes\r\nyes\r\nyes\r\nno\r\nno\r\n"}]
| false |
stdio
| null | true |
817/E
|
817
|
E
|
PyPy 3
|
TESTS
| 1 | 187 | 5,017,600 |
170367366
|
from collections import defaultdict, deque, Counter
import sys
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce, lru_cache
from bisect import bisect_left, bisect_right
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# sys.setrecursionlimit(10000000)
# import pypyjit
# pypyjit.set_param('max_unroll_recursion=-1')
inf = float('inf')
eps = 10 ** (-12)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
class Multiset():
def __init__(self, digit):
self.d = defaultdict(int)
self.digit = digit
def add(self, a, i):
c = 0
for k in range(self.digit - 1, -2, -1):
self.d[(c, k + 1)] += i
if k >= 0:
c += (a & (1 << k))
# set中にpi^x < tarなるpiがいくつ含まれるか
def xor_count(self, x, tar):
c, res = 0, 0
for k in range(self.digit - 1, -1, -1):
# tarのフラグが1の時のみカウントが進む
res += self.d[(c, k)] * (((tar & (1 << k)) > 0))
c += (x & (1 << k))
return res
V = Multiset(32)
N = getN()
for _ in range(N):
q = getList()
if q[0] == 1:
V.add(q[1], 1)
elif q[0] == 2:
V.add(q[1], -1)
else:
print(V.xor_count(q[1], q[2]))
| 42 | 358 | 28,262,400 |
132474088
|
import sys
input = sys.stdin.buffer.readline
def binary_trie(l):
G0, G1, cnt = [-1], [-1], [0]
return G0, G1, cnt, l
def insert(x):
j = 0
for i in range(l, -1, -1):
cnt[j] += 1
if x & pow2[i]:
if G1[j] == -1:
G0.append(-1)
G1.append(-1)
cnt.append(0)
G1[j] = len(cnt) - 1
j = G1[j]
else:
if G0[j] == -1:
G0.append(-1)
G1.append(-1)
cnt.append(0)
G0[j] = len(cnt) - 1
j = G0[j]
cnt[j] += 1
return
def erase(x):
j = 0
for i in range(l, -1, -1):
cnt[j] -= 1
if x & pow2[i]:
j = G1[j]
else:
j = G0[j]
cnt[j] -= 1
return
def xor_and_count_min(x, k):
j = 0
ans = 0
for i in range(l, -1, -1):
if not x & pow2[i]:
if k & pow2[i]:
if G0[j] ^ -1:
ans += cnt[G0[j]]
j = G1[j]
else:
j = G0[j]
else:
if k & pow2[i]:
if G1[j] ^ -1:
ans += cnt[G1[j]]
j = G0[j]
else:
j = G1[j]
return ans
q = int(input())
pow2 = [1]
for _ in range(31):
pow2.append(2 * pow2[-1])
G0, G1, cnt, l = binary_trie(31)
ans = []
for _ in range(q):
t = list(map(int, input().split()))
p = t[1]
if t[0] == 1:
insert(p)
elif t[0] == 2:
erase(p)
else:
li = t[2]
ans0 = xor_and_count_min(p, li)
ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans)))
|
Educational Codeforces Round 23
|
ICPC
| 2,017 | 2 | 256 |
Choosing The Commander
|
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.
Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.
Each warrior is represented by his personality — an integer number pi. Each commander has two characteristics — his personality pj and leadership lj (both are integer numbers). Warrior i respects commander j only if $$p_i \oplus p_j < l_j$$ ($$x \oplus y$$ is the bitwise excluding OR of x and y).
Initially Vova's army is empty. There are three different types of events that can happen with the army:
- 1 pi — one warrior with personality pi joins Vova's army;
- 2 pi — one warrior with personality pi leaves Vova's army;
- 3 pi li — Vova tries to hire a commander with personality pi and leadership li.
For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.
|
The first line contains one integer q (1 ≤ q ≤ 100000) — the number of events.
Then q lines follow. Each line describes the event:
- 1 pi (1 ≤ pi ≤ 108) — one warrior with personality pi joins Vova's army;
- 2 pi (1 ≤ pi ≤ 108) — one warrior with personality pi leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment);
- 3 pi li (1 ≤ pi, li ≤ 108) — Vova tries to hire a commander with personality pi and leadership li. There is at least one event of this type.
|
For each event of the third type print one integer — the number of warriors who respect the commander Vova tries to hire in the event.
| null |
In the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him ($$4 \oplus 6 = 2$$, and 2 < 3, but $$3 \oplus 6 = 5$$, and 5 ≥ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.
|
[{"input": "5\n1 3\n1 4\n3 6 3\n2 4\n3 6 3", "output": "1\n0"}]
| 2,000 |
["bitmasks", "data structures", "trees"]
| 42 |
[{"input": "5\r\n1 3\r\n1 4\r\n3 6 3\r\n2 4\r\n3 6 3\r\n", "output": "1\r\n0\r\n"}]
| false |
stdio
| null | true |
774/H
|
774
|
H
|
Python 3
|
TESTS
| 0 | 46 | 4,812,800 |
26153704
|
n = int(input())
a = list(map(int, input().split()))
cur = 0
k = 0
for i in range(n - 1, -1, -1):
k += cur
a[i] -= k
cur += a[i]
b = [[0, 0]] * n;
for i in range(n - 1, -1, -1):
b[i] = [ a[i], i + 1 ]
for i in range(n):
for j in range(n - 1):
if b[j][0] < b[j + 1][0]:
swap(b[j][0], b[j + 1][0])
pos = 0
cur = 'a'
ans = [' '] * n;
while b[0][0] > 0:
for i in range(pos, pos + b[0][1]):
ans[i] = cur
if cur == 'a':
cur = 'b'
else:
cur = 'a'
pos += b[0][1]
b[0][0] -= 1;
for i in range(n - 1):
if b[j][0] < b[j + 1][0]:
swap(b[j][0], b[j + 1][0])
for i in range(n):
print(ans[i])
| 44 | 62 | 0 |
120297469
|
import sys
n = int(input())
c = list(map(int, input().split()))
cc = ord('a')
ans = ""
cur = n - 1
if 1:
cur = n - 1
while cur >= 0:
while c[cur] > 0:
if chr(cc) > 'z':
cc = ord('a')
ans += chr(cc) * (cur + 1)
c[cur] -= 1
for i in range(cur):
c[i] -= (cur - i + 1)
cc += 1
cur -= 1
print(ans)
|
VK Cup 2017 - Wild Card Round 1
|
ICPC
| 2,017 | 2 | 256 |
Repairing Of String
|
Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet.
After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c1, c2, ..., cn, where n equals the length of the string s, and ci equals the number of substrings in the string s with the length i, consisting of the same letters. The substring is a sequence of consecutive characters in the string s.
For example, if the Stepan's favorite string is equal to "tttesst", the sequence c looks like: c = [7, 3, 1, 0, 0, 0, 0].
Stepan asks you to help to repair his favorite string s according to the given sequence c1, c2, ..., cn.
|
The first line contains the integer n (1 ≤ n ≤ 2000) — the length of the Stepan's favorite string.
The second line contains the sequence of integers c1, c2, ..., cn (0 ≤ ci ≤ 2000), where ci equals the number of substrings of the string s with the length i, consisting of the same letters.
It is guaranteed that the input data is such that the answer always exists.
|
Print the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet.
| null |
In the first test Stepan's favorite string, for example, can be the string "kkrrrq", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3).
|
[{"input": "6\n6 3 1 0 0 0", "output": "kkrrrq"}, {"input": "4\n4 0 0 0", "output": "abcd"}]
| 2,200 |
["*special", "constructive algorithms"]
| 44 |
[{"input": "6\r\n6 3 1 0 0 0\r\n", "output": "aaabbc\r\n"}, {"input": "4\r\n4 0 0 0\r\n", "output": "abcd\r\n"}, {"input": "1\r\n1\r\n", "output": "a\r\n"}, {"input": "5\r\n5 0 0 0 0\r\n", "output": "abcde\r\n"}, {"input": "10\r\n10 8 7 6 5 4 3 2 1 0\r\n", "output": "aaaaaaaaab\r\n"}, {"input": "20\r\n20 16 12 8 5 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0\r\n", "output": "aaaaaaabbbbbcccccddd\r\n"}, {"input": "99\r\n99 26 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\r\n", "output": "aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstu\r\n"}, {"input": "200\r\n200 180 160 140 122 106 92 79 69 60 52 45 38 32 26 20 14 8 4 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\r\n", "output": "aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccddddddddddddddddddeeeeeeeeeeeeeeeeefffffffffffffffffgggggggggggghhhhhhhhhhiiiiiiiiijjjjjjjjkkkkkkklllllllmmmmmmmnnnnnnooooopppppqqqqrrrrsssttt\r\n"}]
| false |
stdio
|
import sys
def main(input_path, output_path, sub_path):
with open(input_path) as f:
n = int(f.readline())
c_input = list(map(int, f.readline().split()))
with open(sub_path) as f:
s = f.readline().strip()
if len(s) != n:
print(0)
return
if not s.islower() or not s.isalpha():
print(0)
return
c_computed = []
for i in range(1, n+1):
count = 0
for j in range(len(s) - i + 1):
substr = s[j:j+i]
if all(c == substr[0] for c in substr):
count += 1
c_computed.append(count)
print(1 if c_computed == c_input else 0)
if __name__ == "__main__":
input_path = sys.argv[1]
output_path = sys.argv[2]
sub_path = sys.argv[3]
main(input_path, output_path, sub_path)
| true |
817/E
|
817
|
E
|
PyPy 3
|
TESTS
| 1 | 92 | 1,228,800 |
120284085
|
from sys import stdin
input=stdin.readline
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
self.count=0
class Trie():
def __init__(self):
self.root=Node(0)
def insert(self,preXor):
self.temp=self.root
for i in range(31,-1,-1):
val=preXor&(1<<i)
if val:
if not self.temp.right:
self.temp.right=Node(0)
self.temp=self.temp.right
self.temp.count+=1
else:
if not self.temp.left:
self.temp.left=Node(0)
self.temp=self.temp.left
self.temp.count+=1
self.temp.data=preXor
def delete(self,val):
self.temp=self.root
for i in range(31,-1,-1):
active=val&(1<<i)
if active:
self.temp=self.temp.right
self.temp.count-=1
else:
self.temp=self.temp.left
self.temp.count-=1
def query(self, val,li):
self.temp = self.root
ans=0
for i in range(31, -1, -1):
active = val & (1 << i)
bb=li&(1<<i)
if (active and bb) or (active!=0 and bb==0):
if self.temp.right and self.temp.right.count > 0:
self.temp = self.temp.right
ans+=self.temp.count
else:
break
# self.temp = self.temp.left
else:
if self.temp.left and self.temp.left.count > 0:
self.temp = self.temp.left
# elif self.temp.right:
# self.temp = self.temp.right
return ans
trie=Trie()
for i in range(int(input())):
l=list(input().strip().split())
if l[0]=="1":
trie.insert(int(l[1]))
elif l[0]=="2":
trie.delete(int(l[1]))
else:
print(trie.query(int(l[1]),int(l[2])))
| 42 | 623 | 45,158,400 |
111339985
|
import sys
from collections import defaultdict
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
q = int(sys.stdin.readline())
root = Node(0)
# def search(node, bit, )
for _ in range(q):
l = list(map(int, sys.stdin.readline().split()))
if l[0] == 1:
# add
bit = 28
cur = root
num = l[1]
# print(num,'num')
while bit >= 0:
if ((1<<bit)&num) == (1<<bit):
if cur.right is None:
cur.right = Node(1)
# print(bit,'bit right')
else:
cur.right.val += 1
# print(bit,'bit add right')
cur = cur.right
else:
if cur.left is None:
cur.left = Node(1)
# print(bit,'bit left', cur.left.val)
else:
cur.left.val += 1
# print(bit,'bit add left', cur.left.val)
cur = cur.left
bit -= 1
if l[0] == 2:
num = l[1]
bit, cur = 28, root
# print(num,'num')
while bit >= 0:
if((1<<bit)&num) == (1<<bit):
cur.right.val -= 1
cur = cur.right
else:
cur.left.val -= 1
cur = cur.left
bit -= 1
# remove
if l[0] == 3:
# print
res, cur, bit = 0, root, 28
# print(res, cur, bit)
while bit >= 0:
num = (1<<bit)
# print(bit,'bit')
if (num&l[2]) and (num&l[1]):
# print("A")
if cur.right is not None:
res += cur.right.val
if cur.left is None:
break
cur = cur.left
bit -= 1
continue
if (num&l[2]) and not (num&l[1]):
# print("B")
if cur.left is not None:
res += cur.left.val
if cur.right is None:
break
cur = cur.right
bit -= 1
continue
if not (num&l[2]) and (num&l[1]):
# print("C")
if cur.right is None:
break
cur = cur.right
bit -= 1
continue
if not (num&l[2]) and not (num&l[1]):
# print("D")
if cur.left is None:
break
cur = cur.left
bit -= 1
continue
print(res)
|
Educational Codeforces Round 23
|
ICPC
| 2,017 | 2 | 256 |
Choosing The Commander
|
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.
Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.
Each warrior is represented by his personality — an integer number pi. Each commander has two characteristics — his personality pj and leadership lj (both are integer numbers). Warrior i respects commander j only if $$p_i \oplus p_j < l_j$$ ($$x \oplus y$$ is the bitwise excluding OR of x and y).
Initially Vova's army is empty. There are three different types of events that can happen with the army:
- 1 pi — one warrior with personality pi joins Vova's army;
- 2 pi — one warrior with personality pi leaves Vova's army;
- 3 pi li — Vova tries to hire a commander with personality pi and leadership li.
For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.
|
The first line contains one integer q (1 ≤ q ≤ 100000) — the number of events.
Then q lines follow. Each line describes the event:
- 1 pi (1 ≤ pi ≤ 108) — one warrior with personality pi joins Vova's army;
- 2 pi (1 ≤ pi ≤ 108) — one warrior with personality pi leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment);
- 3 pi li (1 ≤ pi, li ≤ 108) — Vova tries to hire a commander with personality pi and leadership li. There is at least one event of this type.
|
For each event of the third type print one integer — the number of warriors who respect the commander Vova tries to hire in the event.
| null |
In the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him ($$4 \oplus 6 = 2$$, and 2 < 3, but $$3 \oplus 6 = 5$$, and 5 ≥ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.
|
[{"input": "5\n1 3\n1 4\n3 6 3\n2 4\n3 6 3", "output": "1\n0"}]
| 2,000 |
["bitmasks", "data structures", "trees"]
| 42 |
[{"input": "5\r\n1 3\r\n1 4\r\n3 6 3\r\n2 4\r\n3 6 3\r\n", "output": "1\r\n0\r\n"}]
| false |
stdio
| null | true |
717/D
|
717
|
D
|
PyPy 3
|
TESTS
| 1 | 77 | 1,740,800 |
103902825
|
import os
from io import BytesIO
#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main():
n = 0
r = 0
r2 = 0
class Matrix():
def __init__(self,ar):
self.ar = ar
def __mul__(self,other):
ans = [0 for i in r]
for i in r2:
i2 = i * n
for j in r2:
for k in r2:
ans[i2+j] += self.ar[i2+k] * other.ar[k*n+j]
return Matrix(ans)
def __mod__(self,other):
for i in r:
self.ar[i] %= other
return self
mod = 10**9 + 7
def power(number, n):
res = number
while(n):
if n & 1:
res *= number
number *= number
n >>= 1
return res
n,x = map(int,input().split())
n2= n
x += 1
n = x
r = range(x*x)
r2 = range(x)
ai = list(map(float,input().split()))
ar = [1 for i in r]
for i in r2:
for j in range(i,n):
temp = ((i ^ j) != 0) * ai[i] * ai[j]
ar[i*n+j] = temp
ar[j*n+i] = temp
m1 = Matrix(ar)
if n2 == 1:
print(1 - ai[0])
elif n2 == 2:
ans = 0
for i in r:
ans += ar[i]
print(ans)
else:
print(ar)
ansm = power(m1,n2-2).ar
print(ansm)
ans = 0
for i in r:
ans += ansm[i]
print(ans)
main()
| 11 | 108 | 1,945,600 |
103911369
|
import os
from io import BytesIO
#input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main():
def mult(m1,m2):
ans = [0] * 128
for i in range(128):
for j in range(128):
ans[i^j] += m1[i] * m2[j]
return ans
def power(number, n):
res = number
while(n):
if n & 1:
res = mult(res,number)
number = mult(number,number)
n >>= 1
return res
n,x = map(int,input().split())
ai = list(map(float,input().split()))
ai += [0]*(128-len(ai))
if n == 1:
print(1 - ai[0])
return
ansm = power(ai,n-1)
print(1 - ansm[0])
main()
|
Bubble Cup 9 - Finals [Online Mirror]
|
ICPC
| 2,016 | 1 | 256 |
Dexterina’s Lab
|
Dexterina and Womandark have been arch-rivals since they’ve known each other. Since both are super-intelligent teenage girls, they’ve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges they’ve given to one another, their score is equal and they’re both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim.
Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0, x]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game.
Womandark is coming up with a brand new and evil idea on how to thwart Dexterina’s plans, so she hasn’t got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above.
|
The first line of the input contains two integers n (1 ≤ n ≤ 109) and x (1 ≤ x ≤ 100) — the number of heaps and the maximum number of objects in a heap, respectively. The second line contains x + 1 real numbers, given with up to 6 decimal places each: P(0), P(1), ... , P(X). Here, P(i) is the probability of a heap having exactly i objects in start of a game. It's guaranteed that the sum of all P(i) is equal to 1.
|
Output a single real number, the probability that the first player wins. The answer will be judged as correct if it differs from the correct answer by at most 10 - 6.
| null | null |
[{"input": "2 2\n0.500000 0.250000 0.250000", "output": "0.62500000"}]
| 1,900 |
["games", "matrices", "probabilities"]
| 11 |
[{"input": "2 2\r\n0.500000 0.250000 0.250000\r\n", "output": "0.62500000\r\n"}, {"input": "9 9\r\n0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000 0.100000\r\n", "output": "0.93687014\r\n"}, {"input": "1000001 5\r\n0.000000 0.300000 0.000000 0.500000 0.000000 0.200000\r\n", "output": "1.00000000\r\n"}, {"input": "1000000 5\r\n0.000000 0.000000 1.000000 0.000000 0.000000 0.000000\r\n", "output": "0.00000000\r\n"}, {"input": "100 20\r\n0.065682 0.015963 0.024840 0.025856 0.000807 0.004366 0.020977 0.151841 0.050870 0.009918 0.044345 0.009672 0.077615 0.019520 0.166791 0.028122 0.010873 0.018634 0.172648 0.037614 0.043046\r\n", "output": "0.96875000\r\n"}, {"input": "1000000 50\r\n0.034403 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.033928 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.071853 0.000000 0.000000 0.016440 0.000000 0.000000 0.000000 0.000000 0.023167 0.067938 0.000000 0.000000 0.000000 0.000000 0.176349 0.030154 0.180266 0.272662 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.014462 0.000000 0.000000 0.037916 0.040462\r\n", "output": "0.98437500\r\n"}]
| false |
stdio
|
import sys
def main():
input_path = sys.argv[1]
correct_output_path = sys.argv[2]
submission_output_path = sys.argv[3]
try:
with open(correct_output_path, 'r') as f:
correct_line = f.read().strip()
correct_val = float(correct_line)
except:
print(0)
return
try:
with open(submission_output_path, 'r') as f:
submission_line = f.read().strip()
submission_val = float(submission_line)
except:
print(0)
return
diff = abs(submission_val - correct_val)
print(1 if diff <= 1e-6 else 0)
if __name__ == "__main__":
main()
| true |
66/C
|
66
|
C
|
Python 3
|
TESTS
| 0 | 30 | 0 |
205652350
|
foldersName = set()
filesName = []
while True:
try:
path = input().strip()
# Split path into folders and files
folders = []
for folder in path.split("\\"):
if "." not in folder:
folders.append(folder)
# Add folders and files to sets
foldersName.update(folders[1:])
files = [file for file in path.split("\\") if "." in file]
if files:
filesName.extend(files)
except EOFError:
break
print(len(foldersName), len(filesName))
| 100 | 342 | 4,403,200 |
97929765
|
is_file = dict()
edges = dict()
used = dict()
dirs_count = dict()
files_count = dict()
def dfs(key):
dirs_count[key] = 1 - is_file.get(key, 0)
files_count[key] = is_file.get(key, 0)
used.setdefault(key, 1)
for v in edges[key]:
if used.get(v, 0) == 0:
dfs(v)
dirs_count[key] += dirs_count[v]
files_count[key] += files_count[v]
while True:
try:
text = input()
except:
break
splited = text.split('\\')
n = len(splited)
for i in range(2, n):
t1 = '\\'.join(splited[0:i])
t2 = '\\'.join(splited[0:(i + 1)])
edges.setdefault(t1, list())
edges.setdefault(t2, list())
edges[t1].append(t2)
edges[t2].append(t1)
is_file.setdefault(text, 1)
for key in edges:
if used.get(key, 0) == 0:
dfs(key)
max_dirs = 0
max_files = 0
for key, value in dirs_count.items():
max_dirs = max(max_dirs, value - 1)
for key, value in files_count.items():
max_files = max(max_files, value)
print(max_dirs, max_files)
|
Codeforces Beta Round 61 (Div. 2)
|
CF
| 2,011 | 3 | 256 |
Petya and File System
|
Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested folders, and so on) and what folder contains most files (including the files in the subfolders).
More formally, the subfolders of the folder are all its directly nested folders and the subfolders of these nested folders. The given folder is not considered the subfolder of itself. A file is regarded as lying in a folder, if and only if it either lies directly in this folder, or lies in some subfolder of the folder.
For a better understanding of how to count subfolders and files for calculating the answer, see notes and answers to the samples.
You are given a few files that Petya has managed to create. The path to each file looks as follows:
diskName:\folder1\folder2\...\ foldern\fileName
- diskName is single capital letter from the set {C,D,E,F,G}.
- folder1, ..., foldern are folder names. Each folder name is nonempty sequence of lowercase Latin letters and digits from 0 to 9. (n ≥ 1)
- fileName is a file name in the form of name.extension, where the name and the extension are nonempty sequences of lowercase Latin letters and digits from 0 to 9.
It is also known that there is no file whose path looks like diskName:\fileName. That is, each file is stored in some folder, but there are no files directly in the root. Also let us assume that the disk root is not a folder.
Help Petya to find the largest number of subfolders, which can be in some folder, and the largest number of files that can be in some folder, counting all its subfolders.
|
Each line of input data contains the description of one file path. The length of each line does not exceed 100, and overall there are no more than 100 lines. It is guaranteed, that all the paths are correct and meet the above rules. It is also guaranteed, that there are no two completely equal lines. That is, each file is described exactly once.
There is at least one line in the input data.
|
Print two space-separated numbers. The first one is the maximal number of possible subfolders in a folder (including nested folders, nested folders of nested folders, and so on). The second one is the maximal number of files in a folder (including nested files in subfolders). Note that the disks are not regarded as folders.
| null |
In the first sample we have one folder on the "C" disk. It has no subfolders, which is why the first number in the answer is 0. But this folder contains one file, so the second number of the answer is 1.
In the second sample we have several different folders. Consider the "folder1" folder on the "C" disk. This folder directly contains one folder, "folder2". The "folder2" folder contains two more folders — "folder3" and "folder4". Thus, the "folder1" folder on the "C" drive has exactly 3 subfolders. Also this folder contains two files, even though they do not lie directly in the folder, but they are located in subfolders of "folder1".
In the third example we see that the names of some folders and some subfolders are identical. Consider the "file" folder, which lies directly on the "C" disk. That folder contains another "file" folder, which in turn contains another "file" folder, which contains two more folders, "file" and "file2". Thus, the "file" folder, which lies directly on the "C" disk, contains 4 subfolders.
|
[{"input": "C:\n\\\nfolder1\n\\\nfile1.txt", "output": "0 1"}, {"input": "C:\n\\\nfolder1\n\\\nfolder2\n\\\nfolder3\n\\\nfile1.txt\nC:\n\\\nfolder1\n\\\nfolder2\n\\\nfolder4\n\\\nfile1.txt\nD:\n\\\nfolder1\n\\\nfile1.txt", "output": "3 2"}, {"input": "C:\n\\\nfile\n\\\nfile\n\\\nfile\n\\\nfile\n\\\nfile.txt\nC:\n\\\nfile\n\\\nfile\n\\\nfile\n\\\nfile2\n\\\nfile.txt", "output": "4 2"}]
| 1,800 |
["data structures", "implementation"]
| 100 |
[{"input": "C:\\folder1\\file1.txt\r\n", "output": "0 1\r\n"}, {"input": "C:\\folder1\\folder2\\folder3\\file1.txt\r\nC:\\folder1\\folder2\\folder4\\file1.txt\r\nD:\\folder1\\file1.txt\r\n", "output": "3 2\r\n"}, {"input": "C:\\file\\file\\file\\file\\file.txt\r\nC:\\file\\file\\file\\file2\\file.txt\r\n", "output": "4 2\r\n"}, {"input": "C:\\file\\file.txt\r\nD:\\file\\file.txt\r\nE:\\file\\file.txt\r\nF:\\file\\file.txt\r\nG:\\file\\file.txt\r\n", "output": "0 1\r\n"}, {"input": "C:\\a\\b\\c\\d\\d.txt\r\nC:\\a\\b\\c\\e\\f.txt\r\n", "output": "4 2\r\n"}, {"input": "C:\\z\\z.txt\r\nD:\\1\\1.txt\r\nD:\\1\\2.txt\r\n", "output": "0 2\r\n"}, {"input": "D:\\0000\\1.txt\r\nE:\\00000\\1.txt\r\n", "output": "0 1\r\n"}, {"input": "C:\\a\\b\\c\\d.txt\r\nC:\\a\\e\\c\\d.txt\r\n", "output": "4 2\r\n"}, {"input": "C:\\test1\\test2\\test3\\test.txt\r\nC:\\test1\\test3\\test3\\test4\\test.txt\r\nC:\\test1\\test2\\test3\\test2.txt\r\nD:\\test1\\test2\\test.txt\r\nD:\\test1\\test3\\test4.txt\r\n", "output": "5 3\r\n"}, {"input": "C:\\test1\\test2\\test.txt\r\nC:\\test1\\test2\\test2.txt\r\n", "output": "1 2\r\n"}]
| false |
stdio
| null | true |
13/B
|
13
|
B
|
PyPy 3
|
TESTS
| 1 | 1,778 | 10,547,200 |
118548184
|
def dot(a,b):
return a[0]*b[0] + a[1]*b[1]
for _ in range(int(input())):
points = [list(map(int,input().split())) for i in range(3)]
points = [[points[i][:2],points[i][2:]] for i in range(3)]
diff = [[[points[i][ti^1][k] - points[i][ti][k] for k in range(2)] for ti in range(2)] for i in range(3)]
worked = 0
for i in range(3):
for j in range(3):
if i != j:
for ti in range(2):
for tj in range(2):
if points[i][ti] == points[j][tj]: # common endpoint
if 0 <= dot(diff[i][ti], diff[j][tj]) and \
dot(diff[i][ti], diff[j][tj])**2 < (diff[i][ti][0]**2 + diff[i][ti][1]**2)*(diff[j][tj][0]**2 + diff[j][tj][1]**2): # (0-90] degrees
#print(i,ti,j,tj)
# k = the other line
k = (i+1)%3
if k == j:
k = (k+1)%3
# check that 3rd seg has 1 point in common and 1/4 ratio
check = [i,j]
work_both = 1
for a in check:
work = 0
for tk in range(2):
if (points[k][tk][0] - points[a][0][0]) * diff[a][0][1] == \
(points[k][tk][1] - points[a][0][1]) * diff[a][0][0]: # on line
delta_x = []
for ta in range(2):
delta_x.append(abs(points[a][ta][0]-points[k][tk][0]))
if delta_x == [0,0]: # edge case of vertical line
delta_x = []
for ta in range(2):
delta_x.append(abs(points[a][ta][1] - points[k][tk][1]))
delta_x.sort()
if 4*delta_x[0] >= delta_x[1]: # >= 1/4 ratio
#print(delta_x)
work = 1
if not work:
work_both = 0
if work_both:
worked = 1
if worked:
print("YES")
else:
print("NO")
| 2 | 528 | 409,600 |
69798233
|
""" A : Determine if three line segments form A """
def cross(vecA, vecB):
return vecA[0] * vecB[1] - vecA[1] * vecB[0]
def dot(vecA, vecB):
return vecA[0] * vecB[0] + vecA[1] * vecB[1]
def angle(lineA, lineB):
x1, y1 = (lineA[0][0] - lineA[1][0], lineA[0][1] - lineA[1][1])
x2, y2 = (lineB[0][0] - lineB[1][0], lineB[0][1] - lineB[1][1])
d1 = (x1 ** 2 + y1 ** 2) ** 0.5
d2 = (x2 ** 2 + y2 ** 2) ** 0.5
return (x1 * x2 + y1 * y2) / (d1*d2)
def div_ratio(line, point):
# Simple way to approximately check if the point lies on the line
mx, my = point
(a, b), (c, d) = line
if not (min(a, c) <= mx <= max(a, c) and min(b, d) <= my <= max(b, d)):
return -1
# Again make sure the point lies on the line
vecA = (a - mx, b - my)
vecB = (a - c, b - d)
if cross(vecA, vecB) != 0:
return -1
# Finally compute the ratio
if c == a and d == b: return -1
if d != b:
ratio = (my - b) / (d - b)
if a != c:
ratio = (mx - a) / (c - a)
if ratio < 0.2 or ratio > 0.8:
ratio = -1
return ratio
def isA(lines):
""" Given three line segments check if they form A of not"""
# Find the two slanted line segments
k, l = -1, -1
lines_found = False
for i in range(3):
if lines_found: break
temp = set(lines[i])
for j in range(i + 1, 3):
# Check which of the two points is the common point
if lines[j][0] in temp:
common = lines[j][0]
k, l = i, j
lines_found = True
break
if not lines_found and lines[j][1] in temp:
common = lines[j][1]
k, l = i, j
lines_found = True
break
if not lines_found: return False
# Process the lines
lineA = lines[k]
if lineA[0] != common:
lineA = [lineA[1], lineA[0]]
lineB = lines[l]
if lineB[0] != common:
lineB = [lineB[1], lineB[0]]
# Check the angle between two lines. Must be greater than 0 and less than 90
degree = angle(lineA, lineB)
# print("Degree ", degree)
if degree < 0 or degree >= 1: return False
# The third is the line connecting two slanted line segments
divider = lines[3 - k - l]
# If first point of divider does not divide (or lie on) either of the line segments, it does not form A
thresh = 0.2 # Converted 1/4 to 1/5 in another metric
r1 = div_ratio(lineA, divider[0])
if r1 == -1:
r2 = div_ratio(lineB, divider[0]) # div[0] lies on lineB
if r2 == -1: return False
r1 = div_ratio(lineA, divider[1]) # div[1] lies on lineA
if r1 == -1: return False
else:
r2 = div_ratio(lineB, divider[1])
if r2 == -1: return False
# For everything else
return True
def CF14C():
N = int(input())
result = []
for _ in range(N):
lines = []
for _ in range(3):
a, b, c, d = map(int, input().split())
lines.append(((a, b), (c, d)))
res = isA(lines)
result.append("YES" if res else "NO")
return result
res = CF14C()
print("\n".join(res))
|
Codeforces Beta Round 13
|
ICPC
| 2,010 | 1 | 64 |
Letter A
|
Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.
You are given three segments on the plane. They form the letter A if the following conditions hold:
- Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.
- The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.
- The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).
|
The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.
|
Output one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.
| null | null |
[{"input": "3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1", "output": "YES\nNO\nYES"}]
| 2,000 |
["geometry", "implementation"]
| 2 |
[{"input": "3\r\n4 4 6 0\r\n4 1 5 2\r\n4 0 4 4\r\n0 0 0 6\r\n0 6 2 -4\r\n1 1 0 1\r\n0 0 0 5\r\n0 5 2 -1\r\n1 2 0 1\r\n", "output": "YES\r\nNO\r\nYES\r\n"}]
| false |
stdio
| null | true |
474/F
|
474
|
F
|
PyPy 3
|
TESTS
| 1 | 390 | 5,529,600 |
202420101
|
import math
def main():
n = int(input())
a = list(map(int, input().split()))
t = int(input())
for _ in range(t):
l, r = map(int, input().split())
l -= 1
r -= 1
gcd = math.gcd(a[l], a[r])
cnt = sum(1 for i in range(l, r + 1) if a[i] == gcd)
print(r - l + 1 - cnt)
main()
| 65 | 608 | 23,756,800 |
188542239
|
## user: https://codeforces.com/contest/474/submission/122199538
import sys,os,io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
#for deep recursion__________________________________________-
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,p - 2, p)) % p
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
c = dict(Counter(l))
return list(set(l))
# return c
def power(x, y, p) :
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
#____________________GetPrimeFactors in log(n)________________________________________
def sieveForSmallestPrimeFactor():
MAXN = 100001
spf = [0 for i in range(MAXN)]
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, math.ceil(math.sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
return spf
def getPrimeFactorizationLOGN(x):
spf = sieveForSmallestPrimeFactor()
ret = list()
while (x != 1):
ret.append(spf[x])
x = x // spf[x]
return ret
#____________________________________________________________
def SieveOfEratosthenes(n):
#time complexity = nlog(log(n))
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
def si():
return input()
def divideCeil(n,x):
if (n%x==0):
return n//x
return n//x+1
def ii():
return int(input())
def li():
return list(map(int,input().split()))
#__________________________TEMPLATE__________________OVER_______________________________________________________
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SegmentTree:
def __init__(self, data, default=0, func=gcd):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
n = ii()
s = li()
d = defaultdict(lambda:[])
for i in range(n):
d[s[i]].append(i)
def cnt(x,left,right):
l = bisect_left(d[x],left)
r = bisect_right(d[x],right)
return r-l
seg = SegmentTree(s)
for i in range(ii()):
l,r = li()
l-=1
r-=1
g = seg.query(l,r+1)
print(r-l+1-cnt(g,l,r))
# def solve():
# t = 1
# t = ii()
# for _ in range(t):
# solve()
|
Codeforces Round 271 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
Ant colony
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
|
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
| null |
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
[{"input": "5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5", "output": "4\n4\n1\n1"}]
| 2,100 |
["data structures", "math", "number theory"]
| 65 |
[{"input": "5\r\n1 3 2 4 2\r\n4\r\n1 5\r\n2 5\r\n3 5\r\n4 5\r\n", "output": "4\r\n4\r\n1\r\n1\r\n"}]
| false |
stdio
| null | true |
474/F
|
474
|
F
|
PyPy 3-64
|
TESTS
| 1 | 124 | 8,192,000 |
212136414
|
import sys
import math
def binary_search(nums, target):
start, end = 0, len(nums) - 1
while end - start > 1:
mid = (start + end) // 2
if target <= nums[mid]:
end = mid
else:
start = mid
if nums[start] >= target:
return start
if nums[end] >= target:
return end
return len(nums)
n = int(sys.stdin.readline())
s = list(map(int, sys.stdin.readline().split()))
t = int(sys.stdin.readline())
indices = {}
for i, num in enumerate(s):
if num in indices:
indices[num].append(i)
else:
indices[num] = [i]
for _ in range(t):
l, r = map(int, sys.stdin.readline().split())
l -= 1
r -= 1
gcd_val = math.gcd(s[l], s[r])
if gcd_val not in indices:
print(r - l + 1)
else:
temp = binary_search(indices[gcd_val], l)
temp2 = binary_search(indices[gcd_val], r)
length = len(indices[gcd_val])
if temp == length:
print(r - l + 1)
else:
if temp2 == length:
temp2 -= 1
if indices[gcd_val][temp2] > r:
temp2 -= 1
print(r - l + 1 - (temp2 - temp + 1))
| 65 | 717 | 71,475,200 |
198901725
|
import bisect
import heapq
import sys
from types import GeneratorType
from functools import cmp_to_key
from collections import defaultdict, Counter, deque
import math
from functools import lru_cache
from heapq import nlargest
from functools import reduce
import random
from operator import mul
inf = float("inf")
PLATFORM = "CF"
if PLATFORM == "LUOGU":
import numpy as np
sys.setrecursionlimit(1000000)
class FastIO:
def __init__(self):
return
@staticmethod
def _read():
return sys.stdin.readline().strip()
def read_int(self):
return int(self._read())
def read_float(self):
return float(self._read())
def read_ints(self):
return map(int, self._read().split())
def read_floats(self):
return map(float, self._read().split())
def read_ints_minus_one(self):
return map(lambda x: int(x) - 1, self._read().split())
def read_list_ints(self):
return list(map(int, self._read().split()))
def read_list_floats(self):
return list(map(float, self._read().split()))
def read_list_ints_minus_one(self):
return list(map(lambda x: int(x) - 1, self._read().split()))
def read_str(self):
return self._read()
def read_list_strs(self):
return self._read().split()
def read_list_str(self):
return list(self._read())
@staticmethod
def st(x):
return sys.stdout.write(str(x) + '\n')
@staticmethod
def lst(x):
return sys.stdout.write(" ".join(str(w) for w in x) + '\n')
@staticmethod
def round_5(f):
res = int(f)
if f - res >= 0.5:
res += 1
return res
@staticmethod
def max(a, b):
return a if a > b else b
@staticmethod
def min(a, b):
return a if a < b else b
@staticmethod
def bootstrap(f, queue=[]):
def wrappedfunc(*args, **kwargs):
if queue:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if isinstance(to, GeneratorType):
queue.append(to)
to = next(to)
else:
queue.pop()
if not queue:
break
to = queue[-1].send(to)
return to
return wrappedfunc
class SparseTable1:
def __init__(self, lst, fun="max"):
# 只要fun满足单调性就可以进行静态区间查询
self.fun = fun
self.n = len(lst)
self.lst = lst
self.f = [[0] * (int(math.log2(self.n)) + 1) for _ in range(self.n+1)]
self.gen_sparse_table()
return
def gen_sparse_table(self):
for i in range(1, self.n + 1):
self.f[i][0] = self.lst[i - 1]
for j in range(1, int(math.log2(self.n)) + 1):
for i in range(1, self.n - (1 << j) + 2):
a = self.f[i][j - 1]
b = self.f[i + (1 << (j - 1))][j - 1]
if self.fun == "max":
self.f[i][j] = a if a > b else b
elif self.fun == "min":
self.f[i][j] = a if a < b else b
elif self.fun == "gcd":
self.f[i][j] = math.gcd(a, b)
elif self.fun == "and":
self.f[i][j] = a & b
elif self.fun == "or":
self.f[i][j] = a | b
return
def query(self, left, right):
# 查询数组的索引 left 和 right 从 1 开始
k = int(math.log2(right - left + 1))
a = self.f[left][k]
b = self.f[right - (1 << k) + 1][k]
if self.fun == "max":
return a if a > b else b
elif self.fun == "min":
return a if a < b else b
elif self.fun == "gcd":
return math.gcd(a, b)
elif self.fun == "and":
return a & b
elif self.fun == "or":
return a | b
def main(ac=FastIO()):
n = ac.read_int()
nums = ac.read_list_ints()
dct = defaultdict(list)
for i, num in enumerate(nums):
dct[num].append(i)
st_gcd = SparseTable1(nums, "gcd")
st_min = SparseTable1(nums, "min")
for _ in range(ac.read_int()):
x, y = ac.read_ints_minus_one()
num1 = st_gcd.query(x+1, y+1)
num2 = st_min.query(x+1, y+1)
if num1 == num2:
res = bisect.bisect_right(dct[num1], y) - bisect.bisect_left(dct[num1], x)
ac.st(y-x+1-res)
else:
ac.st(y-x+1)
return
main()
|
Codeforces Round 271 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
Ant colony
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
|
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
| null |
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
[{"input": "5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5", "output": "4\n4\n1\n1"}]
| 2,100 |
["data structures", "math", "number theory"]
| 65 |
[{"input": "5\r\n1 3 2 4 2\r\n4\r\n1 5\r\n2 5\r\n3 5\r\n4 5\r\n", "output": "4\r\n4\r\n1\r\n1\r\n"}]
| false |
stdio
| null | true |
817/E
|
817
|
E
|
PyPy 3-64
|
TESTS
| 2 | 93 | 3,891,200 |
213147568
|
from collections import *
from functools import *
from itertools import *
from operator import *
from bisect import *
from heapq import *
import math
import re
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def I():
return input().decode('utf-8').strip()
def II(base=10):
return int(input(),base)
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
class Trie:
def __init__(self,n,L):
self.t = [[0]*(n*L+1) for _ in range(2)]
self.i = 0
self.L = L
self.s = [0]*(n*L+1)
def add(self, x):
p = 0
for j in range(self.L-1, -1, -1):
bit = (x>>j)&1
if not self.t[bit][p]:
self.i += 1
self.t[bit][p] = self.i
p = self.t[bit][p]
self.s[p] += 1
def remove(self,x):
p = 0
for j in range(self.L-1,-1,-1):
bit = (x>>j)&1
p = self.t[bit][p]
self.s[p]-=1
def query(self, x, high):
res = 0
p = 0
for j in range(self.L-1, -1, -1):
bit = (x>>j)&1
h = (high>>j)&1
if h:
res += self.s[self.t[bit][p]]
if not self.t[bit^h][p]:
return res
p = self.t[bit^h][p]
res += self.s[p]
return res
q = II()
trie = Trie(q,27)
for _ in range(q):
B = LII()
if B[0]==1:
trie.add(B[1])
elif B[0]==2:
trie.remove(B[1])
else:
print(trie.query(B[1],B[2]))
| 42 | 857 | 105,881,600 |
213145853
|
from collections import *
from functools import *
from itertools import *
from operator import *
from bisect import *
from heapq import *
import math
import re
import os
import io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def I():
return input().decode('utf-8').strip()
def II(base=10):
return int(input(),base)
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
L = 28
A = [defaultdict(int) for _ in range(L)]
for _ in range(II()):
B = LII()
if B[0]==1:
p = B[1]
for i in range(L):
A[i][p>>i]+=1
elif B[0]==2:
p = B[1]
for i in range(L):
A[i][p>>i]-=1
else:
p,h = B[1],B[2]
res = 0
for i in range(L):
if h&1:
res += A[i][p^h^1]
h >>= 1
p >>= 1
print(res)
|
Educational Codeforces Round 23
|
ICPC
| 2,017 | 2 | 256 |
Choosing The Commander
|
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.
Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.
Each warrior is represented by his personality — an integer number pi. Each commander has two characteristics — his personality pj and leadership lj (both are integer numbers). Warrior i respects commander j only if $$p_i \oplus p_j < l_j$$ ($$x \oplus y$$ is the bitwise excluding OR of x and y).
Initially Vova's army is empty. There are three different types of events that can happen with the army:
- 1 pi — one warrior with personality pi joins Vova's army;
- 2 pi — one warrior with personality pi leaves Vova's army;
- 3 pi li — Vova tries to hire a commander with personality pi and leadership li.
For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.
|
The first line contains one integer q (1 ≤ q ≤ 100000) — the number of events.
Then q lines follow. Each line describes the event:
- 1 pi (1 ≤ pi ≤ 108) — one warrior with personality pi joins Vova's army;
- 2 pi (1 ≤ pi ≤ 108) — one warrior with personality pi leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment);
- 3 pi li (1 ≤ pi, li ≤ 108) — Vova tries to hire a commander with personality pi and leadership li. There is at least one event of this type.
|
For each event of the third type print one integer — the number of warriors who respect the commander Vova tries to hire in the event.
| null |
In the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him ($$4 \oplus 6 = 2$$, and 2 < 3, but $$3 \oplus 6 = 5$$, and 5 ≥ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.
|
[{"input": "5\n1 3\n1 4\n3 6 3\n2 4\n3 6 3", "output": "1\n0"}]
| 2,000 |
["bitmasks", "data structures", "trees"]
| 42 |
[{"input": "5\r\n1 3\r\n1 4\r\n3 6 3\r\n2 4\r\n3 6 3\r\n", "output": "1\r\n0\r\n"}]
| false |
stdio
| null | true |
397/B
|
397
|
B
|
Python 3
|
TESTS
| 0 | 109 | 0 |
46220368
|
t=int(input())
for i in range(t):
n,l,r=map(int,input().split())
if r>n:
print("NO")
elif(l==r)and(n%l!=0):
print("NO")
elif l>n//2:
print("NO")
else:
print("YES")
| 6 | 62 | 0 |
136741825
|
t=int(input())
while t>0:
t-=1
n,l,r=map(int,input().split())
k=n//l
if r*k>=n:
print('Yes')
else:
print('No')
|
Codeforces Round 232 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
On Corruption and Numbers
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
|
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
|
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
| null |
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
[{"input": "2\n5 2 3\n6 4 5", "output": "Yes\nNo"}]
| null |
["constructive algorithms", "implementation", "math"]
| 6 |
[{"input": "2\r\n5 2 3\r\n6 4 5\r\n", "output": "Yes\r\nNo\r\n"}, {"input": "50\r\n69 6 6\r\n22 1 1\r\n23 3 3\r\n60 13 13\r\n13 3 3\r\n7 4 7\r\n6 1 1\r\n49 7 9\r\n68 8 8\r\n20 2 2\r\n34 1 1\r\n79 5 5\r\n22 1 1\r\n77 58 65\r\n10 3 3\r\n72 5 5\r\n47 1 1\r\n82 3 3\r\n92 8 8\r\n34 1 1\r\n42 9 10\r\n63 14 14\r\n10 3 3\r\n38 2 2\r\n80 6 6\r\n79 5 5\r\n53 5 5\r\n44 7 7\r\n85 2 2\r\n24 2 2\r\n57 3 3\r\n95 29 81\r\n77 6 6\r\n24 1 1\r\n33 4 4\r\n93 6 6\r\n55 22 28\r\n91 14 14\r\n7 1 1\r\n16 1 1\r\n20 3 3\r\n43 3 3\r\n53 3 3\r\n49 3 3\r\n52 5 5\r\n2 1 1\r\n60 5 5\r\n76 57 68\r\n67 3 3\r\n61 52 61\r\n", "output": "No\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\n"}]
| false |
stdio
| null | true |
397/B
|
397
|
B
|
Python 3
|
TESTS
| 1 | 46 | 0 |
12519021
|
__author__ = 'aadityataparia'
def is_sum():
m, l, r = (input()).split()
m = int(m)
l = int(l)
r = int(r)
jj=m
poss=list(range(l,r+1))
j=len(poss)-1
while(j>=0):
ab=poss[j]
jj=jj%ab
j-=1
if jj==0:
return 'Yes'
return'No'
n = int(input())
Ans = [0, ] * n
for i in range(0, n):
Ans[i] = is_sum()
for i in range(0, n):
print(Ans[i])
| 6 | 77 | 0 |
6759074
|
t = int(input())
for _ in range(t):
n, l, r = map(int, input().split())
print("No" if n // l * r < n else "Yes")
|
Codeforces Round 232 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
On Corruption and Numbers
|
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
|
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri).
|
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
| null |
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
|
[{"input": "2\n5 2 3\n6 4 5", "output": "Yes\nNo"}]
| null |
["constructive algorithms", "implementation", "math"]
| 6 |
[{"input": "2\r\n5 2 3\r\n6 4 5\r\n", "output": "Yes\r\nNo\r\n"}, {"input": "50\r\n69 6 6\r\n22 1 1\r\n23 3 3\r\n60 13 13\r\n13 3 3\r\n7 4 7\r\n6 1 1\r\n49 7 9\r\n68 8 8\r\n20 2 2\r\n34 1 1\r\n79 5 5\r\n22 1 1\r\n77 58 65\r\n10 3 3\r\n72 5 5\r\n47 1 1\r\n82 3 3\r\n92 8 8\r\n34 1 1\r\n42 9 10\r\n63 14 14\r\n10 3 3\r\n38 2 2\r\n80 6 6\r\n79 5 5\r\n53 5 5\r\n44 7 7\r\n85 2 2\r\n24 2 2\r\n57 3 3\r\n95 29 81\r\n77 6 6\r\n24 1 1\r\n33 4 4\r\n93 6 6\r\n55 22 28\r\n91 14 14\r\n7 1 1\r\n16 1 1\r\n20 3 3\r\n43 3 3\r\n53 3 3\r\n49 3 3\r\n52 5 5\r\n2 1 1\r\n60 5 5\r\n76 57 68\r\n67 3 3\r\n61 52 61\r\n", "output": "No\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nYes\r\nNo\r\nYes\r\nNo\r\nNo\r\nYes\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nNo\r\nNo\r\nNo\r\nYes\r\nYes\r\nNo\r\nNo\r\nYes\r\n"}]
| false |
stdio
| null | true |
355/B
|
355
|
B
|
Python 3
|
TESTS
| 0 | 15 | 0 |
232313765
|
cost=list(map(int,input().split()))
n,m=map(int,input().split())
bus=list(map(int,input().split()))
troller=list(map(int,input().split()))
bt=0
tt=0
for num in bus:
if num*cost[0]>=cost[1]:
bt+=cost[1]
else:
bt+=cost[0]*num
if bt>=cost[2]:
bt=cost[2]
if bt>= cost[3]:
bt=cost[3]
break
print(bt)
for num in troller:
if num*cost[0]>=cost[1]:
tt+=cost[1]
else:
tt+=cost[0]*num
if tt>=cost[2]:
tt=cost[2]
if tt>= cost[3]:
tt=cost[3]
break
if tt+bt>cost[3]:
print(cost[3])
else:
print(tt+bt)
| 27 | 46 | 307,200 |
4782118
|
c1,c2,c3,c4 = map(int, input().split())
n,m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
suma = sum(min(c1*x, c2) for x in a)
sumb = sum(min(c1*x, c2) for x in b)
print(min(min(suma,c3) + min(sumb, c3), c4))
|
Codeforces Round 206 (Div. 2)
|
CF
| 2,013 | 1 | 256 |
Vasya and Public Transport
|
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.
Public transport is not free. There are 4 types of tickets:
1. A ticket for one ride on some bus or trolley. It costs c1 burles;
2. A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles;
3. A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles;
4. A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles.
Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
|
The first line contains four integers c1, c2, c3, c4 (1 ≤ c1, c2, c3, c4 ≤ 1000) — the costs of the tickets.
The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use.
The third line contains n integers ai (0 ≤ ai ≤ 1000) — the number of times Vasya is going to use the bus number i.
The fourth line contains m integers bi (0 ≤ bi ≤ 1000) — the number of times Vasya is going to use the trolley number i.
|
Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.
| null |
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles.
In the second sample the profitable strategy is to buy one ticket of the fourth type.
In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
|
[{"input": "1 3 7 19\n2 3\n2 5\n4 4 4", "output": "12"}, {"input": "4 3 2 1\n1 3\n798\n1 2 3", "output": "1"}, {"input": "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42", "output": "16"}]
| 1,100 |
["greedy", "implementation"]
| 27 |
[{"input": "1 3 7 19\r\n2 3\r\n2 5\r\n4 4 4\r\n", "output": "12\r\n"}, {"input": "4 3 2 1\r\n1 3\r\n798\r\n1 2 3\r\n", "output": "1\r\n"}, {"input": "100 100 8 100\r\n3 5\r\n7 94 12\r\n100 1 47 0 42\r\n", "output": "16\r\n"}, {"input": "3 103 945 1000\r\n7 9\r\n34 35 34 35 34 35 34\r\n0 0 0 0 0 0 0 0 0\r\n", "output": "717\r\n"}, {"input": "7 11 597 948\r\n4 1\r\n5 1 0 11\r\n7\r\n", "output": "40\r\n"}, {"input": "7 32 109 645\r\n1 3\r\n0\r\n0 0 0\r\n", "output": "0\r\n"}, {"input": "680 871 347 800\r\n10 100\r\n872 156 571 136 703 201 832 213 15 333\r\n465 435 870 95 660 237 694 594 423 405 27 866 325 490 255 989 128 345 278 125 708 210 771 848 961 448 871 190 745 343 532 174 103 999 874 221 252 500 886 129 185 208 137 425 800 34 696 39 198 981 91 50 545 885 194 583 475 415 162 712 116 911 313 488 646 189 429 756 728 30 985 114 823 111 106 447 296 430 307 388 345 458 84 156 169 859 274 934 634 62 12 839 323 831 24 907 703 754 251 938\r\n", "output": "694\r\n"}, {"input": "671 644 748 783\r\n100 10\r\n520 363 816 957 635 753 314 210 763 819 27 970 520 164 195 230 708 587 568 707 343 30 217 227 755 277 773 497 900 589 826 666 115 784 494 467 217 892 658 388 764 812 248 447 876 581 94 915 675 967 508 754 768 79 261 934 603 712 20 199 997 501 465 91 897 257 820 645 217 105 564 8 668 171 168 18 565 840 418 42 808 918 409 617 132 268 13 161 194 628 213 199 545 448 113 410 794 261 211 539\r\n147 3 178 680 701 193 697 666 846 389\r\n", "output": "783\r\n"}, {"input": "2 7 291 972\r\n63 92\r\n7 0 0 6 0 13 0 20 2 8 0 17 7 0 0 0 0 2 2 0 0 8 20 0 0 0 3 0 0 0 4 20 0 0 0 12 0 8 17 9 0 0 0 0 4 0 0 0 17 11 3 0 2 15 0 18 11 19 14 0 0 20 13\r\n0 0 0 3 7 0 0 0 0 8 13 6 15 0 7 0 0 20 0 0 12 0 12 0 15 0 0 1 11 14 0 11 12 0 0 0 0 0 16 16 0 17 20 0 11 0 0 20 14 0 16 0 3 6 12 0 0 0 0 0 15 3 0 9 17 12 20 17 0 0 0 0 15 9 0 14 10 10 1 20 16 17 20 6 6 0 0 16 4 6 0 7\r\n", "output": "494\r\n"}, {"input": "4 43 490 945\r\n63 92\r\n0 0 0 0 0 0 6 5 18 0 6 4 0 17 0 19 0 19 7 16 0 0 0 9 10 13 7 0 10 16 0 0 0 0 0 14 0 14 9 15 0 0 2 0 0 0 0 5 0 0 0 11 11 0 0 0 0 0 10 12 3 0 0\r\n0 12 0 18 7 7 0 0 9 0 0 13 17 0 18 12 4 0 0 14 18 20 0 0 12 9 17 1 19 0 11 0 5 0 0 14 0 0 16 0 19 15 9 14 7 10 0 19 19 0 0 1 0 0 0 6 0 0 0 6 0 20 1 9 0 0 10 17 5 2 5 4 16 6 0 11 0 8 13 4 0 2 0 0 13 10 0 13 0 0 8 4\r\n", "output": "945\r\n"}, {"input": "2 50 258 922\r\n42 17\r\n0 2 0 1 0 1 0 11 18 9 0 0 0 0 10 15 17 4 20 0 5 0 0 13 13 0 0 2 0 7 0 20 4 0 19 3 7 0 0 0 0 0\r\n8 4 19 0 0 19 14 17 6 0 18 0 0 0 0 9 0\r\n", "output": "486\r\n"}, {"input": "1 1 3 4\r\n2 3\r\n1 1\r\n1 1 1\r\n", "output": "4\r\n"}, {"input": "4 4 4 1\r\n1 1\r\n0\r\n0\r\n", "output": "0\r\n"}, {"input": "100 100 1 100\r\n10 10\r\n100 100 100 100 100 100 100 100 100 100\r\n100 100 100 100 100 100 100 100 100 100\r\n", "output": "2\r\n"}]
| false |
stdio
| null | true |
474/F
|
474
|
F
|
Python 3
|
TESTS
| 4 | 686 | 5,632,000 |
207153785
|
import math
# Node class representing a node in the segment tree
class Node:
def __init__(self, value, gcd):
self.value = value
self.gcd = gcd
# Function to build the segment tree
def build_segment_tree(arr, tree, node, start, end):
if start == end:
tree[node] = Node(arr[start], arr[start])
else:
mid = (start + end) // 2
build_segment_tree(arr, tree, 2 * node, start, mid)
build_segment_tree(arr, tree, 2 * node + 1, mid + 1, end)
tree[node] = Node(min(tree[2 * node].value, tree[2 * node + 1].value), math.gcd(tree[2 * node].gcd, tree[2 * node + 1].gcd))
# Function for range minimum query (RMQ) on the segment tree
def range_minimum_query(tree, node, start, end, left, right):
if left > end or right < start:
return float('inf')
if left <= start and right >= end:
return tree[node].value
mid = (start + end) // 2
left_min = range_minimum_query(tree, 2 * node, start, mid, left, right)
right_min = range_minimum_query(tree, 2 * node + 1, mid + 1, end, left, right)
return min(left_min, right_min)
# Function for range GCD query on the segment tree
def range_gcd_query(tree, node, start, end, left, right):
if left > end or right < start:
return 0
if left <= start and right >= end:
return tree[node].gcd
mid = (start + end) // 2
left_gcd = range_gcd_query(tree, 2 * node, start, mid, left, right)
right_gcd = range_gcd_query(tree, 2 * node + 1, mid + 1, end, left, right)
return math.gcd(left_gcd, right_gcd)
# Function to count the occurrences of a value in a range
def count_occurrences(tree, node, start, end, left, right, value):
if left > end or right < start:
return 0
if left <= start and right >= end:
return tree[node].value == value
mid = (start + end) // 2
left_count = count_occurrences(tree, 2 * node, start, mid, left, right, value)
right_count = count_occurrences(tree, 2 * node + 1, mid + 1, end, left, right, value)
return left_count + right_count
# Main function
def main():
n = int(input())
strengths = list(map(int, input().split()))
t = int(input())
# Build the segment tree
tree_size = 4 * n # Adjust the size of the tree if necessary
tree = [None] * tree_size
build_segment_tree(strengths, tree, 1, 0, n - 1)
# Process each query
for _ in range(t):
li, ri = map(int, input().split())
min_value = range_minimum_query(tree, 1, 0, n - 1, li - 1, ri - 1)
gcd_value = range_gcd_query(tree, 1, 0, n - 1, li - 1, ri - 1)
num_values = count_occurrences(tree, 1, 0, n - 1, li - 1, ri - 1, gcd_value)
num_eaten = (ri - li + 1) - num_values
print(num_eaten)
# Execute the main function
if __name__ == "__main__":
main()
| 65 | 889 | 60,211,200 |
196363549
|
import time
import bisect
import functools
import math
import os
import random
import re
import sys
import threading
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from io import BytesIO, IOBase
from itertools import accumulate, combinations, permutations
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase
from typing import *
BUFSIZE = 4096
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 = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')
# from types import GeneratorType
# def bootstrap(f, stack=[]):
# def wrappedfunc(*args, **kwargs):
# if stack:
# return f(*args, **kwargs)
# else:
# to = f(*args, **kwargs)
# while True:
# if type(to) is GeneratorType:
# stack.append(to)
# to = next(to)
# else:
# stack.pop()
# if not stack:
# break
# to = stack[-1].send(to)
# return to
# return wrappedfunc
# RANDOM = random.getrandbits(32)
# class Wrapper(int):
# def __init__(self, x):
# int.__init__(x)
# def __hash__(self):
# return super(Wrapper, self).__hash__() ^ RANDOM
class SparseTable:
def __init__(self, data, merge_method):
self.note = [0] * (len(data) + 1)
self.merge_method = merge_method
l, r, v = 1, 2, 0
while True:
for i in range(l, r):
if i >= len(self.note):
break
self.note[i] = v
else:
l *= 2
r *= 2
v += 1
continue
break
self.ST = [[0] * len(data) for _ in range(self.note[-1]+1)]
self.ST[0] = data
for i in range(1, len(self.ST)):
for j in range(len(data) - (1 << i) + 1):
self.ST[i][j] = merge_method(self.ST[i-1][j], self.ST[i-1][j + (1 << (i-1))])
def query(self, l, r):
pos = self.note[r-l+1]
return self.merge_method(self.ST[pos][l], self.ST[pos][r - (1 << pos) + 1])
class SegmentTree:
def __init__(self, n, merge):
self.n = n
self.tree = [[inf, 0]] * (2 * self.n)
self._merge = merge
def query(self, ql, qr):
lans = [inf, 0]
rans = [inf, 0]
ql += self.n
qr += self.n + 1
while ql < qr:
if ql % 2:
lans = self._merge(lans, self.tree[ql])
ql += 1
if qr % 2:
qr -= 1
rans = self._merge(rans, self.tree[qr])
ql //= 2
qr //= 2
return self._merge(lans, rans)
def update(self, index, value):
index += self.n
self.tree[index] = value
while index:
index //= 2
self.tree[index] = self._merge(self.tree[2 * index], self.tree[2 * index + 1])
n = II()
nums = LII()
st_gcd = SparseTable(nums, math.gcd)
def merge_min(x, y):
min1, cnt1 = x
min2, cnt2 = y
if min1 < min2: return [min1, cnt1]
if min1 > min2: return [min2, cnt2]
return [min1, cnt1 + cnt2]
seg = SegmentTree(n, merge_min)
for i, v in enumerate(nums):
seg.update(i, [v, 1])
q = II()
for _ in range(q):
l, r = GMI()
v = st_gcd.query(l, r)
mi, c = seg.query(l, r)
if v == mi:
print(r - l + 1 - c)
else:
print(r - l + 1)
|
Codeforces Round 271 (Div. 2)
|
CF
| 2,014 | 1 | 256 |
Ant colony
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
|
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
| null |
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
[{"input": "5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5", "output": "4\n4\n1\n1"}]
| 2,100 |
["data structures", "math", "number theory"]
| 65 |
[{"input": "5\r\n1 3 2 4 2\r\n4\r\n1 5\r\n2 5\r\n3 5\r\n4 5\r\n", "output": "4\r\n4\r\n1\r\n1\r\n"}]
| false |
stdio
| null | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.