prob_desc_time_limit
stringclasses 21
values | prob_desc_sample_outputs
stringlengths 5
329
| src_uid
stringlengths 32
32
| prob_desc_notes
stringlengths 31
2.84k
β | prob_desc_description
stringlengths 121
3.8k
| prob_desc_output_spec
stringlengths 17
1.16k
β | prob_desc_input_spec
stringlengths 38
2.42k
β | prob_desc_output_to
stringclasses 3
values | prob_desc_input_from
stringclasses 3
values | lang
stringclasses 5
values | lang_cluster
stringclasses 1
value | difficulty
int64 -1
3.5k
β | file_name
stringclasses 111
values | code_uid
stringlengths 32
32
| prob_desc_memory_limit
stringclasses 11
values | prob_desc_sample_inputs
stringlengths 5
802
| exec_outcome
stringclasses 1
value | source_code
stringlengths 29
58.4k
| prob_desc_created_at
stringlengths 10
10
| tags
sequencelengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
sequencelengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 second | ["4 5 9 13 18", "10 11 12 13 14 15 16 17", "-1"] | b8c440664f8073d3e273878b0ca1e810 | NoteIn the first example, there are $$$3$$$ triples $$$(i, j, k)$$$ that contribute to the balance of the score distribution. $$$(1, 2, 3)$$$ $$$(1, 3, 4)$$$ $$$(2, 4, 5)$$$ | Kuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round.The round consists of $$$n$$$ problems, numbered from $$$1$$$ to $$$n$$$. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the score of $$$i$$$-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding $$$10^9$$$. A harder problem should grant a strictly higher score than an easier problem. In other words, $$$1 \leq a_1 < a_2 < \dots < a_n \leq 10^9$$$. The balance of the score distribution, defined as the number of triples $$$(i, j, k)$$$ such that $$$1 \leq i < j < k \leq n$$$ and $$$a_i + a_j = a_k$$$, should be exactly $$$m$$$. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output $$$-1$$$. | If there is no solution, print a single integer $$$-1$$$. Otherwise, print a line containing $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them. | The first and single line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 5000$$$, $$$0 \leq m \leq 10^9$$$)Β β the number of problems and the required balance. | standard output | standard input | Python 3 | Python | 2,200 | train_075.jsonl | f989312c23fe7001d6dfd1a1a53b1167 | 256 megabytes | ["5 3", "8 0", "4 10"] | PASSED | def main():
n, m = map(int, input().split())
x = []
i = 1
while (n > 0 and m >= len(x) // 2):
m -= len(x) // 2
n -= 1
x.append(i)
i += 1
k = i - 1
if (m == 0 and n == 0):
print(*x)
return
elif (n == 0):
print(-1)
return
else:
x.append(2 * k - m * 2)
n -= 1
for i in range(n):
x.append(20000 * (i + 1) + 1)
print(*x)
main() | 1583246100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["1\n......\n.X.XX.\n......", "2\n..........\n..........\n...XX.....\n..........\n..........\n..........\n.....XX...\n..........\n..........\n..........", "0\nX....\n..XXX\n..XXX\n..XXX"] | 9602fa7b9d05560959ee5fdeeb1f6507 | null | The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $$$n \times m$$$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as "X" while the remaining ones were marked as ".". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $$$0$$$) some trees were set on fire. At the beginning of minute $$$0$$$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $$$8$$$ neighboring trees. At the beginning of minute $$$T$$$, the fire was extinguished.The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $$$T$$$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $$$T$$$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.Note that you'd like to maximize value $$$T$$$ but the set of trees can be arbitrary. | In the first line print the single integer $$$T$$$ β the maximum time the Forest was on fire. In the next $$$n$$$ lines print the certificate: the map ($$$n \times m$$$ rectangle) where the trees that were set on fire are marked as "X" and all other trees are marked as ".". | The first line contains two integer $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le n \cdot m \le 10^6$$$) β the sizes of the map. Next $$$n$$$ lines contain the map. The $$$i$$$-th line corresponds to the $$$i$$$-th row of the map and contains $$$m$$$-character string. The $$$j$$$-th character of the $$$i$$$-th string is "X" if the corresponding tree is burnt and "." otherwise. It's guaranteed that the map contains at least one "X". | standard output | standard input | PyPy 3 | Python | 2,200 | train_067.jsonl | 6ab4bf3de7c1e5d4fee2159522fbe4b7 | 512 megabytes | ["3 6\nXXXXXX\nXXXXXX\nXXXXXX", "10 10\n.XXXXXX...\n.XXXXXX...\n.XXXXXX...\n.XXXXXX...\n.XXXXXXXX.\n...XXXXXX.\n...XXXXXX.\n...XXXXXX.\n...XXXXXX.\n..........", "4 5\nX....\n..XXX\n..XXX\n..XXX"] | PASSED | import sys
input = lambda:sys.stdin.readline().rstrip()
h,w=map(int,input().split())
d=w+2
b=[0]*(w+2)
for i in range(h):
b+=([0]+[int(j=="X") for j in input()]+[0])
b+=([0]*(w+2))
co=sum(b)
t=10**10
for i in range(1,h+1):
f=0
for j in range(w+2):
f+=b[i*d+j]
if b[i*d+j]==0 and f:
t=min(t,(f-1)//2)
f=0
for j in range(1,w+1):
f=0
for i in range(h+2):
f+=b[i*d+j]
if b[i*d+j]==0 and f:
t=min(t,(f-1)//2)
f=0
coo=0
ans=[-1]*(w+2)*(h+2)
stack=[]
for i in range(h+2):
for j in range(w+2):
if b[i*d+j]==0:
stack.append(i*d+j)
ans[i*d+j]=0
dij=[(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
for ij in stack:
i,j=divmod(ij,d)
for x,y in dij:
if 0<=i+x<h+2 and 0<=j+y<w+2:
if ans[(i+x)*d+j+y]==-1:
ans[(i+x)*d+j+y]=ans[i*d+j]+1
if ans[(i+x)*d+j+y]>t:
coo+=1
stack.append((i+x)*d+(j+y))
if coo*6<co and t==1:
t-=1
print(t)
for i in range(1,h+1):
print("".join([".X"[int(t<j)]for j in ans[i*d+1:i*d+w+1]])) | 1574582700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["YES\nNO", "NO\nYES\nNO\nYES"] | c6633581d7424d670eaa0f8a5c8cc366 | NoteIn the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.Explanation of the second example. The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good. The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide. The third query: "NO", because characters "?" can't be replaced with bad letters. The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x". | It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.The good letters are given to Petya. All the others are bad. | Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrary. | The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad. The second line contains the patternΒ β a string s of lowercase English letters, characters "?" and "*" (1ββ€β|s|ββ€β105). It is guaranteed that character "*" occurs in s no more than once. The third line contains integer n (1ββ€βnββ€β105)Β β the number of query strings. n lines follow, each of them contains single non-empty string consisting of lowercase English lettersΒ β a query string. It is guaranteed that the total length of all query strings is not greater than 105. | standard output | standard input | Python 2 | Python | 1,600 | train_002.jsonl | 1ccf82b55190a55c7d8c939691ba149d | 256 megabytes | ["ab\na?a\n2\naaa\naab", "abc\na?a?a*\n4\nabacaba\nabaca\napapa\naaaaax"] | PASSED |
def check(g1,g2,s,star):
for idx,char in enumerate(g1):
if char==s[idx]:
continue
elif char=='?':
if alpha[ord(s[idx])-97]==1:
continue
else:
return "NO"
else:
return "NO"
ss=s[::-1]
for idx,char in enumerate(reversed(g2)):
if char==ss[idx]:
continue
elif char=='?':
if alpha[ord(ss[idx])-97]==1:
continue
else:
return "NO"
else:
return "NO"
x=star
while x<=star+len(s)-len(glob):
if alpha[ord(s[x])-97]==0:
x+=1
else:
return "NO"
return "YES"
def equal(glob,s):
for idx,char in enumerate(glob):
if char==s[idx]:
continue
elif char=='?':
if alpha[ord(s[idx])-97]==1:
continue
else:
return "NO"
elif char=='*':
if alpha[ord(s[idx])-97]==0:
continue
else:
return "NO"
else:
return "NO"
return "YES"
def justless(glob1,s):
for idx,char in enumerate(glob1):
if char==s[idx]:
continue
elif char=='?':
if alpha[ord(s[idx])-97]==1:
continue
else:
return "NO"
else:
return "NO"
return "YES"
good=list(raw_input())
alpha=[0]*26
for char in good:
alpha[ord(char)-97]=1
glob=list(raw_input())
glen=len(glob)
flag=f=0
for i,char in enumerate(glob):
if char=="*":
flag=1
glob1=glob[:i]+glob[i+1:]
g1=glob[:i]
g2=glob[i+1:]
star=i
break
n=input()
for _ in xrange(n):
s=raw_input()
f=0
if flag==0:
if len(s)==glen:
for idx,char in enumerate(glob):
if char==s[idx]:
continue
elif char=='?':
if alpha[ord(s[idx])-97]==1:
continue
else:
print "NO"
break
else:
print "NO"
break
else:
print "YES"
else:
print "NO"
else:
if len(s)==glen:
print equal(glob,s)
elif len(s)==glen-1:
print justless(glob1,s)
elif len(s)<len(glob1):
print "NO"
else:
print check(g1,g2,s,star)
| 1500906900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["8", "10"] | 13574507efa5089f3420cf002c3f8077 | NoteIn the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb". In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once. | After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of mβ+βn tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s|β=βmβ+βn) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1β<βp2β<β...β<βpq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts. | Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109β+β7. Please note, that you are not asked to maximize the remainder modulo 109β+β7! The goal is to maximize the initial value and then print the remainder. | The first line of the input contains two integers n and k (0ββ€βnββ€β1β000β000, 1ββ€βkββ€β26). The second line contains a string t (|t|β=βm,β1ββ€βmββ€β1β000β000) consisting of only first k lowercase English letters. | standard output | standard input | PyPy 2 | Python | 2,200 | train_037.jsonl | eea3af4b392f7a80448d73b36a242770 | 256 megabytes | ["1 3\nac", "0 2\naaba"] | PASSED | #
# http://codeforces.com/problemset/problem/655/E
MOD = 10 ** 9 + 7
def read_ints():
return map(int, raw_input().split())
N, K = read_ints()
counts, indexes = [0] * K, [-1] * K
count = 1
for i, c in enumerate(raw_input()):
c = ord(c) - ord('a')
counts[c], count, indexes[c] = count, (2 * count - counts[c]) % MOD, i
counts = [counts[i] for i in sorted(xrange(K), key=lambda _: indexes[_])]
for i in xrange(N):
counts[i % K], count = count, (2 * count - counts[i % K]) % MOD
print count
| 1458318900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["3", "8", "-1"] | bc93c89cf41c8e44584045ac52b9acc6 | NoteIn the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.Olya does not recommend drinking energy drinks and generally believes that this is bad. | Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.Formally, her room can be represented as a field of nβΓβm cells, each cell of which is empty or littered with cans.Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.Now Olya needs to get from cell (x1,βy1) to cell (x2,βy2). How many seconds will it take her if she moves optimally?It's guaranteed that cells (x1,βy1) and (x2,βy2) are empty. These cells can coincide. | Print a single integer β the minimum time it will take Olya to get from (x1,βy1) to (x2,βy2). If it's impossible to get from (x1,βy1) to (x2,βy2), print -1. | The first line contains three integers n, m and k (1ββ€βn,βm,βkββ€β1000) β the sizes of the room and Olya's speed. Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i,βj) is littered with cans, and "." otherwise. The last line contains four integers x1,βy1,βx2,βy2 (1ββ€βx1,βx2ββ€βn, 1ββ€βy1,βy2ββ€βm) β the coordinates of the first and the last cells. | standard output | standard input | PyPy 2 | Python | 2,100 | train_003.jsonl | 11795e61c46fbd7c96ba6a38cddb554b | 256 megabytes | ["3 4 4\n....\n###.\n....\n1 1 3 1", "3 4 1\n....\n###.\n....\n1 1 3 1", "2 2 1\n.#\n#.\n1 1 2 2"] | PASSED | from sys import *
f = lambda: map(int,raw_input().split())
n, m, k = f()
t = [[1e9 * (q == '.') for q in stdin.readline()] for i in range(n)]
t.append([0] * m)
a, b, c, d = [q - 1 for q in f()]
u = [(a, b)]
t[a][b] = l = 0
def g(i, x, y):
if i > k or t[x][y] < l: return 0
if t[x][y] > l:
t[x][y] = l
v.append((x, y))
return 1
while u and t[c][d] == 1e9:
l += 1
v = []
for x, y in u:
i = j = 1
while g(i, x - i, y): i += 1
while g(j, x + j, y): j += 1
i = j = 1
while g(i, x, y - i): i += 1
while g(j, x, y + j): j += 1
u = v
print(l if t[c][d] < 1e9 else -1) | 1508773500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["aaaaa", ":(", "ababacac", ":("] | b5bcb6d78daacd56362fd76e35b903ac | NoteIn the first example, we have $$$s = $$$ "aaaaa", and $$$s' = $$$ "".In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$.In the third example, we have $$$s = $$$ "ababacac", and $$$s' = $$$ "bbcc", and $$$t = s + s' = $$$ "ababacacbbcc". | Bob has a string $$$s$$$ consisting of lowercase English letters. He defines $$$s'$$$ to be the string after removing all "a" characters from $$$s$$$ (keeping all other characters in the same order). He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example).You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique. | Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). | The first line of input contains a string $$$t$$$ ($$$1 \leq |t| \leq 10^5$$$) consisting of lowercase English letters. | standard output | standard input | Python 3 | Python | 1,100 | train_019.jsonl | 60c369d078d2239e0bb1331ab3a79f74 | 256 megabytes | ["aaaaa", "aacaababc", "ababacacbbcc", "baba"] | PASSED | s = input()
import re
r = re.sub('a','',s)
if r == 2*r[:len(r)//2] and (s[-len(r)//2:].count('a') == 0 or r == ''):
print(s[:len(s)-len(r)//2])
else: print(':(') | 1555783500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["a\nabcdfdcba\nxyzyx\nc\nabba"] | beaccd2c0213a330538fe741d1f4b5bf | NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$. It is a palindrome. "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s". | This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions: The length of $$$t$$$ does not exceed the length of $$$s$$$. $$$t$$$ is a palindrome. There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$. | For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them. | The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$10^6$$$. | standard output | standard input | Python 3 | Python | 1,800 | train_014.jsonl | 52285b8521d672b951c513d14d9f3570 | 256 megabytes | ["5\na\nabcdfdcecba\nabbaxyzyx\ncodeforces\nacbba"] | PASSED | #!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
import threading
from math import floor
# from bisect import bisect_right
from collections import Counter
from math import gcd
mod=998244353
def kmp(pat,M):
len = 0
lps=[0]*M
i = 1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
# to search step.
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
return lps[-1]
def main():
for _ in range(int(input())):
s=input()
n=len(s)
start=0
end=n-1
while start<end and s[start]==s[end]:
start+=1
end-=1
ans=s[:start]
t=s[start:end+1]
t1=t+'*'+t[::-1]
t2=t[::-1]+'*'+t
c1=kmp(t1,len(t1))
c2=kmp(t2,len(t2))
if c1<c2:
ans+=t2[:c2]
else:
ans+=t1[:c1]
ans+=s[end+1:]
print(ans)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | 1584628500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["6", "1"] | f52a416cdf09f69995112126c312da6f | null | Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting. | Print a single integer β the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1,β2) and (2,β1) are considered identical. | The first line contains integers n and p (3ββ€βnββ€β3Β·105;Β 0ββ€βpββ€βn) β the number of coders in the F company and the minimum number of agreed people. Each of the next n lines contains two integers xi, yi (1ββ€βxi,βyiββ€βn) β the numbers of coders named by the i-th coder. It is guaranteed that xiββ βi,βΒ yiββ βi,βΒ xiββ βyi. | standard output | standard input | PyPy 3 | Python | 1,900 | train_081.jsonl | f956809a41258e17e8e0385653c752f2 | 256 megabytes | ["4 2\n2 3\n1 4\n1 4\n2 1", "8 6\n5 6\n5 7\n5 8\n6 2\n2 1\n7 3\n1 3\n1 4"] | PASSED | from collections import defaultdict
from bisect import bisect_left as lower
import sys
input = sys.stdin.readline
def put():
return map(int, input().split())
try:
n,m = put()
cnt, mp, ans = [0]*n, defaultdict(), [0]*n
for _ in range(n):
x,y = put()
x,y = x-1,y-1
key = (min(x,y), max(x,y))
if key in mp:
mp[key]+=1
else:
mp[key]=1
cnt[x]+=1
cnt[y]+=1
except:
print('lol')
for (x,y),val in mp.items():
if cnt[x]+cnt[y]>= m and cnt[x]+cnt[y]-val<m:
ans[x]-=1
ans[y]-=1
scnt = cnt.copy()
scnt.sort()
for i in range(n):
ans[i]+= n-lower(scnt, m-cnt[i])
if 2*cnt[i]>=m:
ans[i]-=1
print(sum(ans)//2)
| 1398169200 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["10.0000000000", "-1", "74.6757620881"] | d1c53bd1359efa662604d55176d8af75 | null | Once upon a time in the galaxy of far, far away...Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon β space mines. Let's describe a space mine's build.Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius r with the center in the point O. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point P, such that (transporting long-spiked mines is problematic), where |OP| is the length of the segment connecting O and P. It is convenient to describe the point P by a vector p such that Pβ=βOβ+βp.The Death Star is shaped like a ball with the radius of R (R exceeds any mine's radius). It moves at a constant speed along the v vector at the speed equal to |v|. At the moment the rebels noticed the Star of Death, it was located in the point A.The rebels located n space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed). | If the rebels will succeed in stopping the Death Star using space mines, print the time from the moment the Death Star was noticed to the blast. If the Death Star will not touch a mine, print "-1" (without quotes). For the answer the absolute or relative error of 10β-β6 is acceptable. | The first input data line contains 7 integers Ax,βAy,βAz,βvx,βvy,βvz,βR. They are the Death Star's initial position, the direction of its movement, and its radius (β-β10ββ€βvx,βvy,βvzββ€β10, |v|β>β0, 0β<βRββ€β100). The second line contains an integer n, which is the number of mines (1ββ€βnββ€β100). Then follow n data blocks, the i-th of them describes the i-th mine. The first line of each block contains 5 integers Oix,βOiy,βOiz,βri,βmi, which are the coordinates of the mine centre, the radius of its body and the number of spikes (0β<βriβ<β100,β0ββ€βmiββ€β10). Then follow mi lines, describing the spikes of the i-th mine, where the j-th of them describes the i-th spike and contains 3 integers pijx,βpijy,βpijz β the coordinates of the vector where the given spike is directed (). The coordinates of the mines' centers and the center of the Death Star are integers, their absolute value does not exceed 10000. It is guaranteed that Rβ>βri for any 1ββ€βiββ€βn. For any mines iββ βj the following inequality if fulfilled: . Initially the Death Star and the mines do not have common points. | standard output | standard input | Python 2 | Python | 2,500 | train_014.jsonl | 278e65412a7f02f990c5b80560c2481e | 256 megabytes | ["0 0 0 1 0 0 5\n2\n10 8 0 2 2\n0 -3 0\n2 2 0\n20 0 0 4 3\n2 4 0\n-4 3 0\n1 -5 0", "8 8 4 4 4 2 6\n1\n-2 -2 -1 3 0", "30 30 2 1 2 1 20\n3\n0 0 40 5 1\n1 4 4\n-10 -40 -5 7 0\n100 200 95 8 1\n-10 0 0"] | PASSED | import math
inf = float('inf')
ax,ay,az,vx,vy,vz,R=map(int,raw_input().split())
n=input()
t=inf
def check(ox,oy,oz,r):
x,y,z=ax-ox,ay-oy,az-oz
a=vx**2+vy**2+vz**2
b=2*(x*vx+y*vy+z*vz)
c=x**2+y**2+z**2-r**2
d=b*b-4*a*c
if d<0: return
x1=(-b+d**0.5)/a/2
x2=(-b-d**0.5)/a/2
global t
if x1>=0: t=min(t,x1)
if x2>=0: t=min(t,x2)
for i in xrange(n):
ox,oy,oz,r,m = map(int,raw_input().split())
check(ox,oy,oz,r+R)
for j in xrange(m):
rx,ry,rz = map(int,raw_input().split())
check(rx+ox,ry+oy,rz+oz,R)
print -1 if t==inf else "%.20f"%t
| 1308236400 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["2\n3\n1\n1"] | 1b13c9d9fa0c5a44d035bcf6d70e1a60 | NoteIn the first test case there are two possible sums: $$$1+2+5=8$$$ and $$$1+3+5=9$$$. | During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: The cell with coordinates $$$(x, y)$$$ is at the intersection of $$$x$$$-th row and $$$y$$$-th column. Upper left cell $$$(1,1)$$$ contains an integer $$$1$$$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $$$(x,y)$$$ in one step you can move to the cell $$$(x+1, y)$$$ or $$$(x, y+1)$$$. After another Dinwows update, Levian started to study "Celex-2021" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $$$(x_1, y_1)$$$ to another given cell $$$(x_2, y_2$$$), if you can only move one cell down or right.Formally, consider all the paths from the cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths. | For each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 57179$$$) β the number of test cases. Each of the following $$$t$$$ lines contains four natural numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le 10^9$$$, $$$1 \le y_1 \le y_2 \le 10^9$$$) β coordinates of the start and the end cells. | standard output | standard input | PyPy 3 | Python | 1,600 | train_025.jsonl | b8a67074c94cdbb67563dd4d3b22f3c1 | 256 megabytes | ["4\n1 1 2 2\n1 2 2 4\n179 1 179 100000\n5 7 5 7"] | PASSED | import sys
# sys.setrecursionlimit(10**6)
input=sys.stdin.readline
t=int(input())
import math
def f(a,b):
z2=min(a-1,b-1)
z4=math.pow(2,z2)
return int(z4)
for t1 in range(t):
x,y,a,b=list(map(int,input().split(" ")))
# z1=min(x-1,y-1)
x-=1
y-=1
a-=x
b-=y
ans=0
if(a==1 or b==1):
ans=1
else:
ans=1+(a-1)*(b-1)
print(ans) | 1590503700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1 2\n2 3\n3 4\n4 5\n1 3\n3 5", "-1"] | 959709bfe7b26a4b9f2e7430350650a9 | null | Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers. | If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β description of all the direct connections in the system. Each direct connection is described by two numbers β indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any. | The first input line contains 3 space-separated integer numbers n, m, v (3ββ€βnββ€β105,β0ββ€βmββ€β105,β1ββ€βvββ€βn), n β amount of servers, m β amount of direct connections, v β index of the server that fails and leads to the failure of the whole system. | standard output | standard input | Python 3 | Python | 1,700 | train_020.jsonl | c7e790cfa80b3d52252f3629ede63c30 | 256 megabytes | ["5 6 3", "6 100 1"] | PASSED | n,m,v=map(int,input().split())
if m<n-1 or m>(n-1)*(n-2)//2+1:
print(-1)
exit()
if v==1:
print(1,2)
t=[1]+[i for i in range(3,n+1)]
s=1
i,j=0,1
k=len(t)
while s<m and i<k-1:
print(t[i],t[j])
j+=1
if j==k:
i+=1
j=i+1
s+=1
else:
print(1,v)
t=[i for i in range(v,n+1)]+[i for i in range(2,v)]
s=1
i,j=0,1
k=len(t)
while s<m and i<k-1:
print(t[i],t[j])
j+=1
if j==k:
i+=1
j=i+1
s+=1 | 1277823600 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["1", "12"] | 6e85f83d544eeb16f57523eb532abf04 | null | Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c β one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a,βb), (b,βc), (a,βd), (d,βc) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.When rhombi are compared, the order of intersections b and d doesn't matter. | Print the required number of "damn rhombi". | The first line of the input contains a pair of integers n, m (1ββ€βnββ€β3000,β0ββ€βmββ€β30000) β the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai,βbi (1ββ€βai,βbiββ€βn;aiββ βbi) β the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one. | standard output | standard input | PyPy 2 | Python | 1,700 | train_059.jsonl | 90f8b927bb2f9e41dc07e18f5cb6aedf | 256 megabytes | ["5 4\n1 2\n2 3\n1 4\n4 3", "4 12\n1 2\n1 3\n1 4\n2 1\n2 3\n2 4\n3 1\n3 2\n3 4\n4 1\n4 2\n4 3"] | PASSED | from __future__ import division, print_function
import bisect
import math
import itertools
import sys
from atexit import register
if sys.version_info[0] < 3:
from io import BytesIO as stream
else:
from io import StringIO as stream
if sys.version_info[0] < 3:
class dict(dict):
"""dict() -> new empty dictionary"""
def items(self):
"""D.items() -> a set-like object providing a view on D's items"""
return dict.iteritems(self)
def keys(self):
"""D.keys() -> a set-like object providing a view on D's keys"""
return dict.iterkeys(self)
def values(self):
"""D.values() -> an object providing a view on D's values"""
return dict.itervalues(self)
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
def sync_with_stdio(sync=True):
"""Set whether the standard Python streams are allowed to buffer their I/O.
Args:
sync (bool, optional): The new synchronization setting.
"""
global input, flush
if sync:
flush = sys.stdout.flush
else:
sys.stdin = stream(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
sys.stdout = stream()
register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
def main():
g=[]
n,m=map(int, input().split())
for i in range(n):
g.append([])
for j in range(m):
p,q=map(int, input().split())
g[p-1].append(q)
cnt=0
#print(g)
for i in range(n):
a=[0]*n
for j in range(len(g[i])):
for k in range(len(g[g[i][j]-1])):
a[g[g[i][j]-1][k]-1]+=1
#print(a)
for t in range(n):
if t==i:
continue
j=a[t]
if j>1:
cnt+=(((j-1)*j)//2)
print(cnt)
if __name__ == '__main__':
sync_with_stdio(False)
main() | 1416238500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["9", "17"] | ad9fd71025c5f91cece740ea95b0eb6f | NoteIn the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1,β1), (1,β2), (1,β3), (2,β1), (2,β2), (2,β3), (3,β1), (3,β2), (3,β3).In the second example the mayor can change p2 to 4 and p3 to 5. | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.There are n stations in the subway. It was built according to the Bertown Transport Law: For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly piβ=βi; For each station i there exists exactly one station j such that pjβ=βi. The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x,βy) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1ββ€βx,βyββ€βn).The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! | Print one number β the maximum possible value of convenience. | The first line contains one integer number n (1ββ€βnββ€β100000) β the number of stations. The second line contains n integer numbers p1, p2, ..., pn (1ββ€βpiββ€βn) β the current structure of the subway. All these numbers are distinct. | standard output | standard input | Python 3 | Python | 1,500 | train_011.jsonl | e5c24d3c9ed17ec970f4f49dd7c2a852 | 256 megabytes | ["3\n2 1 3", "5\n1 5 4 3 2"] | PASSED | input()
l = [[int(x)-1,False] for x in input().split()]
loop = []
for begin in l:
if begin[1]:
continue
count = 0;
nextI = begin[0];
while not l[nextI][1]:
l[nextI][1]=True
nextI = l[nextI][0]
count += 1
loop.append(count)
s = sorted(loop,reverse=True)
total = sum(map(lambda x:x*x,s)) + (2*s[0]*s[1] if len(s)>=2 else 0)
print(total)
| 1509113100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2", "1\n6", "1\n0"] | f0a138b9f6ad979c5ca32437e05d6f43 | NoteNumber 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. | You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself. The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move. | In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer β his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them. | The first line contains the only integer q (1ββ€βqββ€β1013). 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. | standard output | standard input | Python 2 | Python | 1,400 | train_003.jsonl | 014bef652a4312c3f91993d5fe8a26f3 | 256 megabytes | ["6", "30", "1"] | PASSED | #!/usr/bin/env python
from sys import stdin as cin
def find_div(q):
d = 0
if q == 1:
return 1
if q % 2 == 0:
return 2
else:
for d in range(3, int(q**0.5) + 3, 2):
if q % d == 0:
return d
return q
def main():
q = int(next(cin))
if q == 1:
return 1,0
d = find_div(q)
if d in (1, q):
return 1,0
q = q // d
e = find_div(q)
if e in (1, q):
return 2,
else:
return 1, e * d
print '\n'.join(map(str, main()))
| 1329490800 | [
"number theory",
"math",
"games"
] | [
1,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["4\n1\n146981438\n747093407"] | ff4fce15470e5dbd1153bd23b26896f1 | NoteYou have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to $$$2$$$, but there is also a distribution where the difference is $$$10^9 + 8$$$, then the answer is $$$2$$$, not $$$1$$$.In the first test case of the example, there're the following numbers: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$, and $$$8$$$. We can divide them into such two sets: $$${4, 8, 16}$$$ and $$${8, 16}$$$. Then the difference between the sums of numbers in sets would be $$$4$$$. | Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems. The boy has found an online judge with tasks divided by topics they cover. He has picked $$$p^{k_i}$$$ problems from $$$i$$$-th category ($$$p$$$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.Formally, given $$$n$$$ numbers $$$p^{k_i}$$$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $$$10^{9}+7$$$. | Output one integerΒ β the reminder of division the answer by $$$1\,000\,000\,007$$$. | Input consists of multiple test cases. The first line contains one integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$Β β the number of test cases. Each test case is described as follows: The first line contains two integers $$$n$$$ and $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. The second line contains $$$n$$$ integers $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$. The sum of $$$n$$$ over all test cases doesn't exceed $$$10^6$$$. | standard output | standard input | PyPy 3 | Python | 1,900 | train_016.jsonl | 6e323ae8e3dc57a21ff2c0cc34eddaf9 | 256 megabytes | ["4\n5 2\n2 3 4 4 3\n3 1\n2 10 1000\n4 5\n0 1 1 100\n1 8\n89"] | PASSED | from sys import stdin, stdout
import math
from collections import defaultdict
def main():
MOD7 = 1000000007
t = int(stdin.readline())
pw = [0] * 21
for w in range(20,-1,-1):
pw[w] = int(math.pow(2,w))
for ks in range(t):
n,p = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
if p == 1:
if n % 2 ==0:
stdout.write("0\n")
else:
stdout.write("1\n")
continue
arr.sort(reverse=True)
left = -1
i = 0
val = [0] * 21
tmp = p
val[0] = p
slot = defaultdict(int)
for x in range(1,21):
tmp = (tmp * tmp) % MOD7
val[x] = tmp
while i < n:
x = arr[i]
if left == -1:
left = x
else:
slot[x] += 1
tmp = x
if x == left:
left = -1
slot.pop(x)
else:
while slot[tmp] % p == 0:
slot[tmp+1] += 1
slot.pop(tmp)
tmp += 1
if tmp == left:
left = -1
slot.pop(tmp)
i+=1
if left == -1:
stdout.write("0\n")
continue
res = 1
for w in range(20,-1,-1):
pww = pw[w]
if pww <= left:
left -= pww
res = (res * val[w]) % MOD7
if left == 0:
break
for x,c in slot.items():
tp = 1
for w in range(20,-1,-1):
pww = pw[w]
if pww <= x:
x -= pww
tp = (tp * val[w]) % MOD7
if x == 0:
break
res = (res - tp * c) % MOD7
stdout.write(str(res)+"\n")
main() | 1591281300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4 13"] | 28b031722c279783ec44c755ef933836 | NoteIn the first test the initial coordinates of people are $$$9$$$, $$$6$$$, $$$6$$$, $$$9$$$, $$$9$$$ and their speeds are $$$1$$$, $$$2$$$, $$$1$$$, $$$1$$$, $$$1$$$. So, it's easy to see, that at the moment $$$4$$$ one coordinate was modified from $$$13$$$ to $$$12$$$.This is the first test in the hack format:5 79 6 6 9 91 2 1 1 12 3 4 1 00 2 3 1 44 3 0 1 21 3 4 0 21 4 0 2 32 4 1 3 02 4 1 3 04 0 12 | Cirno gives AquaMoon a problem. There are $$$m$$$ people numbered from $$$0$$$ to $$$m - 1$$$. They are standing on a coordinate axis in points with positive integer coordinates. They are facing right (i.e. in the direction of the coordinate increase). At this moment everyone will start running with the constant speed in the direction of coordinate increasing. The initial coordinate of the $$$i$$$-th person on the line is $$$x_i$$$, and the speed of the $$$i$$$-th person is $$$v_i$$$. So the coordinate of the $$$i$$$-th person at the moment $$$t$$$ will be $$$x_i + t \cdot v_i$$$.Cirno captured the coordinates of $$$m$$$ people in $$$k$$$ consecutive integer moments from $$$0$$$ to $$$k - 1$$$. In every moment, the coordinates of $$$m$$$ people were recorded in arbitrary order.To make the problem more funny, Cirno modified one coordinate at the moment $$$y$$$ ($$$0 < y < k-1$$$) to a different integer.AquaMoon wants to find the moment $$$y$$$ and the original coordinate $$$p$$$ before the modification. Actually, she is not a programmer at all. So she wasn't able to solve it. Can you help her? | Print a single line with two integers $$$y$$$, $$$p$$$ β the moment that contains the modified coordinate and the original coordinate. | This problem is made as interactive. It means, that your solution will read the input, given by the interactor. But the interactor will give you the full input at the beginning and after that, you should print the answer. So you should solve the problem, like as you solve the usual, non-interactive problem because you won't have any interaction process. The only thing you should not forget is to flush the output buffer, after printing the answer. Otherwise, you can get an "Idleness limit exceeded" verdict. Refer to the interactive problems guide for the detailed information about flushing the output buffer. The first line contains two integers $$$m$$$ and $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) β the number of people and the number of recorded moments. The next $$$k$$$ lines contain captured positions. $$$i$$$-th of these lines contains $$$m$$$ integers between $$$1$$$ and $$$10^6$$$ (inclusive), representing positions captured by Cirno at the moment $$$i-1$$$. The input is guaranteed to be valid (i.e. only one integer was modified to a different value according to the problem statement). Also, it is guaranteed, that $$$1 \le v_i \le 1000$$$ for all $$$1 \leq i \leq m$$$. Hack format: The first line should contain two integers $$$m$$$ and $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) β the number of people and the number of moments. In the second line, there should be $$$m$$$ integers $$$x_0, x_1, \dots,x_{m - 1}$$$ ($$$1 \le x_i \le 10^6$$$), where $$$x_i$$$ is the initial coordinate of the $$$i$$$-th person. In the third line, there should be $$$m$$$ integers $$$v_0, v_1, \dots,v_{m - 1}$$$ ($$$1 \le v_i \le 1000$$$), where $$$v_i$$$ is the speed of the $$$i$$$-th person. It should be true that $$$x_i + (k-1) v_i \leq 10^6$$$ for each $$$0 \leq i < m$$$. In the next $$$k$$$ lines, each line should contain $$$m$$$ integers. $$$i$$$-th line should contain $$$m$$$ distinct integers $$$p_0, p_1, \ldots, p_{m-1}$$$ ($$$0 \leq p_j < m$$$). The meaning of these numbers: $$$j$$$-th integer in the input in the $$$i$$$-th moment is the coordinate of the $$$p_{j}$$$-th person. In the last line, there should be three integers $$$y$$$, $$$i$$$, $$$c$$$. Cirno modified the coordinate of the $$$i$$$-th person at the moment $$$y$$$ to $$$c$$$ ($$$1 \leq y \leq k-2$$$, $$$0 \leq i \leq m - 1$$$, $$$1 \leq c \leq 10^6$$$, $$$c \neq x_i + y \cdot v_i$$$). | standard output | standard input | PyPy 3-64 | Python | 3,000 | train_086.jsonl | c7cd001fc5adce73aef24db2fea3faa4 | 256 megabytes | ["5 7\n6 9 9 6 9\n10 7 10 8 10\n11 11 11 10 8\n12 12 12 12 9\n14 13 12 10 13\n11 14 16 14 14\n12 15 18 15 15"] | PASSED | import os,sys
from random import randint
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# b = list(map(int, input().split()))
# if sum(a) != sum(b):
# print(-1)
# else:
# pos, neg = [], []
# for i in range(n):
# if a[i] > b[i]:
# pos.append([a[i] - b[i], i])
# elif a[i] < b[i]:
# neg.append([b[i] - a[i], i])
# ans = []
# while pos:
# ans.append((pos[-1][1], neg[-1][1]))
# pos[-1][0] -= 1
# neg[-1][0] -= 1
# if pos[-1][0] == 0:
# pos.pop()
# if neg[-1][0] == 0:
# neg.pop()
# print(len(ans))
# for i, j in ans:
# print(i + 1, j + 1)
# for _ in range(int(input())):
# n, m = list(map(int, input().split()))
# cnt = [[0] * m for _ in range(26)]
# for _ in range(n):
# s = input()
# for i in range(m):
# cnt[ord(s[i]) - ord('a')][i] += 1
# for _ in range(n - 1):
# s = input()
# for i in range(m):
# cnt[ord(s[i]) - ord('a')][i] -= 1
# ans = []
# for j in range(m):
# for i in range(26):
# if cnt[i][j]:
# ans.append(chr(97 + i))
# break
# print(''.join(ans))
# for _ in range(int(input())):
# def solve():
# n = int(input())
# a = list(map(int, input().split()))
# b = sorted(a)
# odd = defaultdict(list)
# even = defaultdict(list)
# for i in range(n):
# if i % 2:
# odd[b[i]].append(i)
# else:
# even[b[i]].append(i)
# for i in range(n):
# if i % 2:
# if not odd[a[i]]:
# print('NO')
# return
# odd[a[i]].pop()
# else:
# if not even[a[i]]:
# print('NO')
# return
# even[a[i]].pop()
# print('YES')
# solve()
# mod = 998244353
# N = 100010
# fac = [1] * N
# for i in range(2, N):
# fac[i] = fac[i - 1] * i % mod
# invfac = [1] * N
# invfac[N - 1] = pow(fac[N - 1], mod - 2, mod)
# for i in range(N - 1)[::-1]:
# invfac[i] = invfac[i + 1] * (i + 1) % mod
# def c(i, j):
# return fac[i] * invfac[j] * invfac[i - j] % mod
# for _ in range(int(input())):
# n = int(input())
# s = input()
# cnt11 = cnt0 = 0
# cur = 0
# for i in range(n):
# if s[i] == '1':
# cur += 1
# else:
# cnt0 += 1
# cnt11 += cur // 2
# cur = 0
# cnt11 += cur // 2
# print(c(cnt0 + cnt11, cnt0))
m, k = list(map(int, input().split()))
a_1d = [list(map(int, input().split())) for _ in range(k)]
sum_1d = [sum(a_1d[i]) for i in range(k)]
dif_1d = [sum_1d[i + 1] - sum_1d[i] for i in range(k - 1)]
for i in range(k - 2):
if dif_1d[i] == dif_1d[i + 1]:
real_dif_1d = dif_1d[i]
break
for i in range(k - 1):
if dif_1d[i] != real_dif_1d:
add_1d = real_dif_1d - dif_1d[i]
pos = i + 1
break
sum_2d = []
for i in range(k):
t = 0
for j in range(m):
t += a_1d[i][j] * a_1d[i][j]
sum_2d.append(t)
dif_2d = [sum_2d[i + 1] - sum_2d[i] for i in range(k - 1)]
difdif_2d = [dif_2d[i + 1] - dif_2d[i] for i in range(k - 2)]
real_dif_2d = difdif_2d[0]
for i in range(k - 3):
if difdif_2d[i] == difdif_2d[i + 1]:
real_dif_2d = difdif_2d[i]
break
if pos > 1:
real_2d = sum_2d[pos - 1] + sum_2d[pos - 1] - sum_2d[pos - 2] + real_dif_2d
else:
real_2d = sum_2d[pos + 1] - ((sum_2d[pos + 2] - sum_2d[pos + 1]) - real_dif_2d)
add2d = real_2d - sum_2d[pos]
ori = (add_1d + add2d // add_1d) // 2
print(pos, ori)
# ori - last = add
# ori^2-last^2=add2
# ori+last=add2//add
# ori = (add+add2//add) // 2
# x1 ... xk
# x1+v1 ... xk+vk
# x1+2v1 ... xk+2vk
# sum0
# sum0+dif = fake + x
# sum0+dif*2
# 66999 21111
# 87101010
# a, b, c, d, e = 6, 6, 9, 9, 9
# pre = a*a+b*b+c*c+d*d+e*e
# for _ in range(6):
# a += 2
# b += 1
# c += 1
# d += 1
# e += 1
# print(a*a+b*b+c*c+d*d+e*e, a*a+b*b+c*c+d*d+e*e - pre)
# pre = a*a+b*b+c*c+d*d+e*e
# ori**2 -last**2 -
| 1626012300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds | ["2 5 5", "1 2 2"] | f3ed9a3d4566cdb04cdc26be51027d44 | NoteIn the first test case, the minimum number of exchanges needed to exchange a chocolate of type $$$6$$$ to a chocolate of type $$$9$$$ is $$$5$$$. The sequence of exchanges is as follows: $$$6 \rightarrow 2 \rightarrow 0 \rightarrow 1 \rightarrow 7 \rightarrow 9$$$.In the second test case, the minimum number of exchanges needed to exchange a chocolate of type $$$4$$$ to a chocolate of type $$$8$$$ is $$$2$$$. The sequence of exchanges is as follows: $$$4 \rightarrow 0 \rightarrow 8$$$. | Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains $$$n$$$ chocolates. The $$$i$$$-th chocolate has a non-negative integer type $$$a_i$$$.Icy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all $$$a_i$$$ are distinct). Icy wants to make at least one pair of chocolates the same type. As a result, she asks her grandparents to perform some chocolate exchanges. Before performing any chocolate exchanges, Icy chooses two chocolates with indices $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$).In a chocolate exchange, Icy's grandparents choose a non-negative integer $$$k$$$, such that $$$2^k \ge a_x$$$, and change the type of the chocolate $$$x$$$ from $$$a_x$$$ to $$$2^k - a_x$$$ (that is, perform $$$a_x := 2^k - a_x$$$).The chocolate exchanges will be stopped only when $$$a_x = a_y$$$. Note that other pairs of equal chocolate types do not stop the procedure.Icy's grandparents are smart, so they would choose the sequence of chocolate exchanges that minimizes the number of exchanges needed. Since Icy likes causing trouble, she wants to maximize the minimum number of exchanges needed by choosing $$$x$$$ and $$$y$$$ appropriately. She wonders what is the optimal pair $$$(x, y)$$$ such that the minimum number of exchanges needed is maximized across all possible choices of $$$(x, y)$$$.Since Icy is not good at math, she hopes that you can help her solve the problem. | Output three integers $$$x$$$, $$$y$$$, and $$$m$$$. $$$x$$$ and $$$y$$$ are indices of the optimal chocolates to perform exchanges on. Your output must satisfy $$$1 \le x, y \le n$$$, $$$x \ne y$$$. $$$m$$$ is the number of exchanges needed to obtain $$$a_x = a_y$$$. We can show that $$$m \le 10^9$$$ for any pair of chocolates. If there are multiple solutions, output any. | The first line of the input contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β β the number of chocolates. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that all $$$a_i$$$ are distinct. | standard output | standard input | PyPy 3 | Python | 2,700 | train_100.jsonl | d4bca23d181485f9f5095ca56ac22a5e | 512 megabytes | ["5\n5 6 7 8 9", "2\n4 8"] | PASSED | from sys import *
n = int(stdin.readline())
tree = [{} for _ in range(31)]
idx, iid = {}, 0
for x in map(int, stdin.readline().split()):
iid += 1
idx[x] = iid
tree[x.bit_length()][x] = (x, 0)
x, y, m = 0, 0, 0
for i in range(30, 0, -1):
if not tree[i]:
continue
k, mp = 1 << i, tree[i]
kk = k >> 1
for a in mp:
av, ac = mp[a]
b = k - a if a > kk else 0
j = b.bit_length()
if b in tree[j]:
bv, bc = tree[j][b]
r = ac + bc + 1
if r > m:
x, y, m = av, bv, r
if ac + 1 > bc:
tree[j][b] = (av, ac + 1)
else:
tree[j][b] = (av, ac + 1)
print(idx[x], idx[y], m) | 1639661700 | [
"number theory",
"graphs",
"trees",
"math",
"games"
] | [
1,
0,
1,
1,
1,
0,
0,
1
] |
|
1 second | ["? 2 2\n? 5 5\n? 4 7\n? 1 5\n! 2 3 4 5"] | 7d72a14dd0429e5f8ad9b75c1e35f1e7 | null | This is an interactive problem!As part of your contribution in the Great Bubble War, you have been tasked with finding the newly built enemy fortress. The world you live in is a giant $$$10^9 \times 10^9$$$ grid, with squares having both coordinates between $$$1$$$ and $$$10^9$$$. You know that the enemy base has the shape of a rectangle, with the sides parallel to the sides of the grid. The people of your world are extremely scared of being at the edge of the world, so you know that the base doesn't contain any of the squares on the edges of the grid (the $$$x$$$ or $$$y$$$ coordinate being $$$1$$$ or $$$10^9$$$). To help you locate the base, you have been given a device that you can place in any square of the grid, and it will tell you the manhattan distance to the closest square of the base. The manhattan distance from square $$$(a, b)$$$ to square $$$(p, q)$$$ is calculated as $$$|aβp|+|bβq|$$$. If you try to place the device inside the enemy base, you will be captured by the enemy. Because of this, you need to make sure to never place the device inside the enemy base. Unfortunately, the device is powered by a battery and you can't recharge it. This means that you can use the device at most $$$40$$$ times. | null | The input contains the answers to your queries. | standard output | standard input | Python 3 | Python | 2,100 | train_085.jsonl | c5b9c0e78622270eeec9dd7222e37ae3 | 256 megabytes | ["1\n1\n2\n1"] | PASSED | from sys import stdout
from math import ceil, floor
endv = 1000000000
print("? 1 1")
stdout.flush()
dstart = int(input())
print(("? 1000000000 1000000000"))
stdout.flush()
dend = int(input())
start, end = 1, min(endv, dstart)
while start < end:
midx = int(ceil((start + end) / 2))
print(f"? {midx} 1")
stdout.flush()
test = int(input())
stdout.flush()
if test > dstart + 1 - midx:
end = midx - 1
else:
start = midx
indstart = (start, dstart + 2 - start)
start = max(endv - dend, indstart[0])
if endv - dend > indstart[1]:
end = endv
else:
end = endv - (dend - (endv - indstart[1]))
while start < end:
midx = int(floor((start+end)/2))
print(f"? {midx} {endv}")
stdout.flush()
test = int(input())
stdout.flush()
if test > dend + midx - endv:
start = midx + 1
else:
end = midx
indend = (end, endv - (dend - (endv - end)))
print(f"! {indstart[0]} {indstart[1]} {indend[0]} {indend[1]}")
| 1633770300 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["3 0 3", "0 0 0", "4 14 4 16 10"] | d0cb479bbe2fca382a439148af77e082 | NoteIn the first example, there will be only one team consisting of persons $$$1$$$ and $$$3$$$. The optimal strategy for them is to assign the first task to the $$$3$$$-rd person and the second task to the $$$1$$$-st person, this will lead to score equal to $$$1 + 2 = 3$$$.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case... | Zibi is a competitive programming coach. There are $$$n$$$ competitors who want to be prepared well. The training contests are quite unusualΒ β there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the $$$i$$$-th competitor will always have score $$$x_i$$$ when he codes the first task and $$$y_i$$$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are $$$m$$$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in? | Output $$$n$$$ integersΒ β the sum of scores for all participants in the same order as they appear in the input. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 300\,000$$$, $$$0 \le m \le 300\,000$$$)Β β the number of participants and the number of pairs of people who will not write a contest together. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^9 \le x_i, y_i \le 10^9$$$)Β β the scores which will the $$$i$$$-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both $$$x_i$$$ and $$$y_i$$$ same. Each of the next $$$m$$$ lines contain two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$)Β β indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once. | standard output | standard input | Python 3 | Python | 1,900 | train_013.jsonl | 0539420ef6df4b7505adfd2d1a4e6c60 | 256 megabytes | ["3 2\n1 2\n2 3\n1 3\n1 2\n2 3", "3 3\n1 2\n2 3\n1 3\n1 2\n2 3\n1 3", "5 3\n-1 3\n2 4\n1 1\n3 5\n2 2\n1 4\n2 3\n3 5"] | PASSED | from sys import stdin
from operator import add
from itertools import repeat
def main():
n, m = map(int, stdin.readline().split())
inp = list(map(int, stdin.read().split(), repeat(10, 2*n+2*m)))
xys = inp[:2*n]
exc = list(map(add, inp[2*n:], repeat(-1)))
a = list(range(n))
a.sort(key=lambda i: xys[2*i] - xys[2*i+1])
xs, ys = 0, sum(xys[1::2])
res = [0]*n
for i, idx in enumerate(a):
x, y = xys[2*idx], xys[2*idx+1]
ys -= y
res[idx] = i*y + (n-1-i)*x + xs + ys
xs += x
for i in range(m):
u, v = exc[2*i], exc[2*i+1]
dif = min(xys[2*u] + xys[2*v+1], xys[2*v] + xys[2*u+1])
res[u] -= dif
res[v] -= dif
print(' '.join(map(str,res)))
main() | 1540740900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4", "10", "16"] | da2fb0ea61808905a133021223f6148d | NoteExample $$$1$$$: you can subtract $$$a_1$$$ from $$$b_1$$$, and add $$$a_3$$$, $$$a_4$$$, and $$$a_5$$$ to $$$b_3$$$, $$$b_4$$$, and $$$b_5$$$ respectively. The final array will be [$$$-1$$$, $$$0$$$, $$$3$$$, $$$4$$$, $$$5$$$] after $$$4$$$ moves.Example $$$2$$$: you can reach [$$$-3$$$, $$$-2$$$, $$$-1$$$, $$$0$$$, $$$1$$$, $$$2$$$, $$$3$$$] in $$$10$$$ moves. | You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \leq i \leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \leq i \leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)? | Print a single integer, the minimum number of moves to make $$$b$$$ increasing. | The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) β the elements of the array $$$a$$$. | standard output | standard input | PyPy 3-64 | Python | 1,300 | train_084.jsonl | 756614fc06ef48dd47bf82310eec8489 | 256 megabytes | ["5\n1 2 3 4 5", "7\n1 2 1 2 1 2 1", "8\n1 8 2 7 3 6 4 5"] | PASSED | n = int(input())
a = list(map(int, input().split()))
Min = 1e18
for l in range(n - 1):
m = a[l]
answer = 1
for i in range(l-1, -1, -1):
answer += (m + a[i]) // a[i]
m = a[i] * ((m + a[i]) // a[i])
# if l + 1 < n:
m = 0
for i in range(l + 2, n):
answer += (m + a[i]) // a[i]
m = a[i] * ((m + a[i]) // a[i])
Min = min(answer, Min)
print(Min) | 1650378900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6", "8", "28"] | 869f94e76703cde502bd908b476d970e | NoteConsider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are , , initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1},β{2},β{3},β{1,β2},β{1,β3},β{2,β3}. Note that the empty set is invalid because if no roads are flipped, then towns 1,β2,β3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip.The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing. | ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (aiββ βi). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after.ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1,βA2,β...,βAk (kβ>β1) such that for every 1ββ€βiβ<βk there is a road from town Ai to town Aiβ+β1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns.Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing.Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities. | Print a single integerΒ β the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109β+β7. | The first line of the input contains single integer n (2ββ€βnββ€β2Β·105)Β β the number of towns in Udayland. The next line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€βn,βaiββ βi), ai denotes a road going from town i to town ai. | standard output | standard input | Python 3 | Python | 1,900 | train_068.jsonl | d1c862939fc505a46c9470f6884facc9 | 256 megabytes | ["3\n2 3 1", "4\n2 1 1 1", "5\n2 4 2 5 3"] | PASSED | n = int(input())
l = list(map(int, input().split()))
l.insert(0,0)
mark = {}
loop, pos, res , mod= 0, 1, 1, int(1e9+7)
for i in range(1, n+1):
if not i in mark:
start, j = pos, i
while not j in mark:
mark[j] = pos
pos+= 1
j = l[j]
if mark[j]>=start:
size = pos-mark[j]
loop+= size
res*= pow(2, size)-2+mod
res%= mod
res = (res * pow(2, n-loop,mod))%mod
print(res)
| 1472472300 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES", "NO", "NO"] | 6214a85d2be0a908dcbfe089327cf51a | null | Volodya and Vlad play the following game. There are k pies at the cells of nββΓββm board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy. | Output only one word: "YES" β if Volodya wins, "NO" β otherwise. | First line contains 3 integers, separated by space: 1ββ€βn,βmββ€β100 β dimensions of the board and 0ββ€βkββ€β100 β the number of pies. Each of the next k lines contains 2 integers, separated by space: 1ββ€βxββ€βn, 1ββ€βyββ€βm β coordinates of the corresponding pie. There could be more than one pie at a cell. | standard output | standard input | Python 3 | Python | 1,900 | train_019.jsonl | 64026f537185d01954e0f04eb41ccf29 | 256 megabytes | ["2 2 1\n1 2", "3 4 0", "100 50 2\n50 25\n50 25"] | PASSED | n, m, k = map(int, input().split())
win = False
for i in range(k):
x, y = map(int, input().split())
if abs(x - 1) <= 4 or abs(y - 1) <= 4 or \
abs(n - x) <= 4 or abs(m - y) <= 4:
win = True
print('YES' if win else 'NO')
| 1294992000 | [
"games"
] | [
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["3\n1 3 2", "5\n1 3 2 5 4", "3\n1 2 3 1 2"] | 2aaa31d52d69ff3703f93177b25671a3 | NoteIn the first sample the park consists of three squares: 1βββ3βββ2. Thus, the balloon colors have to be distinct. Illustration for the first sample. In the second example there are following triples of consequently connected squares: 1βββ3βββ2 1βββ3βββ4 1βββ3βββ5 2βββ3βββ4 2βββ3βββ5 4βββ3βββ5 We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. Illustration for the second sample. In the third example there are following triples: 1βββ2βββ3 2βββ3βββ4 3βββ4βββ5 We can see that one or two colors is not enough, but there is an answer that uses three colors only. Illustration for the third sample. | Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.The park consists of n squares connected with (nβ-β1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.Andryusha wants to use as little different colors as possible. Help him to choose the colors! | In the first line print single integer kΒ β the minimum number of colors Andryusha has to use. In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k. | The first line contains single integer n (3ββ€βnββ€β2Β·105)Β β the number of squares in the park. Each of the next (nβ-β1) lines contains two integers x and y (1ββ€βx,βyββ€βn)Β β the indices of two squares directly connected by a path. It is guaranteed that any square is reachable from any other using the paths. | standard output | standard input | Python 3 | Python | 1,600 | train_010.jsonl | 8dceb524d18acfc8dea92ba97b9d3674 | 256 megabytes | ["3\n2 3\n1 3", "5\n2 3\n5 3\n4 3\n1 3", "5\n2 1\n3 2\n4 3\n5 4"] | PASSED | import sys
sys.setrecursionlimit(200000)
n = int(input())
arr = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
arr[a - 1].append(b - 1)
arr[b - 1].append(a - 1)
s = max([len(p) for p in arr]) + 1
print(s)
colored = [0] * n
def dfs(v, c, d):
colored[v] = p = c
for u in arr[v]:
if not colored[u]:
c = c + 1 if c < s else 1
if c == d:
c = c + 1 if c < s else 1
dfs(u, c, p)
if s > 3:
dfs(0, 1, 0)
else:
i = 0
c = 1
while len(arr[i]) != 1:
i += 1
for j in range(n):
colored[i] = c
c = c + 1 if c < s else 1
if j < n - 1:
i = arr[i][0] if not colored[arr[i][0]] else arr[i][1]
print(" ".join(map(str, colored))) | 1488705300 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["5\n6\n3\n4\n4\n-1"] | 81abcdc77ffcf8858b4e81f3db5ee7fb | null | You wanted to write a text $$$t$$$ consisting of $$$m$$$ lowercase Latin letters. But instead, you have written a text $$$s$$$ consisting of $$$n$$$ lowercase Latin letters, and now you want to fix it by obtaining the text $$$t$$$ from the text $$$s$$$.Initially, the cursor of your text editor is at the end of the text $$$s$$$ (after its last character). In one move, you can do one of the following actions: press the "left" button, so the cursor is moved to the left by one position (or does nothing if it is pointing at the beginning of the text, i.βe. before its first character); press the "right" button, so the cursor is moved to the right by one position (or does nothing if it is pointing at the end of the text, i.βe. after its last character); press the "home" button, so the cursor is moved to the beginning of the text (before the first character of the text); press the "end" button, so the cursor is moved to the end of the text (after the last character of the text); press the "backspace" button, so the character before the cursor is removed from the text (if there is no such character, nothing happens). Your task is to calculate the minimum number of moves required to obtain the text $$$t$$$ from the text $$$s$$$ using the given set of actions, or determine it is impossible to obtain the text $$$t$$$ from the text $$$s$$$.You have to answer $$$T$$$ independent test cases. | For each test case, print one integer β the minimum number of moves required to obtain the text $$$t$$$ from the text $$$s$$$ using the given set of actions, or -1 if it is impossible to obtain the text $$$t$$$ from the text $$$s$$$ in the given test case. | The first line of the input contains one integer $$$T$$$ ($$$1 \le T \le 5000$$$) β the number of test cases. Then $$$T$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 5000$$$) β the length of $$$s$$$ and the length of $$$t$$$, respectively. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the test case contains the string $$$t$$$ consisting of $$$m$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$). | standard output | standard input | PyPy 3-64 | Python | 2,500 | train_098.jsonl | 799d33c9b735098e3233747f89e79b81 | 256 megabytes | ["6\n\n9 4\n\naaaaaaaaa\n\naaaa\n\n7 3\n\nabacaba\n\naaa\n\n5 4\n\naabcd\n\nabcd\n\n4 2\n\nabba\n\nbb\n\n6 4\n\nbaraka\n\nbaka\n\n8 7\n\nquestion\n\nproblem"] | PASSED | #!/usr/bin/env PyPy3
from collections import Counter, defaultdict, deque
import itertools
import re
import math
from functools import reduce
import operator
import bisect
from heapq import *
import functools
mod=998244353
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
INF = 1 << 31
T = int(input())
for _ in range(T):
n,m = map(int,input().split())
s = input().rstrip()
t = input().rstrip()
dp = [[INF] * (m+1) for _ in range(3)]
dp[0][0] = 1
dp[1][0] = 0
for i in range(n):
ndp = [[INF] * (m+1) for _ in range(3)]
for k in range(2):
for j in range(m+1):
dp[k+1][j] = min(dp[k+1][j],dp[k][j])
for j in range(m+1):
ndp[0][j] = min(ndp[0][j],dp[0][j] + 2)
ndp[2][j] = min(ndp[2][j],dp[2][j] + 1)
if j < m:
if s[i] == t[j]:
ndp[0][j+1] = min(ndp[0][j+1],dp[0][j]+1)
ndp[1][j+1] = min(ndp[1][j+1],dp[1][j])
ndp[2][j+1] = min(ndp[2][j+1],dp[2][j]+1)
dp = ndp
ans = min(dp[0][-1],dp[1][-1],dp[2][-1])
if ans == INF:
print(-1)
else:
print(ans)
| 1657290900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds | ["314"] | 202396838c98654c4e40179f21a225a0 | null | Let's denote the size of the maximum matching in a graph $$$G$$$ as $$$\mathit{MM}(G)$$$.You are given a bipartite graph. The vertices of the first part are numbered from $$$1$$$ to $$$n$$$, the vertices of the second part are numbered from $$$n+1$$$ to $$$2n$$$. Each vertex's degree is $$$2$$$.For a tuple of four integers $$$(l, r, L, R)$$$, where $$$1 \le l \le r \le n$$$ and $$$n+1 \le L \le R \le 2n$$$, let's define $$$G'(l, r, L, R)$$$ as the graph which consists of all vertices of the given graph that are included in the segment $$$[l, r]$$$ or in the segment $$$[L, R]$$$, and all edges of the given graph such that each of their endpoints belongs to one of these segments. In other words, to obtain $$$G'(l, r, L, R)$$$ from the original graph, you have to remove all vertices $$$i$$$ such that $$$i \notin [l, r]$$$ and $$$i \notin [L, R]$$$, and all edges incident to these vertices.Calculate the sum of $$$\mathit{MM}(G(l, r, L, R))$$$ over all tuples of integers $$$(l, r, L, R)$$$ having $$$1 \le l \le r \le n$$$ and $$$n+1 \le L \le R \le 2n$$$. | Print one integerΒ β the sum of $$$\mathit{MM}(G(l, r, L, R))$$$ over all tuples of integers $$$(l, r, L, R)$$$ having $$$1 \le l \le r \le n$$$ and $$$n+1 \le L \le R \le 2n$$$. | The first line contains one integer $$$n$$$ ($$$2 \le n \le 1500$$$)Β β the number of vertices in each part. Then $$$2n$$$ lines follow, each denoting an edge of the graph. The $$$i$$$-th line contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$n + 1 \le y_i \le 2n$$$)Β β the endpoints of the $$$i$$$-th edge. There are no multiple edges in the given graph, and each vertex has exactly two incident edges. | standard output | standard input | PyPy 3-64 | Python | 2,600 | train_104.jsonl | 41bd3f73363cc3d11f0b33d92c75e8c2 | 512 megabytes | ["5\n4 6\n4 9\n2 6\n3 9\n1 8\n5 10\n2 7\n3 7\n1 10\n5 8"] | PASSED |
class unionfind:
def __init__(self,uni_num):
self.uni_num=uni_num
self.union_root = [-1 for i in range(self.uni_num + 1)]
self.union_depth = [0] * (self.uni_num + 1)
self.e_num=[0]*(self.uni_num+1)
def find(self,x): # θ¦ͺγ―θͺ°οΌ
if self.union_root[x] < 0:
return x
else:
self.union_root[x] = self.find(self.union_root[x])
return self.union_root[x]
def unite(self,x, y):
x = self.find(x)
y = self.find(y)
if x == y:
self.e_num[x]+=1
return
if self.union_depth[x] < self.union_depth[y]:
x, y = y, x
if self.union_depth[x] == self.union_depth[y]:
self.union_depth[x] += 1
self.union_root[x] += self.union_root[y]
self.union_root[y] = x
self.e_num[x]+=self.e_num[y]+1
def size(self,x):
return -self.union_root[self.find(x)]
def same(self,x,y):
return self.find(x)==self.find(y)
def edge(self,x):
return self.e_num[self.find(x)]
n=int(input())
root=[[] for i in range(2*n+3)]
uf=unionfind(2*n+10)
for i in range(2*n):
u,v=map(int,input().split())
root[u].append(v)
root[v].append(u)
uf.unite(u,v)
seen=[0]*(2*n+4)
def cnt(mal,mir,maL,miR,ng1,ng2):
if mal>mir or maL>miR:return 0
res1=mal*(n+1-mir)
if 1<=ng1<=n:
a,b=min(mal,ng1),max(mir,ng1)
res1-=a*(n+1-b)
if 1<=ng2<=n:
a, b = min(mal, ng2), max(mir, ng2)
res1 -= a * (n + 1 - b)
if (1<=ng1<=n and 1<=ng2<=n):
a,b=min(mal,ng1,ng2),max(mir,ng1,ng2)
res1+=a*(n+1-b)
maL-=n
miR-=n
ng1-=n
ng2-=n
res2=maL*(n+1-miR)
if 1<=ng1<=n:
a,b=min(maL,ng1),max(miR,ng1)
res2-=a*(n+1-b)
if 1<=ng2<=n:
a, b = min(maL, ng2), max(miR, ng2)
res2 -= a * (n + 1 - b)
if (1<=ng1<=n and 1<=ng2<=n):
a,b=min(maL,ng1,ng2),max(miR,ng1,ng2)
res2+=a*(n+1-b)
return res1*res2
ans=0
for x in range(1,2*n+1):
if x!=uf.find(x):continue
path=[x]
now=x
while 1:
seen[now]=1
flag=0
for y in root[now]:
if seen[y]:continue
now=y
path.append(y)
flag=1
break
if not flag:break
m=len(path)
for indl in range(m):
maxl = 10 ** 10
minr = -10 ** 10
maxL = 10 ** 10
minR = -10 ** 10
indr=(indl+1)%m
num=0
while 1:
if indr==indl:break
ans+=(num//2)*cnt(maxl,minr,maxL,minR,path[indl],path[indr])
nod=path[indr]
if nod<=n:
maxl=min(maxl,nod)
minr=max(minr,nod)
else:
maxL=min(maxL,nod)
minR=max(minR,nod)
num+=1
indr+=1
indr%=m
for ind in range(m):
maxl = 10 ** 10
minr = -10 ** 10
maxL = 10 ** 10
minR = -10 ** 10
i=(ind+1)%m
while 1:
if i==ind:break
nod = path[i]
if nod <= n:
maxl = min(maxl, nod)
minr = max(minr, nod)
else:
maxL = min(maxL, nod)
minR = max(minR, nod)
i=(i+1)%m
num=m-1
ans+=(num//2)*cnt(maxl,minr,maxL,minR,path[ind],path[ind])
maxl = 10 ** 10
minr = -10 ** 10
maxL = 10 ** 10
minR = -10 ** 10
for i in range(m):
nod = path[i]
if nod <= n:
maxl = min(maxl, nod)
minr = max(minr, nod)
else:
maxL = min(maxL, nod)
minR = max(minR, nod)
num=m
ans += (num // 2) * cnt(maxl, minr, maxL, minR,10**9,10**9)
print(ans)
| 1646922900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["14", "14", "18"] | d8349ff9b695612473b2ba00d08e505b | NoteIn the first example, the farmer can reduce the power of the $$$4$$$-th machine by $$$2$$$ times, and increase the power of the $$$1$$$-st machine by $$$2$$$ times, then the powers will be: $$$[2, 2, 3, 2, 5]$$$.In the second example, the farmer can reduce the power of the $$$3$$$-rd machine by $$$2$$$ times, and increase the power of the $$$2$$$-nd machine by $$$2$$$ times. At the same time, the farmer can leave is be as it is and the total power won't change.In the third example, it is optimal to leave it be as it is. | One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $$$n$$$ machines, and the power of the $$$i$$$-th machine is $$$a_i$$$. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $$$x$$$, then choose one machine and reduce the power of its machine by $$$x$$$ times, and at the same time increase the power of one another machine by $$$x$$$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $$$i$$$ and $$$j$$$, and one integer $$$x$$$ such that $$$x$$$ is a divisor of $$$a_i$$$, and change powers as following: $$$a_i = \frac{a_i}{x}$$$, $$$a_j = a_j \cdot x$$$Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him! | Print one integerΒ β minimum total power. | The first line contains one integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$)Β β the number of machines. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$)Β β the powers of the machines. | standard output | standard input | PyPy 2 | Python | 1,300 | train_034.jsonl | df477ca32bad7a0409760aaaa8e838e5 | 256 megabytes | ["5\n1 2 3 4 5", "4\n4 2 4 4", "5\n2 4 2 3 7"] | PASSED | n=int(raw_input())
a=list(map(int,raw_input().split()))
a = sorted(a)
ans=99999999999999999999999999999999999999999999999999999999999999999999
i=n-1
total=sum(a)
if n > 1:
while i > 0:
for j in xrange(1,101):
if a[i]%j==0:
minn=a[0]*j
maxx=a[i]/j
ans=min(ans,total-a[0]-a[i]+minn+maxx)
i -= 1
print ans
else:
print sum(a) | 1550334900 | [
"number theory"
] | [
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second | ["12", "1"] | 482d128baf37eeeb28b874934aded534 | NoteIn the first example, the leaf nodes are $$$2,3,4,5$$$. The ways to partition the leaves are in the following image In the second example, the only leaf is node $$$10$$$ so there is only one partition. Note that node $$$1$$$ is not a leaf. | You are given a rooted tree with $$$n$$$ nodes, labeled from $$$1$$$ to $$$n$$$. The tree is rooted at node $$$1$$$. The parent of the $$$i$$$-th node is $$$p_i$$$. A leaf is node with no children. For a given set of leaves $$$L$$$, let $$$f(L)$$$ denote the smallest connected subgraph that contains all leaves $$$L$$$.You would like to partition the leaves such that for any two different sets $$$x, y$$$ of the partition, $$$f(x)$$$ and $$$f(y)$$$ are disjoint. Count the number of ways to partition the leaves, modulo $$$998244353$$$. Two ways are different if there are two leaves such that they are in the same set in one way but in different sets in the other. | Print a single integer, the number of ways to partition the leaves, modulo $$$998244353$$$. | The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$)Β β the number of nodes in the tree. The next line contains $$$n-1$$$ integers $$$p_2, p_3, \ldots, p_n$$$ ($$$1 \leq p_i < i$$$). | standard output | standard input | Python 2 | Python | 2,500 | train_022.jsonl | fd9e70b728166d44f0b8cc4c48670ee4 | 256 megabytes | ["5\n1 1 1 1", "10\n1 2 3 4 5 6 7 8 9"] | PASSED | from sys import stdin
from itertools import repeat
def main():
n = int(stdin.readline())
p = [-1, -1] + map(int, stdin.readline().split(), repeat(10, n - 1))
ch = [[] for _ in xrange(n + 1)]
for i in xrange(2, n + 1):
ch[p[i]].append(i)
st = []
pu = st.append
po = st.pop
pu(1)
col = [None] * (n + 1)
dp = [None for _ in range(n + 1)]
mod = 998244353
while st:
x = po()
if col[x] is None:
pu(x)
col[x] = 1
for y in ch[x]:
pu(y)
else:
if ch[x]:
dp[x] = (1, 0, 0)
else:
dp[x] = (0, 0, 1)
for y in ch[x]:
dp[x] = (dp[x][0] * (dp[y][0] + dp[y][2]) % mod, (dp[x][0] * (dp[y][1] + dp[y][2]) + dp[x][1] * (dp[y][0] + dp[y][2])) % mod, ((dp[x][1] + dp[x][2]) * (dp[y][1] + dp[y][2]) + dp[x][2] * (dp[y][0] + dp[y][2])) % mod)
print (dp[1][0] + dp[1][2]) % mod
main()
| 1555783500 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["1\n2 1\n1 2 3"] | d253d8efc344b0848a19876ff52c09a8 | NoteIn the first test case, Eikooc has only one choice. Sushi will have no moves to play after Eikooc chooses this node and Eikooc will win.In the second test case, $$$1 \oplus 2 = 3 \nleq min(1, 2)$$$. Hence, after Eikooc picks either of the nodes, Sushi will have no moves to play and Eikooc will win. Both $$$\{1, 2\}$$$ and $$$\{2, 1\}$$$ are optimal relabelings. | Eikooc and Sushi play a game.The game is played on a tree having $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$. Recall that a tree having $$$n$$$ nodes is an undirected, connected graph with $$$n-1$$$ edges.They take turns alternately moving a token on the tree. Eikooc makes the first move, placing the token on any node of her choice. Sushi makes the next move, followed by Eikooc, followed by Sushi, and so on. In each turn after the first, a player must move the token to a node $$$u$$$ such that $$$u$$$ is adjacent to the node $$$v$$$ the token is currently on $$$u$$$ has not been visited before $$$u \oplus v \leq min(u, v)$$$ Here $$$x \oplus y$$$ denotes the bitwise XOR operation on integers $$$x$$$ and $$$y$$$.Both the players play optimally. The player who is unable to make a move loses.The following are examples which demonstrate the rules of the game. Suppose Eikooc starts the game by placing the token at node $$$4$$$. Sushi then moves the token to node $$$6$$$, which is unvisited and adjacent to $$$4$$$. It also holds that $$$6 \oplus 4 = 2 \leq min(6, 4)$$$. In the next turn, Eikooc moves the token to node $$$5$$$, which is unvisited and adjacent to $$$6$$$. It holds that $$$5 \oplus 6 = 3 \leq min(5, 6)$$$. Sushi has no more moves to play, so she loses. Suppose Eikooc starts the game by placing the token at node $$$3$$$. Sushi moves the token to node $$$2$$$, which is unvisited and adjacent to $$$3$$$. It also holds that $$$3 \oplus 2 = 1 \leq min(3, 2)$$$. Eikooc cannot move the token to node $$$6$$$ since $$$6 \oplus 2 = 4 \nleq min(6, 2)$$$. Since Eikooc has no moves to play, she loses. Before the game begins, Eikooc decides to sneakily relabel the nodes of the tree in her favour. Formally, a relabeling is a permutation $$$p$$$ of length $$$n$$$ (sequence of $$$n$$$ integers wherein each integer from $$$1$$$ to $$$n$$$ occurs exactly once) where $$$p_i$$$ denotes the new numbering of node $$$i$$$.She wants to maximize the number of nodes she can choose in the first turn which will guarantee her a win. Help Eikooc find any relabeling which will help her do so. | For each test case print any suitable relabeling Β β a permutation of length $$$n$$$ which maximizes the number of nodes that can be chosen in the first turn that guarantee a win for Eikooc. If there are multiple such relabelings, you may print any of them. | The first line contains a single integer $$$t~(1 \le t \le 10^5)$$$ Β β the number of test cases. The description of each test case is as follows. The first line of each test case contains an integer $$$n~(1 \le n \le 2 \cdot 10^5)$$$ Β β the number of nodes in the tree. The next $$$n-1$$$ lines contain two integers $$$u$$$ and $$$v$$$ $$$(1 \le u, v \le n; u \neq v)$$$ Β β denoting an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 2,100 | train_097.jsonl | fced03019ab1e250bc154008823b972f | 256 megabytes | ["3\n1\n2\n1 2\n3\n1 2\n1 3"] | PASSED | import sys
from collections import deque
ipt=sys.stdin.readline
T=int(ipt())
for _ in range(T):
n=int(input())
lg=0
while 2**lg<=n:
lg+=1
lg-=1
t=[[] for i in range(n+1)]
for i in range(n-1):
x, y=map(int, ipt().split())
t[x].append(y)
t[y].append(x)
if n==1:
print(1)
continue
a=[0 for i in range(n+1)]
v=[0 for i in range(n+1)]
deq=deque()
deq.append((1, 0))
v[1]=1
while deq:
x, y=deq.popleft()
for i in t[x]:
if not v[i]:
v[i]=1
if y==0:
a[i]=1
deq.append((i, 1))
else:
a[i]=0
deq.append((i, 0))
s=sum(a)
idx=1
if s>=1<<lg:
s=n-s
for i in range(1, n+1):
a[i]^=1
for i in range(lg):
if s&(1<<i):
for j in range(1<<i, 1<<(i+1)):
while a[idx]==0:
idx+=1
a[idx]=j
idx+=1
idx=1
for i in range(lg):
if not s&(1<<i):
for j in range(1<<i, 1<<(i+1)):
while a[idx]:
idx+=1
a[idx]=j
idx+=1
for i in range(1<<lg, n+1):
while a[idx]:
idx+=1
a[idx]=i
idx+=1
print(*a[1:]) | 1636727700 | [
"games",
"trees"
] | [
1,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second | ["1\n2\n4\n4\n8\n8\n15\n6"] | d55660b8091bca2211fa1ad56402aebd | NoteThe first test case contains exactly one subsegment and $$$mex({0}) = 1 > med({0}) = 0$$$ on it.In the third test case, on the following subsegments: $$$[1, 0]$$$, $$$[0]$$$, $$$[1, 0, 2]$$$ and $$$[0, 2]$$$, $$$mex$$$ is greater than $$$med$$$.In the fourth test case, on the following subsegments: $$$[0, 2]$$$, $$$[0]$$$, $$$[0, 2, 1]$$$ and $$$[0, 2, 1, 3]$$$, $$$mex$$$ greater than $$$med$$$. | You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ of numbers $$$0, \ldots, n - 1$$$. Count the number of subsegments $$$1 \leq l \leq r \leq n$$$ of this permutation such that $$$mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r)$$$.$$$mex$$$ of $$$S$$$ is the smallest non-negative integer that does not occur in $$$S$$$. For example: $$$mex({0, 1, 2, 3}) = 4$$$ $$$mex({0, 4, 1, 3}) = 2$$$ $$$mex({5, 4, 0, 1, 2}) = 3$$$$$$med$$$ of the set $$$S$$$ is the median of the set, i.e. the element that, after sorting the elements in non-decreasing order, will be at position number $$$\left \lfloor{ \frac{|S| + 1}{2} } \right \rfloor$$$ (array elements are numbered starting from $$$1$$$ and here $$$\left \lfloor{v} \right \rfloor$$$ denotes rounding $$$v$$$ down.). For example: $$$med({0, 1, 2, 3}) = 1$$$ $$$med({0, 4, 1, 3}) = 1$$$ $$$med({5, 4, 0, 1, 2}) = 2$$$A sequence of $$$n$$$ numbers is called a permutation if it contains all the numbers from $$$0$$$ to $$$n - 1$$$ exactly once. | For each test case print the answer in a single line: the number of subsegments $$$1 \leq l \leq r \leq n$$$ of this permutation such that $$$mex(p_l, p_{l+1}, \ldots, p_r) > med(p_l, p_{l+1}, \ldots, p_r)$$$. | The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$), the number of test cases. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$), the length of the permutation $$$p$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$0 \leq p_i \leq n - 1$$$), elements of permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 2,000 | train_094.jsonl | 670eb5cd4649deb067d7b6043f13bc46 | 256 megabytes | ["8\n\n1\n\n0\n\n2\n\n1 0\n\n3\n\n1 0 2\n\n4\n\n0 2 1 3\n\n5\n\n3 1 0 2 4\n\n6\n\n2 0 4 1 3 5\n\n8\n\n3 7 2 6 0 1 5 4\n\n4\n\n2 0 1 3"] | PASSED | m=int(input())
for _ in range(m):
n=int(input())
s=dict(zip(map(int,input().split()),range(n)))
mi=s[0]
ma=mi
lists=0
n0=int(n/2)+n%2
for i in range(n0):
si=s[i]
mi=min(mi,si)
ma=max(ma,si)
b1=2*i+1
b2=b1+1
a1=min(b1-ma+mi,mi+1,n-ma,n-b1+1)
a2=min(b2-ma+mi,mi+1,n-ma,n-b2+1)
if b2<=n and a2>0:
lists=lists+a2
if a1>0:
lists=lists+a1
print(lists)
| 1665930900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["4\n2\n31\n7"] | 5b40c60ba54c7bb9a649b15588ef6510 | NoteIn the first example, the valid subsequences are $$$[0]$$$, $$$[1]$$$, $$$[0,1]$$$ and $$$[0,2]$$$.In the second example, the valid subsequences are $$$[0]$$$ and $$$[1]$$$.In the third example, any non-empty subsequence is valid. | Let's call a sequence of integers $$$x_1, x_2, \dots, x_k$$$ MEX-correct if for all $$$i$$$ ($$$1 \le i \le k$$$) $$$|x_i - \operatorname{MEX}(x_1, x_2, \dots, x_i)| \le 1$$$ holds. Where $$$\operatorname{MEX}(x_1, \dots, x_k)$$$ is the minimum non-negative integer that doesn't belong to the set $$$x_1, \dots, x_k$$$. For example, $$$\operatorname{MEX}(1, 0, 1, 3) = 2$$$ and $$$\operatorname{MEX}(2, 1, 5) = 0$$$.You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo $$$998244353$$$. Note: a subsequence of an array $$$a$$$ is a sequence $$$[a_{i_1}, a_{i_2}, \dots, a_{i_m}]$$$ meeting the constraints $$$1 \le i_1 < i_2 < \dots < i_m \le n$$$. If two different ways to choose the sequence of indices $$$[i_1, i_2, \dots, i_m]$$$ yield the same subsequence, the resulting subsequence should be counted twice (i.βe. two subsequences are different if their sequences of indices $$$[i_1, i_2, \dots, i_m]$$$ are not the same). | For each test case, print a single integerΒ β the number of non-empty MEX-correct subsequences of a given array, taken modulo $$$998244353$$$. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)Β β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$5 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,900 | train_090.jsonl | 0d4b2c83f1d4316b89955f4a20c758ca | 256 megabytes | ["4\n3\n0 2 1\n2\n1 0\n5\n0 0 0 0 0\n4\n0 1 2 3"] | PASSED | import sys
import os
from io import BytesIO, IOBase
# region fastio
# BUFSIZE = 8192
#
# class FastIO(IOBase):
# newlines = 0
#
# def __init__(self, file):
# self._fd = file.fileno()
# self.buffer = BytesIO()
# self.writable = "x" in file.mode or "r" not in file.mode
# self.write = self.buffer.write if self.writable else None
#
# def read(self):
# while True:
# b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
# if not b:
# break
# ptr = self.buffer.tell()
# self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
# self.newlines = 0
# return self.buffer.read()
#
# def readline(self):
# while self.newlines == 0:
# b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
# self.newlines = b.count(b"\n") + (not b)
# ptr = self.buffer.tell()
# self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
# self.newlines -= 1
# return self.buffer.readline()
#
# def flush(self):
# if self.writable:
# os.write(self._fd, self.buffer.getvalue())
# self.buffer.truncate(0), self.buffer.seek(0)
#
# class IOWrapper(IOBase):
# def __init__(self, file):
# self.buffer = FastIO(file)
# self.flush = self.buffer.flush
# self.writable = self.buffer.writable
# self.write = lambda s: self.buffer.write(s.encode("ascii"))
# self.read = lambda: self.buffer.read().decode("ascii")
# self.readline = lambda: self.buffer.readline().decode("ascii")
#
# if sys.version_info[0] < 3:
# sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
# else:
# sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
f = sys.stdin
if os.environ.get('USER') == "loic":
f = open("data.in")
line = lambda: f.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
def solve():
ones = 0
sz = N + 2
dp = [0] * sz
pref = [0] * sz
for val in A:
if val == 1:
ones = (ones * 2 + 1) % M
mex = val
if mex >= 1:
dp[mex] = (dp[mex] * 2) % M
dp[mex] = (dp[mex] + pref[mex-1]) % M
pref[mex] = (pref[mex] * 2) % M
pref[mex] = (pref[mex] + pref[mex-1]) % M
else:
dp[0] = (dp[0] * 2 + 1) % M
pref[0] = (pref[0] * 2 + 1) % M
if val >= 2:
mex = val - 2
dp[mex] = (dp[mex] * 2) % M
res = ones
for i in range(sz):
res = (res + dp[i]) % M
res %= M
return str(res)
Z = 5 * 10**5
M = 998244353
# POW = power_two(Z)
for test in range(1,ui()+1):
N = ui()
A = li()
print(solve())
f.close() | 1638369300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2\n1\n0\n3\n17\n1111"] | e8f12eb9144ac2ea1c18fbfb15a84a0e | NoteIn query one the suitable numbers are 1 and 4. | You're given Q queries of the form (L,βR). For each query you have to find the number of such x that Lββ€βxββ€βR and there exist integer numbers aβ>β0, pβ>β1 such that xβ=βap. | Output Q lines β the answers to the queries. | The first line contains the number of queries Q (1ββ€βQββ€β105). The next Q lines contains two integers L, R each (1ββ€βLββ€βRββ€β1018). | standard output | standard input | PyPy 2 | Python | 2,100 | train_005.jsonl | ebd2486e36fcde356f15297619cc17b8 | 256 megabytes | ["6\n1 4\n9 9\n5 7\n12 29\n137 591\n1 1000000"] | PASSED | import math
from sys import stdin, stdout
q = int(stdin.readline())
D = set()
#v.append(1)
mv = int(1e18)
for i in range(2,1000001):
j = i*i*i
while(j<=mv):
y = int(math.sqrt(j))
if(y*y == j):
j=j*i
continue
D.add(j)
j = j*i
v=[]
for key in D:
v.append(key)
v.sort()
final=[]
while(q):
q-=1
L = (stdin.readline()).split()
l = int(L[0])
r = int(L[1])
root_r = int(math.sqrt(r))
root_l = int(math.sqrt(l-1))
if(root_r*root_r > r):
root_r-=1
if(root_l*root_l > (l-1) ):
root_l -= 1
#print(root_l,root_r)
ans = root_r-root_l
#print(ans)
be = 0
en = len(v)-1
ind = -1
while(be<=en):
mid = (be+en)/2
if(v[mid]<=r):
ind=mid
be=mid+1
else:
en=mid-1
if(ind==-1):
final.append(ans)
continue
in2 = -1
be = 0
en = len(v)-1
while(be<=en):
mid = (be+en)/2
if(v[mid]>=l):
in2 = mid
en=mid-1
else:
be=mid+1
if(in2==-1):
final.append(ans)
continue
# print(ind,v[ind],in2,v[in2])
ans += (ind-in2+1)
final.append(ans)
for i in final:
stdout.write(str(i)+'\n')
| 1521822900 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["a\nz"] | b663dadb1033d435775bf000c2041d43 | NoteTest case 1:Initially $$$s$$$ is "a". In the first operation, Keine chooses "a", and replaces it with "ab". $$$s$$$ becomes "ab". In the second operation, Keine chooses "b", and replaces it with "cd". $$$s$$$ becomes "acd".So the final string is "acd", and $$$t=[$$$"a", "ab", "b", "cd"$$$]$$$ before being shuffled.Test case 2:Initially $$$s$$$ is "z". In the first operation, Keine chooses "z", and replaces it with "aa". $$$s$$$ becomes "aa". In the second operation, Keine chooses "a", and replaces it with "ran". $$$s$$$ becomes "aran". In the third operation, Keine chooses "a", and replaces it with "yakumo". $$$s$$$ becomes "yakumoran".So the final string is "yakumoran", and $$$t=[$$$"z", "aa", "a", "ran", "a", "yakumo"$$$]$$$ before being shuffled. | As a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.βPerfect Memento in Strict SenseKeine has the ability to manipulate history. The history of Gensokyo is a string $$$s$$$ of length $$$1$$$ initially. To fix the chaos caused by Yukari, she needs to do the following operations $$$n$$$ times, for the $$$i$$$-th time: She chooses a non-empty substring $$$t_{2i-1}$$$ of $$$s$$$. She replaces $$$t_{2i-1}$$$ with a non-empty string, $$$t_{2i}$$$. Note that the lengths of strings $$$t_{2i-1}$$$ and $$$t_{2i}$$$ can be different.Note that if $$$t_{2i-1}$$$ occurs more than once in $$$s$$$, exactly one of them will be replaced.For example, let $$$s=$$$"marisa", $$$t_{2i-1}=$$$"a", and $$$t_{2i}=$$$"z". After the operation, $$$s$$$ becomes "mzrisa" or "marisz".After $$$n$$$ operations, Keine got the final string and an operation sequence $$$t$$$ of length $$$2n$$$. Just as Keine thinks she has finished, Yukari appears again and shuffles the order of $$$t$$$. Worse still, Keine forgets the initial history. Help Keine find the initial history of Gensokyo!Recall that a substring is a sequence of consecutive characters of the string. For example, for string "abc" its substrings are: "ab", "c", "bc" and some others. But the following strings are not its substring: "ac", "cba", "acb".HacksYou cannot make hacks in this problem. | For each test case, print the initial string in one line. | Each test contains multiple test cases. The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 10^3$$$) β the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n < 10 ^ 5$$$) β the number of operations. The next $$$2n$$$ lines contains one non-empty string $$$t_{i}$$$ β the $$$i$$$-th string of the shuffled sequence $$$t$$$. The next line contains one non-empty string $$$s$$$ β the final string. It is guaranteed that the total length of given strings (including $$$t_i$$$ and $$$s$$$) over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$. All given strings consist of lowercase English letters only. It is guaranteed that the initial string exists. It can be shown that the initial string is unique. | standard output | standard input | PyPy 3-64 | Python | 1,700 | train_091.jsonl | d913e274e1869d4367950f1c8da0dd29 | 256 megabytes | ["2\n\n2\n\na\n\nab\n\nb\n\ncd\n\nacd\n\n3\n\nz\n\na\n\na\n\naa\n\nyakumo\n\nran\n\nyakumoran"] | PASSED | from __future__ import print_function
from collections import defaultdict
import os,sys,io
import random
#from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li(): return list(mi())
def di(): return defaultdict(int)
def dl(): return defaultdict(list)
def ceil(x,y):
if x%y==0:
return x//y
else:
return x//y+1
def powerMod(x,y,p):
res = 1
x %= p
while y > 0:
if y&1:
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def read():
sys.stdin = open('tests.txt', 'r')
sys.stdout = open('result.txt', 'w')
def main():
for _ in range(ii()):
n = ii()
ocurrence = di()
#dict = defaultdict(str)
for i in range(2*n):
s = input()
for j in range(len(s)):
ocurrence[(s[j])] = ocurrence[(s[j])] + 1
final = input()
for k in range(len(final)):
ocurrence[(final[k])] = ocurrence[(final[k])] + 1
res = -1
for x in ocurrence:
if ocurrence[x] != 0 and ocurrence[x] % 2 == 1:
res = x
break
print(res)
#read()
main()
| 1654266900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["1\n1 1", "1\n1 1", "2\n1 1\n1 2"] | e40774a2c34251eec2df869611731a48 | NoteExample $$$1$$$: one half-queen is enough. Note: a half-queen on $$$(1, 1)$$$ attacks $$$(1, 1)$$$.Example $$$2$$$: one half-queen is enough too. $$$(1, 2)$$$ or $$$(2, 1)$$$ would be wrong solutions, because a half-queen on $$$(1, 2)$$$ does not attack the cell $$$(2, 1)$$$ and vice versa. $$$(2, 2)$$$ is also a valid solution.Example $$$3$$$: it is impossible to cover the board with one half queen. There are multiple solutions for $$$2$$$ half-queens; you can print any of them. | You are given a board with $$$n$$$ rows and $$$n$$$ columns, numbered from $$$1$$$ to $$$n$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$.A half-queen attacks cells in the same row, same column, and on one diagonal. More formally, a half-queen on $$$(a, b)$$$ attacks the cell $$$(c, d)$$$ if $$$a=c$$$ or $$$b=d$$$ or $$$a-b=c-d$$$. The blue cells are under attack. What is the minimum number of half-queens that can be placed on that board so as to ensure that each square is attacked by at least one half-queen?Construct an optimal solution. | In the first line print a single integer $$$k$$$ β the minimum number of half-queens. In each of the next $$$k$$$ lines print two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) β the position of the $$$i$$$-th half-queen. If there are multiple solutions, print any. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β the size of the board. | standard output | standard input | PyPy 3-64 | Python | 2,400 | train_084.jsonl | 025a37247651d6d69ae8d886816565eb | 256 megabytes | ["1", "2", "3"] | PASSED | import sys
# import numpy
input = sys.stdin.readline
inf = float('inf')
def getInt():
return int(input())
def getStr():
return input().strip()
def getList(split=True):
s = getStr()
if split:
s = s.split()
return map(int, s)
# t = getInt()
t = 1
def solve():
n = int(input())
print((2*n+1) // 3)
while n and n % 3 != 2:
print(n, n)
n -= 1
if n == 0:
return
x = n // 3
if x & 1:
y = x+1
else:
x, y = x+1, x
for i in range(x):
print(i+1, x-i)
for i in range(y):
print(n-i, n+1-y+i)
# first fill 1, 1
# greediyly choose two fill the two longest symetric dianal on different rrow / column
# diag = set(range(n))
# diff = 0
# res = []
# used = [0] * (n+1)
# i = 1
# while len(diag) > 1:
# while used[i]:
# i += 1
# j = i + diff
# res.append((i, j))
# if i != j:
# res.append((j, i))
# diag.discard(diff)
# diag.discard(n-i)
# diag.discard(n-j)
# used[i] = used[j] = 1
# diff += 1
# print(diag)
# if diag:
# res.append((n-diag.pop(), ) * 2)
# print(len(res))
# for v in res:
# print(*v)
for _ in range(t):
solve()
"""
a + b - 1 <= k
a >= n - k
b >= n - k
2 * n - 2 * k - 1 <= k
k >= ( 2* n - 1 ) / 3
k = 2*n-1 / 3
n = 3 * x + 2
k = 2 * x + 1
k can cover a square of size x + 1
x + 1 and x can cover 2 * x + 1 both size so 2 * x + 1 + x + 1 = 3 * x + 2 perfectly fit the square
"""
| 1650378900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["0\n12\n5\n0\n16", "3\n0\n3"] | 859d66fc2c204a8c002012b1fb206645 | null | Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire. Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number iβ-β1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number iβ+β1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots. | On the i-th line of the output print the number of birds on the i-th wire. | The first line of the input contains an integer n, (1ββ€βnββ€β100). The next line contains a list of space-separated integers a1,βa2,β...,βan, (0ββ€βaiββ€β100). The third line contains an integer m, (0ββ€βmββ€β100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1ββ€βxiββ€βn,β1ββ€βyi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment. | standard output | standard input | PyPy 2 | Python | 800 | train_000.jsonl | ee56c03ada685ee50fc42b7e71105e4a | 256 megabytes | ["5\n10 10 10 10 10\n5\n2 5\n3 13\n2 12\n1 13\n4 6", "3\n2 4 1\n1\n2 2"] | PASSED | n = input()
a = map(int, raw_input().split())
m = input()
def shoot(m):
x = m[0]
y = m[1]
x -= 1
if x < (n - 1):
a[x + 1] += a[x] - y
if x > 0:
a[x - 1] += y - 1
a[x] = 0
map(shoot, [map(int, raw_input().split()) for i in range(m)])
for i in a:
print i | 1365348600 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2.5 seconds | ["2\n1 2", "2\n3 2"] | 0f181629eb10c5b2718f7a8f79043543 | null | You are given an undirected connected weighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges. Let's denote the length of the shortest path from vertex $$$1$$$ to vertex $$$i$$$ as $$$d_i$$$. You have to erase some edges of the graph so that at most $$$k$$$ edges remain. Let's call a vertex $$$i$$$ good if there still exists a path from $$$1$$$ to $$$i$$$ with length $$$d_i$$$ after erasing the edges.Your goal is to erase the edges in such a way that the number of good vertices is maximized. | In the first line print $$$e$$$ β the number of edges that should remain in the graph ($$$0 \le e \le k$$$). In the second line print $$$e$$$ distinct integers from $$$1$$$ to $$$m$$$ β the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible. | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 3 \cdot 10^5$$$, $$$n - 1 \le m$$$, $$$0 \le k \le m$$$) β the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$, $$$w$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$, $$$1 \le w \le 10^9$$$), denoting an edge connecting vertices $$$x$$$ and $$$y$$$ and having weight $$$w$$$. The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices). | standard output | standard input | PyPy 2 | Python | 1,800 | train_020.jsonl | f365a5f39a7e93a833f20b3f20b291ad | 256 megabytes | ["3 3 2\n1 2 1\n3 2 1\n1 3 3", "4 5 2\n4 1 8\n2 4 1\n2 1 3\n3 4 9\n3 1 5"] | PASSED | from sys import stdin
from collections import defaultdict
from heapq import heappop, heappush
n, m, k = map(int, stdin.readline().split())
graph = defaultdict(list)
for i, line in enumerate(stdin.readlines()):
x, y, w = map(int, line.split())
graph[x].append((y, w, i))
graph[y].append((x, w, i))
res = []
dist = [10e310] * (n + 1)
dist[1] = 0
queue = [(0, 1, -1)]
while True:
path_len, v, index = heappop(queue)
if path_len == dist[v]:
if index != -1:
res.append(index + 1)
if len(res) == k or len(res) == n - 1:
break
for (w, edge_len, index) in graph[v]:
if edge_len + path_len < dist[w]:
dist[w] = edge_len + path_len
heappush(queue, (edge_len + path_len, w, index))
print len(res)
print " ".join(map(str, res)) | 1542033300 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["8\n3\n1 2 3 \n0", "27\n1\n2 \n2\n1 2\n2 3"] | 4750f5a5aaa1ef727ebf2376641bd8ed | NoteFor the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red):For the first example, the cost of building power stations in all cities is $$$3 + 2 + 3 = 8$$$. It can be shown that no configuration costs less than 8 yen.For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is $$$2 \cdot (3 + 2) = 10$$$. The cost of connecting City 2 and City 3 is $$$3 \cdot (2 + 3) = 15$$$. Thus the total cost is $$$2 + 10 + 15 = 27$$$. It can be shown that no configuration costs less than 27 yen. | Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:There are $$$n$$$ new cities located in Prefecture X. Cities are numbered from $$$1$$$ to $$$n$$$. City $$$i$$$ is located $$$x_i$$$ km North of the shrine and $$$y_i$$$ km East of the shrine. It is possible that $$$(x_i, y_i) = (x_j, y_j)$$$ even when $$$i \ne j$$$.Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. Building a power station in City $$$i$$$ will cost $$$c_i$$$ yen; Making a connection between City $$$i$$$ and City $$$j$$$ will cost $$$k_i + k_j$$$ yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City $$$i$$$ and City $$$j$$$ are connected by a wire, the wire will go through any shortest path from City $$$i$$$ to City $$$j$$$. Thus, the length of the wire if City $$$i$$$ and City $$$j$$$ are connected is $$$|x_i - x_j| + |y_i - y_j|$$$ km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. | In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer $$$v$$$ β the number of power stations to be built. Next, print $$$v$$$ space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from $$$1$$$ to $$$n$$$ and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer $$$e$$$ β the number of connections to be made. Finally, print $$$e$$$ pairs of integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$, $$$a \ne b$$$), denoting that a connection between City $$$a$$$ and City $$$b$$$ will be made. Each unordered pair of cities should be included at most once (for each $$$(a, b)$$$ there should be no more $$$(a, b)$$$ or $$$(b, a)$$$ pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. | First line of input contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$) β the number of cities. Then, $$$n$$$ lines follow. The $$$i$$$-th line contains two space-separated integers $$$x_i$$$ ($$$1 \leq x_i \leq 10^6$$$) and $$$y_i$$$ ($$$1 \leq y_i \leq 10^6$$$) β the coordinates of the $$$i$$$-th city. The next line contains $$$n$$$ space-separated integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \leq c_i \leq 10^9$$$) β the cost of building a power station in the $$$i$$$-th city. The last line contains $$$n$$$ space-separated integers $$$k_1, k_2, \dots, k_n$$$ ($$$1 \leq k_i \leq 10^9$$$). | standard output | standard input | PyPy 2 | Python | 1,900 | train_071.jsonl | a9367e148609f475d7836a85dbe9961e | 256 megabytes | ["3\n2 3\n1 1\n3 2\n3 2 3\n3 2 3", "3\n2 1\n1 2\n3 3\n23 2 23\n3 2 3"] | PASSED | import os
import sys
from atexit import register
from io import BytesIO
range = xrange
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
def mst(mat):
n = len(mat)
root = 0
found = [0]*n
found[root] = 1
vec = list(mat[root])
who = [root]*n
pairs = []
I = 0
for _ in range(n - 1):
while found[I]: I += 1
i = k = I
minval = vec[I]
while k < n:
if not found[k] and vec[k] < minval:
minval = vec[k]
i = k
k += 1
pairs.append((who[i], i))
found[i] = 1
vec2 = mat[i]
for j in range(n):
if vec2[j] < vec[j]:
vec[j] = vec2[j]
who[j] = i
return pairs
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
X = inp[ii:ii + 2*n: 2]
Y = inp[ii + 1: ii + 2*n: 2]
ii += 2 * n
C = [float(c) for c in inp[ii:ii + n]]; ii += n
K = [float(c) for c in inp[ii:ii + n]]; ii += n
mat = [[0.0]*(n + 1) for _ in range(n + 1)]
for a in range(n):
for b in range(a + 1, n):
val = (K[a] + K[b]) * (abs(X[a] - X[b]) + abs(Y[a] - Y[b]))
mat[a][b] = mat[b][a] = val
for i in range(n):
mat[i][n] = mat[n][i] = C[i]
cost = 0
power = []
pairs = []
for i,j in mst(mat):
if i > j:
i,j = j,i
cost += mat[i][j]
if j == n:
power.append(i)
else:
pairs.append((i,j))
print int(cost)
print len(power)
print ' '.join(str(x + 1) for x in power)
print len(pairs)
print '\n' .join('%d %d' % (a+1,b+1) for a,b in pairs)
| 1572618900 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["14 4 4 15"] | 5c844c0dc0eb718aea7b2446e90ce250 | NoteLet's consider each $$$a_i$$$: $$$a_1 = 19$$$. You can, firstly, increase it by one to get $$$20$$$ and then multiply it by two $$$13$$$ times. You'll get $$$0$$$ in $$$1 + 13 = 14$$$ steps. $$$a_2 = 32764$$$. You can increase it by one $$$4$$$ times: $$$32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0$$$. $$$a_3 = 10240$$$. You can multiply it by two $$$4$$$ times: $$$10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0$$$. $$$a_4 = 49$$$. You can multiply it by two $$$15$$$ times. | Suppose you have an integer $$$v$$$. In one operation, you can: either set $$$v = (v + 1) \bmod 32768$$$ or set $$$v = (2 \cdot v) \bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$? | Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the minimum number of operations required to make $$$a_i$$$ equal to $$$0$$$. | The first line contains the single integer $$$n$$$ ($$$1 \le n \le 32768$$$)Β β the number of integers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 32768$$$). | standard output | standard input | Python 3 | Python | 1,300 | train_092.jsonl | 66531e10d663c9c0bfaa64eb98415e11 | 256 megabytes | ["4\n19 32764 10240 49"] | PASSED | from math import ceil, log
res =[]
int(input())
l = list(map(int, input().split()) )
c = 32768
def nexp(i, max):
exp = ceil(log(i, 2))
if 2**exp -i < 15 and 2**exp -i + 15 - exp < 15:
return 2**exp -i + 15 - exp
else:
tmp = i
steps=0
if i%2 !=0:
i+=1
steps+=1
while i % c != 0:
if steps > max:
return max +1
i*=2
steps +=1
return steps
def minsteps(i):
exp = ceil(log(i, 2))
if i==0:
return 0
else:
steps = 15
for j in range(15):
tmp = j+i
c =0
while tmp%2==0:
tmp /= 2
c+=1
steps = min(steps, j+ 15-c)
return steps
s =''
for i in l:
if i ==0:
s+="0 "#print("0",end=" ")
else:
steps=minsteps(i)
s+= str(steps)+ " "
print(s)
| 1649514900 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["-1\n-1\n0 0 19\n0 3 3 3 29\n-1\n-1\n0\n0 0 0 1000000000000000000"] | b7ed6f296536d7cd464768b6f315fb99 | NoteIn the first, the second, the fifth and the sixth test cases of the example it is possible to show that such array does not exist.In the third testcase of the example $$$a = [0, 0, 19]$$$. The sum of elements in it is equal to 19, the beauty of it is equal to $$$\left ( \left \lfloor \frac{0}{6} \right \rfloor + \left \lfloor \frac{0}{6} \right \rfloor + \left \lfloor \frac{19}{6} \right \rfloor \right ) = (0 + 0 + 3) = 3$$$.In the fourth testcase of the example $$$a = [0, 3, 3, 3, 29]$$$. The sum of elements in it is equal to $$$38$$$, the beauty of it is equal to $$$(0 + 0 + 0 + 0 + 7) = 7$$$. | Stanley defines the beauty of an array $$$a$$$ of length $$$n$$$, which contains non-negative integers, as follows: $$$$$$\sum\limits_{i = 1}^{n} \left \lfloor \frac{a_{i}}{k} \right \rfloor,$$$$$$ which means that we divide each element by $$$k$$$, round it down, and sum up the resulting values.Stanley told Sam the integer $$$k$$$ and asked him to find an array $$$a$$$ of $$$n$$$ non-negative integers, such that the beauty is equal to $$$b$$$ and the sum of elements is equal to $$$s$$$. Help SamΒ β find any of the arrays satisfying the conditions above. | For each test case print $$$-1$$$ if such array $$$a$$$ does not exist. Otherwise print $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_{i} \leq 10^{18}$$$)Β β the answer. | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains integers $$$n$$$, $$$k$$$, $$$b$$$, $$$s$$$ ($$$1 \leq n \leq 10^{5}$$$, $$$1 \leq k \leq 10^{9}$$$, $$$0 \leq b \leq 10^{9}$$$, $$$0 \leq s \leq 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,000 | train_082.jsonl | 99fc57ddfe9a5d704b9d4376938fc9e0 | 256 megabytes | ["8\n\n1 6 3 100\n\n3 6 3 12\n\n3 6 3 19\n\n5 4 7 38\n\n5 4 7 80\n\n99978 1000000000 100000000 1000000000000000000\n\n1 1 0 0\n\n4 1000000000 1000000000 1000000000000000000"] | PASSED | t = int(input())
for _ in range(t):
a = list(map(int, input().split()))
n = a[0]
k = a[1]
b = a[2]
s = a[3]
f = []
import math
if n == 1:
if math.floor(s / k) == b:
print(s)
else:
print(-1)
else:
for __ in range(n - 1):
f.append(0)
f.append(s)
if s < (b + 1) * k - 1:
if s < b * k:
print(-1)
else:
print((n - 1) * '0 ' + str(s))
else:
num = math.ceil((s - (b + 1) * k + 1) / (n - 1))
if float(num) == (s - (b + 1) * k + 1) / (n - 1):
for l in range(n - 1):
f[l] += num
f[n - 1] = (b + 1) * k - 1
else:
for i in range(n - 1):
f[i] += num - 1
f[n - 1] = (b + 1) * k - 1
r = (s - (b + 1) * k + 1) % (n - 1)
a = (b + 1) * k - 1
for j in range(r):
f[j] += 1
c = 0
sum = 0
sumk = 0
for m in f:
if m < 0:
c = c + 1
if len(f) != n:
c = c + 1
for p in f:
sum = sum + p
if sum != s:
c = c + 1
for hh in f:
sumk += math.floor(hh / k)
if sumk != b:
c += 1
if c > 0:
print(-1)
else:
for j in range(n):
print(f[j], end=' ')
print() | 1661006100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | 79b629047e674883a9bc04b1bf0b7f09 | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$)Β β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$)Β β the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,000 | train_107.jsonl | 8ef38d02bf9d86fa98934b694153b453 | 256 megabytes | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | PASSED | import sys
def read_ints():
return [int(i) for i in sys.stdin.readline().strip().split()]
def read_int():
return int(sys.stdin.readline().strip())
def check_and_output(lines, nodes):
route = [lines[int(i)-1][int(j)-1] for i, j in zip(nodes[:-1],
nodes[1:])]
in_reverse = list(reversed(route))
print("YES")
print(" ".join(nodes))
#print("".join(route))
#assert "*" not in route, "self loop in route " + route
#assert route == in_reverse, " ".join(route) + " is not palindrome"
def nodes_for_3graph(length, start, middle, end):
#print("start %s middle %s end %s" % (start, middle, end))
return [(start if (d + length // 2) % 2 else middle) for d in range(length // 2 + 1)] + [(middle if d % 2 else end) for d in range(length // 2)]
def output_for_3graph(lines, length, start, middle, end):
nodes = nodes_for_3graph(length, start, middle, end)
check_and_output(lines, nodes)
def solve(n, length, lines):
#print(length, "-".join(lines))
if length % 2 == 1:
nodes = [("1" if d % 2 else "2") for d in range(length + 1)]
check_and_output(lines, nodes)
return
for i in range(n):
for j in range(n):
if i != j and lines[i][j] == lines[j][i]:
nodes = [str(i + 1 if d % 2 else j + 1) for d in range(length + 1)]
check_and_output(lines, nodes)
return
if n == 2:
print("NO")
return
if length == 2:
for i in range(n):
for j in range(n):
for k in range(n):
if i != j and j != k and i != k:
if lines[i][j] == lines[j][k]:
nodes = [str(i + 1), str(j + 1), str(k + 1)]
check_and_output(lines, nodes)
return
print("NO")
return
# consider only nodes 1, 2, 3
if lines[0][1] == lines[1][2] == lines[2][0]:
nodes = [str((d % 3) + 1) for d in range(length + 1)]
check_and_output(lines, nodes)
return
if lines[0][2] == lines[2][1] == lines[1][0]:
nodes = [str(3 - (d % 3)) for d in range(length + 1)]
check_and_output(lines, nodes)
return
# centre at node 0 (1)
if lines[0][1] == lines[2][0]:
output_for_3graph(lines, length, "2", "1", "3")
return
# centre at node 1 (2)
if lines[0][1] == lines[1][2]:
output_for_3graph(lines, length, "1", "2", "3")
return
# centre at node 2 (3)
if lines[0][2] == lines[2][1]:
output_for_3graph(lines, length, "1", "3", "2")
return
ncases = read_int()
lines = []
"""
skip = False
if ncases == 320:
n, length = read_ints()
skip = True
if length == 6:
for j in range(n):
lines.append(sys.stdin.readline().strip())
for i in range(53):
lines = []
n, length = read_ints()
for j in range(n):
lines.append(sys.stdin.readline().strip())
output = "";
for i in range(20):
output += sys.stdin.readline().strip() + "----"
print(output)
"""
for i in range(ncases):
lines = []
n, length = read_ints()
skip = False
for j in range(n):
lines.append(sys.stdin.readline().strip())
solve(n, length, lines)
| 1612535700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["2 2 1 1 0 0", "0 1 1 2 1 1 0 0"] | abdf06347e6db23932ef07020f49aa52 | NoteFor the first sample, the corresponding optimal values of s' after removal 0 through |s|β=β5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}. For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}. | Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.More formally, let's define as maximum value of over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know for all x from 0 to |s| where |s| denotes the length of string s. | Print |s|β+β1 space-separated integers in a single line representing the for all x from 0 to |s|. | The first line of the input contains the string s (1ββ€β|s|ββ€β2β000). The second line of the input contains the string p (1ββ€β|p|ββ€β500). Both strings will only consist of lower case English letters. | standard output | standard input | PyPy 3 | Python | 2,200 | train_055.jsonl | c4262816dbcc14465cb603acff4888b6 | 256 megabytes | ["aaaaa\naa", "axbaxxb\nab"] | PASSED | s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
i, j = x, m
while i and j:
j -= s[i - 1] == p[j - 1]
i -= 1
if not j:
for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
for y in range(x): d[x][y] = max(d[x][y], d[x - 1][y])
print(*d[-1])
| 1413122400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["2", "4"] | d17d2fcfb088bf51e9c1f3fce4133a94 | NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$. | Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$. | Print one integer β the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$. | The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$). | standard output | standard input | PyPy 3 | Python | 1,900 | train_012.jsonl | a66c042093eb5581f3d89fd2f361f199 | 256 megabytes | ["3\n1 2 3", "2\n1 5"] | PASSED | t=int(input())
lst=[int(ele) for ele in input().split()]
maxn=max(lst)
n=len(bin(maxn)[2:])
newlst=["0"*(n-len(bin(ele)[2:]))+bin(ele)[2:] for ele in lst]
def catchEvil(lstrino,loc):
count0,count1=[],[]
for ele in lstrino:
if ele[n-1-loc]=='1':
count1.append(ele)
else:
count0.append(ele)
if len(count0)==0:
if loc==0:
return 0
else:
return catchEvil(lstrino,loc-1)
elif len(count1)==0:
if loc==0:
return 0
else:
return catchEvil(lstrino,loc-1)
else:
if loc==0:
return 1
else:
return min(catchEvil(count1,loc-1),catchEvil(count0,loc-1))+(1<<loc)
if n==0:
print(0)
else:
print(int(catchEvil(newlst,n-1)))
| 1578665100 | [
"strings",
"trees"
] | [
0,
0,
0,
0,
0,
0,
1,
1
] |
|
1 second | ["11 6 4 0", "13"] | 14fd47f6f0fcbdb16dbd73dcca8a782f | NoteIn the first testcase, value of the array $$$[11, 6, 4, 0]$$$ is $$$f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9$$$.$$$[11, 4, 0, 6]$$$ is also a valid answer. | Anu has created her own function $$$f$$$: $$$f(x, y) = (x | y) - y$$$ where $$$|$$$ denotes the bitwise OR operation. For example, $$$f(11, 6) = (11|6) - 6 = 15 - 6 = 9$$$. It can be proved that for any nonnegative numbers $$$x$$$ and $$$y$$$ value of $$$f(x, y)$$$ is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array $$$[a_1, a_2, \dots, a_n]$$$ is defined as $$$f(f(\dots f(f(a_1, a_2), a_3), \dots a_{n-1}), a_n)$$$ (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible? | Output $$$n$$$ integers, the reordering of the array with maximum value. If there are multiple answers, print any. | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). Elements of the array are not guaranteed to be different. | standard output | standard input | PyPy 2 | Python | 1,500 | train_005.jsonl | 1c00423cdb5c32287ca07ba1abb07fb6 | 256 megabytes | ["4\n4 0 11 6", "1\n13"] | PASSED | from __future__ import division,print_function
#from sortedcontainers import SortedList
import sys
#sys.__stdout__.flush()
le=sys.__stdin__.read().split("\n")
le.pop()
le=le[::-1]
n=int(le.pop())
l=list(map(bin,map(int,le.pop().split())))
d=max(map(len,l))
l=['0'*(d-len(k))+k[2:] for k in l]
d-=2
#print(l)
tab=[0]*d
for k in l:
for i in range(d):
tab[i]+=int(k[i])
m='0'*d
im=0
for k in range(n):
v=l[k]
te=''.join(str(i if j==1 else 0) for i,j in zip(v,tab))
if te>m:
m=te
im=k
m=l[im]
l.remove(m)
l=[m]+l
l=[str(sum(2**(d-1-i)*int(k[i]) for i in range(d))) for k in l]
#print(l)
print(" ".join(l))
| 1581257100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["3", "9"] | acff03fe274e819a74b5e9350a859471 | NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7β-β4β=β3. In total the answer is 0β+β0β+β3β=β3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4β-β3)β+β(4β-β1)β+β(3β-β1)β+β(4β-β1)β=β9. | Leha decided to move to a quiet town ViΔkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in ViΔkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109β+β7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date. | Print a single integerΒ β the required sum modulo 109β+β7. | The first line contains one integer n (1ββ€βnββ€β3Β·105) denoting the number of hacked computers. The second line contains n integers x1,βx2,β...,βxn (1ββ€βxiββ€β109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct. | standard output | standard input | PyPy 3 | Python | 1,500 | train_013.jsonl | 2700e20e0d52fece931e3897db14f53f | 256 megabytes | ["2\n4 7", "3\n4 3 1"] | PASSED | #!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1
n=int(input())
A=list(map(int,input().split()))
A.sort()
for i in range(n):
ans-=pow(2,n-i-1,mod)*A[i]
ans+=pow(2,i,mod)*A[i]
ans%=mod
print(ans) | 1495303500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["8"] | c277a257b3621249098e67c1546a8bc4 | NoteIn the first query there is a good subtree of size $$$8$$$. The vertices belonging to this subtree are $$${9, 4, 10, 2, 5, 1, 6, 3}$$$. | Assume that you have $$$k$$$ one-dimensional segments $$$s_1, s_2, \dots s_k$$$ (each segment is denoted by two integers β its endpoints). Then you can build the following graph on these segments. The graph consists of $$$k$$$ vertexes, and there is an edge between the $$$i$$$-th and the $$$j$$$-th vertexes ($$$i \neq j$$$) if and only if the segments $$$s_i$$$ and $$$s_j$$$ intersect (there exists at least one point that belongs to both of them).For example, if $$$s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$$$, then the resulting graph is the following: A tree of size $$$m$$$ is good if it is possible to choose $$$m$$$ one-dimensional segments so that the graph built on these segments coincides with this tree.You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.Note that you have to answer $$$q$$$ independent queries. | For each query print one integer β the maximum size of a good subtree of the given tree. | The first line contains one integer $$$q$$$ ($$$1 \le q \le 15 \cdot 10^4$$$) β the number of the queries. The first line of each query contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) β the number of vertices in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) denoting an edge between vertices $$$x$$$ and $$$y$$$. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$. | standard output | standard input | PyPy 2 | Python | 2,200 | train_044.jsonl | 1f46dccdb4706b1b55e5b500e21c84cc | 256 megabytes | ["1\n10\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n4 9\n4 10"] | PASSED | from __future__ import division,print_function
import sys
le=sys.__stdin__.read().split("\n")[::-1]
aff=[]
#basculer en non enracinΓ©
def f():
n=int(le.pop())
ar=[[] for k in range(n)]
for k in range(n-1):
a,b=map(int,le.pop().split())
a-=1
b-=1
ar[a].append(b)
ar[b].append(a)
if n<5:
aff.append(n)
return None
pf=[0]*n
d=[len(k) for k in ar]
nd=d[:]
m=0
pi=[k for k in range(n) if d[k]==1]
for n2 in range(n):
v=pi.pop()
if d[v]==1:
w=ar[v][0]
if pf[w]:
m=max(m,1+pf[w])
pf[v]=1+pf[w]#pour leprincipe, normalement pas utiles
else:
pf[v]=1
nd[w]-=1
if nd[w]==1:
pi.append(w)
else:
m1,m2=0,0
for k in ar[v]:
if pf[k]:
if pf[k]>m2:
m2,m1=pf[k],m2
elif pf[k]>m1:
m1=pf[k]
else:
nd[k] -= 1
if nd[k]==1:
pi.append(k)
if n2!=n-1:
m=max(m1+m2+d[v]-1,m)
else:
m=max(m1+m2+d[v]-1,m)
pf[v]=m2+d[v]-1
aff.append(m)
def fm():
n=int(le.pop())
ar=[[] for k in range(n)]
for k in range(n-1):
a,b=map(int,le.pop().split())
a-=1
b-=1
ar[a].append(b)
ar[b].append(a)
p=[0]*n
pf=[0]*n
def parc(v,pere):
p[v]=pere
for k in ar[v]:
if k!=pere:
parc(k,v)
parc(0,0)
d=[len(k)-1 for k in ar]
d[0]+=1
nd=d[:]
m=0
pi=[k for k in range(n) if not(d[k])]
while pi:
v=pi.pop()
nd[p[v]]-=1
if not(nd[p[v]]):
pi.append(p[v])
te=sorted([pf[w] for w in ar[v]])
if d[v]:
pf[v]=te[-1]+d[v]
else:
pf[v]=1
if d[v]>1:
if v:
m=max(te[-1]+te[-2]+d[v],m)
else:
m=max(te[-1]+te[-2]+d[v]-1,m)
elif d[v]==1:
m=max(te[0]+1,m)
aff.append(m)
for q in range(int(le.pop())):
f()
print("\n".join(map(str,aff)))
| 1570545300 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second | ["4\n5\n4\n1\n3\n4"] | a4b170cc058c485a50bf18982fd96851 | NoteIn the first test case, one of the longest strange subsequences is $$$(a_1, a_2, a_3, a_4)$$$In the second test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5, a_7)$$$.In the third test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5)$$$.In the fourth test case, one of the longest strange subsequences is $$$(a_2)$$$.In the fifth test case, one of the longest strange subsequences is $$$(a_1, a_2, a_4)$$$. | A sequence $$$(b_1, b_2, \ldots, b_k)$$$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $$$(i, j)$$$ with $$$1 \le i<j \le k$$$, we have $$$|a_i-a_j|\geq MAX$$$, where $$$MAX$$$ is the largest element of the sequence. In particular, any sequence of length at most $$$1$$$ is strange.For example, the sequences $$$(-2021, -1, -1, -1)$$$ and $$$(-1, 0, 1)$$$ are strange, but $$$(3, 0, 1)$$$ is not, because $$$|0 - 1| < 3$$$.Sifid has an array $$$a$$$ of $$$n$$$ integers. Sifid likes everything big, so among all the strange subsequences of $$$a$$$, he wants to find the length of the longest one. Can you help him?A sequence $$$c$$$ is a subsequence of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements. | For each test case output a single integer β the length of the longest strange subsequence of $$$a$$$. | The first line contains an integer $$$t$$$ $$$(1\le t\le 10^4)$$$ β the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 10^5)$$$ β the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(-10^9\le a_i \le 10^9)$$$ β the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,100 | train_085.jsonl | 04562af0a57f7a24132e3ca507d86d84 | 256 megabytes | ["6\n4\n-1 -2 0 0\n7\n-3 4 -2 0 -4 6 1\n5\n0 5 -3 2 -5\n3\n2 3 1\n4\n-3 0 2 0\n6\n-3 -2 -1 1 1 1"] | PASSED | tcs = int(input())
for _ in range(tcs):
n = int(input())
a = list(map(int, input().split()))
a.sort()
if a[n-1] <= 0:
print(n)
else:
flag = 0
pi = 0
while(a[pi] <= 0):
pi += 1
for i in range(pi):
x = a[i] - a[i+1]
if abs(x) < a[pi]:
flag = 1
print(pi+1 if flag == 0 else pi)
| 1621866900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n0"] | d8c4c2d118e07c3b148495fc04d8fcb5 | null | Petya and Gena play a very interesting game "Put a Knight!" on a chessboard nβΓβn in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r,βc) can threat squares (rβ-β1,βcβ+β2), (rβ-β1,βcβ-β2), (rβ+β1,βcβ+β2), (rβ+β1,βcβ-β2), (rβ-β2,βcβ+β1), (rβ-β2,βcβ-β1), (rβ+β2,βcβ+β1) and (rβ+β2,βcβ-β1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts. | For each niβΓβni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1". | The first line contains integer T (1ββ€βTββ€β100) β the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1ββ€βniββ€β10000) β the sizes of the chessboards. | output.txt | input.txt | PyPy 2 | Python | 1,400 | train_015.jsonl | cc6a140c4011ea48c54eefd058feb15b | 256 megabytes | ["2\n2\n1"] | PASSED | import sys
sys.stdin, sys.stdout=open('input.txt','r'),open('output.txt','w')
for _ in range(input()):print 1-(input()&1)
| 1318919400 | [
"math",
"games"
] | [
1,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["2\n-1\n3\n2\n-1"] | 7c6e8bc160a17dbc6d55c6dc40fe0988 | Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$). | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y>x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her! | For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal. | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$)Β β the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | standard output | standard input | PyPy 3 | Python | 1,700 | train_025.jsonl | 34c8b34c0663b882165dd89e65ea2980 | 256 megabytes | ["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"] | PASSED | import sys
input = sys.stdin.readline
def print(val):
sys.stdout.write(str(val) + '\n')
def prog():
for _ in range(int(input())):
n = int(input())
a = list(input().strip())
b = input().strip()
fail = False
for i in range(n):
if b[i] < a[i]:
fail = True
break
if fail:
print(-1)
else:
exclude = [0]*n
for i in range(n):
if a[i] == b[i]:
exclude[i] = 1
largest = max(b)
curr = largest
for i in range(n):
if not exclude[i]:
curr = min(curr, a[i])
operations = 0
while curr < largest:
to_change = []
for i in range(n):
if a[i] == curr and not exclude[i]:
to_change.append(i)
smallest = largest
for i in to_change:
smallest = min(smallest, b[i])
for i in to_change:
if b[i] == smallest:
exclude[i] = 1
a[i] = smallest
curr = largest
for i in range(n):
if not exclude[i]:
curr = min(curr, a[i])
operations += 1
print(operations)
prog()
| 1595601300 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds | ["4 5 2 3 1", "12 13 14 7 3 1", "4 5 2 6 3 1"] | 1ccbcc5986bf7e7272b7dd65e061d66d | null | You are given a set Y of n distinct positive integers y1,βy2,β...,βyn.Set X of n distinct positive integers x1,βx2,β...,βxn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: Take any integer xi and multiply it by two, i.e. replace xi with 2Β·xi. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2Β·xiβ+β1. Note that integers in X are not required to be distinct after each operation.Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.Note, that any set of integers (or its permutation) generates itself.You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible. | Print n integersΒ β set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them. | The first line of the input contains a single integer n (1ββ€βnββ€β50β000)Β β the number of elements in Y. The second line contains n integers y1,β...,βyn (1ββ€βyiββ€β109), that are guaranteed to be distinct. | standard output | standard input | Python 3 | Python | 1,900 | train_072.jsonl | 9eef3b1df0206d66c8676af17ace3276 | 256 megabytes | ["5\n1 2 3 4 5", "6\n15 14 3 13 1 12", "6\n9 7 13 17 5 11"] | PASSED | def main():
from heapq import heapify, heapreplace
input()
s = set(map(int, input().split()))
xx = [-x for x in s]
heapify(xx)
while True:
x = -xx[0]
while x != 1:
x //= 2
if x not in s:
s.add(x)
heapreplace(xx, -x)
break
else:
break
print(' '.join(str(-x) for x in xx))
if __name__ == '__main__':
main()
| 1475330700 | [
"strings",
"trees"
] | [
0,
0,
0,
0,
0,
0,
1,
1
] |
|
2 seconds | ["3", "1"] | c02922c33eb816eea872b4d8a3c1dc0e | NoteThe first example is illustrated by the following: For example, you can add roads ($$$6, 4$$$), ($$$7, 9$$$), ($$$1, 7$$$) to make all the cities reachable from $$$s = 1$$$.The second example is illustrated by the following: In this example, you can add any one of the roads ($$$5, 1$$$), ($$$5, 2$$$), ($$$5, 3$$$), ($$$5, 4$$$) to make all the cities reachable from $$$s = 5$$$. | There are $$$n$$$ cities and $$$m$$$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?New roads will also be one-way. | Print one integer β the minimum number of extra roads needed to make all the cities reachable from city $$$s$$$. If all the cities are already reachable from $$$s$$$, print 0. | The first line of input consists of three integers $$$n$$$, $$$m$$$ and $$$s$$$ ($$$1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$$$) β the number of cities, the number of roads and the index of the capital. Cities are indexed from $$$1$$$ to $$$n$$$. The following $$$m$$$ lines contain roads: road $$$i$$$ is given as a pair of cities $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). For each pair of cities $$$(u, v)$$$, there can be at most one road from $$$u$$$ to $$$v$$$. Roads in opposite directions between a pair of cities are allowed (i.e. from $$$u$$$ to $$$v$$$ and from $$$v$$$ to $$$u$$$). | standard output | standard input | Python 3 | Python | 2,000 | train_016.jsonl | 02b94c121d4f3b644bf724703312d5aa | 256 megabytes | ["9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1", "5 4 5\n1 2\n2 3\n3 4\n4 1"] | PASSED | from collections import defaultdict
import sys
def dfs(u):
avail[u] = False
for v in g[u]:
if avail[v]:
dfs(v)
topo.append(u)
sys.setrecursionlimit(6000)
n, m, s = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
g[u - 1].append(v - 1)
avail, topo = [True] * n, []
for i,a in enumerate(avail):
if a:
dfs(i)
avail, res = [True] * n, 0
dfs(s - 1)
for i in reversed(topo):
if avail[i]:
res += 1
dfs(i)
print(res) | 1529591700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"] | 1637670255f8bd82a01e2ab20cdcc9aa | NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \cdot 4 + 4^2 \cdot 3 + 4^1 \cdot 2 + 4^0 \cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \cdot 5 + 5^3 \cdot 2 + 5^2 \cdot 4 + 5^1 \cdot 3 + 5^0 \cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \cdot 6 + 6^4 \cdot 1 + 6^3 \cdot 5 + 6^2 \cdot 3 + 6^1 \cdot 4 + 6^0 \cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$. | You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i.Β e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above. | For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them. | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$)Β β values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,100 | train_109.jsonl | 9153a8cff9a8a4b0fa95e1499a8ea9d5 | 512 megabytes | ["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"] | PASSED | from collections import deque
t = int(input())
for klmn in range(t):
n = int(input())
used = [0 for i in range(n)]
p = list(map(int, input().split()))
ans = deque([])
dob = deque([])
m = n
le = n
while le > 0:
if used[m-1] == 0:
num = p[-1]
dob.appendleft(num)
used[num-1] = 1
p.pop()
le -= 1
else:
ans += dob
dob = deque([])
m -= 1
print(*ans + dob)
| 1614071100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["3", "10"] | 35bd08a2f5350890b2a520672538d712 | NoteIn the first example, one can achieve the maximum $$$S$$$ with the following assignment: With this assignment, $$$mex(1, 2) = 0$$$, $$$mex(1, 3) = 2$$$ and $$$mex(2, 3) = 1$$$. Therefore, $$$S = 0 + 2 + 1 = 3$$$.In the second example, one can achieve the maximum $$$S$$$ with the following assignment: With this assignment, all non-zero mex value are listed below: $$$mex(1, 3) = 1$$$ $$$mex(1, 5) = 2$$$ $$$mex(2, 3) = 1$$$ $$$mex(2, 5) = 2$$$ $$$mex(3, 4) = 1$$$ $$$mex(4, 5) = 3$$$ Therefore, $$$S = 1 + 2 + 1 + 2 + 1 + 3 = 10$$$. | INSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of $$$n$$$ small gangs. This network contains exactly $$$n - 1$$$ direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from $$$0$$$ to $$$n - 2$$$ such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass $$$S$$$ password layers, with $$$S$$$ being defined by the following formula:$$$$$$S = \sum_{1 \leq u < v \leq n} mex(u, v)$$$$$$Here, $$$mex(u, v)$$$ denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang $$$u$$$ to gang $$$v$$$.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of $$$S$$$, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible $$$S$$$ before he returns? | Print the maximum possible value of $$$S$$$Β β the number of password layers in the gangs' network. | The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 3000$$$), the number of gangs in the network. Each of the next $$$n - 1$$$ lines contains integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$; $$$u_i \neq v_i$$$), indicating there's a direct link between gangs $$$u_i$$$ and $$$v_i$$$. It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path. | standard output | standard input | PyPy 2 | Python | 2,300 | train_065.jsonl | 93f9160eff0905e90868f8be926d0e60 | 512 megabytes | ["3\n1 2\n2 3", "5\n1 2\n1 3\n1 4\n3 5"] | PASSED | import sys
range = xrange
input = raw_input
# Read input and build the graph
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
# Relabel to speed up n^2 operations later on
bfs = [0]
found = [0]*n
found[0] = 1
for node in bfs:
for nei in coupl[node]:
if not found[nei]:
found[nei] = 1
bfs.append(nei)
new_lable = [0]*n
for i in range(n):
new_lable[bfs[i]] = i
coupl = [coupl[i] for i in bfs]
for c in coupl:
c[:] = [new_lable[x] for x in c]
##### DP using multisource bfs
DP = [0] * (n * n)
size = [1] * (n * n)
P = [-1] * (n * n)
# Create the bfs ordering
bfs = [root * n + root for root in range(n)]
for ind in bfs:
P[ind] = ind
for ind in bfs:
node, root = divmod(ind, n)
for nei in coupl[node]:
ind2 = nei * n + root
if P[ind2] == -1:
bfs.append(ind2)
P[ind2] = ind
del bfs[:n]
# Do the DP
for ind in reversed(bfs):
node, root = divmod(ind, n)
pind = P[ind]
parent = pind//n
# Calculate size of parent
size[pind] += size[ind]
# Calculate DP val of parent
DP[root * n + parent] = DP[pind] = max(DP[pind], DP[ind] + size[ind] * size[root * n + node])
print max(DP[root * n + root] for root in range(n))
| 1579440900 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds | ["YES\n2 1\n1 2"] | 1e061d8c4bff217047ddc58e88be0c3f | NoteIn the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist. | Print "NO" (without quotes), if such graph doesn't exist. Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines. The description of the made graph must start with numbers n and m β the number of vertices and edges respectively. Each of the next m lines must contain two integers, a and b (1ββ€βa,βbββ€βn, aββ βb), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order. The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges). | The single line of the input contains integer k (1ββ€βkββ€β100) β the required degree of the vertices of the regular graph. | standard output | standard input | PyPy 3 | Python | 1,900 | train_036.jsonl | b7522beb4ed6f6e57bb66f80627c6b5e | 256 megabytes | ["1"] | PASSED | k = int(input())
if k % 2 == 0:
print('NO')
else:
print('YES')
reb = [[1, 2]]
for v in range(3, k + 2):
reb.append([1, v])
reb.append([v, k + 2 * v - 4])
reb.append([v, k + 2 * v - 3])
reb.append([k + 2 * v - 4, k + 2 * v - 3])
for u in range(v + 1, k + 2):
if v + u != k + 4:
reb.append([v, u])
reb.append([k + 2 * v - 4, k + 2 * u - 4])
reb.append([k + 2 * v - 3, k + 2 * u - 3])
for v in range(3 * k, 4 * k - 1):
reb.append([2, v])
reb.append([v, 2 * v - 2 * k - 1])
reb.append([v, 2 * v - 2 * k])
reb.append([2 * v - 2 * k, 2 * v - 2 * k - 1])
for u in range(v + 1, 4 * k - 1):
if v + u != 7 * k - 2:
reb.append([v, u])
reb.append([2 * v - 2 * k, 2 * u - 2 * k])
reb.append([2 * v - 2 * k - 1, 2 * u - 2 * k - 1])
print(2 * (3 * k - 2), k * (3 * k - 2))
for a, b in reb:
print(a, b)
| 1433435400 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["6\n15"] | 648ec67565c506c3e2ffd007ad44e8c3 | NoteIn the first test case, integer $$$6$$$ have following divisors: $$$[1, 2, 3, 6]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$1$$$. There is no smaller integer with at least $$$4$$$ divisors.In the second test case, integer $$$15$$$ have following divisors: $$$[1, 3, 5, 15]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$2$$$.The answer $$$12$$$ is INVALID because divisors are $$$[1, 2, 3, 4, 6, 12]$$$. And the difference between, for example, divisors $$$2$$$ and $$$3$$$ is less than $$$d=2$$$. | Positive integer $$$x$$$ is called divisor of positive integer $$$y$$$, if $$$y$$$ is divisible by $$$x$$$ without remainder. For example, $$$1$$$ is a divisor of $$$7$$$ and $$$3$$$ is not divisor of $$$8$$$.We gave you an integer $$$d$$$ and asked you to find the smallest positive integer $$$a$$$, such that $$$a$$$ has at least $$$4$$$ divisors; difference between any two divisors of $$$a$$$ is at least $$$d$$$. | For each test case print one integer $$$a$$$Β β the answer for this test case. | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3000$$$)Β β the number of test cases. The first line of each test case contains a single integer $$$d$$$ ($$$1 \leq d \leq 10000$$$). | standard output | standard input | Python 3 | Python | 1,000 | train_100.jsonl | 82bfeebd63c6cfa61dbf5a71fc773227 | 256 megabytes | ["2\n1\n2"] | PASSED | t = int(input())
for i in range(t):
d = int(input())
p1 = 1 + d
while True:
m = True
for j in range(2, int(p1 ** 0.5) + 1):
if p1 % j != 0:
continue
else:
m = False
break
if m != False:
break
else:
p1 += 1
p2 = p1 + d
while True:
m = True
for j in range(2, int((p2 ** 0.5)) + 1):
if p2 % j != 0:
continue
else:
m = False
break
if m != False:
break
else:
p2 += 1
if (p1 * p2) <= p1**3:
print(p1 * p2)
else:
print(p1**3) | 1611066900 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["YES\n1\n1 3 4", "NO"] | 623f12b8c5a5c850c7edd9875af56f32 | NoteIn the first example, the array becomes $$$[4 \oplus 1 \oplus 7, 2, 4 \oplus 1 \oplus 7, 4 \oplus 1 \oplus 7, 2] = [2, 2, 2, 2, 2]$$$. | Ksenia has an array $$$a$$$ consisting of $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$. In one operation she can do the following: choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$, and then change all of $$$a_i, a_j, a_k$$$ to $$$a_i \oplus a_j \oplus a_k$$$ simultaneously, where $$$\oplus$$$ denotes the bitwise XOR operation. She wants to make all $$$a_i$$$ equal in at most $$$n$$$ operations, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her! | Print YES or NO in the first line depending on whether it is possible to make all elements equal in at most $$$n$$$ operations. If it is possible, print an integer $$$m$$$ ($$$0 \leq m \leq n$$$), which denotes the number of operations you do. In each of the next $$$m$$$ lines, print three distinct integers $$$i, j, k$$$, representing one operation. If there are many such operation sequences possible, print any. Note that you do not have to minimize the number of operations. | The first line contains one integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$)Β β the length of $$$a$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)Β β elements of $$$a$$$. | standard output | standard input | Python 3 | Python | 2,200 | train_017.jsonl | 6e8680c9864ea16650dbcd69703e50a4 | 256 megabytes | ["5\n4 2 1 7 2", "4\n10 4 49 22"] | PASSED | # abc means a xor b xor c
#
# a b c -> abc abc abc
#
#
# a b c d -> abc abc abc d
# -> abc d d d only YES if abc=d (abcd=0)
#
#
# a b c d e -> abc abc abc d e
# -> abc abc abcde abcde abcde
# ^ ^ ^
# -> abcde abcde abcde abcde abcde
#
#
# a b c d e f -> abc abc abc d e f
# -> abc abc abc def def def odd number of abc
# only YES if abc=def (abcdef=0)
#
# a b c d e f g -> abc abc abc d e f g
# -> abc abc abc def def def g
# ^ ^ ^
# -> abcdefg abc abc abcdefg def def abcdefg
# ^ ^ ^
# -> abcdefg abcdefg abcdefg abcdefg def def abcdefg
# -> abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg
#
#
# a b c d e f g
# abc abc abc d e f g
# abc abc abcde abcde abcde f g
# abc abc abcde abcde abcdefg abcdefg abcdefg
# abc abc abcdefg abcdefg abcdefg abcdefg abcdefg
# abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg
#
# induction: assume true for n-2 and can be done in n-4 steps.
# for n:
# a1 a2 a3 ... an
# (1 step, position 012)
# a1a2a3 a1a2a3 a1a2a3 a4 a5 ... an
# [ n-2 ]
# (n-4 steps)
# 234
# 456
# 678 ...
# 456
# 234
#
# a1a2a3 a1a2a3 [a1a2...an a1a2...an a1a2...an]
# ^ ^ ^
# (1 step)
# 012
#
# Total n-2 steps. induction is correct
n = int(input())
a = list(map(int,input().split()))
if n % 2 != 0:
print('YES')
print(n-2)
for i in range(n):
print(i*2+1,i*2+2,i*2+3) # 123,345,567,...,n-2 n-1 n
if i*2+3 == n:
break
for i in range(2,n):
if n-i*2+2 < 3:
break
print(n-i*2,n-i*2+1,n-i*2+2)
# n-4 n-3 n-2, n-6 n-5 n-4, ... , 123
else:
xor = 0
for num in a:
xor = xor ^ num
if xor != 0:
print('NO')
else:
n -= 1
print('YES')
print(n-2)
for i in range(n):
print(i*2+1,i*2+2,i*2+3) # 123,345,567,...,n-2 n-1 n
if i*2+3 == n:
break
for i in range(2,n):
if n-i*2+2 < 3:
break
print(n-i*2,n-i*2+1,n-i*2+2)
# n-4 n-3 n-2, n-6 n-5 n-4, ... , 123
| 1605278100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1.5 seconds | ["0\n3\n4\n4"] | b62586b55bcfbd616d936459c30579a6 | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | For each test case, print one integer β the minimum number of cells you have to change so that every path in the matrix is palindromic. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) β the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) β the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | standard output | standard input | Python 3 | Python | 1,500 | train_003.jsonl | ab3ef230e4d2fb5592007bd0e0d9f3c7 | 256 megabytes | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | PASSED | # import sys
# sys.stdin = open('inputf.in','r')
#sys.stdout = open('outputf.in','w')
t = int(input())
while(t):
t -= 1
n,m = map(int, input().split(' '))
d0 = {}
d1 = {}
for i in range(1, n + 1):
l = list(map(int, input().split(' ')))
for j in range(1, m + 1):
x = i + j
if x not in d0:
d0[x] = 0
if x not in d1:
d1[x] = 0
d0[x] += (l[j - 1] == 0)
d1[x] += (l[j - 1] == 1)
ans = 0
i = 2
j = n + m
while(i < j):
x1 = d1[i] + d1[j]
x2 = d0[i] + d0[j]
i += 1
j -= 1
ans += min(x1, x2)
print(ans) | 1591886100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["8\n2\n4", "0\n3\n1"] | 951b6dfb8d9839857c0c8abd550e9b15 | NoteConsider the first example. In the first query of second type all characters coincide, so the answer is 8. In the second query we compare string "TTTTT..." and the substring "TGCAT". There are two matches. In the third query, after the DNA change, we compare string "TATAT..."' with substring "TGTAT". There are 4 matches. | Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string s initially. Evolution of the species is described as a sequence of changes in the DNA. Every change is a change of some nucleotide, for example, the following change can happen in DNA strand "AAGC": the second nucleotide can change to "T" so that the resulting DNA strand is "ATGC".Scientists know that some segments of the DNA strand can be affected by some unknown infections. They can represent an infection as a sequence of nucleotides. Scientists are interested if there are any changes caused by some infections. Thus they sometimes want to know the value of impact of some infection to some segment of the DNA. This value is computed as follows: Let the infection be represented as a string e, and let scientists be interested in DNA strand segment starting from position l to position r, inclusive. Prefix of the string eee... (i.e. the string that consists of infinitely many repeats of string e) is written under the string s from position l to position r, inclusive. The value of impact is the number of positions where letter of string s coincided with the letter written under it. Being a developer, Innokenty is interested in bioinformatics also, so the scientists asked him for help. Innokenty is busy preparing VK Cup, so he decided to delegate the problem to the competitors. Help the scientists! | For each scientists' query (second type query) print a single integer in a new lineΒ β the value of impact of the infection on the DNA. | The first line contains the string s (1ββ€β|s|ββ€β105) that describes the initial DNA strand. It consists only of capital English letters "A", "T", "G" and "C". The next line contains single integer q (1ββ€βqββ€β105)Β β the number of events. After that, q lines follow, each describes one event. Each of the lines has one of two formats: 1Β xΒ c, where x is an integer (1ββ€βxββ€β|s|), and c is a letter "A", "T", "G" or "C", which means that there is a change in the DNA: the nucleotide at position x is now c. 2Β lΒ rΒ e, where l, r are integers (1ββ€βlββ€βrββ€β|s|), and e is a string of letters "A", "T", "G" and "C" (1ββ€β|e|ββ€β10), which means that scientists are interested in the value of impact of infection e to the segment of DNA strand from position l to position r, inclusive. | standard output | standard input | PyPy 2 | Python | 2,100 | train_077.jsonl | 14ec79f4ed94ae56b99b0580cccc4a2f | 512 megabytes | ["ATGCATGC\n4\n2 1 8 ATGC\n2 2 6 TTT\n1 4 T\n2 2 6 TA", "GAGTTGTTAA\n6\n2 3 4 TATGGTG\n1 1 T\n1 6 G\n2 5 9 AGTAATA\n1 10 G\n2 2 6 TTGT"] | PASSED | import sys
range = xrange
input = raw_input
class segtree:
def __init__(s, data):
s.n = len(data)
s.m = 1
while s.m < s.n: s.m *= 2
s.data = [0]*s.m
s.data += data
for i in reversed(range(2, s.n + s.m)):
s.data[i >> 1] += s.data[i]
def add(s, i, x):
i += s.m
while i:
s.data[i] += x
i >>= 1
def summa(s, l, r):
l += s.m
r += s.m
tot = 0
while l<r:
if l & 1:
tot += s.data[l]
l += 1
if r & 1:
tot += s.data[r - 1]
l >>= 1
r >>= 1
return tot
def trans(x):
if x == 'A':
return 0
elif x == 'C':
return 1
elif x == 'G':
return 2
return 3
inp = sys.stdin.read().split()
ii = 0
S = [trans(x) for x in inp[ii]]
ii += 1
segs = [
[
[
segtree([+(s==c) for s in S[j::i]]) for c in range(4)
]
for j in range(i)
]
for i in range(11)
]
q = int(inp[ii])
ii += 1
out = []
for _ in range(q):
c = inp[ii]
ii += 1
if c == '1':
ind = int(inp[ii]) - 1
ii += 1
char = trans(inp[ii])
ii += 1
old_char = S[ind]
for i in range(1,11):
seg = segs[i][ind % i]
seg[old_char].add(ind // i, -1)
seg[char].add(ind // i, 1)
S[ind] = char
else:
l = int(inp[ii]) - 1
ii += 1
r = int(inp[ii])
ii += 1
e = inp[ii]
ii += 1
tot = 0
i = len(e)
for k in range(i):
L = l + k
start = L//i
length = (r - L + i - 1)//i
tot += segs[i][L % i][trans(e[k])].summa(start, start + length)
out.append(tot)
print '\n'.join(str(x) for x in out)
| 1499791500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
4 seconds | ["1 3 6", "3 14 15 92 6"] | 584f7008e27dde53037396d2459efd84 | null | You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1ββ€βiββ€βn) of array s equals . The operation xΒ modΒ y means that we take the remainder of the division of number x by number y. Then we write the contents of the array s to the array a. Element number i (1ββ€βiββ€βn) of the array s becomes the i-th element of the array a (aiβ=βsi). You task is to find array a after exactly k described operations are applied. | Print n integers Β β elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces. | The first line contains two space-separated integers n and k (1ββ€βnββ€β2000, 0ββ€βkββ€β109). The next line contains n space-separated integers a1,βa2,β...,βanΒ β elements of the array a (0ββ€βaiββ€β109). | standard output | standard input | PyPy 3 | Python | 1,900 | train_014.jsonl | ea7c0d005e4cc2b4aae06d7f4ff80b83 | 256 megabytes | ["3 1\n1 2 3", "5 0\n3 14 15 92 6"] | PASSED | leng, repeat=list(map(int,input().split()))
Lis = list(map(int,input().split()))
mod = 10**9 + 7
cum = [1]
ans = [0]*leng
for i in range(1, 2001):
cum.append((cum[-1] * (repeat + i - 1) * pow(i, mod-2, mod)) % mod)
for i in range(leng):
for j in range(i + 1):
ans[i] = (ans[i] + cum[i-j] * Lis[j]) % mod
print(*ans)
| 1347809400 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["3 2", "3 4"] | 38dc16395b742f2a0e9f359a8bf33061 | NoteIn the first sample the appropriate pairs are (0,β3) and (0,β4). In the second sample the appropriate pairs are (0,β4), (1,β4), (2,β4) and (3,β4). | Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1){ int j = i; while (j > 0 && a[j] < a[j - 1]) { swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1] j = j - 1; }}Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to nβ-β1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases. | Print two integers: the minimum number of times the swap function is executed and the number of such pairs (i,βj) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions. | The first line contains a single integer n (2ββ€βnββ€β5000) β the length of the permutation. The second line contains n different integers from 0 to nβ-β1, inclusive β the actual permutation. | standard output | standard input | PyPy 3 | Python | 1,900 | train_044.jsonl | 6110a275ecf73d262745aae08323ca65 | 256 megabytes | ["5\n4 0 3 1 2", "5\n1 2 3 4 0"] | PASSED | arr = [0 for i in range(5001)]
def insertion_sort(n, a):
def modify(t):
while t > 0:
arr[t] += 1
t -= t & (-t)
def query(t):
res = 0
while t < 5001:
res += arr[t]
t += t & (-t)
return res
s = 0
ans = 0
way = 0
for i in range(n):
a[i] += 1
for i in range(n):
global arr
arr = [0 for j in range(5001)]
for j in range(i + 1, n):
if a[i] < a[j]:
continue
s += 1
tmp = 1 + 2 * query(a[j])
if tmp > ans:
ans = tmp
way = 1
elif tmp == ans:
way += 1
modify(a[j])
return s - ans, way
if __name__ == "__main__":
n = int(input())
a = list(map(int, input().split()))
result = insertion_sort(n, a)
print(*result)
| 1384443000 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["YES", "YES", "NO"] | 4b352854008a9378551db60b76d33cfa | NoteIn the first example PolandBall knows much more words and wins effortlessly.In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins. | PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally? | In a single line of print the answerΒ β "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally. | The first input line contains two integers n and m (1ββ€βn,βmββ€β103)Β β number of words PolandBall and EnemyBall know, respectively. Then n strings follow, one per lineΒ β words familiar to PolandBall. Then m strings follow, one per lineΒ β words familiar to EnemyBall. Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players. Each word is non-empty and consists of no more than 500 lowercase English alphabet letters. | standard output | standard input | PyPy 2 | Python | 1,100 | train_002.jsonl | 60ee2f26b2117bf42c92911ad22307f8 | 256 megabytes | ["5 1\npolandball\nis\na\ncool\ncharacter\nnope", "2 2\nkremowka\nwadowicka\nkremowka\nwiedenska", "1 2\na\na\nb"] | PASSED | n, m = [int(x) for x in raw_input().split()]
wp = set()
for _ in range(n):
wp.add(raw_input().strip())
we = set()
for _ in range(m):
we.add(raw_input().strip())
nb = len(wp & we)
np = len(wp - we)
ne = len(we - wp)
mp = (nb + 1) // 2 + np
me = nb // 2 + ne
print "YES" if mp > me else "NO"
| 1484499900 | [
"games",
"strings"
] | [
1,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["1.000000000000", "1.500000000000"] | 260666df22ee510fcce3ebdfbb8b71a2 | NoteIn the second example, the best scenario would be: one contestant fails at the first question, the other fails at the next one. The total reward will be $$$\displaystyle \frac{1}{2} + \frac{1}{1} = 1.5$$$ dollars. | 3R2 - Standby for ActionOur dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. $$$n$$$"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are $$$s$$$ ($$$s > 0$$$) opponents remaining and $$$t$$$ ($$$0 \le t \le s$$$) of them make a mistake on it, JOE receives $$$\displaystyle\frac{t}{s}$$$ dollars, and consequently there will be $$$s - t$$$ opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead? | Print a number denoting the maximum prize (in dollars) JOE could have. Your answer will be considered correct if it's absolute or relative error won't exceed $$$10^{-4}$$$. In other words, if your answer is $$$a$$$ and the jury answer is $$$b$$$, then it must hold that $$$\frac{|a - b|}{max(1, b)} \le 10^{-4}$$$. | The first and single line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), denoting the number of JOE's opponents in the show. | standard output | standard input | Python 3 | Python | 1,000 | train_001.jsonl | 1dd1189937de9239f23e95213123b5de | 256 megabytes | ["1", "2"] | PASSED | n = int(input())
num = n
cash = 0.0
for i in range(n):
if num!=0:
cash+=1/num
num-=1
print(cash)
| 1579440900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["0\n40\n41664916690999888"] | b4b69320c6040d2d264ac32e9ba5196f | null | You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases. | For each test case print the answer β the minimum number of moves needed to get all the figures into one cell. | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) β the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n < 5 \cdot 10^5$$$) β the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$). | standard output | standard input | PyPy 3 | Python | 1,000 | train_004.jsonl | f0dc0e065f9ba49f75d3876417fdeb92 | 256 megabytes | ["3\n1\n5\n499993"] | PASSED |
def fun():
n=int(input())
x=0
i=3
while(i<=n):
x=int((i*i-(i-2)*(i-2))*(i-1)/2+x)
i=i+2
print(x)
t=int(input())
i=0
for i in range(t):
fun()
| 1589466900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["3", "-1", "4"] | db5a99701dabe3516f97fd172118807e | NoteIn the first sample, the path with largest value is $$$1 \to 3 \to 4 \to 5$$$. The value is $$$3$$$ because the letter 'a' appears $$$3$$$ times. | You are given a graph with $$$n$$$ nodes and $$$m$$$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $$$3$$$. Your task is find a path whose value is the largest. | Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead. | The first line contains two positive integers $$$n, m$$$ ($$$1 \leq n, m \leq 300\,000$$$), denoting that the graph has $$$n$$$ nodes and $$$m$$$ directed edges. The second line contains a string $$$s$$$ with only lowercase English letters. The $$$i$$$-th character is the letter assigned to the $$$i$$$-th node. Then $$$m$$$ lines follow. Each line contains two integers $$$x, y$$$ ($$$1 \leq x, y \leq n$$$), describing a directed edge from $$$x$$$ to $$$y$$$. Note that $$$x$$$ can be equal to $$$y$$$ and there can be multiple edges between $$$x$$$ and $$$y$$$. Also the graph can be not connected. | standard output | standard input | PyPy 2 | Python | 1,700 | train_037.jsonl | ec63a955276c3bb781bee10661a10341 | 256 megabytes | ["5 4\nabaca\n1 2\n1 3\n3 4\n4 5", "6 6\nxzyabc\n1 2\n3 1\n2 3\n5 4\n4 3\n6 4", "10 14\nxzyzyzyzqx\n1 2\n2 4\n3 5\n4 5\n2 6\n6 8\n6 5\n2 10\n3 9\n10 9\n4 6\n1 10\n2 8\n3 7"] | PASSED | def dfs(dp,node,edges,s,visited):
stack = [node]
while stack:
node = stack[-1]
if node not in visited:
count = 0
for kid in edges[node]:
if kid in visited:
count += 1
stack.append(kid)
if count == len(edges[node]):
for kid in edges[node]:
for i in xrange(26):
dp[node][i] = max(dp[node][i],dp[kid][i])
dp[node][ord(s[node-1])-ord('a')] += 1
visited.add(node)
stack.pop()
else:
stack.pop()
def dfs2(edges,node,visited,recursion_stack):
stack = [node]
while stack:
node = stack[-1]
visited.add(node)
recursion_stack.add(node)
count = 0
for kid in edges[node]:
if kid not in visited:
stack.append(kid)
elif kid in recursion_stack:
return True
else:
count += 1
if count == len(edges[node]):
stack.pop()
recursion_stack.remove(node)
return False
def cycle(edges,n):
visited = set()
recursion_stack = set()
for i in xrange(1,n+1):
if i not in visited:
if dfs2(edges,i,visited,recursion_stack):
return True
return False
def main():
n,m = map(int,raw_input().split())
edges = {}
for i in xrange(1,n+1):
edges[i] = []
incoming = set()
for i in xrange(1,n+1):
incoming.add(i)
s = raw_input()
for i in xrange(m):
a,b = map(int,raw_input().split())
edges[a].append(b)
if b in incoming:
incoming.remove(b)
if cycle(edges,n):
print -1
return
dp = [[0 for i in xrange(26)] for j in xrange(n+1)]
visited = set()
for i in incoming:
if i not in visited:
dfs(dp,i,edges,s,visited)
ans = 0
for i in incoming:
ans = max(ans,max(dp[i]))
print ans
main()
| 1517403900 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2.5 seconds | ["1", "1"] | 31d95251cd79d889ff9f0a624ef31394 | NoteThe first example corresponds to the matrix: $$$11100111$$$ $$$11100111$$$ $$$11100111$$$ $$$00000000$$$ $$$00000000$$$ $$$11100111$$$ $$$11100111$$$ $$$11100111$$$ It is easy to see that the answer on this example is $$$1$$$. | You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Let's denote an $$$x$$$-compression of the given matrix as a matrix $$$B$$$ of size $$$\frac{n}{x} \times \frac{n}{x}$$$ such that for every $$$i \in [1, n], j \in [1, n]$$$ the condition $$$A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$$$ is met.Obviously, $$$x$$$-compression is possible only if $$$x$$$ divides $$$n$$$, but this condition is not enough. For example, the following matrix of size $$$2 \times 2$$$ does not have any $$$2$$$-compression: $$$01$$$ $$$10$$$ For the given matrix $$$A$$$, find maximum $$$x$$$ such that an $$$x$$$-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input. | Print one number: maximum $$$x$$$ such that an $$$x$$$-compression of the given matrix is possible. | The first line contains one number $$$n$$$ ($$$4 \le n \le 5200$$$) β the number of rows and columns in the matrix $$$A$$$. It is guaranteed that $$$n$$$ is divisible by $$$4$$$. Then the representation of matrix follows. Each of $$$n$$$ next lines contains $$$\frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are 1011, and if the number is $$$5$$$, then the corresponding elements are 0101. Elements are not separated by whitespaces. | standard output | standard input | PyPy 2 | Python | 1,800 | train_068.jsonl | 4f0295c75b98ab5e89f426ed61e45873 | 256 megabytes | ["8\nE7\nE7\nE7\n00\n00\nE7\nE7\nE7", "4\n7\nF\nF\nF"] | PASSED | import atexit, io, sys
# A stream implementation using an in-memory bytes
# buffer. It inherits BufferedIOBase.
buffer = io.BytesIO()
sys.stdout = buffer
# print via here
@atexit.register
def write():
sys.__stdout__.write(buffer.getvalue())
def gcd(a,b):
if(a>b):
temp=b
b=a
a=temp
if(a==0):
return b
else:
return gcd(b%a,a)
n=int(raw_input())
arr=[]
mindiff=10**9
ans=-1
flag=0
for i in range(n):
s=raw_input()
s1=''
j=0
while(j<len(s)):
if(65<=ord(s[j])<=70):
num=10+(ord(s[j])-65)
s1+=bin(num)[2:]
else:
num=bin(int(s[j]))[2:]
num=(4-len(num))*'0'+num
s1+=num
j+=1
initial=s1[0]
j=1
count=1
while(j<len(s1)):
if(s1[j]==initial):
count+=1
else:
if(ans==-1):
ans=count
else:
ans=gcd(ans,count)
count=1
initial=s1[j]
j+=1
if(ans==-1):
ans=count
else:
ans=gcd(ans,count)
arr.append(s1)
#print(*arr)
if(ans==1):
print(1)
exit(0)
for i in range(n):
initial=arr[0][i]
count=1
for j in range(1,n):
if(arr[j][i]==initial):
count+=1
else:
ans=gcd(ans,count)
count=1
initial=arr[j][i]
if(ans==1):
print(1)
exit(0)
ans=gcd(ans,count)
if(ans==1):
print(1)
exit(0)
print(ans) | 1548516900 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds | ["1\n5\n2"] | ab99c564f98bc6caea26b28280858c21 | NoteIn the first test case, $$$p^1 = p = [1, 3, 4, 2]$$$ and the sequence starting from $$$1$$$: $$$1, p[1] = 1, \dots$$$ is an infinite path.In the second test case, $$$p^5 = [1, 2, 3, 4, 5]$$$ and it obviously contains several infinite paths.In the third test case, $$$p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$$$ and the sequence starting from $$$4$$$: $$$4, p^2[4]=8, p^2[8]=4, \dots$$$ is an infinite path since $$$c_4 = c_8 = 4$$$. | You are given a colored permutation $$$p_1, p_2, \dots, p_n$$$. The $$$i$$$-th element of the permutation has color $$$c_i$$$.Let's define an infinite path as infinite sequence $$$i, p[i], p[p[i]], p[p[p[i]]] \dots$$$ where all elements have same color ($$$c[i] = c[p[i]] = c[p[p[i]]] = \dots$$$).We can also define a multiplication of permutations $$$a$$$ and $$$b$$$ as permutation $$$c = a \times b$$$ where $$$c[i] = b[a[i]]$$$. Moreover, we can define a power $$$k$$$ of permutation $$$p$$$ as $$$p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$$$.Find the minimum $$$k > 0$$$ such that $$$p^k$$$ has at least one infinite path (i.e. there is a position $$$i$$$ in $$$p^k$$$ such that the sequence starting from $$$i$$$ is an infinite path).It can be proved that the answer always exists. | Print $$$T$$$ integers β one per test case. For each test case print minimum $$$k > 0$$$ such that $$$p^k$$$ has at least one infinite path. | The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) β the number of test cases. Next $$$3T$$$ lines contain test cases β one per three lines. The first line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the size of the permutation. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, $$$p_i \neq p_j$$$ for $$$i \neq j$$$) β the permutation $$$p$$$. The third line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le n$$$) β the colors of elements of the permutation. It is guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,200 | train_024.jsonl | 4462e4f18351498791a6cf1b45513bdd | 256 megabytes | ["3\n4\n1 3 4 2\n1 2 2 3\n5\n2 3 4 5 1\n1 2 3 4 5\n8\n7 4 5 6 1 8 3 2\n5 3 6 4 7 5 8 4"] | PASSED | import sys
input = lambda: sys.stdin.readline().rstrip()
from math import sqrt
def primeFactor(n):
ret, i, d, sq = {}, 2, 2, int(sqrt(n)) + 1
while i < 4:
k = 0
while n % i == 0:
n, k = n//i, k+1
ret[i], sq = k, int(sqrt(n)) + 1
i = i * 2 - 1
while i <= sq:
k = 0
while n % i == 0:
n, k = n//i, k+1
ret[i], sq = k, int(sqrt(n)) + 1
i, d = i + d, d ^ 6
if n > 1: ret[n] = 1
return ret
def divisors(N):
pf = primeFactor(N)
ret = [1]
for p in pf:
prev = ret[:]
q = 1
for i in range(1, pf[p]+1):
q *= p
for r in prev:
ret.append(r * q)
return sorted(ret)
def chk(X):
n = len(X)
XX = X * 2
mi = 1 << 30
for d in divisors(n):
if d >= mi: break
for i in range(d):
for j in range(i, n+i, d):
if XX[j] != XX[j+d]:
break
else:
mi = min(mi, d)
return mi
T = int(input())
for _ in range(T):
N = int(input())
A = [int(a) - 1 for a in input().split()]
C = [int(a) - 1 for a in input().split()]
done = [0] * N
L = []
for i in range(N):
if done[i]: continue
t = [C[i]]
j = A[i]
while j != i:
t.append(C[j])
done[j] = 1
j = A[j]
L.append(t)
print(min([chk(a) for a in L])) | 1584974100 | [
"number theory",
"math",
"graphs"
] | [
0,
0,
1,
1,
1,
0,
0,
0
] |
|
3 seconds | ["YES\n1\n1\n0", "NO", "YES\n1\n2\n0", "YES\n1\n4\n1\n156"] | 0ef5e0621f13107d0c8786766ae2ac56 | null | Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di β the number of people in Berland in the year of i, then either diβ=β12diβ-β2, or diβ=β13diβ-β1β-β12diβ-β2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1,βa2,β...,βak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation. | On the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO. If the answer is YES, then you also have to print number k β the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers β a1,βa2,β...,βak. Those numbers have to be output in the increasing order. On the next line you should output number p β how many variants of the number of people could be in the years of a1,βa2,β...,βak, apart from the A variant. On each of the next p lines you have to print one number β the sought number of residents. Those number also have to go in the increasing order. If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order. The numbers should have no leading zeros. | The first line contains integer A (1ββ€βAβ<β10300). It is guaranteed that the number doesn't contain leading zeros. | standard output | standard input | Python 3 | Python | 2,600 | train_006.jsonl | 3c215cb03465bf6ce217e8bfe929c854 | 256 megabytes | ["2", "3", "13", "1729"] | PASSED | a = int(input())
ans = set()
def work(i, z, y):
z.add(y)
# print(">>", i, y)
if y == a:
ans.add(i)
if len(z) > 1000:
z.remove(max(z))
pos = [set(), set([2])]
for i in range(2):
for x in pos[i]:
if x == a:
ans.add(i)
def dfs(i, last, cur):
if i > 988:
return
while len(pos) - 1 < i:
pos.append(set())
if len(pos[i]) == 0 and cur > a:
return
if cur in pos[i]:
return
work(i, pos[i], cur)
dfs(i + 1, cur, last * 12)
dfs(i + 1, cur, cur * 13 - last * 12)
dfs(2, 2, 13)
if len(ans) == 0:
print("NO")
else:
print("YES")
count = 0
print(min(1000, len(ans)))
z = set()
for i in sorted(ans):
if count < 1000:
print(i)
count += 1
for y in pos[i]:
if y != a:
z.add(y)
if len(z) > 1000:
z.remove(max(z))
count = 0
print(min(1000, len(z)))
for i in sorted(z):
print(i)
count += 1
if count >= 1000:
break | 1288972800 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["2", "10"] | 3b42ca8bf066e9c5b6f5ff822cdc9214 | NoteThe first example can be solved by transposing the graph and moving the token to vertex $$$4$$$, taking $$$2$$$ seconds.The best way to solve the second example is the following: transpose the graph, move the token to vertex $$$2$$$, transpose the graph again, move the token to vertex $$$3$$$, transpose the graph once more and move the token to vertex $$$4$$$. | You are given a directed graph of $$$n$$$ vertices and $$$m$$$ edges. Vertices are numbered from $$$1$$$ to $$$n$$$. There is a token in vertex $$$1$$$.The following actions are allowed: Token movement. To move the token from vertex $$$u$$$ to vertex $$$v$$$ if there is an edge $$$u \to v$$$ in the graph. This action takes $$$1$$$ second. Graph transposition. To transpose all the edges in the graph: replace each edge $$$u \to v$$$ by an edge $$$v \to u$$$. This action takes increasingly more time: $$$k$$$-th transposition takes $$$2^{k-1}$$$ seconds, i.e. the first transposition takes $$$1$$$ second, the second one takes $$$2$$$ seconds, the third one takes $$$4$$$ seconds, and so on. The goal is to move the token from vertex $$$1$$$ to vertex $$$n$$$ in the shortest possible time. Print this time modulo $$$998\,244\,353$$$. | Print one integer: the minimum required time modulo $$$998\,244\,353$$$. | The first line of input contains two integers $$$n, m$$$ ($$$1 \le n, m \le 200\,000$$$). The next $$$m$$$ lines contain two integers each: $$$u, v$$$ ($$$1 \le u, v \le n; u \ne v$$$), which represent the edges of the graph. It is guaranteed that all ordered pairs $$$(u, v)$$$ are distinct. It is guaranteed that it is possible to move the token from vertex $$$1$$$ to vertex $$$n$$$ using the actions above. | standard output | standard input | Python 3 | Python | 2,400 | train_020.jsonl | ac9b1fe8dc6cbe624a860dabccc1da64 | 512 megabytes | ["4 4\n1 2\n2 3\n3 4\n4 1", "4 3\n2 1\n2 3\n4 3"] | PASSED | from heapq import heappush, heappop;mod = 998244353;N, M = map(int, input().split());E1 = [[] for _ in range(N)];E2 = [[] for _ in range(N)]
for _ in range(M):u, v = map(int, input().split());u -= 1;v -= 1;E1[u].append(v);E2[v].append(u)
mask1 = (1<<23) - 1;mask2 = (1<<18) - 1;inf = 1<<62;dist = [inf] * (1<<23);start = 0;dist[start] = 0;q = [start]
while q:
v = heappop(q); dist_v = v >> 23; v &= mask1; n_trans = v >> 18; v_node = v & mask2
if v_node == N-1: print(dist_v % mod); exit()
if n_trans > 20: break
if dist[v] != dist_v: continue
for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]):
u = n_trans<<18 | u_node; dist_u = dist_v + 1
if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<23 | u)
u = n_trans+1<<18 | v_node; dist_u = dist_v + (1<<n_trans)
if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<23 | u)
mask1 = (1<<37) - 1;mask2 = (1<<19) - 1;mask3 = (1<<18)-1;REV = 1<<18;dist = [inf] * (1<<19);start = 0;dist[start] = 0;q = [start]
while q:
v = heappop(q);dist_v = v >> 19;n_trans = dist_v >> 18;v &= mask2;v_node = v & mask3
if v_node == N-1:ans = pow(2, n_trans, mod) - 1 + (dist_v&mask3);print(ans);exit()
rev = v & REV
if dist[v] != dist_v: continue
for u_node in (E1[v_node] if n_trans&1==0 else E2[v_node]):
u = rev | u_node; dist_u = dist_v + 1
if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<19 | u)
u = v ^ REV; dist_u = dist_v + (1<<18)
if dist_u < dist[u]: dist[u] = dist_u; heappush(q, dist_u<<19 | u)
assert False | 1604327700 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["8 4 2 1 \n5 2 1 3 4 5 5 \n101 1 \n4 3 2 2 3 4 \n7 1 4 2 3 4 5 1"] | 64458fc3c2bf40ca911b566092f544e8 | null | You are given an array $$$a$$$ consisting of $$$n$$$ nonnegative integers. Let's define the prefix OR array $$$b$$$ as the array $$$b_i = a_1~\mathsf{OR}~a_2~\mathsf{OR}~\dots~\mathsf{OR}~a_i$$$, where $$$\mathsf{OR}$$$ represents the bitwise OR operation. In other words, the array $$$b$$$ is formed by computing the $$$\mathsf{OR}$$$ of every prefix of $$$a$$$.You are asked to rearrange the elements of the array $$$a$$$ in such a way that its prefix OR array is lexicographically maximum.An array $$$x$$$ is lexicographically greater than an array $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, $$$x_i > y_i$$$. | For each test case print $$$n$$$ integers β any rearrangement of the array $$$a$$$ that obtains the lexicographically maximum prefix OR array. | The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) β the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ nonnegative integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,500 | train_099.jsonl | 309763d395e83373324228c487df8ea2 | 256 megabytes | ["5\n\n4\n\n1 2 4 8\n\n7\n\n5 1 2 3 4 5 5\n\n2\n\n1 101\n\n6\n\n2 3 4 2 3 4\n\n8\n\n1 4 2 3 4 5 7 1"] | PASSED | import sys
input = lambda: sys.stdin.readline().rstrip()
# ----------------------- #
def main():
n = int(input())
A = tuple(map(int, input().split()))
B = []
seen = [False] * n
ok_bit = set()
for i in range(29, -1, -1):
if i in ok_bit:
continue
bits = [[a, j] for j, a in enumerate(A) if a >> i & 1]
for j in ok_bit:
for k in range(len(bits)):
bits[k][0] &= ~(1<<j)
for a, v in sorted(bits, key=lambda x: bin(x[0]))[::-1]:
if a >> i & 1 == 0:
break
if seen[v]:
continue
B.append(A[v])
for k in range(A[v].bit_length()):
if A[v] >> k & 1:
ok_bit.add(k)
seen[v] = True
break
B.extend([A[i] for i in range(n) if not seen[i]])
return ' '.join(map(str, B))
print('\n'.join(str(main()) for _ in range(int(input()))))
| 1665671700 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["10", "996"] | 1d58ae45a677023dc8fd6c9473a89737 | NoteFor the first test, two examples of good subsequences are $$$[2, 7]$$$ and $$$[2, 2, 4, 7]$$$:For $$$b = [2, 7]$$$ we can use $$$(-3, -4)$$$ as the first sequence and $$$(-2, -1, \ldots, 4)$$$ as the second. Note that subsequence $$$[2, 7]$$$ appears twice in $$$[2, 2, 4, 7]$$$, so we have to count it twice. Green circles denote $$$(-3, -4)$$$ and orange squares denote $$$(-2, -1, \ldots, 4)$$$. For $$$b = [2, 2, 4, 7]$$$ the following sequences would satisfy the properties: $$$(-1, 0)$$$, $$$(-3, -2)$$$, $$$(0, 1, 2, 3)$$$ and $$$(-3, -2, \ldots, 3)$$$ | Lee couldn't sleep lately, because he had nightmares. In one of his nightmares (which was about an unbalanced global round), he decided to fight back and propose a problem below (which you should solve) to balance the round, hopefully setting him free from the nightmares.A non-empty array $$$b_1, b_2, \ldots, b_m$$$ is called good, if there exist $$$m$$$ integer sequences which satisfy the following properties: The $$$i$$$-th sequence consists of $$$b_i$$$ consecutive integers (for example if $$$b_i = 3$$$ then the $$$i$$$-th sequence can be $$$(-1, 0, 1)$$$ or $$$(-5, -4, -3)$$$ but not $$$(0, -1, 1)$$$ or $$$(1, 2, 3, 4)$$$). Assuming the sum of integers in the $$$i$$$-th sequence is $$$sum_i$$$, we want $$$sum_1 + sum_2 + \ldots + sum_m$$$ to be equal to $$$0$$$. You are given an array $$$a_1, a_2, \ldots, a_n$$$. It has $$$2^n - 1$$$ nonempty subsequences. Find how many of them are good.As this number can be very large, output it modulo $$$10^9 + 7$$$.An array $$$c$$$ is a subsequence of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements. | Print a single integerΒ β the number of nonempty good subsequences of $$$a$$$, modulo $$$10^9 + 7$$$. | The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β β the size of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. | standard output | standard input | PyPy 3-64 | Python | 2,000 | train_085.jsonl | a8a6ae1c973ecdb434f85d251e5d1b11 | 256 megabytes | ["4\n2 2 4 7", "10\n12391240 103904 1000000000 4142834 12039 142035823 1032840 49932183 230194823 984293123"] | PASSED | import sys
input = sys.stdin.readline
n = int(input().split('\n')[0])
a = [int(x) for x in input().split()]
o = [x for x in a if x%2 == 1]
e = [x for x in a if x%2 == 0]
ans = 0
ans += 2**(len(e))*(2**(len(o))-1)
while len(e)>=2:
o = [x//2 for x in e if (x//2)%2==1]
e = [x//2 for x in e if (x//2)%2==0]
ans += 2**(len(e))*(2**max(0, len(o)-1)-1)
print(ans%(10**9+7)) | 1637678100 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["2.000000000000000000", "0.500000000000000000", "3.333333333333333333"] | 7bdd8f0cf42855bebda4ccc56d8fe788 | NoteIn the first example it is necessary to put weights like this: It is easy to see that the diameter of this tree is $$$2$$$. It can be proved that it is the minimum possible diameter.In the second example it is necessary to put weights like this: | You are given a tree (an undirected connected graph without cycles) and an integer $$$s$$$.Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $$$s$$$. At the same time, he wants to make the diameter of the tree as small as possible.Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.Find the minimum possible diameter that Vanya can get. | Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $$$s$$$. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. 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)} \leq 10^{-6}$$$. | The first line contains two integer numbers $$$n$$$ and $$$s$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq s \leq 10^9$$$) β the number of vertices in the tree and the sum of edge weights. Each of the following $$$nβ1$$$ lines contains two space-separated integer numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) β the indexes of vertices connected by an edge. The edges are undirected. It is guaranteed that the given edges form a tree. | standard output | standard input | Python 3 | Python | 1,700 | train_019.jsonl | b693d62494d48d4dac2458e83a325761 | 256 megabytes | ["4 3\n1 2\n1 3\n1 4", "6 1\n2 1\n2 3\n2 5\n5 4\n5 6", "5 5\n1 2\n2 3\n3 4\n3 5"] | PASSED | n,s = [int(x) for x in input().split()]
v=[ [] ]
for i in range(n):
v.append([])
for i in range(n-1):
a, b =[int(x) for x in input().split()]
v[a].append(b)
v[b].append(a)
ans =0
for i in range(1,n+1):
if len(v[i])==1:
ans+=1
print(2*s/ans)
| 1545572100 | [
"trees"
] | [
0,
0,
0,
0,
0,
0,
0,
1
] |
|
3 seconds | ["YES\n2 1\n2 3\n3 4", "YES\n1 2\n1 3\n4 1", "NO"] | 0cfaaa70b7990e4f170eb397cd8756f8 | NoteThe picture corresponding to the first and second examples: The picture corresponding to the third example: | You are given an undirected unweighted connected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.Your task is to find any spanning tree of this graph such that the degree of the first vertex (vertex with label $$$1$$$ on it) is equal to $$$D$$$ (or say that there are no such spanning trees). Recall that the degree of a vertex is the number of edges incident to it. | If there is no spanning tree satisfying the condition from the problem statement, print "NO" in the first line. Otherwise print "YES" in the first line and then print $$$n-1$$$ lines describing the edges of a spanning tree such that the degree of the first vertex (vertex with label $$$1$$$ on it) is equal to $$$D$$$. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge $$$(v, u)$$$ is considered the same as the edge $$$(u, v)$$$). If there are multiple possible answers, print any of them. | The first line contains three integers $$$n$$$, $$$m$$$ and $$$D$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2}), 1 \le D < n$$$) β the number of vertices, the number of edges and required degree of the first vertex, respectively. The following $$$m$$$ lines denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i.βe. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the list of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. | standard output | standard input | PyPy 2 | Python | 1,900 | train_006.jsonl | 22953516921e89fcc3812eb5129415a5 | 256 megabytes | ["4 5 1\n1 2\n1 3\n1 4\n2 3\n3 4", "4 5 3\n1 2\n1 3\n1 4\n2 3\n3 4", "4 4 3\n1 2\n1 4\n2 3\n3 4"] | PASSED | from sys import stdin
from io import BytesIO
class disjointset:
def __init__(self, n):
self.rank, self.parent, self.n = [0] * (n + 1), [i for i in range(n + 1)], n
def find(self, x):
xcopy = x
while x != self.parent[x]:
x = self.parent[x]
while xcopy != x:
self.parent[xcopy], xcopy = x, self.parent[xcopy]
return x
def union(self, x, y):
xpar, ypar = self.find(x), self.find(y)
# already union
if xpar == ypar:
return -1
# perform union by rank
par, child = xpar, ypar
if self.rank[xpar] < self.rank[ypar]:
par, child = ypar, xpar
elif self.rank[xpar] == self.rank[ypar]:
self.rank[xpar] += 1
self.parent[child] = par
self.n -= 1
out.append([x, y])
# find min total weight tree
def kruskal(self):
result = ['YES']
# loop over v-1
for i in range(len(out) - 1, -1, -1):
u, v = out[i]
upar, vpar = self.find(u), self.find(v)
# no cycle
if upar != vpar:
result.append('%d %d' % (u, v))
self.union(upar, vpar)
# print MST
print('\n'.join(result))
stdin = BytesIO(stdin.read())
rints = lambda: [int(x) for x in stdin.readline().split()]
n, m, d = rints()
dis, edges, out = disjointset(n), [], []
for _ in range(m):
u, v = rints()
if u == 1 or v == 1:
edges.append([u, v])
else:
dis.union(u, v)
if d < dis.n - 1 or len(edges) < d:
print('NO')
else:
ext = []
for u, v in edges:
if dis.union(u, v) == -1:
ext.append([u, v])
else:
d -= 1
out += ext[:d]
dis1 = disjointset(n)
dis1.kruskal()
| 1551971100 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["NO\nNO\nNO\nYES\nYES\nYES\nYES\nNO"] | b3c08abbaeec9ecbcc71fe34336d039a | null | A wild basilisk just appeared at your doorstep. You are not entirely sure what a basilisk is and you wonder whether it evolved from your favorite animal, the weasel. How can you find out whether basilisks evolved from weasels? Certainly, a good first step is to sequence both of their DNAs. Then you can try to check whether there is a sequence of possible mutations from the DNA of the weasel to the DNA of the basilisk. Your friend Ron is a talented alchemist and has studied DNA sequences in many of his experiments. He has found out that DNA strings consist of the letters A, B and C and that single mutations can only remove or add substrings at any position in the string (a substring is a contiguous sequence of characters). The substrings that can be removed or added by a mutation are AA, BB, CC, ABAB or BCBC. During a sequence of mutations a DNA string may even become empty.Ron has agreed to sequence the DNA of the weasel and the basilisk for you, but finding out whether there is a sequence of possible mutations that leads from one to the other is too difficult for him, so you have to do it on your own. | For each test case, print YES if there is a sequence of mutations to get from $$$u$$$ to $$$v$$$ and NO otherwise. | Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 100$$$) β the number of test cases. The descriptions of the $$$t$$$ test cases follow. The first line of each test case contains a string $$$u$$$ ($$$1\le |u|\le 200$$$) β the DNA of the weasel. The second line of each test case contains a string $$$v$$$ ($$$1\le |v|\le 200$$$) β the DNA of the basilisk. The values $$$|u|$$$, $$$|v|$$$ denote the lengths of the strings $$$u$$$ and $$$v$$$. It is guaranteed that both strings $$$u$$$ and $$$v$$$ consist of the letters A, B and C. | standard output | standard input | PyPy 3 | Python | -1 | train_085.jsonl | 26b502e1ada23435d429648113436a7f | 256 megabytes | ["8\n\nA\n\nB\n\nB\n\nC\n\nC\n\nA\n\nAA\n\nBB\n\nBB\n\nCC\n\nCC\n\nAA\n\nABAB\n\nBCBC\n\nABC\n\nCBA"] | PASSED |
strings = ['AA', 'BB', 'CC', 'ABAB', 'BCBC']
reduction = [['AA', ''], ['BB', ''], ['CC', ''], ['ABAB', ''], ['BCBC', ''],
['CB', 'BC'], ['AB', 'BA']] # move all Bs left
# def simulator():
# s = 'CA'
# # get all possible outcomes from s
# l = len(s)
# vi = set()
# vi.add(s)
# st = [s]
# while st:
# s = st.pop()
# n = len(s)
# for s2 in strings:
# for i in range(n + 1):
# # remove
# if s[i: i + len(s2)] == s2:
# s3 = s[:i] + s[i + len(s2):]
# if s3 not in vi:
# st.append(s3)
# vi.add(s3)
# # add
# s3 = s[: i] + s2 + s[i:]
# # if s3 == 'ABAB':
# # print('s2:{}'.format(s2))
# if len(s3) <= l + 8 and s3 not in vi:
# st.append(s3)
# vi.add(s3)
# for s in vi:
# if len(s) <= l + 2:
# print(s)
# simulator()
def reduce_string(s):
changed = 1
while changed == 1:
changed = 0
for complex_form, reduced_form in reduction:
if complex_form in s:
s = s.replace(complex_form, reduced_form)
changed = 1
return s
def main():
T = int(input())
allans = []
for _ in range(T):
s = input()
t = input()
s2 = reduce_string(s)
t2 = reduce_string(t)
# print('s:{} t:{} s2:{} t2:{}'.format(s, t, s2, t2))
if s2 == t2:
ans = 'YES'
else:
ans = 'NO'
allans.append(ans)
multiLineArrayPrint(allans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
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')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | 1650798300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["1", "-1", "0.666667"] | ffafd385ec79aa28b8d30224baf6bcfe | NoteIn the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.In the second example, there are not enough players.In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team. | As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si β how many students who play basketball belong to this department.Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other. | Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10β-β6. | The first line contains three integers n, m and h (1ββ€βnββ€β100,β1ββ€βmββ€β1000,β1ββ€βhββ€βm) β the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly. The second line contains a single-space-separated list of m integers si (1ββ€βsiββ€β100), denoting the number of students in the i-th department. Note that sh includes Herr Wafa. | standard output | standard input | Python 2 | Python | 1,600 | train_022.jsonl | cb1224ae076041cad9c68790088ed1d2 | 256 megabytes | ["3 2 1\n2 1", "3 2 1\n1 1", "3 2 1\n2 2"] | PASSED | from fractions import *
def C(n, k):
res = 1
for i in xrange(1, k+1):
res = res*(n-i+1)/i
return res
def calc(a, b, n):
s = a + b
if s < n:
return -1
if b == 0:
return 0
good = 0
for i in xrange(0, min(a+1, n)):
good += C(a, i)*C(b, n-i)
return float(Fraction(good, C(s, n)))
n, m, h = map(int, raw_input().split(' '))
c = map(int, raw_input().split(' '))
print calc(sum(c)-c[h-1], c[h-1]-1, n-1) | 1314111600 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
4 seconds | ["Yes\n3 2\n1 3", "Yes\n1 3\n5 7\n3 2\n7 4\n2 4\n6 1"] | 40720fb6da02d5da97df2b90719c5559 | null | You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains nβ-β1 edges and can be obtained by removing some of the edges from G.The degree of a vertex is the number of edges incident to this vertex. | If the answer doesn't exist print "No" (without quotes) in the only line of the output. Otherwise, in the first line print "Yes" (without quotes). In the each of the next (nβ-β1) lines print two integers β the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them. | The first line of the input contains two integers n and m (2ββ€βnββ€β200β000, 1ββ€βmββ€βmin(400β000,βnΒ·(nβ-β1)β/β2))Β β the number of vertices and the number of edges in the graph. The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1ββ€βu,βvββ€βn, uββ βv)Β β the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers s, t, ds, dt (1ββ€βs,βtββ€βn, sββ βt, 1ββ€βds,βdtββ€βnβ-β1). | standard output | standard input | Python 2 | Python | 2,300 | train_041.jsonl | de58341e427c6aace0631df40ebec0df | 256 megabytes | ["3 3\n1 2\n2 3\n3 1\n1 2 1 1", "7 8\n7 4\n1 3\n5 4\n5 7\n3 2\n2 4\n6 1\n1 2\n6 4 1 4"] | PASSED | n, m = map(int, raw_input().split(" "))
edge = (map(int, raw_input().split(" ")) for i in xrange(m))
mapuv = [[] for i in xrange(n + 1)]
for u, v in edge:
mapuv[u].append(v)
mapuv[v].append(u)
#print mapuv
s, t, ds, dt = map(int, raw_input().split(" "))
colors = [-1 for i in xrange(n + 1)]
total_color = 0
ans = []
def dfs(u, color):
q = [u]
colors[u] = color
while q:
u = q.pop()
for v in mapuv[u]:
if v in (s, t):
continue
if colors[v] == -1:
colors[v] = color
ans.append((u, v))
q.append(v)
for u in xrange(1, n + 1):
if u in (s, t):
continue
if colors[u] == -1:
dfs(u, total_color)
total_color += 1
#print ans
#print colors
color_to_s = [-1 for i in xrange(total_color)]
color_to_t = [-1 for i in xrange(total_color)]
issct = False
issct_now = False
for v in mapuv[s]:
if v in (s, t):
issct = True
continue
color_to_s[colors[v]] = v
#print color_to_s
for v in mapuv[t]:
if v in (s, t):
issct = True
continue
color_to_t[colors[v]] = v
#print color_to_t
for i in xrange(total_color):
if color_to_s[i] > 0:
if color_to_t[i] == -1:
ans.append((s, color_to_s[i]))
ds -= 1
elif color_to_t[i] > 0:
ans.append((t, color_to_t[i]))
dt -= 1
#print ans
for i in xrange(total_color):
if color_to_s[i] > 0 and color_to_t[i] > 0:
if not issct_now:
ans.append((s, color_to_s[i]))
ans.append((t, color_to_t[i]))
issct_now = True
dt -= 1
ds -= 1
elif dt > ds:
dt -= 1
ans.append((t, color_to_t[i]))
else:
ds -= 1
ans.append((s, color_to_s[i]))
#print ans
if not issct_now:
ans.append((s, t))
ds -= 1
dt -= 1
if ds >= 0 and dt >= 0:
print 'Yes'
for u, v in ans:
print u, v
else:
print 'No'
#print ans
| 1475494500 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds | ["5.0000000000"] | 979e1b735d1c152d01955e27ee8d0b8a | NoteFollowing image describes initial position in the first sample case: | And while Mishka is enjoying her trip...Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.Once walking with his friend, John gave Chris the following problem:At the infinite horizontal road of width w, bounded by lines yβ=β0 and yβ=βw, there is a bus moving, presented as a convex polygon of n vertices. The bus moves continuously with a constant speed of v in a straight Ox line in direction of decreasing x coordinates, thus in time only x coordinates of its points are changing. Formally, after time t each of x coordinates of its points will be decreased by vt.There is a pedestrian in the point (0,β0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0,β0) and (0,βw) with any speed not exceeding u. Thus the pedestrian can move only in a straight line Oy in any direction with any speed not exceeding u and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.Please look at the sample note picture for better understanding.We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0,βw) and not to be hit by the bus. | Print the single real tΒ β the time the pedestrian needs to croos the road and not to be hit by the bus. The answer is considered correct if its relative or absolute error doesn't exceed 10β-β6. | The first line of the input contains four integers n, w, v, u (3ββ€βnββ€β10β000, 1ββ€βwββ€β109, 1ββ€βv,ββuββ€β1000)Β β the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively. The next n lines describes polygon vertices in counter-clockwise order. i-th of them contains pair of integers xi and yi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€βw)Β β coordinates of i-th polygon point. It is guaranteed that the polygon is non-degenerate. | standard output | standard input | Python 2 | Python | 2,100 | train_059.jsonl | 997f6f1659afdef199bae92a9522756c | 256 megabytes | ["5 5 1 2\n1 2\n3 1\n4 3\n3 4\n1 4"] | PASSED | n,w,v,u = map(int,raw_input().split(' '))
later = []
flag = True
for i in range(n):
p = map(int,raw_input().split(' '))
if p[0] >= 0:
reach = p[0]/float(v)
if p[1] > u*reach:
flag = False
if p[1] <= u*reach:
later.append((reach,p[1]))
if p[0] < 0:
flag = False
later.sort(key=lambda x:x[1])
if flag:
print w/float(u)
else:
current_t = 0
current_p = 0
for t,p in later:
if (t-current_t)*u > (p-current_p):
current_p = p
current_t = t
print current_t + (w-current_p)/float(u)
| 1470323700 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second | ["Mike\nJoe"] | 0a187d80fdc3df579909840e9111ac7e | NoteIn the first test case, Mike just takes all $$$37$$$ stones on his first turn.In the second test case, Joe can just copy Mike's moves every time. Since Mike went first, he will hit $$$0$$$ on the first pile one move before Joe does so on the second pile. | Mike and Joe are playing a game with some stones. Specifically, they have $$$n$$$ piles of stones of sizes $$$a_1, a_2, \ldots, a_n$$$. These piles are arranged in a circle.The game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile $$$1$$$. Formally, if a player removed stones from pile $$$i$$$ on a turn, the other player removes stones from pile $$$((i\bmod n) + 1)$$$ on the next turn.If a player cannot remove any stones on their turn (because the pile is empty), they lose. Mike goes first.If Mike and Joe play optimally, who will win? | For each test case print the winner of the game, either "Mike" or "Joe" on its own line (without quotes). | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) Β β the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) Β β the size of the piles. | standard output | standard input | Python 3 | Python | 1,000 | train_089.jsonl | a67d50e5bc9c80d7addf97de7762ab8a | 256 megabytes | ["2\n\n1\n\n37\n\n2\n\n100 100"] | PASSED | t = int(input())
ar = [[] for i in range(t)]
p1, p2 = 'Mike', 'Joe'
for i in range(t):
n = int(input())
ar[i] += [int(o) for o in input().split()]
for i in range(t):
if (len(ar[i]) % 2 == 1):
print("Mike")
else:
smallest = 0
for j in range(len(ar[i])):
if (ar[i][j] < ar[i][smallest]):
smallest = j
# print(smallest)
if (smallest % 2 == 0):
print("Joe")
else:
print("Mike")
# if (sum([s for s in ar[i][::2]]) > sum([s for s in ar[i][1::2]])):
# print("Mike\n")
# else:
# print("Joe\n")
| 1655562900 | [
"games"
] | [
1,
0,
0,
0,
0,
0,
0,
0
] |
|
7 seconds | ["5927", "24812", "25267"] | 88607047027bab73ea56352969b02242 | NoteIn the first example, any two events form a line, and the table will be winning if any two events happen. The probability of this is $$$\frac{11}{16}$$$, and $$$5927 \cdot 16 \equiv 11 \pmod{31\,607}$$$. | Getting ready for VK Fest 2021, you prepared a table with $$$n$$$ rows and $$$n$$$ columns, and filled each cell of this table with some event related with the festival that could either happen or not: for example, whether you will win a prize on the festival, or whether it will rain.Forecasting algorithms used in VK have already estimated the probability for each event to happen. Event in row $$$i$$$ and column $$$j$$$ will happen with probability $$$a_{i, j} \cdot 10^{-4}$$$. All of the events are mutually independent.Let's call the table winning if there exists a line such that all $$$n$$$ events on it happen. The line could be any horizontal line (cells $$$(i, 1), (i, 2), \ldots, (i, n)$$$ for some $$$i$$$), any vertical line (cells $$$(1, j), (2, j), \ldots, (n, j)$$$ for some $$$j$$$), the main diagonal (cells $$$(1, 1), (2, 2), \ldots, (n, n)$$$), or the antidiagonal (cells $$$(1, n), (2, n - 1), \ldots, (n, 1)$$$).Find the probability of your table to be winning, and output it modulo $$$31\,607$$$ (see Output section). | Print the probability that your table will be winning, modulo $$$31\,607$$$. Formally, let $$$M = 31\,607$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | The first line contains a single integer $$$n$$$Β ($$$2 \le n \le 21$$$)Β β the dimensions of the table. The $$$i$$$-th of the next $$$n$$$ lines contains $$$n$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, n}$$$ ($$$0 < a_{i, j} < 10^4$$$). The probability of event in cell $$$(i, j)$$$ to happen is $$$a_{i, j} \cdot 10^{-4}$$$. | standard output | standard input | PyPy 3 | Python | 2,600 | train_105.jsonl | 5ebb98f747554df336d581b08b363fe3 | 512 megabytes | ["2\n5000 5000\n5000 5000", "2\n2500 6000\n3000 4000", "3\n1000 2000 3000\n4000 5000 6000\n7000 8000 9000"] | PASSED | import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
def cmb(n, r, mod):
if r < 0 or r > n:return 0
r = min(r, n-r);return g1[n] * g2[r] * g2[n-r] % mod
mod = 31607;N = 31606;g1 = [1]*(N+1);g2 = [1]*(N+1);inverse = [1]*(N+1)
for i in range(2, N + 1):g1[i] = ((g1[i-1]*i) % mod);inverse[i] = ((-inverse[mod % i]*(mod//i)) % mod);g2[i] = ((g2[i-1]*inverse[i]) % mod)
inverse[0]=0;ans = 1;N = int(input());A = [list(map(int,input().split())) for i in range(N)];P = [1 for i in range(N)];Q = [1 for j in range(N)]
for i in range(N):
for j in range(N):A[i][j] *= inverse[10**4];A[i][j] %= mod
for i in range(N):
for j in range(N):P[i] *= A[i][j];P[i] %= mod;Q[j] *= A[i][j];Q[j] %= mod
res = 0;tmp = [1 for j in range(1<<N)];bit_prod = [0]*(1<<N)
for j in range(1<<N):
for i in range(N):
if j>>i & 1:tmp[j] = (-tmp[j]) * Q[i] % mod
for i in range(N):
bit_prod[0] = P[i];tmp[0] = tmp[0] * (1-bit_prod[0]) % mod
for n in range(N):
for j in range(2**n,2**(n+1)):bit_prod[j] = bit_prod[j-2**n] * inverse[A[i][n]] % mod;tmp[j] = tmp[j] * (1-bit_prod[j]) % mod
ans -= (sum([tmp[j] for j in range(1<<N)]) % mod);ans %= mod;P = [1 for i in range(N)];Q = [1 for j in range(N)];R = 1
for i in range(N):
for j in range(N):
if j != i:P[i] *= A[i][j];P[i] %= mod
if j != i:Q[j] *= A[i][j];Q[j] %= mod
else:R *= A[i][j];R %= mod
res = 0;tmp = [R for j in range(1<<N)]
for j in range(1<<N):
for i in range(N):
if j>>i & 1:tmp[j] = (-tmp[j]) * Q[i] % mod
for i in range(N):
bit_prod[0] = P[i];tmp[0] = tmp[0] * (1-bit_prod[0]) % mod
for n in range(N):
for j in range(2**n,2**(n+1)):bit_prod[j] = (bit_prod[j-2**n] * inverse[A[i][n]] % mod if n != i else bit_prod[j-2**n] % mod);tmp[j] = tmp[j] * (1-bit_prod[j]) % mod
ans += (sum([tmp[j] for j in range(1<<N)]) % mod);ans %= mod;P = [1 for i in range(N)];Q = [1 for j in range(N)];R = 1
for i in range(N):
for j in range(N):
if j != N-1-i:P[i] *= A[i][j];P[i] %= mod
if j != N-1-i:Q[j] *= A[i][j];Q[j] %= mod
else:R *= A[i][j];R %= mod
res = 0;tmp = [R for j in range(1<<N)]
for j in range(1<<N):
for i in range(N):
if j>>i & 1:tmp[j] = (-tmp[j]) * Q[i] % mod
for i in range(N):
bit_prod[0] = P[i];tmp[0] = tmp[0] * (1-bit_prod[0]) % mod
for n in range(N):
for j in range(2**n,2**(n+1)):bit_prod[j] = (bit_prod[j-2**n] * inverse[A[i][n]] % mod if n != N-1-i else bit_prod[j-2**n] % mod);tmp[j] = tmp[j] * (1-bit_prod[j]) % mod
ans += (sum([tmp[j] for j in range(1<<N)]) % mod);ans %= mod;P = [1 for i in range(N)];Q = [1 for j in range(N)];R = 1
for i in range(N):
for j in range(N):
if j != N-1-i and j != i:P[i] *= A[i][j];P[i] %= mod
if j != N-1-i and j != i:Q[j] *= A[i][j];Q[j] %= mod
else:R *= A[i][j];R %= mod
res = 0;tmp = [R for j in range(1<<N)]
for j in range(1<<N):
for i in range(N):
if j>>i & 1:tmp[j] = (-tmp[j]) * Q[i] % mod
for i in range(N):
bit_prod[0] = P[i];tmp[0] = tmp[0] * (1-bit_prod[0]) % mod
for n in range(N):
for j in range(2**n,2**(n+1)):bit_prod[j] = (bit_prod[j-2**n] * inverse[A[i][n]] % mod if n != N-1-i and n != i else bit_prod[j-2**n] % mod);tmp[j] = tmp[j] * (1-bit_prod[j]) % mod
ans -= (sum([tmp[j] for j in range(1<<N)]) % mod);print(ans%mod) | 1626532500 | [
"probabilities",
"math"
] | [
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1 second | ["8\n11\n19\n1\n3999999999987"] | 2a4f4c91522d83bc8f1ca2f086d24c3c | NoteFor $$$n = 5$$$ we calculate unfairness of the following sequence (numbers from $$$0$$$ to $$$5$$$ written in binary with extra leading zeroes, so they all have the same length): $$$000$$$ $$$001$$$ $$$010$$$ $$$011$$$ $$$100$$$ $$$101$$$ The differences are equal to $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$ respectively, so unfairness is equal to $$$1 + 2 + 1 + 3 + 1 = 8$$$. | The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $$$5 = 101_2$$$ and $$$14 = 1110_2$$$ equals to $$$3$$$, since $$$0101$$$ and $$$1110$$$ differ in $$$3$$$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $$$0$$$ to $$$n$$$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers. | Output $$$t$$$ lines. For each test case, you should output a single line with one integerΒ β the unfairness of the contest if the rating sequence equals to $$$0$$$, $$$1$$$, ..., $$$n - 1$$$, $$$n$$$. | The input consists of multiple test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$)Β β the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{18})$$$. | standard output | standard input | PyPy 3 | Python | 1,400 | train_002.jsonl | 82ef88cc10c290a6b20ff966fae3efdf | 256 megabytes | ["5\n5\n7\n11\n1\n2000000000000"] | PASSED | t = int(input())
for iteration in range(0, t):
n = int(input())
res = 0
for _pow in range(0, 65):
if (n + 1) % (1 << _pow) == 0:
res += (n + 1) // (1 << _pow) - 1
else:
res += (n + 1) // (1 << _pow)
print(res)
| 1591281300 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["6 7\n14 21\n2 4\n-1 -1"] | e8ba3fb95800806465386ecbfbe924e9 | null | Let $$$LCM(x, y)$$$ be the minimum positive integer that is divisible by both $$$x$$$ and $$$y$$$. For example, $$$LCM(13, 37) = 481$$$, $$$LCM(9, 6) = 18$$$.You are given two integers $$$l$$$ and $$$r$$$. Find two integers $$$x$$$ and $$$y$$$ such that $$$l \le x < y \le r$$$ and $$$l \le LCM(x, y) \le r$$$. | For each test case, print two integers: if it is impossible to find integers $$$x$$$ and $$$y$$$ meeting the constraints in the statement, print two integers equal to $$$-1$$$; otherwise, print the values of $$$x$$$ and $$$y$$$ (if there are multiple valid answers, you may print any of them). | The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) β the number of test cases. Each test case is represented by one line containing two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$). | standard output | standard input | Python 3 | Python | 800 | train_003.jsonl | 66d97768b57188dcf4a32970c11aec51 | 256 megabytes | ["4\n1 1337\n13 69\n2 4\n88 89"] | PASSED |
# def hcf(a,b):
# if(b==0):
# return a
# else:
# return hcf(b,a%b)
#
#
# def lcm(a,b):
# return (a*b)//hcf(a,b)
#
# x=int(input())
# for i in range(x):
# a,b=map(int,input().split())
# for i in range(a,b+1):
# for j in range(a+1,b+1):
# if(lcm(i,j)*2<=r):
# print(lcm(i,j),lcm(i,j)*2)
# break
# else:
# print('-1 -1')
# break
#
# # # Two separate lists
# # cars = ["Aston", "Audi", "McLaren"]
# # accessories = ["GPS kit", "Car repair-tool kit"]
# #
# # # Single dictionary holds prices of cars and
# # # its accessories.
# # # First three items store prices of cars and
# # # next two items store prices of accessories.
# # prices = {1:"570000$", 2:"68000$", 3:"450000$",
# # 4:"8900$", 5:"4500$"}
# #
# # # Printing prices of cars
# # for index, c in enumerate(cars, start=1):
# # print ("Car: %s Price: %s"%(c, prices[index]))
# #
# # # Printing prices of accessories
# # for index, a in enumerate(accessories,start=1):
# # print ("Accessory: %s Price: %s" \
# # %(a,prices[index+len(cars)]))
# #
# #
# #
# #
# # # a=[1,2,3,4,5,6,7,8,9]
# # # b=0
# # # c=[]
# # # for i in a:
# # # b+=i
# # # c.append(b)
# # # print(c)
# # #
# # #
# # # # a=3.547498
# # # # print('%.5f'%a)
# # #
# # # # #input
# # # # a=list(map(int,input().split()))
# # # #
# # # # #output
# # # # for i in a:
# # # # print(i)
# # # #
# # # #
# # # #
# # # # # try:
# # # # # a=int(input())
# # # # # for i in range(a):
# # # # # b,c=map(int,input().split())
# # # # # e=[]
# # # # # d=list(map(int,input().split()))
# # # # # for k in d:
# # # # # if(k%c==0):
# # # # # e.append('1')
# # # # # else:
# # # # # e.append('0')
# # # # #
# # # # #
# # # # # f=''.join(e)
# # # # # print(str(f))
# # # # #
# # # # # except:
# # # # # pass
# # # #
# # # #
# # # #
# # # #
# # # # # a=int(input())
# # # # # b=list(map(int,input().split()))
# # # # #
# # # # # c=set(b)
# # # # #
# # # # # c.remove(max(c))
# # # # # print(max(c))
# # # # # a=['rahul','ayush','ayush ki bndi',2,6,5,7]
# # # # # with open ('a.txt','w') as b:
# # # # # for i in a:
# # # # # print(i,file=b)
# # # # #
# # # # #
# # # # #
# # # # # # a,b=input()
# # # # # #
# # # # # # # try:
# # # # # # # a=int(input())
# # # # # # # for i in range(a):
# # # # # # # b=int(input())
# # # # # # # c=input()
# # # # # # # d=set(c)
# # # # # # # for j in d:
# # # # # # # if(c.count(j)%2==0):
# # # # # # # b-=c.count(j)
# # # # # # #
# # # # # # # if(b==0):
# # # # # # # print('YES')
# # # # # # # else:
# # # # # # # print('NO')
# # # # # # # except:
# # # # # # # pass
# # # # # #
# # # # # #
# # # # # # # a={'rahul','ram','ayush','akansha','holi','lodaram'}
# # # # # # # print(a)
# # # # # # # print(a)
# # # # # # # print(sorted(a))
# # # # # # #
# # # # # # # # a=int(input())
# # # # # # # #
# # # # # # # # while(a!=0):
# # # # # # # # x=0
# # # # # # # # y=[]
# # # # # # # # l,r,m=map(int,input().split())
# # # # # # # # for i in range(min(l,r),max(l,r)+1):
# # # # # # # # for j in range(min(l,r),max(l,r)+1):
# # # # # # # # for k in range(min(l,r),max(l,r)):
# # # # # # # # n=(m+j-k)//i
# # # # # # # # if(n>0):
# # # # # # # # x+=1
# # # # # # # # y.append((i,j,k))
# # # # # # # #
# # # # # # # #
# # # # # # # # print(y)
# # # # # # # # for i in y:
# # # # # # # # if(len(set(i))==3):
# # # # # # # # print(i)
# # # # # # # # break
# # # # # # # #
# # # # # # # #
# # # # # # # # a-=1
# # # # # # #
# # # # # # #
# # # # # # # # a=int(input())
# # # # # # # #
# # # # # # # # while(a!=0):
# # # # # # # # x=0
# # # # # # # # l,r,m=map(int,input().split())
# # # # # # # # for i in range(min(l,r),max(l,r)+1):
# # # # # # # # for j in range(min(l,r),max(l,r)+1):
# # # # # # # # for k in range(min(l,r),max(l,r)):
# # # # # # # # n=(m+j-k)//i
# # # # # # # # if(n>0):
# # # # # # # # x+=1
# # # # # # # # print(i,j,k)
# # # # # # # # if(x==1):
# # # # # # # # break
# # # # # # # # if(x==1):
# # # # # # # # break
# # # # # # # # if(x==1):
# # # # # # # # break
# # # # # # # # else:
# # # # # # # # continue
# # # # # # # #
# # # # # # # # a-=1
# # # # # # #
# # # # # # # # t = int(input().strip())
# # # # # # # # for _ in range(t):
# # # # # # # # l, r, m = map(int, input().split())
# # # # # # # # max_diff = r - l
# # # # # # # # for i in range(l, r + 1):
# # # # # # # # temp = m - (m - m % i)
# # # # # # # # if temp <= max_diff:
# # # # # # # # if m < l:
# # # # # # # # print('{} {} {}'.format(i, l, l + temp))
# # # # # # # # else:
# # # # # # # # print('{} {} {}'.format(i, l + temp, l))
# # # # # # # # break
# # # # # # #
# # # # # # #
# # # # # # # ##ββββββββββββββββββββββββββββββββββββββββ¦ββββ
# # # # # # # # βββββββββββββββββββββββββββββββββ βββββββββββ
# # # # # # # # ββββ¦ββββββ¦βββββββ¦βββ¦βββ¦βββ¦βββ¬ββββ βββββββ ββββ
# # # # # # # # βββββββ£ββββββ£ββββββββββββββββ¬βββββββββββββββ
# # # # # # # # ββββββββββββββββββββββββββ βββββββ βββ£ββββββββ
# # # # # # # # ββββ©βββ©βββ©βββ©ββββ©β©β©β©βββ©βββ©βββ©ββββ©βββ©ββββββββ
# # # # # # # # ββββββββββββββββββββββββββββββββββββββββββββ
# # # # # # # # ββββββββββββββββββββββββββββββββββββββββββββ
# # # # # # #
# # # # # # # # # try:
# # # # # # # # # a=int(input())
# # # # # # # # # while(a!=0):
# # # # # # # # #
# # # # # # # # # b=int(input())
# # # # # # # # # c,d=map(int,input().split())
# # # # # # # # # e=int(input())
# # # # # # # # # for i in range(e):
# # # # # # # # # f=list(map(int,input().split()))
# # # # # # # # # if(f[0]+f[1]<c):
# # # # # # # # # print(0)
# # # # # # # # # elif(c<f[0]+f[1]<d):
# # # # # # # # # print(c)
# # # # # # # # # elif(f[0]+f[1]>d):
# # # # # # # # # print(d-c)
# # # # # # # # # elif(f[0]+f[1]==c or f[0]+f[1]==d):
# # # # # # # # # print(-1)
# # # # # # # # #
# # # # # # # # # a-=1
# # # # # # # # # except:
# # # # # # # # # pass
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # try:
# # # # # # # # # a=int(input())
# # # # # # # # # while(a!=0):
# # # # # # # # # b=int(input())
# # # # # # # # # c=list(map(int,input().split()))
# # # # # # # # # d=1
# # # # # # # # # for i in c:
# # # # # # # # # d*=i
# # # # # # # # #
# # # # # # # # # if(d%2==0):
# # # # # # # # # print('NO')
# # # # # # # # # else:
# # # # # # # # # print('Yes')
# # # # # # # # # a-=1
# # # # # # # # # except:
# # # # # # # # # pass
# # # # # # # #
# # # # # # # # a={'A':1,'B':2}
# # # # # # # # b=2
# # # # # # # # c=[]
# # # # # # # # for i in a.keys():
# # # # # # # # c.append(i)
# # # # # # # # for i in c:
# # # # # # # # if(a.get(i)==b):
# # # # # # # # print(i)
# # # # # # # # break
# # # # # # # # else:
# # # # # # # # print('no such value :P')
# # # # # # # #
# # # # # # # # # a={'A':1,'B':2}
# # # # # # # # # print(a)
# # # # # # # # # a={x:key for key , x in a.items()}
# # # # # # # # # print(a)
# # # # # # # # # print(a.get(1))
# # # # # # # #
# # # # # # # #
# # # # # # # # # from pytube import YouTube
# # # # # # # # # from pytube import extract
# # # # # # # # # from pytube.streams import Stream
# # # # # # # # #
# # # # # # # # # YouTube("Your link here").streams.first().download()
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # def getPairsCount(arr, n, sum):
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # for i in range(0, n):
# # # # # # # # # for j in range(i + 1, n):
# # # # # # # # # if arr[i] + arr[j] == sum:
# # # # # # # # # c=[]
# # # # # # # # # c.append(str(arr[i]))
# # # # # # # # # c.append(str(arr[j]))
# # # # # # # # #
# # # # # # # # # print(' '.join(c))
# # # # # # # # #
# # # # # # # # # a=int(input())
# # # # # # # # # d=[]
# # # # # # # # # for i in range(1,(a**2)+1):
# # # # # # # # # d.append(i)
# # # # # # # # # arr = d
# # # # # # # # # n = len(arr)
# # # # # # # # # sum = arr[0]+arr[len(arr)-1]
# # # # # # # # # y=getPairsCount(arr,n,sum)
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # #
# # # # # # # # # a=int(input())
# # # # # # # # # for i in range(a):
# # # # # # # # # b,c=map(int,input().split())
# # # # # # # # # print(min(b,c,(b+c)//3))
# # # # # # # #
# # # # # # # #
# # # # # # # # # if a == 0:
# # # # # # # # # return b
# # # # # # # # # return gcd(b % a, a)
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # def lcm(a,b):
# # # # # # # # # return (a*b) // gcd(a,b)
# # # # # # # # #
# # # # # # # # # def getPairsCount(arr, n, sum):
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # c=[]
# # # # # # # # # for i in range(0, n):
# # # # # # # # # for j in range(i + 1, n):
# # # # # # # # # if arr[i] + arr[j] == sum:
# # # # # # # # #
# # # # # # # # # c.append(arr[i])
# # # # # # # # # c.append(arr[j])
# # # # # # # # # return c
# # # # # # # # #
# # # # # # # # # n=int(input())
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # for i in range(n):
# # # # # # # # # x=int(input())
# # # # # # # # # d=[]
# # # # # # # # # for i in range(x):
# # # # # # # # # d.append(i)
# # # # # # # # # arr = d
# # # # # # # # # n = len(arr)
# # # # # # # # # sum = x
# # # # # # # # # y=getPairsCount(arr,n,sum)
# # # # # # # # #
# # # # # # # # # if(x%2==0):
# # # # # # # # # print(x//2,x//2)
# # # # # # # # # else:
# # # # # # # # # e=[]
# # # # # # # # # for i in range(len(y)):
# # # # # # # # # if(i%2==0):
# # # # # # # # # e.append(lcm(y[i],y[i+1]))
# # # # # # # # #
# # # # # # # # # z=(e.index(min(e)))
# # # # # # # # # print(y[z*2],y[(z*2)+1])
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # # # for i in range(a):
# # # # # # # # # # b=int(input())
# # # # # # # # # # for j in range(b):
# # # # # # # # # # print('1',end=' ')
# # # # # # # # # # print()
# # # # # # # # #
# # # # # # # # # # a=int(input())
# # # # # # # # # #
# # # # # # # # # # c=[]
# # # # # # # # # #
# # # # # # # # # # while(a!=0):
# # # # # # # # # # b=int(input())
# # # # # # # # # # if(b<=2):
# # # # # # # # # # for j in range(1000):
# # # # # # # # # # c.append(j)
# # # # # # # # # # else:
# # # # # # # # # # for k in range(b):
# # # # # # # # # # for l in range(1000):
# # # # # # # # # # if(k>=2):
# # # # # # # # # # for m in range(k):
# # # # # # # # # # if(c[m]+c[m+1]==c[m+2]):
# # # # # # # # # # pass
# # # # # # # # # # else:
# # # # # # # # # # c.append(l)
# # # # # # # # # # else:
# # # # # # # # # # c.append(l)
# # # # # # # # # # print(c)
# # # # # # # # # # a-=1
# # # # # # # # #
# # # # # # # # # # while(True):
# # # # # # # # # # import random
# # # # # # # # # # #
# # # # # # # # # # # a,b=map(int,input().split())
# # # # # # # # # # #
# # # # # # # # # # # c=random.randint(1,6)
# # # # # # # # # # #
# # # # # # # # # # # print(c)
# # # # # # # # # #
# # # # # # # # # # # while(True):
# # # # # # # # # # # a=[1,2,3]
# # # # # # # # # # #
# # # # # # # # # # # i=int(input('Enter any number to check thatt it is present in list or not'))
# # # # # # # # # # #
# # # # # # # # # # # if(i in a):
# # # # # # # # # # # print('Yes')
# # # # # # # # # # # else:
# # # # # # # # # # # print('No')
# # # # # # # # # # # #there are two w
# # # # # # # # # #
# # # # # # # # # # # a=int(input())
# # # # # # # # # # #for i in range(len(b))
# # # # # # # # # # #print(9n-1)
# # # # # # # # # #
# # # # # # # # # # #prin(n-1)# for i in range(a):
# # # # # # # # # #
# # # # # # # # # # # b = list(map(int,input().split()))
# # # # # # # # # # # if b[0]>3 and b[1]>3 and b[2]>3:
# # # # # # # # # # # print(7)
# # # # # # # # # # # else:
# # # # # # # # # # # if 1 in b:
# # # # # # # # # # # c = b.count(1)
# # # # # # # # # # # if c==1 and b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif c==1 and b.count(0)==1:
# # # # # # # # # # # print(2)
# # # # # # # # # # # elif c==1:
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif c==2 and b.count(0)==1:
# # # # # # # # # # # print(2)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # # # elif 2 in b:
# # # # # # # # # # # c = b.count(2)
# # # # # # # # # # # if c==3:
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif c==1 and b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif c==1 and b.count(0)==1:
# # # # # # # # # # # print(3)
# # # # # # # # # # # elif c==2 and b.count(0)==1:
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(5)
# # # # # # # # # # # elif 3 in b:
# # # # # # # # # # # if c==1 and b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif c==1 and b.count(0)==1:
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(6)
# # # # # # # # # # # else:
# # # # # # # # # # # if b.count(0)==3:
# # # # # # # # # # # print(0)
# # # # # # # # # # # elif b.count(0)==2:
# # # # # # # # # # # print(1)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # a=int(input())
# # # # # # # # # # #
# # # # # # # # # # # for i in range(a):
# # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # #
# # # # # # # # # # # if(b[0]>3 and b[1]>3 and b[2]>3):
# # # # # # # # # # # print(7)
# # # # # # # # # # #
# # # # # # # # # # # else:
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # if(1 in b):
# # # # # # # # # # # c=b.count(1)
# # # # # # # # # # # if(c==1 and b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif(c==1 and b.count(0)==1):
# # # # # # # # # # # print(2)
# # # # # # # # # # # elif(c==1):
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif(c==2 and b.count(0)==1):
# # # # # # # # # # # print(2)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # elif(2 in b):
# # # # # # # # # # # c=b.count(2)
# # # # # # # # # # # if(c==2 and b.count(0)==1):
# # # # # # # # # # # print(3)
# # # # # # # # # # # elif(c==3):
# # # # # # # # # # # print(4)
# # # # # # # # # # # elif(c==1 and b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif(c==1 and b.count(0)==1):
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(5)
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # elif(3 in b):
# # # # # # # # # # # c=b.count(3)
# # # # # # # # # # # if(c==1 and b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # elif(c==1 and b.count(0)==1):
# # # # # # # # # # # print(3)
# # # # # # # # # # # else:
# # # # # # # # # # # print(6)
# # # # # # # # # # #
# # # # # # # # # # #
# # # # # # # # # # # else:
# # # # # # # # # # # if(b.count(0)==3):
# # # # # # # # # # # print(0)
# # # # # # # # # # # elif(b.count(0)==2):
# # # # # # # # # # # print(1)
# # # # # # # # # # # else:
# # # # # # # # # # # print(3)
# # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # #a-=1
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # a=int(input())
# # # # # # # # # # #
# # # # # # # # # # # for i in range(a):
# # # # # # # # # # # b,c,d=map(int,input().split())
# # # # # # # # # # # if(a==0):
# # # # # # # # # # # if(b==0 and c==0):
# # # # # # # # # # # print(0)
# # # # # # # # # # # if(b==0 or c==0):
# # # # # # # # # # # print(1)
# # # # # # # # # # # if(b>=2 and c>=2):
# # # # # # # # # # # print(3)
# # # # # # # # # # #
# # # # # # # # # # # # a=[1,3]
# # # # # # # # # # # #
# # # # # # # # # # # # b=[2]
# # # # # # # # # # # #
# # # # # # # # # # # # c=a+b
# # # # # # # # # # # # print(c)
# # # # # # # # # # # # print(id(c))
# # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # a='rahul'
# # # # # # # # # # # # # b=a
# # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # print(id(b))
# # # # # # # # # # # # # print()
# # # # # # # # # # # # #
# # # # # # # # # # # # # for i in range(5):
# # # # # # # # # # # # # a+='mahajan'
# # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # f
# # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # print(id(b))
# # # # # # # # # # # # # # a='rahul'+'mahajan'
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # b=a
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # print(id(a))
# # # # # # # # # # # # # # print(id(b))
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # # def ckeckList(lst):
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # ele = lst[0]
# # # # # # # # # # # # # # # chk = True
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # Comparing each element with first item
# # # # # # # # # # # # # # # for item in lst:
# # # # # # # # # # # # # # # if ele != item:
# # # # # # # # # # # # # # # chk = False
# # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # if (chk == True):
# # # # # # # # # # # # # # # print("Equal")
# # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # print("Not equal")
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # Driver Code
# # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # ckeckList(a)
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # b=a[0]
# # # # # # # # # # # # # # # c=True
# # # # # # # # # # # # # # # for i in a:
# # # # # # # # # # # # # # # if(i!=b):
# # # # # # # # # # # # # # # c=False
# # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # if(c==True):
# # # # # # # # # # # # # # # print(1)
# # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # #
# # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # x=0
# # # # # # # # # # # # # # # y=0
# # # # # # # # # # # # # # # d=[]
# # # # # # # # # # # # # # # e=[]
# # # # # # # # # # # # # # # for i in range(a):
# # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # c=[]
# # # # # # # # # # # # # # # for i in range(1,b+1):
# # # # # # # # # # # # # # # c.append(i)
# # # # # # # # # # # # # # # if(max(c)==1):
# # # # # # # # # # # # # # # print(1)
# # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # if(len(c)%2==0):
# # # # # # # # # # # # # # # for j in range(len(c)):
# # # # # # # # # # # # # # # if(j<((len(c)//2)-1)):
# # # # # # # # # # # # # # # x=c[j]+c[len(c)-2-j]
# # # # # # # # # # # # # # # d.append(x)
# # # # # # # # # # # # # # # print(len(d)+1)
# # # # # # # # # # # # # # # elif(len(c)//2!=0):
# # # # # # # # # # # # # # # print((len(c)//2)+1)
# # # # # # # # # # # # # # # # for k in range(len(c)):
# # # # # # # # # # # # # # # # # e=[]
# # # # # # # # # # # # # # # # y=c[k]+c[len(c)-2-k]
# # # # # # # # # # # # # # # # e.append(y)
# # # # # # # # # # # # # # # # print(len(e)+1)
# # # # # # # # # # # # # # # d.clear()
# # # # # # # # # # # # # # # e.clear()
# # # # # # # # # # # # # # # # print(36+10)
# # # # # # # # # # # # # # # # print(36-8)
# # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # i=0
# # # # # # # # # # # # # # # # # while(a!=0):
# # # # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # # # if(b==1):
# # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # elif(b==2):
# # # # # # # # # # # # # # # # # print((-1))
# # # # # # # # # # # # # # # # # elif(b>2):
# # # # # # # # # # # # # # # # # while(c==1):
# # # # # # # # # # # # # # # # # if(b%6==0):
# # # # # # # # # # # # # # # # # c=(b%6)
# # # # # # # # # # # # # # # # # i+=1
# # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # c=b*2
# # # # # # # # # # # # # # # # # i+=1
# # # # # # # # # # # # # # # # # print(i)
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # while(a!=0):
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # b,c,d=map(int,input().split())
# # # # # # # # # # # # # # # # # # e=[]
# # # # # # # # # # # # # # # # # # for i in range(d+1):
# # # # # # # # # # # # # # # # # # if(i%b==c):
# # # # # # # # # # # # # # # # # # e.append(i)
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # print(max(e))
# # # # # # # # # # # # # # # # # # a-=1
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # a="""Number 1\t The Larch
# # # # # # # # # # # # # # # # # # # Number 2\t the horse chestnut"""
# # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # a="""hello1\trahul
# # # # # # # # # # # # # # # # # # # # mahajan\tmahajana
# # # # # # # # # # # # # # # # # # # # """
# # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # c=sorted(a)
# # # # # # # # # # # # # # # # # # # # # #print(c)
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # d=min(c)
# # # # # # # # # # # # # # # # # # # # # e=c.count(d)
# # # # # # # # # # # # # # # # # # # # # f=0
# # # # # # # # # # # # # # # # # # # # # while(f!=e):
# # # # # # # # # # # # # # # # # # # # # c.remove(a[f])
# # # # # # # # # # # # # # # # # # # # # f+=1
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # z=sorted(c,reverse= 021)
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # g=max(z)
# # # # # # # # # # # # # # # # # # # # # h=z.count(g)
# # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # while(j!=h):
# # # # # # # # # # # # # # # # # # # # # z.remove(z[j])
# # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # #print(z)
# # # # # # # # # # # # # # # # # # # # # print(len(z))
# # # # # # # # # # # # # # # # # # # # # a=[1,1,2,3,3]
# # # # # # # # # # # # # # # # # # # # # for i in a:
# # # # # # # # # # # # # # # # # # # # # a.remove(min(a))
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # a=[1,1,1,2,2,3,4,3]
# # # # # # # # # # # # # # # # # # # # # # c=sorted(a)
# # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # d=min(c)
# # # # # # # # # # # # # # # # # # # # # # e=c.count(d)
# # # # # # # # # # # # # # # # # # # # # # f=0
# # # # # # # # # # # # # # # # # # # # # # while(f!=e):
# # # # # # # # # # # # # # # # # # # # # # c.remove(a[f])
# # # # # # # # # # # # # # # # # # # # # # f+=1
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # z=sorted(c,reverse=1)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # g=max(z)
# # # # # # # # # # # # # # # # # # # # # # h=z.count(g)
# # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # while(j!=h):
# # # # # # # # # # # # # # # # # # # # # # c.remove(a[j])
# # # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # # print(z)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # n,b,d=map(int,input().split())
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # for i in range(n):
# # # # # # # # # # # # # # # # # # # # # # # if(a[i]>b):
# # # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # if(len(a)==0):
# # # # # # # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # c+=a[i]
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # if(c>d):
# # # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # if(a[i]>=b):
# # # # # # # # # # # # # # # # # # # # # # a.remove(a[i])
# # # # # # # # # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # print(j)
# # # # # # # # # # # # # # # # # # # # # # #print(a)
# # # # # # # # # # # # # # # # # # # # # # # a=map(str,input().split())
# # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # c=set(a)
# # # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # # # # while(1):
# # # # # # # # # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # c=b.count(1)
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # d=b.count(2)
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # e=b.count(3)
x=int(input())
for i in range(x):
a,b=map(int,input().split())
if(a*2<=b):
print(a,a*2)
else:
print('-1 -1')
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # if(c==0 or d==0 or e==0):
# # # # # # # # # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # if(c<=d and c<=e):
# # # # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # # # # elif(d<=c and d<=e):
# # # # # # # # # # # # # # # # # # # # # # # # print(d)
# # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # print(e)
# # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # while(1):
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # n,b,d=map(int,input().split())
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # a=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(n):
# # # # # # # # # # # # # # # # # # # # # # # # # if(a[i]>b):
# # # # # # # # # # # # # # # # # # # # # # # # # a.remove(a[i])
# # # # # # # # # # # # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # if(len(a)==0):
# # # # # # # # # # # # # # # # # # # # # # # # # print(0)
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # c+=a[i]
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # if(c>d):
# # # # # # # # # # # # # # # # # # # # # # # # # j+=1
# # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # pass
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # # # # if(a[i]>=b):
# # # # # # # # # # # # # # # # # # # # # # # # # a.remove(a[i])
# # # # # # # # # # # # # # # # # # # # # # # # # break
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # print(j)
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # a=['r','b','g']
# # # # # # # # # # # # # # # # # # # # # # # # # c=len(a)
# # # # # # # # # # # # # # # # # # # # # # # # # #print(c)
# # # # # # # # # # # # # # # # # # # # # # # # # #print(a)
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # # # # print(a[i-1])
# # # # # # # # # # # # # # # # # # # # # # # # # print('-'*20)
# # # # # # # # # # # # # # # # # # # # # # # # # for i in range(len(a)):
# # # # # # # # # # # # # # # # # # # # # # # # # print(a[i])
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # a=int(input())
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=0
# # # # # # # # # # # # # # # # # # # # # # # # # # # d=0
# # # # # # # # # # # # # # # # # # # # # # # # # # # while(len(b)!=0):
# # # # # # # # # # # # # # # # # # # # # # # # # # # if(len(b)%2==0):
# # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+x[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(y)
# # # # # # # # # # # # # # # # # # # # # # # # # # # d=d+y[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(y[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # # # if(len(b)==1):
# # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+x[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # else:
# # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+x[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # #print(y)
# # # # # # # # # # # # # # # # # # # # # # # # # # # d=d+y[(len(b)-1)]
# # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(y[(len(b)-1)])
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(x[a-1])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # y=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # d=d+y[-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b.remove(y[len(b)-1])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # a=a-1
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # print('{0} {1}'.format(c,d))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(len(b))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # s=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # c=c+s[len(s)-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(c)
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b=list(map(int,input().split()))
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(maxi(b))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(len(b))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # x=sorted(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(x[a-1])
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # a=[]
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # for i in range(10):
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # b=int(input())
# # # # # # # # # # # # # # # # # # # # # # # # # # # # a.append(b)
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # j=0
# # # # # # # # # # # # # # # # # # # # # # # # # # # # c=sorted(a)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(c[9])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # j=j+c[len(a)-1]
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(j)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(a)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(len(a)-1)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # print(max(a)) | 1596033300 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds | ["1", "3"] | f14e81618a81946dcaab281e1aa1ff9f | NoteIn the first example, the only pair of points $$$(-3, 0)$$$, $$$(3, 0)$$$ is suitable. The distance to the segment between these points from the points $$$(0, 1)$$$ and $$$(0, -1)$$$ is equal to $$$1$$$, which is less than $$$R=2$$$.In the second example, all possible pairs of points are eligible. | You are given $$$n$$$ distinct points $$$p_1, p_2, \ldots, p_n$$$ on the plane and a positive integer $$$R$$$. Find the number of pairs of indices $$$(i, j)$$$ such that $$$1 \le i < j \le n$$$, and for every possible $$$k$$$ ($$$1 \le k \le n$$$) the distance from the point $$$p_k$$$ to the segment between points $$$p_i$$$ and $$$p_j$$$ is at most $$$R$$$. | Print the number of suitable pairs $$$(i, j)$$$. | The first line contains two integers $$$n$$$, $$$R$$$ ($$$1 \le n \le 3000$$$, $$$1 \le R \le 10^5$$$)Β β the number of points and the maximum distance between a point and a segment. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^5 \le x_i, y_i \le 10^5$$$) that define the $$$i$$$-th point $$$p_i=(x_i, y_i)$$$. All points are distinct. It is guaranteed that the answer does not change if the parameter $$$R$$$ is changed by at most $$$10^{-2}$$$. | standard output | standard input | PyPy 3-64 | Python | 3,200 | train_109.jsonl | cfc06de167e0e52f03ba1a2731a85256 | 256 megabytes | ["4 2\n0 1\n0 -1\n3 0\n-3 0", "3 3\n1 -1\n-1 -1\n0 1"] | PASSED | from math import atan2, asin
def dist(a, b):
return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5
def check(R, p, i, dp):
left, right = float("-inf"), float("inf")
for j in range(len(p)):
if j == i:
continue
d = dist(p[i], p[j])
if R >= d:
continue
delta = asin(R/d)
angle = atan2(p[j][1]-p[i][1], p[j][0]-p[i][0])
l, r = angle-delta, angle+delta
if l > right:
l, r = l-2*PI, r-2*PI
elif r < left:
l, r = l+2*PI, r+2*PI
left, right = max(left, l), min(right, r)
if left > right:
return
for j in range(len(p)):
if j == i:
continue
angle = atan2(p[j][1]-p[i][1], p[j][0]-p[i][0])
if angle > right:
angle -= 2*PI
elif angle < left:
angle += 2*PI
if left <= angle <= right:
dp[i][j] = 1
def solution():
n, R = list(map(int, input().strip().split()))
p = [list(map(int, input().strip().split())) for _ in range(n)]
dp = [[0]*n for _ in range(n)]
for i in range(n):
check(R, p, i, dp)
return sum(dp[i][j] and dp[j][i] for i in range(n) for j in range(i, n))
PI = 2*atan2(1, 0)
print(solution()) | 1636869900 | [
"geometry"
] | [
0,
1,
0,
0,
0,
0,
0,
0
] |
|
2 seconds | ["5", "16", "18"] | e52ec2fa5bcf5d2027d57b0694b4e15a | NoteIn the first example it is possible to connect $$$1$$$ to $$$2$$$ using special offer $$$2$$$, and then $$$1$$$ to $$$3$$$ without using any offers.In next two examples the optimal answer may be achieved without using special offers. | You are given an undirected graph consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is $$$a_i$$$. Initially there are no edges in the graph.You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $$$x$$$ and $$$y$$$ is $$$a_x + a_y$$$ coins. There are also $$$m$$$ special offers, each of them is denoted by three numbers $$$x$$$, $$$y$$$ and $$$w$$$, and means that you can add an edge connecting vertices $$$x$$$ and $$$y$$$ and pay $$$w$$$ coins for it. You don't have to use special offers: if there is a pair of vertices $$$x$$$ and $$$y$$$ that has a special offer associated with it, you still may connect these two vertices paying $$$a_x + a_y$$$ coins for it.What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph. | Print one integer β the minimum number of coins you have to pay to make the graph connected. | The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) β the number of vertices in the graph and the number of special offers, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$) β the numbers written on the vertices. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$ and $$$w$$$ ($$$1 \le x, y \le n$$$, $$$1 \le w \le 10^{12}$$$, $$$x \ne y$$$) denoting a special offer: you may add an edge connecting vertex $$$x$$$ and vertex $$$y$$$, and this edge will cost $$$w$$$ coins. | standard output | standard input | Python 3 | Python | 1,900 | train_000.jsonl | d045b0ecd6aaad78a2574780f55d22a1 | 256 megabytes | ["3 2\n1 3 3\n2 3 5\n2 1 1", "4 0\n1 3 3 7", "5 4\n1 2 3 4 5\n1 2 8\n1 3 10\n1 4 7\n1 5 15"] | PASSED | def read_nums():
return [int(x) for x in input().split()]
class UnionFind:
def __init__(self, size):
self._parents = list(range(size))
# number of elements rooted at i
self._sizes = [1 for _ in range(size)]
def _root(self, a):
while a != self._parents[a]:
self._parents[a] = self._parents[self._parents[a]]
a = self._parents[a]
return a
def find(self, a, b):
return self._root(a) == self._root(b)
def union(self, a, b):
a, b = self._root(a), self._root(b)
if self._sizes[a] < self._sizes[b]:
self._parents[a] = b
self._sizes[b] += self._sizes[a]
else:
self._parents[b] = a
self._sizes[a] += self._sizes[b]
def count_result(num_vertex, edges):
uf = UnionFind(num_vertex)
res = 0
for start, end, cost in edges:
if uf.find(start, end):
continue
else:
uf.union(start, end)
res += cost
return res
def main():
n, m = read_nums()
vertex_nums = read_nums()
edges = []
for i in range(m):
nums = read_nums()
nums[0] -= 1
nums[1] -= 1
edges.append(nums)
min_index = min([x for x in zip(vertex_nums, range(n))], key=lambda x: x[0])[1]
for i in range(n):
if i != min_index:
edges.append((min_index, i, vertex_nums[min_index] + vertex_nums[i]))
edges = sorted(edges, key=lambda x: x[2])
print(count_result(n, edges))
if __name__ == '__main__':
main()
| 1545921300 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds | ["2", "3"] | 941ef8c3dd64e269d18fc4dfce7165e0 | null | Masha lives in a country with $$$n$$$ cities numbered from $$$1$$$ to $$$n$$$. She lives in the city number $$$1$$$. There is a direct train route between each pair of distinct cities $$$i$$$ and $$$j$$$, where $$$i \neq j$$$. In total there are $$$n(n-1)$$$ distinct routes. Every route has a cost, cost for route from $$$i$$$ to $$$j$$$ may be different from the cost of route from $$$j$$$ to $$$i$$$.Masha wants to start her journey in city $$$1$$$, take exactly $$$k$$$ routes from one city to another and as a result return to the city $$$1$$$. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city $$$v$$$, take odd number of routes used by Masha in her journey and return to the city $$$v$$$, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey. | Output a single integerΒ β total cost of the cheapest Masha's successful journey. | First line of input had two integer numbers $$$n,k$$$ ($$$2 \leq n \leq 80; 2 \leq k \leq 10$$$): number of cities in the country and number of routes in Masha's journey. It is guaranteed that $$$k$$$ is even. Next $$$n$$$ lines hold route descriptions: $$$j$$$-th number in $$$i$$$-th line represents the cost of route from $$$i$$$ to $$$j$$$ if $$$i \neq j$$$, and is 0 otherwise (there are no routes $$$i \to i$$$). All route costs are integers from $$$0$$$ to $$$10^8$$$. | standard output | standard input | PyPy 2 | Python | 2,300 | train_025.jsonl | 53b279a96dc2e892e5ca3de827c4f349 | 256 megabytes | ["5 8\n0 1 2 2 0\n0 0 1 1 2\n0 1 0 0 0\n2 1 1 0 0\n2 0 1 2 0", "3 2\n0 1 1\n2 0 1\n2 2 0"] | PASSED | import sys
range = xrange
input = raw_input
n,k = [int(x) for x in input().split()]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
mat = [[] for _ in range(n)]
for i in range(n):
for j in range(n):
mat[j].append(inp[i*n + j])
inf = 10**9 + 100
def randomer(odd, even):
best = [inf]*n
best[0] = 0
best2 = [inf]*n
for _ in range(k):
for j in odd:
opti = inf
matj = mat[j]
for i in even:
val = best[i] + matj[i]
if opti > val:
opti = val
best2[j] = opti
best, best2, odd, even = best2, best, even, odd
return best[0]
sys.modules["hashlib"] = sys.sha512 = sys
import random
best = inf
for _ in range(10 * 2**k):
odd = []
even = [0]
for _ in range(1, n):
(odd if random.randint(0,1) else even).append(_)
best = min(best, randomer(odd, even))
print best
| 1582473900 | [
"probabilities",
"graphs"
] | [
0,
0,
1,
0,
0,
1,
0,
0
] |
|
2 seconds | ["IMPROVE\n4 4\nIMPROVE\n1 1\nOPTIMAL\nOPTIMAL\nOPTIMAL"] | 38911652b3c075354aa8adb2a4c6e362 | NoteThe first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.In the second test case any new entry will increase the number of marriages from $$$0$$$ to $$$1$$$.In the third and the fourth test cases there is no way to add an entry.In the fifth test case there is no way to change the marriages by adding any entry. | The King of Berland Polycarp LXXXIV has $$$n$$$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $$$n$$$ other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from $$$1$$$ to $$$n$$$ and the kingdoms from $$$1$$$ to $$$n$$$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $$$n$$$-th daughter.For example, let there be $$$4$$$ daughters and kingdoms, the lists daughters have are $$$[2, 3]$$$, $$$[1, 2]$$$, $$$[3, 4]$$$, $$$[3]$$$, respectively. In that case daughter $$$1$$$ marries the prince of kingdom $$$2$$$, daughter $$$2$$$ marries the prince of kingdom $$$1$$$, daughter $$$3$$$ marries the prince of kingdom $$$3$$$, leaving daughter $$$4$$$ nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer $$$t$$$ independent test cases. | For each test case print the answer to it. Print "IMPROVE" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers β the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list. If there are multiple ways to add an entry so that the total number of married couples increases then print any of them. Otherwise the only line should contain one word "OPTIMAL". | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β the number of daughters and the number of kingdoms. Each of the next $$$n$$$ lines contains the description of each daughter's list. The first integer $$$k$$$ ($$$0 \le k \le n$$$) is the number of entries in the $$$i$$$-th daughter's list. After that $$$k$$$ distinct integers follow $$$g_i[1], g_i[2], \dots, g_i[k]$$$ ($$$1 \le g_i[j] \le n$$$) β the indices of the kingdoms in the list in the increasing order ($$$g_i[1] < g_i[2] < \dots < g_i[k]$$$). It's guaranteed that the total number of daughters over all test cases does not exceed $$$10^5$$$. It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed $$$10^5$$$. | standard output | standard input | Python 3 | Python | 1,200 | train_013.jsonl | 39330a33b699704969083e7f98b9044f | 256 megabytes | ["5\n4\n2 2 3\n2 1 2\n2 3 4\n1 3\n2\n0\n0\n3\n3 1 2 3\n3 1 2 3\n3 1 2 3\n1\n1 1\n4\n1 1\n1 2\n1 3\n1 4"] | PASSED | import math
from collections import defaultdict
for _ in range(int(input())):
n=int(input())
d=defaultdict(int)
used=[False]*n
noUsed=[]
q=0
for i in range(n):
a=[int(i) for i in input().split()]
b=a[1:]
f=0
for j in b:
if used[j-1]==False:
used[j-1]=True
f=1
break
if(f==0):
noUsed.append(i+1)
if(len(noUsed)==0):
print("OPTIMAL")
else:
print("IMPROVE")
print(noUsed[0],used.index(False)+1) | 1584974100 | [
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second | ["0\n1\n16\n1"] | b5985b619652e606ac96554ecfb9346a | NoteIn the first test case, we don't need to add any element because the arithmetic mean of the array is already $$$1$$$, so the answer is $$$0$$$.In the second test case, the arithmetic mean is not $$$1$$$ initially so we need to add at least one more number. If we add $$$0$$$ then the arithmetic mean of the whole array becomes $$$1$$$, so the answer is $$$1$$$.In the third test case, the minimum number of elements that need to be added is $$$16$$$ since only non-negative integers can be added.In the fourth test case, we can add a single integer $$$4$$$. The arithmetic mean becomes $$$\frac{-2+4}{2}$$$ which is equal to $$$1$$$. | An array $$$b$$$ of length $$$k$$$ is called good if its arithmetic mean is equal to $$$1$$$. More formally, if $$$$$$\frac{b_1 + \cdots + b_k}{k}=1.$$$$$$Note that the value $$$\frac{b_1+\cdots+b_k}{k}$$$ is not rounded up or down. For example, the array $$$[1,1,1,2]$$$ has an arithmetic mean of $$$1.25$$$, which is not equal to $$$1$$$.You are given an integer array $$$a$$$ of length $$$n$$$. In an operation, you can append a non-negative integer to the end of the array. What's the minimum number of operations required to make the array good?We have a proof that it is always possible with finitely many operations. | For each test case, output a single integer β the minimum number of non-negative integers you have to append to the array so that the arithmetic mean of the array will be exactly $$$1$$$. | The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) β the length of the initial array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$-10^4\leq a_i \leq 10^4$$$), the elements of the array. | standard output | standard input | PyPy 3-64 | Python | 800 | train_084.jsonl | c78ab82d9f2ea4425a25d262cd9256d9 | 256 megabytes | ["4\n3\n1 1 1\n2\n1 2\n4\n8 4 6 2\n1\n-2"] | PASSED | from functools import reduce
import sys
from os import path
if(path.exists('input.txt')):
sys.stdin = open("input.txt", 'r')
sys.stdout = open("output.txt", 'w')
input = iter(sys.stdin.readlines())
n = int(next(input))
for _ in range(n):
l = int(next(input))
a = (int(i) for i in next(input).split())
sum1 = sum(a)
ar = sum1 / l
if ar == 1:
sys.stdout.write('0\n')
elif ar < 1:
sys.stdout.write('1\n')
else:
sys.stdout.write(str(sum1-l)+'\n')
sys.stdout.flush()
| 1624026900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds | ["? 1 2\n\n? 12 4\n\n! 4\n? 2000000000 1999999999\n\n! 1000000000"] | 442015fe13f7f75876d7163f438960d8 | NoteThe first hidden number is $$$4$$$, that's why the answers for the queries are:"? 1 2"Β β $$$\gcd(4 + 1, 4 + 2) = \gcd(5, 6) = 1$$$."? 12 4"Β β $$$\gcd(4 + 12, 4 + 4) = \gcd(16, 8) = 8$$$.The second hidden number is $$$10^9$$$, that's why the answer for the query is:"? 2000000000 1999999999"Β β $$$\gcd(3 \cdot 10^9, 3 \cdot 10^9 - 1) = 1$$$.These queries are made only for understanding the interaction and are not enough for finding the true $$$x$$$. | This is an interactive problem.There is a positive integer $$$1 \le x \le 10^9$$$ that you have to guess.In one query you can choose two positive integers $$$a \neq b$$$. As an answer to this query you will get $$$\gcd(x + a, x + b)$$$, where $$$\gcd(n, m)$$$ is the greatest common divisor of the numbers $$$n$$$ and $$$m$$$.To guess one hidden number $$$x$$$ you are allowed to make no more than $$$30$$$ queries. | null | The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) denoting the number of test cases. The integer $$$x$$$ that you have to guess satisfies the constraints: ($$$1 \le x \le 10^9$$$). | standard output | standard input | Python 3 | Python | 2,000 | train_096.jsonl | d84f7b54b5f8bdc02ef65d0d65f2640f | 256 megabytes | ["2\n\n1\n\n8\n\n\n1"] | PASSED | if True:
from math import gcd
from sys import stdout
t = int(input())
for _ in range(t):
num = 0
for i in range(30):
print(f'? {2**i-num} {3*2**i-num}')
stdout.flush()
if int(input()) == 2**(i+1):
num += 2**i
print(f'! {num}')
| 1649428500 | [
"number theory",
"math",
"games"
] | [
1,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["5\n3\n3\n1999999999000000000"] | 4df38c9b42b0f0963a121829080d3571 | NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest. | There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the thirdΒ β at time $$$2 \cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the secondΒ β at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants. | Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case. | The first line contains a single integer $$$k$$$ ($$$1 \le k \le 1000$$$)Β β the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$)Β β the number of participants, the start interval and the contest duration. | standard output | standard input | Python 3 | Python | 1,000 | train_096.jsonl | 825ec541fe94fdd049cf75b74ad3cb5e | 256 megabytes | ["4\n4 2 5\n3 1 2\n3 3 10\n2000000000 1 2000000000"] | PASSED |
def main():
test_case = int(input())
for i in range(0, test_case):
inputs = tuple(map(int, input().split()))
n = inputs[0]
x = inputs[1]
t = inputs[2]
f = t // x
if n < f:
f = n
sum = (2*n*f - f**2 - f)//2
print(f"{sum}")
if __name__ == "__main__":
main()
| 1624183500 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1.5000000000000", "2.6666666666667"] | 2cd5807e3f9685d4eff88f2283904f0d | null | While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface. Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$? | Print a single numberΒ β the depth of the lake at point $$$A$$$. The absolute or relative error should not exceed $$$10^{-6}$$$. Formally, let your answer be $$$A$$$, and the jury's answer be $$$B$$$. Your answer is accepted if and only if $$$\frac{|A - B|}{\max{(1, |B|)}} \le 10^{-6}$$$. | The only line contains two integers $$$H$$$ and $$$L$$$ ($$$1 \le H < L \le 10^{6}$$$). | standard output | standard input | Python 3 | Python | 1,000 | train_000.jsonl | aaf31816c1b7efb05e590ad2ecde2230 | 256 megabytes | ["1 2", "3 5"] | PASSED | from math import sqrt
h, l = map(int, input().split())
print((l * l - h * h) / (2 * h)) | 1564497300 | [
"geometry",
"math"
] | [
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["0\n2 1 4", "1\n1 1"] | 4c387ab2a0d028141634ade32ae97d03 | NoteIn the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1. | Petya has n integers: 1,β2,β3,β...,βn. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group. | Print the smallest possible absolute difference in the first line. In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them. | The first line contains a single integer n (2ββ€βnββ€β60β000) β the number of integers Petya has. | standard output | standard input | Python 3 | Python | 1,300 | train_001.jsonl | cae2f6e4ef82c129ccefc1208ca57dad | 256 megabytes | ["4", "2"] | PASSED | n=int(input())
f=[]
f1=s1=0
for i in range(n,0,-1):
if f1<=s1:
f1+=i
f.append(i)
else:
s1+=i
print(abs(f1-s1))
print(str(len(f)),*f)
| 1513492500 | [
"math",
"graphs"
] | [
0,
0,
1,
1,
0,
0,
0,
0
] |
|
3 seconds | ["b\nac\nabcdebfadg\nbcdefghijklmnopqrstuvwxyza\nbcdefghijklmnopqrstuvwxyaz"] | faf5ec909f5147c11454e1ecb9c372ee | NoteIn the first test case, we couldn't have the string "a", since the letter a would transit to itself. Lexicographically the second string "b" is suitable as an answer.In the second test case, the string "aa" is not suitable, since a would transit to itself. "ab" is not suitable, since the circle would be closed with $$$2$$$ letters, but it must contain all $$$26$$$. The next string "ac" is suitable.Below you can see the schemes for the first three test cases. The non-involved letters are skipped, they can be arbitrary placed in the gaps. | There was a string $$$s$$$ which was supposed to be encrypted. For this reason, all $$$26$$$ lowercase English letters were arranged in a circle in some order, afterwards, each letter in $$$s$$$ was replaced with the one that follows in clockwise order, in that way the string $$$t$$$ was obtained. You are given a string $$$t$$$. Determine the lexicographically smallest string $$$s$$$ that could be a prototype of the given string $$$t$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if: in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter, that appears earlier in the alphabet than the corresponding letter in $$$b$$$. | For each test case, output a single line containing the lexicographically smallest string $$$s$$$ which could be a prototype of $$$t$$$. | The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$) β the number of test cases. The description of test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β the length of the string $$$t$$$. The next line contains the string $$$t$$$ of the length $$$n$$$, containing lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,400 | train_098.jsonl | 6b8c2604c15164ef477a37f2187dc8fe | 256 megabytes | ["5\n\n1\n\na\n\n2\n\nba\n\n10\n\ncodeforces\n\n26\n\nabcdefghijklmnopqrstuvwxyz\n\n26\n\nabcdefghijklmnopqrstuvwxzy"] | PASSED | from heapq import _heapify_max, heapify, heappush, heappop
from bisect import bisect_left, bisect_right, bisect, insort
import math, sys, os
from string import ascii_lowercase
from re import A, L
from collections import defaultdict, Counter
from math import log, ceil, sqrt, floor, gcd, log2, factorial
from itertools import chain, combinations, count
from functools import reduce
'''
int: int(input())
str: input().split()[0]
ints: list(map(int, input().split()))
strs: input().split()
'''
input = sys.stdin.readline
printt = lambda x: sys.stdout.write(str(x) + "\n")
printts = lambda x: sys.stdout.write(" ".join(map(str,x)) + "\n")
divisors = lambda n: set(chain.from_iterable((i, n // i) for i in range(1, int(sqrt(n)) + 1) if not n % i))
is_prime = lambda n: False if (n < 2) else (True if n in [2,3] else (False if n % 2 == 0 else (not any(n % i == 0 for i in range(3, 1 + floor(sqrt(n)), 2)))))
n_is_power_of_p = lambda n, p: not log(n, p) % 1
lcm = lambda a,b: int(a*b/gcd(a,b)) ## PyPy3 doesn't have lcm -_-
is_sqr = lambda num: sqrt(num).is_integer()
def heapsort(iterable):
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]
'''
heapify(arr)
heappush(arr,n)
heappop(arr)
'''
def yes(): printt("YES")
def no(): printt("NO")
mod = 998244353
# for case in range(1):
for case in range(int(input())):
'''
n = int(input())
s = input().split()[0]
map(int, input().split())
arr = list(map(int, input().split()))
arr = input().split()
frr = [list(map(int, input().split())) for _ in range(n)]
'''
n = int(input())
t = input().split()[0]
used = [False] * 26
letters=ascii_lowercase
chainn = {}
res = ''
uniqs = len(set(t))
def loopCheck(l,c):
while l in chainn:
l = chainn[l]
if l == c: return True
return False
for i in range(n):
if t[i] in chainn: continue
for j in range(26):
if used[j] or t[i] == letters[j] or (loopCheck(letters[j], t[i]) and len(chainn) < 25): continue
chainn[t[i]] = letters[j]
used[j] = True
break
printt(''.join(chainn[ch] for ch in t))
'''
''' | 1664721300 | [
"strings",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
1,
0
] |
|
4 seconds | ["3\n2\n0\n2\n3\n2"] | 18ac51a009c907fe8e4cd2bb8612da20 | NoteIn the first test case of the example, all $$$3$$$ words can be used to make an interesting story. The interesting story is "bac aaada e".In the second test case of the example, the $$$1$$$-st and the $$$3$$$-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time.In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is $$$0$$$.In the fourth test case of the example, Stephen can use the $$$3$$$-rd and the $$$4$$$-th words to make an interesting story. The interesting story is "c bc". | Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!To compose a story, Stephen wrote out $$$n$$$ words consisting of the first $$$5$$$ lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs $$$5$$$ times, all other letters occur $$$4$$$ times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total).You are given a sequence of $$$n$$$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $$$0$$$. | For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of the words in the sequence. Then $$$n$$$ lines follow, each of them contains a word β a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i.βe. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$; the sum of the lengths of all words over all test cases doesn't exceed $$$4 \cdot 10^5$$$. | standard output | standard input | PyPy 3-64 | Python | 1,500 | train_099.jsonl | 8fd50b67079b4c7396bf6c3942dcbd95 | 256 megabytes | ["6\n3\nbac\naaada\ne\n3\naba\nabcde\naba\n2\nbaba\nbaba\n4\nab\nab\nc\nbc\n5\ncbdca\nd\na\nd\ne\n3\nb\nc\nca"] | PASSED | from sys import stdin, stdout
t = int(stdin.readline())
for tt in range(t):
n = int(stdin.readline())
a = [stdin.readline().strip() for i in range(n)]
chars = 'abcde'
# c_count = [{c: 0 for c in chars} for i in range(n)]
# not_c_count = [{c: 0 for c in chars} for i in range(n)]
# for i in range(n):
# for c in stdin.readline().strip(): # a[i]:
# c_count[i][c] += 1
# for not_c in chars:
# if not_c != c:
# not_c_count[i][not_c] += 1
# if n >= 100000:
# del a
# sm = {c: sum([c_count[i][c] for i in range(n)]) for c in chars}
# print(sm)
res = {c: 0 for c in chars}
for c in chars:
# c_minus_not_c = [c_count[i][c] - not_c_count[i][c] for i in range(n)]
c_minus_not_c = [0 for i in range(n)]
c_sum = 0
not_c_sum = 0
for i in range(n):
for char in a[i]:
if char == c:
c_minus_not_c[i] += 1
c_sum += 1
else:
c_minus_not_c[i] += -1
not_c_sum += 1
c_minus_not_c.sort()
# c_sum = sm[c]
# not_c_sum = sum([sm[not_c] for not_c in chars if not_c != c])
rem_num = 0
l = 0
while c_sum <= not_c_sum and l < n:
if c_minus_not_c[l] >= 0:
rem_num = n
break
c_sum -= c_minus_not_c[l]
l += 1
rem_num += 1
res[c] = n - rem_num
# if n >= 100000:
# del c_minus_not_c
stdout.write(str(max([res[c] for c in chars])) + '\n')
| 1627050900 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["abab\n1\nertyqw\n3\naaaaa\n1\naksala\n6\navjsmbpfl\n5\np\n1"] | f501e17271a220f3bcd69377c01721a1 | NoteIn the first testcase of the first sample, the string modification results for the sample abab are as follows : for $$$k = 1$$$ : abab for $$$k = 2$$$ : baba for $$$k = 3$$$ : abab for $$$k = 4$$$ : babaThe lexicographically smallest string achievable through modification is abab for $$$k = 1$$$ and $$$3$$$. Smallest value of $$$k$$$ needed to achieve is hence $$$1$$$. | Vasya has a string $$$s$$$ of length $$$n$$$. He decides to make the following modification to the string: Pick an integer $$$k$$$, ($$$1 \leq k \leq n$$$). For $$$i$$$ from $$$1$$$ to $$$n-k+1$$$, reverse the substring $$$s[i:i+k-1]$$$ of $$$s$$$. For example, if string $$$s$$$ is qwer and $$$k = 2$$$, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length $$$2$$$) weqr (after reversing the second substring of length $$$2$$$) werq (after reversing the last substring of length $$$2$$$) Hence, the resulting string after modifying $$$s$$$ with $$$k = 2$$$ is werq. Vasya wants to choose a $$$k$$$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $$$k$$$. Among all such $$$k$$$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. | For each testcase output two lines: In the first line output the lexicographically smallest string $$$s'$$$ achievable after the above-mentioned modification. In the second line output the appropriate value of $$$k$$$ ($$$1 \leq k \leq n$$$) that you chose for performing the modification. If there are multiple values of $$$k$$$ that give the lexicographically smallest string, output the smallest value of $$$k$$$ among them. | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$)Β β the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of $$$n$$$ lowercase latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$. | standard output | standard input | PyPy 3 | Python | 1,400 | train_003.jsonl | e32df1e3fc5766bbd06a42a886f0c73c | 256 megabytes | ["6\n4\nabab\n6\nqwerty\n5\naaaaa\n6\nalaska\n9\nlfpbavjsm\n1\np"] | PASSED | # cook your dish here
for _ in range(int(input())):
n=int(input())
s=input()
ch=s[0]
for i in range(1,n):
if ch>s[i]:
ch=s[i]
ks=[]
for i in range(n):
if(s[i]==ch):
ks.append(i+1)
low=-1
for k in ks:
rev=False
if (n-k+1)%2==1:
rev=True
temp=s[k-1:n]
str1=s[0:k-1]
if rev:
str1=str1[::-1]
temp=temp+str1
if (low==-1) or ans>temp:
low=k
ans=temp
print(ans)
print(low) | 1583332500 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["6 9 3\n21 39 3\n29 43 1\n49 35 7\n146 219 73\n28622 122661788 2"] | d4f4d6341f52cceb862faa89e85a42a3 | NoteIn the first test case, $$$6 + 9 + 3 = 18$$$ and $$$\operatorname{gcd}(6, 9) = 3$$$.In the second test case, $$$21 + 39 + 3 = 63$$$ and $$$\operatorname{gcd}(21, 39) = 3$$$.In the third test case, $$$29 + 43 + 1 = 73$$$ and $$$\operatorname{gcd}(29, 43) = 1$$$. | Given a positive integer $$$n$$$. Find three distinct positive integers $$$a$$$, $$$b$$$, $$$c$$$ such that $$$a + b + c = n$$$ and $$$\operatorname{gcd}(a, b) = c$$$, where $$$\operatorname{gcd}(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. | For each test case, output three distinct positive integers $$$a$$$, $$$b$$$, $$$c$$$ satisfying the requirements. If there are multiple solutions, you can print any. We can show that an answer always exists. | The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)Β β the number of test cases. Description of the test cases follows. The first and only line of each test case contains a single integer $$$n$$$ ($$$10 \le n \le 10^9$$$). | standard output | standard input | PyPy 3-64 | Python | 900 | train_100.jsonl | e769df5794ee4ae7bfe5b1cc709f5bbe | 256 megabytes | ["6\n18\n63\n73\n91\n438\n122690412"] | PASSED | import math
case = int(input())
i=1
while i <= case:
i=i+1
n = int(input())
j=1
while (n-1)%j ==0:
j=j+1
else:
if j==2:
print(math.floor(n/2),math.floor(n/2)-1,1)
else:
k = 2
while math.gcd(k, n - 1) != 1:
k = k + 1
else:
print(k, n - k - 1, 1)
| 1639661700 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["2 3 6 \n1\n2 4 \n0\n2 30 6 3 15 5 10 \n0"] | 406f8f662d2013d87b36dacca663bef5 | NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime. | An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that. | For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them. | The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$Β β the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$Β β the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$. | standard output | standard input | PyPy 3 | Python | 2,100 | train_014.jsonl | 6cf9fb3ad5068af8600c2de91c801dc2 | 256 megabytes | ["3\n6\n4\n30"] | PASSED | import sys, math
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
def prime_factors(n):
factors = []
num = 0
while n % 2 == 0:
num += 1
n //= 2
if num:
factors.append((2,num))
i = 3
while n > 1 and i*i <= n:
num = 0
while n % i == 0:
num += 1
n //= i
if num:
factors.append((i,num))
i += 2
if n > 2:
factors.append((n,1))
return factors
def solve():
N = getInt()
facs = prime_factors(N)
if len(facs) == 2 and facs[0][1] == 1 and facs[1][1] == 1:
print(facs[0][0],facs[1][0],facs[0][0]*facs[1][0])
print(1)
return
prime_facs = [f[0] for f in facs]
facs2 = factors(N)
facs2.remove(1)
for p in prime_facs:
facs2.remove(p)
#facs2 = sorted(list(facs2))
#first we need to make sure all requirements are satisfied, then we add in later elements
to_add = []
lenP = len(prime_facs)
if lenP > 2:
for j in range(lenP):
y = prime_facs[j]*prime_facs[(j+1)%lenP]
to_add.append(y)
facs2.remove(y)
ans = []
for j in range(lenP):
ans.append(prime_facs[j])
ans.append(to_add[j])
elif lenP == 1:
ans = [prime_facs[0]]
else:
p0, p1 = prime_facs
facs2.remove(p0*p1)
facs2.remove(N)
ans = [p0,N,p1,p0*p1]
for ff in facs2:
for p in prime_facs:
if ff % p == 0:
prime = p
break
x = ans.index(prime)
ans.insert(x+1,ff)
assert(len(ans)==len(factors(N))-1)
print(*ans)
print(0)
return
T = getInt()
for t in range(T):
solve()
| 1600526100 | [
"number theory",
"math"
] | [
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second | ["42\n487\n519\n528\n544\n564\n588\n628"] | 7a48218582b90f735a09083df9e15b96 | Note$$$a_{1} = 487$$$ $$$a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$$$ $$$a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$$$ $$$a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$$$ $$$a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$$$ $$$a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$$$ $$$a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$$$ | Let's define the following recurrence: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$$$$$Here $$$minDigit(x)$$$ and $$$maxDigit(x)$$$ are the minimal and maximal digits in the decimal representation of $$$x$$$ without leading zeroes. For examples refer to notes.Your task is calculate $$$a_{K}$$$ for given $$$a_{1}$$$ and $$$K$$$. | For each test case print one integer $$$a_{K}$$$ on a separate line. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of independent test cases. Each test case consists of a single line containing two integers $$$a_{1}$$$ and $$$K$$$ ($$$1 \le a_{1} \le 10^{18}$$$, $$$1 \le K \le 10^{16}$$$) separated by a space. | standard output | standard input | PyPy 3 | Python | 1,200 | train_004.jsonl | 4fc44835588788a606f3efe22c9737df | 256 megabytes | ["8\n1 4\n487 1\n487 2\n487 3\n487 4\n487 5\n487 6\n487 7"] | PASSED | t=int(input())
for _ in range(t):
a1,k=map(int,input().split())
for i in range(k-1):
mi=9
ma=0
for d in str(a1):
if int(d)>ma:
ma=int(d)
if int(d)<mi:
mi=int(d)
if mi==0:
break
a1=a1+(ma*mi)
print(a1) | 1589628900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["1\n11\n21\n10973\n13716\n1111111111"] | 0beecbd62aa072a2f3aab542eeb56373 | null | Mishka wants to buy some food in the nearby shop. Initially, he has $$$s$$$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $$$1 \le x \le s$$$, buy food that costs exactly $$$x$$$ burles and obtain $$$\lfloor\frac{x}{10}\rfloor$$$ burles as a cashback (in other words, Mishka spends $$$x$$$ burles and obtains $$$\lfloor\frac{x}{10}\rfloor$$$ back). The operation $$$\lfloor\frac{a}{b}\rfloor$$$ means $$$a$$$ divided by $$$b$$$ rounded down.It is guaranteed that you can always buy some food that costs $$$x$$$ for any possible value of $$$x$$$.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has $$$s=19$$$ burles then the maximum number of burles he can spend is $$$21$$$. Firstly, he can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback. Now he has $$$s=10$$$ burles, so can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback and spend it too.You have to answer $$$t$$$ independent test cases. | For each test case print the answer on it β the maximum number of burles Mishka can spend if he buys food optimally. | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a separate line and consists of one integer $$$s$$$ ($$$1 \le s \le 10^9$$$) β the number of burles Mishka initially has. | standard output | standard input | PyPy 3 | Python | 900 | train_004.jsonl | 6b28909462269516b2475b6436c53c9c | 256 megabytes | ["6\n1\n10\n19\n9876\n12345\n1000000000"] | PASSED | n = int(input())
for i in range(0, n):
m = int(input())
print(int(m//0.9))
| 1580826900 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["? 3 5 6\n? 32 24 37\n! 5"] | c7f31e0c57cf15f71c401d826c3ee0ef | NoteThe example of interaction is not correct β you should sumbit exactly $$$100$$$ integers in each query. Everything else is correct.Hacks are forbidden in this problem. | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury picked an integer $$$x$$$ not less than $$$0$$$ and not greater than $$$2^{14} - 1$$$. You have to guess this integer.To do so, you may ask no more than $$$2$$$ queries. Each query should consist of $$$100$$$ integer numbers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{100}$$$ (each integer should be not less than $$$0$$$ and not greater than $$$2^{14} - 1$$$). In response to your query, the jury will pick one integer $$$i$$$ ($$$1 \le i \le 100$$$) and tell you the value of $$$a_i \oplus x$$$ (the bitwise XOR of $$$a_i$$$ and $$$x$$$). There is an additional constraint on the queries: all $$$200$$$ integers you use in the queries should be distinct.It is guaranteed that the value of $$$x$$$ is fixed beforehand in each test, but the choice of $$$i$$$ in every query may depend on the integers you send. | To give the answer, your program should print one line $$$!$$$ $$$x$$$ with a line break in the end. After that, it should flush the output and terminate gracefully. | null | standard output | standard input | PyPy 2 | Python | 1,900 | train_030.jsonl | e5909c1623b5df2aa9435eca9539946b | 256 megabytes | ["0\n32"] | PASSED | import sys
import math
import bisect
import atexit
import io
import heapq
from collections import defaultdict, Counter
MOD = int(1e9+7)
# n = map(int, raw_input().split())
# input = map(int, raw_input().split())
def main():
print '?',
for i in range(1, 101):
print i*(2**7),
n1 = map(int, raw_input().split())[0]
print '\n'
# sys.stdout.flush()
print '?',
for i in range(1, 101):
print i,
print '\n'
n2 = map(int, raw_input().split())[0]
# n1, n2 = 128^16383, 1^16383
sys.stdout.flush()
# print n1,n2
# print bin(n1), bin(n2)
n1 = '0'*20 + bin(n1)[2:]
if bin(n2)[2:] <=7:
n2 = '000000000000000000000'
else:
n2 = bin(n2)[2:]
ans = n2[:-7] + n1[-7:]
ans = int(ans, 2)
print '!', ans
main()
| 1566484500 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["2\n2 4\n3 3\n3 1"] | 591372383cf3624f69793c41370022de | null | Numbers $$$1, 2, 3, \dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal: choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$; choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$; choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it. | For each test case, in the first line, print the minimum possible number left on the board after $$$n - 1$$$ operations. Each of the next $$$n - 1$$$ lines should contain two integersΒ β numbers $$$a$$$ and $$$b$$$ chosen and erased in each operation. | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)Β β the number of integers written on the board initially. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$. | standard output | standard input | Python 3 | Python | 1,000 | train_000.jsonl | 88084dde61bbebdebe163309a2bda179 | 256 megabytes | ["1\n4"] | PASSED |
def ii(): return int(input())
def mi(): return map(int, input().split())
if __name__ == '__main__':
for _ in range(ii()):
n = ii()
# if n == 3:
# print("2\n3 1\n2 2")
# continue
if n == 2:
print("2\n2 1")
continue
l = list(range(1, n+1))
a = l.pop()
answer = []
b = l.pop(-2)
answer.append((a, b))
a = int((a + b) / 2)
while l:
b = l.pop()
answer.append((a, b))
a = int((a + b) / 2)
print(a)
for i in answer:
print(*i)
| 1602407100 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second | ["3 2 0 2 0", "2 3 4 0"] | e544ed0904e2def0c1b2d91f94acbc56 | null | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added). | Print n integers a1,βa2,β...,βan, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one. | The first line of the input contains a single number n (1ββ€βnββ€β105) β the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1ββ€βhiββ€β109), where hi equals the number of floors in the i-th house. | standard output | standard input | Python 3 | Python | 1,100 | train_001.jsonl | 5995d4c0bb90ec2b3026b9108a50f587 | 256 megabytes | ["5\n1 2 3 1 2", "4\n3 2 1 4"] | PASSED | n = int(input())
h = map(int, input().split()[::-1])
m_h = 0
res = []
for h in h:
if m_h < h:
res.append(0)
m_h = h
else:
res.append(m_h - h + 1)
print(" ".join(map(str, res[::-1]))) | 1443430800 | [
"math"
] | [
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds | ["Yes", "No", "No"] | e5f422a4247b90af7b42b64875a0f87e | NoteIn the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once.In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t.In the third sample there is no occurrence of string t in string s. | A subsequence of length |x| of string sβ=βs1s2... s|s| (where |s| is the length of string s) is a string xβ=βsk1sk2... sk|x| (1ββ€βk1β<βk2β<β...β<βk|x|ββ€β|s|).You've got two stringsΒ β s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1ββ€βiββ€β|s|), there is such subsequence xβ=βsk1sk2... sk|x| of string s, that xβ=βt and for some j (1ββ€βjββ€β|x|) kjβ=βi. | Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise. | The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105. | standard output | standard input | Python 3 | Python | 1,900 | train_034.jsonl | 6b329a3d711113132010b94250e12283 | 256 megabytes | ["abab\nab", "abacaba\naba", "abc\nba"] | PASSED | import bisect
import string
s = input()
t = input()
max_match = [0 for i in range(len(s))]
min_match = [0 for i in range(len(s))]
char_idx = [0 for i in range(30)]
char_occur = [ [] for i in range(30) ]
for (i, ch) in enumerate(t):
idx = ord(ch) - ord('a')
char_occur[idx].append(i)
for ch in string.ascii_lowercase:
idx = ord(ch) - ord('a')
char_occur[idx].append(len(t)+1)
matched = -1
for (i, ch) in enumerate(s):
if matched==len(t)-1:
max_match[i] = matched
else:
if ch == t[matched+1]:
matched += 1
max_match[i] = matched
matched = len(t)
for (i, ch) in enumerate(s[::-1]):
i = len(s) - i - 1
if matched==0:
min_match[i] = matched
else:
if ch == t[matched-1]:
matched -= 1
min_match[i] = matched
for (i, ch) in enumerate(s):
low = min_match[i]
high = max_match[i]
ch = ord(ch) - ord('a')
idx = char_idx[ch]
while idx<len(char_occur[ch]) and char_occur[ch][idx]<low:
idx += 1
char_idx[ch] = idx
if idx == len(char_occur[ch]):
print("No")
exit()
if char_occur[ch][idx] > high:
print("No")
exit()
print("Yes") | 1347809400 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds | ["1", "6", "2", "1", "24"] | cff3074a82bffdd49579a47c7491f972 | NoteIn the first case, the only possible evolution plan is: In the second case, any permutation of (1,ββ2,ββ3) is valid.In the third case, there are two possible plans: In the fourth case, the only possible evolution plan is: | It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation f of {1,β2,β...,βm}, such that f(x)β=βy means that a Pokemon of type x evolves into a Pokemon of type y.The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.Two evolution plans f1 and f2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f1(i)ββ βf2(i).Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109β+β7. | Output the number of valid evolution plans modulo 109β+β7. | The first line contains two integers n and m (1ββ€βnββ€β105, 1ββ€βmββ€β106)Β β the number of gyms and the number of Pokemon types. The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the integer gi (1ββ€βgiββ€β105)Β β the number of Pokemon in the i-th gym. After that gi integers follow, denoting types of the Pokemons in the i-th gym. Each of these integers is between 1 and m. The total number of Pokemons (the sum of all gi) does not exceed 5Β·105. | standard output | standard input | Python 3 | Python | 1,900 | train_004.jsonl | d94a233013eb65bb040d0a21a5bca39d | 256 megabytes | ["2 3\n2 1 2\n2 2 3", "1 3\n3 1 2 3", "2 4\n2 1 2\n3 2 3 4", "2 2\n3 2 2 1\n2 1 2", "3 7\n2 1 2\n2 3 4\n3 5 6 7"] | PASSED | # ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict,Counter
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for ik in range(1):
n,m=map(int,input().split())
#s = Factorial(mod)
d=defaultdict(list)
for i in range(n):
l=list(map(int,input().split()))
for j in range(1,l[0]+1):
d[l[j]].append(i)
w=m-len(d)
ans=1
#x=list(map(str,d.values()))
tot=defaultdict(int)
#print(x)
for i in d:
str1 = ""
for ele in d[i]:
str1 += str(ele)+" "
#print(str1,end=' ')
tot[str1]+=1
#print()
for e1 in tot:
e=tot[e1]
for i in range(2, e + 1):
ans = ans * i % mod
for i in range(2, w + 1):
ans = ans * i % mod
print(ans)
| 1484235300 | [
"strings"
] | [
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second | ["-1", "3\n2\n1\n3"] | 700b654a2ead672cba715653425029b4 | NoteThe 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). | 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. A list of candidates is prepared, containing some (possibly all) of the n men in some order. Each of the n men decides to give a gift. 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. 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? | 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. | 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. | standard output | standard input | Python 3 | Python | 2,000 | train_051.jsonl | c0d22b1a8cf95aa6bdb15cf41476b480 | 256 megabytes | ["3 2\n1 2\n2 3\n1 2 1", "4 2\n1 2\n3 4\n1 2 3 3"] | PASSED | n, m = map(int, input().split())
adj = [[] for _ in range(n)]
cp = [-1] * n
for i in range(m):
p, c = map(int, input().split())
adj[p - 1].append(c - 1)
cp[c - 1] = p - 1
pres = [i - 1 for i in map(int, input().split())]
level = [0] * n
from collections import deque
def bfs(v):
q = deque([v])
while q:
v = q.pop()
if cp[v] >= 0:
level[v] = level[cp[v]] + 1
for nv in adj[v]:
q.append(nv)
for i in range(n):
if cp[i] == -1:
bfs(i)
for i in range(n):
if level[i] > 0:
par = cp[i]
if pres[i] != pres[par] and level[pres[i]] <= level[par]:
print(-1)
exit()
pres = list(set(pres))
pres = sorted(pres, key = lambda i : level[i], reverse = True)
print(len(pres))
pres = [i + 1 for i in pres]
print("\n".join(map(str, pres))) | 1465922100 | [
"trees",
"graphs"
] | [
0,
0,
1,
0,
0,
0,
0,
1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.