Dataset Viewer
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
] |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 52