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
listlengths 1
5
| hidden_unit_tests
stringclasses 1
value | labels
listlengths 8
8
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 second
|
["aaabb\naabab\nbaaba\nbbaaa\nabb\nbab\naaaaabaaaaabaaaaaaaa"]
|
e32f0615541d97a025bc99c3cbf5380e
| null |
For the given integer $$$n$$$ ($$$n > 2$$$) let's write down all the strings of length $$$n$$$ which contain $$$n-2$$$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string $$$s$$$ of length $$$n$$$ is lexicographically less than string $$$t$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$s_i < t_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$s_j = t_j$$$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if $$$n=5$$$ the strings are (the order does matter): aaabb aabab aabba abaab ababa abbaa baaab baaba babaa bbaaa It is easy to show that such a list of strings will contain exactly $$$\frac{n \cdot (n-1)}{2}$$$ strings.You are given $$$n$$$ ($$$n > 2$$$) and $$$k$$$ ($$$1 \le k \le \frac{n \cdot (n-1)}{2}$$$). Print the $$$k$$$-th string from the list.
|
For each test case print the $$$k$$$-th string from the list of all described above strings of length $$$n$$$. Strings in the list are sorted lexicographically (alphabetically).
|
The input contains one or more test cases. The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case is written on the the separate line containing two integers $$$n$$$ and $$$k$$$ ($$$3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2})$$$. The sum of values $$$n$$$ over all test cases in the test doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_003.jsonl
|
ff78c11ac46c3813ce36875ec6cedb13
|
256 megabytes
|
["7\n5 1\n5 2\n5 8\n5 10\n3 1\n3 2\n20 100"]
|
PASSED
|
t = int(input())
for num in range(t):
n, k = map(int, input().split())
b1 = n - 2
b2 = n - 1
if k < 1000:
i = 0
elif k == (n*(n-1))//2:
b1 = 0
b2 = 1
i = k-1
else:
i = int((1 + (1 - (4 * -1 * k * 2)) ** (1 / 2)) // 2)
b1 = n - i - 1
i *= (i - 1) / 2
while True:
#print(f"iteration: {i}, b1: {b1}, b2: {b2}")
if i == k - 1:
most = ['a']*n
most[b1] = 'b'
most[b2] = 'b'
print(''.join(most))
break
else:
i += 1
if b2 - b1 == 1:
b1 -= 1
b2 = n - 1
else:
b2 -= 1
|
1585233300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["13-12-2013"]
|
dd7fd84f7915ad57b0e21f416e2a3ea0
| null |
A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.
|
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
|
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_007.jsonl
|
e2843da249328fdaa98f52fb3d8dbeb1
|
256 megabytes
|
["777-444---21-12-2013-12-2013-12-2013---444-777"]
|
PASSED
|
import re
def c(d):
d,m,y=map(int,d.split('-'))
M=set([1,3,5,7,8,10,12])
return y > 2012 and y< 2016 and d>0and(d<29 and m==2 or d<32 and m in M or d<30 and m in (set(range(4,13))-M))
d=re.findall("(?=(\d\d-\d\d-\d{4}))", raw_input())
r={}
for i in d:
r[i]=r.get(i,0)+c(i)
print max(r.items(), key=lambda y:y[1])[0]
|
1356622500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1 second
|
["0\n3\n2\n92\n87654322\n9150"]
|
d67a97a3b69d599b03d3fce988980646
|
NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \rightarrow 10 \rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$).
|
You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.
|
For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 800 |
train_000.jsonl
|
6b6b23dc5767f0e13b03c02b44160c2f
|
256 megabytes
|
["6\n5 5\n13 42\n18 4\n1337 420\n123456789 1000000000\n100500 9000"]
|
PASSED
|
n = int(input())
tests = [input() for _ in range(n)]
for test in tests:
a, b = [int(x) for x in test.split(' ')]
count = 0
while True:
if a == b:
print(count)
break
else:
diff = a - b
tens = abs(diff / 10)
if tens.is_integer():
count += tens
else:
count += (int(tens)+1)
print(int(count))
break
|
1599230100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2 7 42", "7 8 56"]
|
f60ea0f2caaec16894e84ba87f90c061
| null |
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.
|
If the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1. If there are multiple answers, print any of them.
|
The single line contains single integer n (1 ≤ n ≤ 104).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,500 |
train_001.jsonl
|
c895b235e69dc87b0dc8de74ca386d10
|
256 megabytes
|
["3", "7"]
|
PASSED
|
n = int(raw_input())
if n==1: print "-1"
elif n==2: print "2 3 6"
else:
isAnswered = False
x = (n+1)/2
while x*2 < 3*n:
c = x*2-n
d = x*n
y = x + 1
while True:
if (2*x*y-n*x-n*y) <= 0:
y += 1
break
if (n*x*y) % (2*x*y-n*x-n*y) == 0:
z = (n*x*y) / (2*x*y-n*x-n*y)
print "%d %d %d" % (x,y,z)
isAnswered = True
break
y += 1
x += 1
if isAnswered: break
|
1481726100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["0", "2", "1"]
|
f8315dc903b0542c453cab4577bcb20d
|
NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
|
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.
|
Print the single number — the number of groups of students that will be kicked out from the club.
|
The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,200 |
train_012.jsonl
|
b9995c62b01c0c0cd01443e59dba4849
|
256 megabytes
|
["3 3\n1 2\n2 3\n3 1", "6 3\n1 2\n2 3\n3 4", "6 5\n1 4\n2 4\n3 4\n5 4\n6 4"]
|
PASSED
|
r = lambda: raw_input().strip()
n,m = map(int,r().split())
ties = [map(int,r().split()) for _ in xrange(m)]
count = 0
while len(ties)>0:
all_ties = []
l1 = len(ties)
for t in ties:
all_ties.append(t[0])
all_ties.append(t[1])
for i in xrange(n):
if all_ties.count(i+1)==1:
for t in xrange(len(ties)):
if ties[t][0] == i+1 or ties[t][1] == i+1:
ties.remove(ties[t])
break
l2 = len(ties)
if l1==l2:
break
count += 1
print count
|
1321337400
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["3\n5\n14\n16\n24\n24\n24\n57\n54\n36\n36\n6\n18\n27\n28"]
|
560e26bdfab14b919a7deadefa57f2de
|
NoteIn the first test case, initially and after each request, the answer is achieved at $$$s = 1$$$, $$$k = 1$$$ or $$$s = 2$$$, $$$k = 1$$$.In the second test case, initially, the answer is achieved when $$$s = 1$$$, $$$k = 2$$$ or $$$s = 3$$$, $$$k = 2$$$. After the first request, the answer is achieved at $$$s = 2$$$, $$$k = 2$$$ or $$$s = 4$$$, $$$k = 2$$$.
|
Tonya was given an array of $$$a$$$ of length $$$n$$$ written on a postcard for his birthday. For some reason, the postcard turned out to be a cyclic array, so the index of the element located strictly to the right of the $$$n$$$-th is $$$1$$$. Tonya wanted to study it better, so he bought a robot "Burenka-179".A program for Burenka is a pair of numbers $$$(s, k)$$$, where $$$1 \leq s \leq n$$$, $$$1 \leq k \leq n-1$$$. Note that $$$k$$$ cannot be equal to $$$n$$$. Initially, Tonya puts the robot in the position of the array $$$s$$$. After that, Burenka makes exactly $$$n$$$ steps through the array. If at the beginning of a step Burenka stands in the position $$$i$$$, then the following happens: The number $$$a_{i}$$$ is added to the usefulness of the program. "Burenka" moves $$$k$$$ positions to the right ($$$i := i + k$$$ is executed, if $$$i$$$ becomes greater than $$$n$$$, then $$$i := i - n$$$). Help Tonya find the maximum possible usefulness of a program for "Burenka" if the initial usefulness of any program is $$$0$$$.Also, Tony's friend Ilyusha asks him to change the array $$$q$$$ times. Each time he wants to assign $$$a_p := x$$$ for a given index $$$p$$$ and a value $$$x$$$. You need to find the maximum possible usefulness of the program after each of these changes.
|
For each test case, output $$$q+1$$$ numbers — the maximum usefulness of a program initially and after each of the changes.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) is the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. The following $$$q$$$ lines contain changes, each of them contains two integers $$$p$$$ and $$$x$$$ ($$$1 \leq p \leq n$$$, $$$1 \leq x \leq 10^9$$$), meaning you should assign $$$a_p := x$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,400 |
train_087.jsonl
|
cb2c1c6aaea9b558ff8c0782fbb9e07c
|
256 megabytes
|
["4\n\n2 1\n\n1 2\n\n1 3\n\n4 4\n\n4 1 3 2\n\n2 6\n\n4 6\n\n1 1\n\n3 11\n\n9 3\n\n1 7 9 4 5 2 3 6 8\n\n3 1\n\n2 1\n\n9 1\n\n6 3\n\n1 1 1 1 1 1\n\n1 5\n\n4 4\n\n3 8"]
|
PASSED
|
import heapq
class segtree():
def __init__(self,init,func,ide):
self.n=len(init)
self.func=func
self.ide=ide
self.size=1<<(self.n-1).bit_length()
self.tree=[self.ide for i in range(2*self.size)]
for i in range(self.n):
self.tree[self.size+i]=init[i]
for i in range(self.size-1,0,-1):
self.tree[i]=self.func(self.tree[2*i], self.tree[2*i|1])
def update(self,k,x):
k+=self.size
self.tree[k]=x
k>>=1
while k:
self.tree[k]=self.func(self.tree[2*k],self.tree[k*2|1])
k>>=1
def get(self,i):
return self.tree[i+self.size]
def query(self,l,r):
l+=self.size
r+=self.size
l_res=self.ide
r_res=self.ide
while l<r:
if l&1:
l_res=self.func(l_res,self.tree[l])
l+=1
if r&1:
r-=1
r_res=self.func(self.tree[r],r_res)
l>>=1
r>>=1
return self.func(l_res,r_res)
def debug(self,s=10):
print([self.get(i) for i in range(min(self.n,s))])
from sys import stdin
input=lambda :stdin.readline()[:-1]
def fact(n):
f=[]
tmp=n
for i in range(2,10**3):
if tmp%i==0:
f.append(i)
while tmp%i==0:
tmp//=i
if tmp>1:
f.append(tmp)
return f
ans=[]
for _ in range(int(input())):
n,q=map(int,input().split())
a=list(map(int,input().split()))
f=fact(n)
M=len(f)
seg_arr=[]
res=[0]*M
for i in range(M):
p=f[i]
d=n//p
x=[0]*(n//p)
for j in range(n):
x[j%d]+=a[j]*d
seg=segtree(x,max,0)
res[i]=seg.tree[1]
seg_arr.append(seg)
ans.append(max(res))
for _ in range(q):
x,y=map(int,input().split())
x-=1
diff=y-a[x]
a[x]=y
for i in range(M):
d=n//f[i]
seg_arr[i].update(x%d,seg_arr[i].get(x%d)+diff*d)
res[i]=seg_arr[i].tree[1]
ans.append(max(res))
print('\n'.join(map(str,ans)))
|
1660660500
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["7\n10\n9\n3\n0"]
|
6f819ce1d88d5211cd475a8673edba97
|
NoteIn the first example, the floor has the size of $$$10\times 10$$$. The initial position of the robot is $$$(6, 1)$$$ and the position of the dirty cell is $$$(2, 8)$$$. See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now $$$(9, 9)$$$, and the position of the dirty cell is $$$(1, 1)$$$. In this example, the robot went straight to the dirty cell and clean it. In the third example, the floor has the size $$$9 \times 8$$$. The initial position of the robot is $$$(5, 6)$$$, and the position of the dirty cell is $$$(2, 1)$$$. In the fourth example, the floor has the size $$$6 \times 9$$$. The initial position of the robot is $$$(2, 2)$$$ and the position of the dirty cell is $$$(5, 8)$$$. In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away.
|
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell. Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.
|
For each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. A test case consists of only one line, containing six integers $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, and $$$c_d$$$ ($$$1 \le n, m \le 100$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$) — the sizes of the room, the initial position of the robot and the position of the dirt cell.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_106.jsonl
|
8345e314f8b03e0919bb38a1cd3d5bb9
|
256 megabytes
|
["5\n10 10 6 1 2 8\n10 10 9 9 1 1\n9 8 5 6 2 1\n6 9 2 2 5 8\n2 2 1 1 2 1"]
|
PASSED
|
#lista=list(map(int,input().split()))
#x=lista[0]
#n=lista[0]
import math
import sys
from collections import deque
#from sys import stdin, stdout
from decimal import *
#lista=list(map(int,input().split()))
#x=lista[0]
#n=lista[0]
rasp_final=""
#my_set=set()
#for x in range(1, 100000):
#my_set.add(2*x*x)
#my_set.add(4*x*x)
#vector_prime=[-1]*21000
#vector_rasp=[0]*21000
#vector_prime[1]=1
#vector_rasp[1]=1
contor=2
#primes sieve
#for i in range(2,21000):
#if vector_prime[i]==-1:
#vector_prime[i]=1
#vector_rasp[contor]=i
#contor=contor+1
#for j in range(i+i,21000,i):
# vector_prime[j]=0
#print(i,j)
#suma=0
#vector=list(map(int,input().split()))
#for i in vector:
#suma=suma+i
#luni = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 'July':7, 'August':8, 'September':9, 'October':10, 'November':11, 'December':0}
#luni_reverse = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 0:'December'}
#alfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26}
#alfabet_2={'1':"a", '2':"b", '3':"c", '4':"d", '5':"e", '6':"f", '7':"g", '8':"h", '9':"i", '10':"j", '11':"k", '12':"l", '13':"m", '14':"n", '15':"o", '16':"p", '17':"q", '18':"r", '19':"s", '20':"t", '21':"u", '22':"v", '23':"w", '24':"x", '25':"y", '26':"z"}
k=int(input())
#k=1
contor=0
while k>0:
contor+=1
waiting=deque()
#n=int(input())
lista=list(map(int,input().split()))
n=lista[0]
m=lista[1]
rb=lista[2]
cb=lista[3]
rd=lista[4]
cd=lista[5]
tr=n+m
tc=n+m
if cd<cb:
tr=2*(m-cb)+cb-cd
if cd>=cb:
tr=cd-cb
if rd>=rb:
tc=rd-rb
if rd<rb:
tc=2*(n-rb)+rb-rd
print(min(tc,tr))
k=k-1
#print(rasp_final)
|
1640698500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["6 3", "1 4 3 3"]
|
015d7871f6560b90d9efe3375f91cce7
|
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left.
|
Kilani is playing a game with his friends. This game can be represented as a grid of size $$$n \times m$$$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $$$i$$$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $$$s_i$$$ (where $$$s_i$$$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.
|
Print $$$p$$$ integers — the number of cells controlled by each player after the game ends.
|
The first line contains three integers $$$n$$$, $$$m$$$ and $$$p$$$ ($$$1 \le n, m \le 1000$$$, $$$1 \le p \le 9$$$) — the size of the grid and the number of players. The second line contains $$$p$$$ integers $$$s_i$$$ ($$$1 \le s \le 10^9$$$) — the speed of the expansion for every player. The following $$$n$$$ lines describe the game grid. Each of them consists of $$$m$$$ symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit $$$x$$$ ($$$1 \le x \le p$$$) denotes the castle owned by player $$$x$$$. It is guaranteed, that each player has at least one castle on the grid.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900 |
train_027.jsonl
|
d9494d760c903dc0fd1a4913956f5f33
|
256 megabytes
|
["3 3 2\n1 1\n1..\n...\n..2", "3 4 4\n1 1 1 1\n....\n#...\n1234"]
|
PASSED
|
import sys
from collections import deque as dq
range = xrange
input = raw_input
h,w,P = [int(x) for x in input().split()]
S = [int(x) for x in input().split()]
S = [min(h*w,s) for s in S]
board = []
for b in sys.stdin.read():
for c in b:
if c=='.':
board.append(-1)
elif c=='#':
board.append(-2)
elif 0<=ord(c)-ord('1')<=9:
board.append(ord(c)-ord('1'))
new_castles = [[] for _ in range(P)]
for y in range(h):
for x in range(w):
if board[y*w + x]>=0:
new_castles[board[y*w+x]].append(y*w+x)
Q = [[] for _ in range(h*w+1)]
while any(new_castles):
for p in range(P):
Q[0],new_castles[p] = new_castles[p],Q[0]
for moves in range(S[p]):
if not Q[moves]:
break
while Q[moves]:
pos = Q[moves].pop()
y = pos//w
x = pos - y*w
if 0<x and board[pos-1]==-1:
board[pos-1]=p
Q[moves+1].append(pos-1)
if x<w-1 and board[pos+1]==-1:
board[pos+1]=p
Q[moves+1].append(pos+1)
if 0<y and board[pos-w]==-1:
board[pos-w]=p
Q[moves+1].append(pos-w)
if y<h-1 and board[pos+w]==-1:
board[pos+w]=p
Q[moves+1].append(pos+w)
new_castles[p],Q[S[p]] = Q[S[p]],new_castles[p]
count = [0 for _ in range(P)]
for x in board:
if x>=0:
count[x] += 1
print ' '.join(str(x) for x in count)
|
1547985900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["1", "3", "4"]
|
a4563e6aea9126e20e7a33df664e3171
|
NoteIn first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.
|
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.
|
Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.
|
First line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences. Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_001.jsonl
|
8307a43bb8a8d8bfd421732bf258027e
|
256 megabytes
|
["3\n1 1", "5\n1 2 2 2", "18\n1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4"]
|
PASSED
|
import sys
from math import sqrt, gcd, ceil, log
# from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
# from heapq import heapify, heappush, heappop
input = sys.stdin.readline
read = lambda: list(map(int, input().strip().split()))
sys.setrecursionlimit(10**6)
def main():
n = int(input()); par = read()
adj = defaultdict(list)
for i in range(n-1):
adj[par[i]].append(i+2)
# print(adj)
lvl = [1]
ans = 0
while lvl:
ans += len(lvl)%2
lvl = [j for i in lvl for j in adj[i]]
print(ans)
if __name__ == "__main__":
main()
|
1520177700
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["100", "-1", "2", "2"]
|
a9ccc8ab91d7ea2a2de074fdc305c3c8
|
NoteIn the first test it is possible to place a detachment in $$$(0, 0)$$$, so that it is possible to check all the detachments for $$$t = 100$$$. It can be proven that it is impossible to check all detachments for $$$t < 100$$$; thus the answer is $$$100$$$.In the second test, there is no such $$$t$$$ that it is possible to check all detachments, even with adding at most one new detachment, so the answer is $$$-1$$$.In the third test, it is possible to place a detachment in $$$(1, 0)$$$, so that Brimstone can check all the detachments for $$$t = 2$$$. It can be proven that it is the minimal such $$$t$$$.In the fourth test, there is no need to add any detachments, because the answer will not get better ($$$t = 2$$$). It can be proven that it is the minimal such $$$t$$$.
|
There are $$$n$$$ detachments on the surface, numbered from $$$1$$$ to $$$n$$$, the $$$i$$$-th detachment is placed in a point with coordinates $$$(x_i, y_i)$$$. All detachments are placed in different points.Brimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts.To move from one detachment to another he should first choose one of four directions of movement (up, right, left or down) and then start moving with the constant speed of one unit interval in a second until he comes to a detachment. After he reaches an arbitrary detachment, he can repeat the same process.Each $$$t$$$ seconds an orbital strike covers the whole surface, so at that moment Brimstone should be in a point where some detachment is located. He can stay with any detachment as long as needed.Brimstone is a good commander, that's why he can create at most one detachment and place it in any empty point with integer coordinates he wants before his trip. Keep in mind that Brimstone will need to visit this detachment, too.Help Brimstone and find such minimal $$$t$$$ that it is possible to check each detachment. If there is no such $$$t$$$ report about it.
|
Output such minimal integer $$$t$$$ that it is possible to check all the detachments adding at most one new detachment. If there is no such $$$t$$$, print $$$-1$$$.
|
The first line contains a single integer $$$n$$$ $$$(2 \le n \le 1000)$$$ — the number of detachments. In each of the next $$$n$$$ lines there is a pair of integers $$$x_i$$$, $$$y_i$$$ $$$(|x_i|, |y_i| \le 10^9)$$$ — the coordinates of $$$i$$$-th detachment. It is guaranteed that all points are different.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,800 |
train_043.jsonl
|
0eaf4f1cc58548705d07d08061346718
|
256 megabytes
|
["4\n100 0\n0 100\n-100 0\n0 -100", "7\n0 2\n1 0\n-3 0\n0 -2\n-1 -1\n-1 -3\n-2 -3", "5\n0 0\n0 -1\n3 0\n-2 0\n-2 1", "5\n0 0\n2 0\n0 -1\n-2 0\n-2 1"]
|
PASSED
|
# import numpy as npy
import functools
import math
n=int(input())
x=[0 for i in range(n+2)]
y=[0 for i in range(n+2)]
adj=[[] for i in range(n+2)]
idx=[]
idy=[]
for i in range(n):
x[i],y[i]=map(int,input().split())
idx.append(i)
idy.append(i)
def cmpx(a,b):
if x[a]!=x[b]:
if x[a]<x[b]:
return -1
else:
return 1
if y[a]!=y[b]:
if y[a]<y[b]:
return -1
else:
return 1
return 0
def cmpy(a,b):
if y[a]!=y[b]:
if y[a]<y[b]:
return -1
else:
return 1
if x[a]!=x[b]:
if x[a]<x[b]:
return -1
else:
return 1
return 0
idx=sorted(idx,key=functools.cmp_to_key(cmpx))
idy=sorted(idy,key=functools.cmp_to_key(cmpy))
# print(idx)
# print(idy)
def disx(a,b):
if x[a]!=x[b]:
return 1e18
return y[b]-y[a]
def disy(a,b):
if y[a]!=y[b]:
return 1e18
return x[b]-x[a]
l=0
r=2000000000
ans=-1
while l<=r:
# print(l,r)
mid=(l+r)//2
for i in range(n):
adj[i]=[]
for i in range(n-1):
if disx(idx[i],idx[i+1])<=mid:
adj[idx[i]].append(idx[i+1])
adj[idx[i+1]].append(idx[i])
# print(idx[i],idx[i+1])
if disy(idy[i],idy[i+1])<=mid:
adj[idy[i]].append(idy[i+1])
adj[idy[i+1]].append(idy[i])
# print(idy[i],idy[i+1])
col=[0 for i in range(n)]
cur=0
def dfs(x):
col[x]=cur
for i in range(len(adj[x])):
if col[adj[x][i]]==0:
dfs(adj[x][i])
for i in range(n):
if col[i]==0:
cur=cur+1
dfs(i)
ok=0
if cur>4:
ok=0
if cur==1:
ok=1
if cur==2:
for i in range(n):
for j in range(i+1,n):
if (col[i]!=col[j]):
d1=abs(x[i]-x[j])
d2=abs(y[i]-y[j])
if d1==0 or d2==0:
if d1+d2<=2*mid:
ok=1
if d1<=mid and d2<=mid:
ok=1
if cur==3:
for i in range(n-1):
px=idx[i]
py=idx[i+1]
if x[px]==x[py] and col[px]!=col[py]:
for j in range(n):
if col[px]!=col[j] and col[py]!=col[j]:
d1=abs(y[px]-y[j])
d2=abs(y[py]-y[j])
d3=abs(x[px]-x[j])
if d1<=mid and d2<=mid and d3<=mid:
ok=1
for i in range(n-1):
px=idy[i]
py=idy[i+1]
if y[px]==y[py] and col[px]!=col[py]:
for j in range(n):
if col[px]!=col[j] and col[py]!=col[j]:
d1=abs(x[px]-x[j])
d2=abs(x[py]-x[j])
d3=abs(y[px]-y[j])
if d1<=mid and d2<=mid and d3<=mid:
ok=1
if cur==4:
for i in range(n-1):
px=idx[i]
py=idx[i+1]
if x[px]==x[py] and col[px]!=col[py]:
for j in range(n-1):
pz=idy[j]
pw=idy[j+1]
if y[pz]==y[pw] and col[pz]!=col[pw]:
if col[pz]!=col[px] and col[pz]!=col[py]:
if col[pw]!=col[px] and col[pw]!=col[py]:
d1=abs(y[px]-y[pz])
d2=abs(y[py]-y[pz])
d3=abs(x[pz]-x[px])
d4=abs(x[pw]-x[px])
if d1<=mid and d2<=mid and d3<=mid and d4<=mid:
ok=1
if ok:
ans=mid
r=mid-1
else:
l=mid+1
print(ans)
|
1600526100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["t \nabs((t-10))"]
|
79c337ca7397eac500ca8e6693f83fb6
|
NoteCorrect functions: 10 (1+2) ((t-3)+(t*4)) abs((t-10)) (abs((((23-t)*(t*t))+((45+12)*(t*t))))*((5*t)+((12*t)-13))) abs((t-(abs((t*31))+14))))Incorrect functions: 3+5+7 (not enough brackets, it should be ((3+5)+7) or (3+(5+7))) abs(t-3) (not enough brackets, it should be abs((t-3)) 2+(2-3 (one bracket too many) 1(t+5) (no arithmetic operation between 1 and the bracket) 5000*5000 (the number exceeds the maximum) The picture shows one of the possible solutions
|
Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.Yesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as (xt = f(t), yt = g(t)), where argument t takes all integer values from 0 to 50. Moreover, f(t) and g(t) should be correct functions.Assume that w(t) and h(t) are some correct functions, and c is an integer ranging from 0 to 50. The function s(t) is correct if it's obtained by one of the following rules: s(t) = abs(w(t)), where abs(x) means taking the absolute value of a number x, i.e. |x|; s(t) = (w(t) + h(t)); s(t) = (w(t) - h(t)); s(t) = (w(t) * h(t)), where * means multiplication, i.e. (w(t)·h(t)); s(t) = c; s(t) = t;Yesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate f(t) and g(t) for any set of at most 50 circles.In each of the functions f(t) and g(t) you are allowed to use no more than 50 multiplications. The length of any function should not exceed 100·n characters. The function should not contain spaces.Ruslan can't keep big numbers in his memory, so you should choose f(t) and g(t), such that for all integer t from 0 to 50 value of f(t) and g(t) and all the intermediate calculations won't exceed 109 by their absolute value.
|
In the first line print a correct function f(t). In the second line print a correct function g(t). The set of the points (xt = f(t), yt = g(t)) (0 ≤ t ≤ 50) must satisfy the condition, that there is at least one point inside or on the border of each of the circles, Ruslan thinks of at the beginning.
|
The first line of the input contains number n (1 ≤ n ≤ 50) — the number of circles Ruslan thinks of. Next follow n lines, each of them containing three integers xi, yi and ri (0 ≤ xi, yi ≤ 50, 2 ≤ ri ≤ 50) — the coordinates of the center and the raduis of the i-th circle.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_043.jsonl
|
f449fd4a7043dbd7ad499da8d45e86ae
|
256 megabytes
|
["3\n0 10 4\n10 0 4\n20 10 4"]
|
PASSED
|
def f(x):
if x == n:
return "0"
if x == 0:
return "(" + str(X[0]) + "+" + f(1) + ")"
ss = "(abs((t-" + str(x-1) + "))-abs((t-" + str(x) + ")))"
tmp = (X[x] - X[x - 1]) // 2
re = (X[x] - X[x - 1]) - 2 * tmp
X[x] -= re
if tmp < 0:
tmp = "(0" +str(tmp)+")"
ss = "((" + str(tmp) + "*" + ss + ")" + "+" + str(tmp) + ")"
return "(" + ss + "+" + f(x + 1) + ")"
n = int(input())
#c = [(int(_) for _ in input().split()) for i in range(n)]
c = [[int(x) for x in input().split()] for i in range(n)]
#print(n, c)
X = [c[i][0] for i in range(n)]
Y = [c[i][1] for i in range(n)]
#print(X)
#print(Y)
print(f(0))
#print(X)
X = Y
print(f(0))
|
1446655500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
3 seconds
|
["14", "6", "0"]
|
8c2e0cd780cf9390e933e28e57643cba
|
NoteIn the first example: In the second example: Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:
|
This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?
|
Print a single integer — the number of pairs of wires that are intersecting.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900 |
train_014.jsonl
|
26ecf2ed6785777a4abe6ac1c779131d
|
256 megabytes
|
["4\n0 0\n1 1\n0 3\n1 2", "4\n0 0\n0 2\n0 4\n2 0", "3\n-1 -1\n1 0\n3 1"]
|
PASSED
|
from itertools import combinations
from collections import Counter
n = input()
points = [map(float, raw_input().split()) for _ in xrange(n)]
lines = set()
#for p1, p2 in combinations(points, 2):
for i in xrange(n):
for j in xrange(i+1, n):
x1, y1 = points[i]
x2, y2 = points[j]
if x1 == x2:
slope = float('inf')
ysect = x1
else:
slope = (y1 - y2) / (x1 - x2)
ysect = (x1 * y2 - x2 * y1) / (x1 - x2)
lines.add((slope, ysect))
L = [x[0] for x in lines]
C = Counter(L)
total = len(L) * (len(L) - 1) / 2
for x in C:
total -= C[x] * (C[x] - 1) / 2
print total
|
1557414300
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["1 1 \n-1\n3 4\n4 2\n2 4\n-3 -6 -6"]
|
d15a758cfdd7a627822fe8be7db4f60b
| null |
You are given an array $$$a$$$ of $$$n$$$ integers.You want to make all elements of $$$a$$$ equal to zero by doing the following operation exactly three times: Select a segment, for each number in this segment we can add a multiple of $$$len$$$ to it, where $$$len$$$ is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of $$$a$$$ equal to zero.
|
The output should contain six lines representing three operations. For each operation, print two lines: The first line contains two integers $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$): the bounds of the selected segment. The second line contains $$$r-l+1$$$ integers $$$b_l, b_{l+1}, \dots, b_r$$$ ($$$-10^{18} \le b_i \le 10^{18}$$$): the numbers to add to $$$a_l, a_{l+1}, \ldots, a_r$$$, respectively; $$$b_i$$$ should be divisible by $$$r - l + 1$$$.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 100\,000$$$): the number of elements of the array. The second line contains $$$n$$$ elements of an array $$$a$$$ separated by spaces: $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_001.jsonl
|
c1a8e9760d34fbeeca7152c0cd339db0
|
256 megabytes
|
["4\n1 3 2 4"]
|
PASSED
|
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def read_float():
return float(buff_readline())
def read_float_n():
return list(map(float, buff_readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
def divisor(n):
for i in range(1, int(n**0.5)+1):
if n % i == 0:
yield i
if i != n // i:
yield n // i
@mt
def slv(N, A):
if N == 1:
print(1, 1)
print(-A[0])
print(1, 1)
print(0)
print(1, 1)
print(0)
return
a = A[:]
na = a[:]
error_print([-na[i] % N for i in range(N)])
for i in range(N-1):
if a[i] > 0:
na[i] = a[i] + (a[i] % N) * (N-1)
else:
na[i] = a[i] - (N - (a[i] % N)) * (N-1)
print(1, N-1)
print(*[na[i] - a[i] for i in range(N-1)])
a = na[:]
for i in range(N-1, N):
if a[i] > 0:
na[i] = a[i] - (a[i] % N)
else:
na[i] = a[i] - (a[i] % N)
print(N, N)
print(*[na[i] - a[i] for i in range(N-1, N)])
print(1, N)
print(*[-na[i] for i in range(N)])
error_print(na)
error_print([-na[i]%N for i in range(N)])
def main():
N = read_int()
A = read_int_n()
slv(N, A)
if __name__ == '__main__':
main()
|
1598798100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nYES\nNO\nNO"]
|
f853a61741518cb884c00c8b760692aa
|
NoteIn the first test case, the graph's diameter equal to 0.In the second test case, the graph's diameter can only be 2.In the third test case, the graph's diameter can only be 1.
|
CQXYM wants to create a connected undirected graph with $$$n$$$ nodes and $$$m$$$ edges, and the diameter of the graph must be strictly less than $$$k-1$$$. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).The diameter of a graph is the maximum distance between any two nodes.The distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.CQXYM wonders whether it is possible to create such a graph.
|
For each test case, print YES if it is possible to create the graph, or print NO if it is impossible. You can print each letter in any case (upper or lower).
|
The input consists of multiple test cases. The first line contains an integer $$$t (1 \leq t \leq 10^5)$$$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains three integers $$$n(1 \leq n \leq 10^9)$$$, $$$m$$$, $$$k$$$ $$$(0 \leq m,k \leq 10^9)$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_089.jsonl
|
20bd24ecfe50ad89afa33475b6144462
|
256 megabytes
|
["5\n1 0 3\n4 5 3\n4 6 3\n5 4 1\n2 1 1"]
|
PASSED
|
"""
Cases:
"""
for t in range(int(input())):
n,m,k = map(int,input().split())
req = ((n)*(n-1))//2
if(m>req or m<(n-1)):
print('NO')
else:
if(n == 1):
if(k>1):
print('YES')
else:
print('NO')
elif(m<req):
if(k>3):
print('YES')
else:
print('NO')
elif(k>2):
print('YES')
else:
print('NO')
|
1632996900
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["A 1\nB 2\nC 1", "B 2\nC 1\nA 1\nC -1"]
|
f23d3e6ca1e4d7fbe5a2ca38ebb37c46
|
NoteFor the first sample, Li Chen's hidden permutation is $$$[2, 3, 1]$$$, and for the second, his hidden permutation is $$$[5, 3, 2, 4, 1, 6]$$$ for both cases.In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose: In the first question, you ask Andrew to look at node $$$1$$$ in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with $$$2$$$. At this point, you know that both of your subtrees contain the same node (i.e. node $$$1$$$ according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node $$$2$$$ in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with $$$1$$$ (this step was given with the only reason — to show you how to ask questions).For the second sample, there are two test cases. The first looks is the one from the statement: We first ask "B 2", and Andrew will tell us $$$3$$$. In this case, we know $$$3$$$ is a common vertex, and moreover, any subtree with size $$$3$$$ that contains node $$$3$$$ must contain node $$$1$$$ as well, so we can output either "C 1" or "C 3" as our answer.In the second case in the second sample, the situation looks as follows: In this case, you know that the only subtree of size $$$3$$$ that doesn't contain node $$$1$$$ is subtree $$$4,5,6$$$. You ask Andrew for the label of node $$$1$$$ in Li Chen's labelling and Andrew says $$$5$$$. In this case, you know that Li Chen's subtree doesn't contain node $$$1$$$, so his subtree must be consist of the nodes $$$4,5,6$$$ (in your labelling), thus the two subtrees have no common nodes.
|
You are playing a strange game with Li Chen. You have a tree with $$$n$$$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from $$$1$$$ to $$$n$$$. Neither of you know the other's labelling of the tree.You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled $$$x_1, x_2, \ldots, x_{k_1}$$$ in your labeling, Li Chen's subtree consists of the vertices labeled $$$y_1, y_2, \ldots, y_{k_2}$$$ in his labeling. The values of $$$x_1, x_2, \ldots, x_{k_1}$$$ and $$$y_1, y_2, \ldots, y_{k_2}$$$ are known to both of you. The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most $$$5$$$ questions, each of which is in one of the following two forms: A x: Andrew will look at vertex $$$x$$$ in your labeling and tell you the number of this vertex in Li Chen's labeling. B y: Andrew will look at vertex $$$y$$$ in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
| null | null |
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_050.jsonl
|
ba28e399d6d12beab211db16bf04d931
|
256 megabytes
|
["1\n3\n1 2\n2 3\n1\n1\n1\n2\n2\n1", "2\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n4\n1 3 4 5\n3\n3 5 2\n3\n6\n1 2\n1 3\n1 4\n4 5\n4 6\n3\n1 2 3\n3\n4 1 6\n5"]
|
PASSED
|
import sys
from math import *
from random import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
e = [[] for i in range(n+1)]
p = [None]*(n+1)
my = [False]*(n+1)
for i in range(n-1):
a,b = mints()
e[a].append(b)
e[b].append(a)
def dfs(x):
for i in e[x]:
if p[i] == None:
p[i] = x
dfs(i)
k1 = mint()
x = list(mints())
for i in x:
my[i] = True
k2 = mint()
y = list(mints())
p[x[0]] = 0
dfs(x[0])
print('B',y[0])
sys.stdout.flush()
z = mint()
while my[z] != True:
z = p[z]
print('A',z)
sys.stdout.flush()
zz = mint()
if zz in y:
print('C',z)
else:
print('C',-1)
sys.stdout.flush()
t = mint()
for i in range(t):
solve()
|
1541355000
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["Yes", "Yes", "No"]
|
c0c7b1900e6be6d14695477355e4d87b
|
NoteIn the first sample, computer set a0 to - 1 on the first move, so if human can set coefficient a1 to 0.5 and win.In the second sample, all coefficients are already set and the resulting polynomial is divisible by x - 100, so the human has won.
|
100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.The following game was chosen for the fights: initially there is a polynomial P(x) = anxn + an - 1xn - 1 + ... + a1x + a0, with yet undefined coefficients and the integer k. Players alternate their turns. At each turn, a player pick some index j, such that coefficient aj that stay near xj is not determined yet and sets it to any value (integer or real, positive or negative, 0 is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by Q(x) = x - k.Polynomial P(x) is said to be divisible by polynomial Q(x) if there exists a representation P(x) = B(x)Q(x), where B(x) is also some polynomial.Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?
|
Print "Yes" (without quotes) if the human has winning strategy, or "No" (without quotes) otherwise.
|
The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, |k| ≤ 10 000) — the size of the polynomial and the integer k. The i-th of the following n + 1 lines contain character '?' if the coefficient near xi - 1 is yet undefined or the integer value ai, if the coefficient is already known ( - 10 000 ≤ ai ≤ 10 000). Each of integers ai (and even an) may be equal to 0. Please note, that it's not guaranteed that you are given the position of the game where it's computer's turn to move.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_029.jsonl
|
92088896b294f7f6b0bd760a939cf360
|
256 megabytes
|
["1 2\n-1\n?", "2 100\n-10000\n0\n1", "4 5\n?\n1\n?\n1\n?"]
|
PASSED
|
def solve():
modx = 179426080107
n,m = map(int,input().split())
cnt = 0
a = []
for i in range(n + 1):
s = input()
if(s == '?'): cnt += 1
a.append(s)
#print(cnt)
if (m == 0):
if (a[0] == '0') : return 1
if (a[0] == '?' and (n + 1 - cnt)% 2 == 1):
return 1
return 0
if(cnt):
if (n % 2 == 1):return 1
return 0
for i in range(n+1):
a[i] = int(a[i])
now = a[n]
tmp = 1
ans = 0
for i in range(n + 1):
ans = ans + (tmp * a[i]) % modx
ans %= modx
tmp = (tmp * m) % modx
if (ans == 0) : return 1
else : return 0
if (solve() == 1) : print("Yes")
else : print("No")
|
1464188700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["4", "7"]
|
6b0d00ecfa260a33e313ae60d8f9ee06
|
NoteFor the first sample testcase, the pretty substrings of s are: "(?" which can be transformed to "()". "?)" which can be transformed to "()". "((?)" which can be transformed to "(())". "(?))" which can be transformed to "(())". For the second sample testcase, the pretty substrings of s are: "??" which can be transformed to "()". "()". "??()" which can be transformed to "()()". "?()?" which can be transformed to "(())". "??" which can be transformed to "()". "()??" which can be transformed to "()()". "??()??" which can be transformed to "()()()".
|
As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem.A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally: Empty string is a correct bracket sequence. if s is a correct bracket sequence, then (s) is also a correct bracket sequence. if s and t are correct bracket sequences, then st (concatenation of s and t) is also a correct bracket sequence. A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence.Will gave his mom a string s consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (l, r) such that 1 ≤ l ≤ r ≤ |s| and the string slsl + 1... sr is pretty, where si is i-th character of s.Joyce doesn't know anything about bracket sequences, so she asked for your help.
|
Print the answer to Will's puzzle in the first and only line of output.
|
The first and only line of input contains string s, consisting only of characters '(', ')' and '?' (2 ≤ |s| ≤ 5000).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,800 |
train_041.jsonl
|
11bc0353336c827652f9af16c25210cc
|
256 megabytes
|
["((?))", "??()??"]
|
PASSED
|
S = raw_input()
N = len(S)
A = 0
for i in xrange(N):
D = 0
Q = 0
for j in xrange(i, N):
D += S[j] == '('
D -= S[j] == ')'
Q += S[j] == '?'
if D + Q < 0:
break
if Q > D:
D, Q = Q, D
if Q == D:
A += 1
print A
|
1517236500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["34"]
|
13b9b9c47ae7e8cfdcaee50f9c187d84
|
NoteThe picture corresponding to the first example:
|
You are given a tree (an undirected connected acyclic graph) consisting of $$$n$$$ vertices and $$$n - 1$$$ edges. A number is written on each edge, each number is either $$$0$$$ (let's call such edges $$$0$$$-edges) or $$$1$$$ (those are $$$1$$$-edges).Let's call an ordered pair of vertices $$$(x, y)$$$ ($$$x \ne y$$$) valid if, while traversing the simple path from $$$x$$$ to $$$y$$$, we never go through a $$$0$$$-edge after going through a $$$1$$$-edge. Your task is to calculate the number of valid pairs in the tree.
|
Print one integer — the number of valid pairs of vertices.
|
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each denoting an edge of the tree. Each edge is represented by three integers $$$x_i$$$, $$$y_i$$$ and $$$c_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$0 \le c_i \le 1$$$, $$$x_i \ne y_i$$$) — the vertices connected by this edge and the number written on it, respectively. It is guaranteed that the given edges form a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,200 |
train_040.jsonl
|
e8ef59f05401fca7d239d8afcc917d02
|
256 megabytes
|
["7\n2 1 1\n3 2 0\n4 2 1\n5 2 0\n6 7 1\n7 2 1"]
|
PASSED
|
import sys
readline = sys.stdin.buffer.readline
read = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
class UnionFind:
def __init__(self, n):
self.ps = [-1] * (n + 1)
def find(self, x):
if self.ps[x] < 0:
return x
else:
self.ps[x] = self.find(self.ps[x])
return self.ps[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.ps[x] > self.ps[y]:
x, y = y, x
self.ps[x] += self.ps[y]
self.ps[y] = x
return True
def same(self, x, y):
return self.find(x) == self.find(y)
def size(self, x):
x = self.find(x)
return -self.ps[x]
def solve():
n = ni()
uni = [UnionFind(n), UnionFind(n)]
for _ in range(n-1):
u, v, c = nm()
u -= 1; v -= 1
uni[c].unite(u, v)
ans = 0
for c in range(2):
for i in range(n):
if uni[c].find(i) == i:
v = uni[c].size(i)
ans += v * (v-1)
for i in range(n):
# print(i, (uni[0].size(i), uni[1].size(i)))
ans += (uni[0].size(i) - 1) * (uni[1].size(i) - 1)
print(ans)
return
solve()
# T = ni()
# for _ in range(T):
# solve()
|
1556721300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["3", "-1"]
|
0372790cbc07605c7e618dc14196fc67
|
NoteThis is the picture for the first example. $$$1$$$, $$$5$$$, $$$7$$$ also can be a valid answer. This is the picture for the second example. You can see that it's impossible to find such root vertex.
|
You have given tree consist of $$$n$$$ vertices. Select a vertex as root vertex that satisfies the condition below. For all vertices $$$v_{1}$$$ and $$$v_{2}$$$, if $$$distance$$$($$$root$$$, $$$v_{1}$$$) $$$= distance$$$($$$root$$$, $$$v_{2})$$$ then $$$degree$$$($$$v_{1}$$$) $$$= degree$$$($$$v_{2}$$$), where $$$degree$$$ means the number of vertices connected to that vertex, and $$$distance$$$ means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them.
|
If there is such root vertex exists, print any of them. Otherwise, print $$$-1$$$.
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of vertices. Each of the next $$$n-1$$$ lines contains two integers $$$v_{i}$$$ and $$$u_{i}$$$ ($$$1 \le v_{i} \lt u_{i} \le n$$$) — it means there is an edge exist between $$$v_{i}$$$ and $$$u_{i}$$$. It is guaranteed that the graph forms tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,400 |
train_021.jsonl
|
55ba2d74977865c675ef56e79721ad5c
|
256 megabytes
|
["7\n1 2\n2 3\n3 4\n4 5\n3 6\n6 7", "6\n1 3\n2 3\n3 4\n4 5\n4 6"]
|
PASSED
|
#!/usr/bin/env python
def longest_path():
try:
d = [-1 for _ in range(n)]
d[0] = 0; q = [0]
for i in range(n):
f = q[i]
for t in g[f]:
if d[t] == -1:
q.append(t)
d[t] = d[f] + 1
u = q[-1]
d = [-1 for _ in range(n)]
p = [-1 for _ in range(n)]
d[u] = 0; q = [u]
for i in range(n):
f = q[i]
for t in g[f]:
if d[t] == -1:
q.append(t)
d[t] = d[f] + 1
p[t] = f
v = q[-1]
ld = d[v]
w = v
if ld & 1:
return u, v, None
while d[w] != (ld >> 1):
w = p[w]
return u, v, w
except:
print(f'Error raised in longest_path()')
def top(u):
try:
if u is None:
return False
dist = [-1 for _ in range(n)]
deg = [-1 for _ in range(n)]
dist[u] = 0; q = [u]
for i in range(n):
f = q[i]
if deg[dist[f]] == -1:
deg[dist[f]] = len(g[f])
elif len(g[f]) != deg[dist[f]]:
return False
for t in g[f]:
if dist[t] == -1:
q.append(t)
dist[t] = dist[f] + 1
return True
except:
print(f'Error raised in top({u})')
def semitop(w):
try:
if w is None:
return False, None
d = [-1 for _ in range(n)]
d[w] = 0; q = [w]; i = 0
while i < len(q):
f = q[i]
for t in g[f]:
if d[t] == -1:
if len(g[t]) != 2:
d[t] = 100_500
if top(t):
return True, t
else:
d[t] = d[f] + 1
q.append(t)
i += 1
return False, None
except:
print(f'Error raised in semitop({w})')
try:
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(lambda _: int(_) - 1, input().split())
g[u].append(v); g[v].append(u)
u, v, w = longest_path()
if top(u):
print(u + 1)
elif top(v):
print(v + 1)
elif top(w):
print(w + 1)
else:
k, t = semitop(w)
if k:
print(t + 1)
else:
print(-1)
except:
print(f'Error raised in main')
|
1560258300
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["errorgorn\nmaomao90"]
|
fc75935b149cf9f4f2ddb9e2ac01d1c2
|
NoteIn the first test case, errorgorn will be the winner. An optimal move is to chop the log of length $$$4$$$ into $$$2$$$ logs of length $$$2$$$. After this there will only be $$$4$$$ logs of length $$$2$$$ and $$$1$$$ log of length $$$1$$$.After this, the only move any player can do is to chop any log of length $$$2$$$ into $$$2$$$ logs of length $$$1$$$. After $$$4$$$ moves, it will be maomao90's turn and he will not be able to make a move. Therefore errorgorn will be the winner.In the second test case, errorgorn will not be able to make a move on his first turn and will immediately lose, making maomao90 the winner.
|
There are $$$n$$$ logs, the $$$i$$$-th log has a length of $$$a_i$$$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.errorgorn and maomao90 will take turns chopping the logs with errorgorn chopping first. On his turn, the player will pick a log and chop it into $$$2$$$ pieces. If the length of the chosen log is $$$x$$$, and the lengths of the resulting pieces are $$$y$$$ and $$$z$$$, then $$$y$$$ and $$$z$$$ have to be positive integers, and $$$x=y+z$$$ must hold. For example, you can chop a log of length $$$3$$$ into logs of lengths $$$2$$$ and $$$1$$$, but not into logs of lengths $$$3$$$ and $$$0$$$, $$$2$$$ and $$$2$$$, or $$$1.5$$$ and $$$1.5$$$.The player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?
|
For each test case, print "errorgorn" if errorgorn wins or "maomao90" if maomao90 wins. (Output without quotes).
|
Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — 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 \leq n \leq 50$$$) — the number of logs. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$) — the lengths of the logs. Note that there is no bound on the sum of $$$n$$$ over all test cases.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_108.jsonl
|
6c8ccd5d42397179980029437b62f01b
|
256 megabytes
|
["2\n\n4\n\n2 4 2 1\n\n1\n\n1"]
|
PASSED
|
num_cases = int(input())
for i in range(num_cases):
count = 0
num_logs = int(input())
logs = [int(log) for log in input().split(' ')]
for log in logs:
count += log - 1
if count % 2 == 0:
print('maomao90')
else:
print('errorgorn')
|
1650722700
|
[
"math",
"games"
] |
[
1,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nNO\nYES"]
|
e2434fd5f9d16d59e646b6e69e37684a
| null |
You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.
|
For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
|
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,000 |
train_010.jsonl
|
383a1e58963802ddcc161b61b9ff3fa4
|
256 megabytes
|
["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"]
|
PASSED
|
q = int(raw_input())
for _ in range(q):
a, b, n, S = map(int, raw_input().split())
if b >= S:
print "YES"
continue
total = S
need = S/n
if need <= a:
total -= need * n
else:
total -= a * n
if b < total:
print "NO"
else:
print "YES"
|
1572873300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3"]
|
cf7cd545a48b050354ae786a263e2847
|
NoteIn the first example: $$$1100\oplus \mbox{shift}^1(1100) = 1010$$$ $$$1000\oplus \mbox{shift}^2(1000) = 1010$$$ $$$0110\oplus \mbox{shift}^3(0110) = 1010$$$ There is no $$$x$$$ such that $$$x \oplus x = 1010$$$, hence the answer is $$$3$$$.
|
After learning about polynomial hashing, Heidi decided to learn about shift-xor hashing. In particular, she came across this interesting problem.Given a bitstring $$$y \in \{0,1\}^n$$$ find out the number of different $$$k$$$ ($$$0 \leq k < n$$$) such that there exists $$$x \in \{0,1\}^n$$$ for which $$$y = x \oplus \mbox{shift}^k(x).$$$In the above, $$$\oplus$$$ is the xor operation and $$$\mbox{shift}^k$$$ is the operation of shifting a bitstring cyclically to the right $$$k$$$ times. For example, $$$001 \oplus 111 = 110$$$ and $$$\mbox{shift}^3(00010010111000) = 00000010010111$$$.
|
Output a single integer: the number of suitable values of $$$k$$$.
|
The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$), the length of the bitstring $$$y$$$. The second line contains the bitstring $$$y$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_016.jsonl
|
59b7975d7ee1c0de558d2731605fd666
|
256 megabytes
|
["4\n1010"]
|
PASSED
|
import sys
range = xrange
n = int(raw_input())
y = [int(x) for x in raw_input()]
def poss(k):
x = [0]*n
for i in range(n-k):
x[i + k] = x[i] ^ y[i]
for i in range(n-k,n):
if x[i] ^ x[i + k - n] != y[i]:
return 0
return 1
possible = [0]*(n+1)
i = 1
while i * i < n:
if n % i == 0:
possible[i] = poss(i)
possible[n//i] = poss(n//i)
i += 1
if i * i == n:
possible[i] = poss(i)
def gcd(a,b):
while b:
a,b = b,a%b
return a
ans = 0
for k in range(1, n+1):
ans += possible[gcd(n,k)]
print(ans)
|
1562483100
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["? 3\n\n? 2\n\n? 4\n\n! 4 2 1 3\n\n? 2\n\n? 3\n\n? 2\n\n! 1 3 4 2"]
|
96ec983bfadc9e96e36ebb8ffc5279d3
|
NoteIn the first test case the hidden permutation $$$p = [4, 2, 1, 3]$$$.Before the first query $$$q = [1, 2, 3, 4]$$$ so answer for the query will be $$$q_3 = 3$$$.Before the second query $$$q = [4, 2, 1, 3]$$$ so answer for the query will be $$$q_2 = 2$$$.Before the third query $$$q = [3, 2, 4, 1]$$$ so answer for the query will be $$$q_4 = 1$$$.In the second test case the hidden permutation $$$p = [1, 3, 4, 2]$$$.Empty strings are given only for better readability. There will be no empty lines in the testing system.
|
This is an interactive problem.The jury has a permutation $$$p$$$ of length $$$n$$$ and wants you to guess it. For this, the jury created another permutation $$$q$$$ of length $$$n$$$. Initially, $$$q$$$ is an identity permutation ($$$q_i = i$$$ for all $$$i$$$).You can ask queries to get $$$q_i$$$ for any $$$i$$$ you want. After each query, the jury will change $$$q$$$ in the following way: At first, the jury will create a new permutation $$$q'$$$ of length $$$n$$$ such that $$$q'_i = q_{p_i}$$$ for all $$$i$$$. Then the jury will replace permutation $$$q$$$ with pemutation $$$q'$$$. You can make no more than $$$2n$$$ queries in order to quess $$$p$$$.
| null |
The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_092.jsonl
|
c8a94476bea447a91eff8d62bcd135f4
|
256 megabytes
|
["2\n4\n\n3\n\n2\n\n1\n\n4\n\n2\n\n4\n\n4"]
|
PASSED
|
import sys
t = int(input())
for _ in range(t):
n = int(input())
p = [0] * n
todo = {j for j in range(1, n + 1)}
while todo:
x = todo.pop()
todo.add(x)
st, ls = set(), []
while True:
print('?', x)
sys.stdout.flush()
y = int(input())
if y in st:
break
else:
st.add(y)
ls.append(y)
if len(ls) == 1:
p[x - 1] = x
todo.remove(x)
else:
for j in range(len(ls)):
p[ls[j] - 1] = ls[(j + 1) % len(ls)]
for x in st:
todo.remove(x)
print('!', ' '.join(map(str, p)))
sys.stdout.flush()
|
1641220500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nYES\nYES\nNO\nNO"]
|
8dcf63e0e4584df7a471c84ce3ca8fe1
|
NoteThe picture corresponding to the example:Consider the queries.The first query is $$$[3, 8, 9, 10]$$$. The answer is "YES" as you can choose the path from the root $$$1$$$ to the vertex $$$u=10$$$. Then vertices $$$[3, 9, 10]$$$ belong to the path from $$$1$$$ to $$$10$$$ and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which also belongs to this path.The second query is $$$[2, 4, 6]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=2$$$. Then the vertex $$$4$$$ has distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$6$$$ has distance $$$1$$$ to the vertex $$$2$$$ which belongs to this path.The third query is $$$[2, 1, 5]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=5$$$ and all vertices of the query belong to this path.The fourth query is $$$[4, 8, 2]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=9$$$ so vertices $$$2$$$ and $$$4$$$ both have distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which belongs to this path.The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex $$$u$$$.
|
You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is a vertex number $$$1$$$.A tree is a connected undirected graph with $$$n-1$$$ edges.You are given $$$m$$$ queries. The $$$i$$$-th query consists of the set of $$$k_i$$$ distinct vertices $$$v_i[1], v_i[2], \dots, v_i[k_i]$$$. Your task is to say if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path.
|
For each query, print the answer — "YES", if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path and "NO" otherwise.
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. The next $$$m$$$ lines describe queries. The $$$i$$$-th line describes the $$$i$$$-th query and starts with the integer $$$k_i$$$ ($$$1 \le k_i \le n$$$) — the number of vertices in the current query. Then $$$k_i$$$ integers follow: $$$v_i[1], v_i[2], \dots, v_i[k_i]$$$ ($$$1 \le v_i[j] \le n$$$), where $$$v_i[j]$$$ is the $$$j$$$-th vertex of the $$$i$$$-th query. It is guaranteed that all vertices in a single query are distinct. It is guaranteed that the sum of $$$k_i$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,900 |
train_010.jsonl
|
7c04391a26ce8a094f9c50b92a0f972f
|
256 megabytes
|
["10 6\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n7 8\n7 9\n9 10\n4 3 8 9 10\n3 2 4 6\n3 2 1 5\n3 4 8 2\n2 6 10\n3 5 4 7"]
|
PASSED
|
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class Graph(object):
def __init__(self):
self.neighbours = {}
def add_node(self, node):
self.neighbours[node] = []
def add_edge(self, edge):
u, v = edge
self.neighbours[u].append(v)
self.neighbours[v].append(u)
@bootstrap
def dfs(self, v, parent, depth=0):
parents[v] = parent
depths[v] = depth
visited[v] = 1
intime[v] = timer[0]
timer[0] += 1
for child in self.neighbours[v]:
if visited[child] == 0:
yield self.dfs(child, v, depth + 1)
outtime[v] = timer[0]
timer[0] += 1
yield
def inPath(x, y):
return intime[x] <= intime[y] and outtime[x] >= outtime[y]
g = Graph()
n, q = map(int, input().split())
for i in range(n):
g.add_node(i + 1)
for i in range(n - 1):
x, y = map(int, input().split())
g.add_edge((x, y))
visited, intime, outtime = [0] * (n + 1), [0] * (n + 1), [0] * (n + 1)
timer = [0]
parents, depths = {}, {}
g.dfs(1, -1)
for i in range(q):
lis = list(map(int, input().split()))[1:]
deep = lis[0]
for j in lis:
if depths[deep] < depths[j]:
deep = j
for j in range(len(lis)):
if lis[j] == deep:
continue
if parents[lis[j]]!=-1:
lis[j] = parents[lis[j]]
ok = True
for j in lis:
ok = ok & inPath(j, deep)
print("YES") if ok else print("NO")
# region fastio
# Credits
# # template credits to cheran-senthil's github Repo
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
|
1585233300
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["5\n2\n1\n3"]
|
a28b84c9d1a54e322ab2d54bd5ab45c8
|
NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$.
|
You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?
|
For each test case, print one integer — the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \dots + a_n)$$$ is divisible by $$$k$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,000 |
train_102.jsonl
|
6bd59c9c0e2a869f240d45d4b287f4fe
|
256 megabytes
|
["4\n1 5\n4 3\n8 8\n8 17"]
|
PASSED
|
t = int(input())
for i in range(t):
n, k = list(map(int, input().split()))
if k % n == 0:
print(k//n)
elif n % k == 0:
print(1)
else:
if k > n:
print((k//n) + 1)
elif k < n:
print(2)
else:
print(1)
|
1611930900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n0\n249561107"]
|
2b391638a9fea31986fe8e41c97b640a
|
NoteConsider the first test case. If the pair of indices $$$(2, 3)$$$ will be chosen, these elements will be swapped and array will become sorted. Otherwise, if one of pairs $$$(1, 2)$$$ or $$$(1, 3)$$$ will be selected, nothing will happen. So, the probability that the array will become sorted after one operation is $$$\frac{1}{3}$$$, the probability that the array will become sorted after two operations is $$$\frac{2}{3} \cdot \frac{1}{3}$$$, the probability that the array will become sorted after three operations is $$$\frac{2}{3} \cdot \frac{2}{3} \cdot \frac{1}{3}$$$ and so on. The expected number of operations is $$$\sum \limits_{i=1}^{\infty} \left(\frac{2}{3} \right)^{i - 1} \cdot \frac{1}{3} \cdot i = 3$$$.In the second test case the array is already sorted so the expected number of operations is zero.In the third test case the expected number of operations equals to $$$\frac{75}{4}$$$ so the answer is $$$75 \cdot 4^{-1} \equiv 249\,561\,107 \pmod {998\,244\,353}$$$.
|
You are given a binary array $$$a$$$ (all elements of the array are $$$0$$$ or $$$1$$$) of length $$$n$$$. You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until $$$a$$$ is sorted: Choose two random indices $$$i$$$ and $$$j$$$ such that $$$i < j$$$. Indices are chosen equally probable among all pairs of indices $$$(i, j)$$$ such that $$$1 \le i < j \le n$$$. If $$$a_i > a_j$$$, then swap elements $$$a_i$$$ and $$$a_j$$$. What is the expected number of such operations you will perform before the array becomes sorted?It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{998\,244\,353}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod 998\,244\,353$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < 998\,244\,353$$$ and $$$x \cdot q \equiv p \pmod{998\,244\,353}$$$.
|
For each test case print one integer — the value $$$p \cdot q^{-1} \bmod 998\,244\,353$$$.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of elements in the binary array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i \in \{0, 1\}$$$) — elements of the array. It's guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_100.jsonl
|
7f9dbb50633c187348ece78d06295258
|
256 megabytes
|
["3\n\n3\n\n0 1 0\n\n5\n\n0 0 1 1 1\n\n6\n\n1 1 1 0 0 1"]
|
PASSED
|
for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
zeros = n - sum(a)
ones = sum(a[:zeros])
rv = n * (n - 1) // 2 * sum(pow(i, -2, 998244353) for i in range(1, ones + 1)) % 998244353
print(rv)
|
1666511400
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
1 second
|
["14\n3", "3\n1"]
|
88961744a28d7c890264a39a0a798708
|
NoteIn the first example: For query $$$1$$$: One of the best ways for JATC to eats those parts is in this order: $$$1$$$, $$$4$$$, $$$3$$$, $$$2$$$. For query $$$2$$$: Both $$$3$$$, $$$4$$$ and $$$4$$$, $$$3$$$ ordering give the same answer. In the second example, any order of eating parts leads to the same answer.
|
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into $$$n$$$ parts, places them on a row and numbers them from $$$1$$$ through $$$n$$$. For each part $$$i$$$, he defines the deliciousness of the part as $$$x_i \in \{0, 1\}$$$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $$$i$$$-th part then his enjoyment of the Banh-mi will increase by $$$x_i$$$ and the deliciousness of all the remaining parts will also increase by $$$x_i$$$. The initial enjoyment of JATC is equal to $$$0$$$.For example, suppose the deliciousness of $$$3$$$ parts are $$$[0, 1, 0]$$$. If JATC eats the second part then his enjoyment will become $$$1$$$ and the deliciousness of remaining parts will become $$$[1, \_, 1]$$$. Next, if he eats the first part then his enjoyment will become $$$2$$$ and the remaining parts will become $$$[\_, \_, 2]$$$. After eating the last part, JATC's enjoyment will become $$$4$$$.However, JATC doesn't want to eat all the parts but to save some for later. He gives you $$$q$$$ queries, each of them consisting of two integers $$$l_i$$$ and $$$r_i$$$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $$$[l_i, r_i]$$$ in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo $$$10^9+7$$$.
|
Print $$$q$$$ lines, where $$$i$$$-th of them contains a single integer — the answer to the $$$i$$$-th query modulo $$$10^9 + 7$$$.
|
The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 100\,000$$$). The second line contains a string of $$$n$$$ characters, each character is either '0' or '1'. The $$$i$$$-th character defines the deliciousness of the $$$i$$$-th part. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the segment of the corresponding query.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_017.jsonl
|
e3dd183fcc82ad86f8c1d165a9e2d2b7
|
256 megabytes
|
["4 2\n1011\n1 4\n3 4", "3 2\n111\n1 2\n3 3"]
|
PASSED
|
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
s = input()
pref = [0 for i in range(n + 1)]
for i in range(1, n + 1):
pref[i] = pref[i - 1] + (s[i - 1] == '1')
mod = 1000000007
ans = []
for i in range(q):
a, b = map(int, input().split())
k = pref[b] - pref[a - 1];
N = b - a + 1
z = N - k
ans.append((pow(2, k, mod) - 1) * pow(2, z, mod) % mod)
print(*ans)
|
1542209700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nYES"]
|
55595ff38a08b80bc86cf1ebae6f55af
|
NoteFor the first test case, this is an example solution: For the second test case, we can show that no solution exists.For the third test case, this is an example solution:
|
You are given a special jigsaw puzzle consisting of $$$n\cdot m$$$ identical pieces. Every piece has three tabs and one blank, as pictured below. The jigsaw puzzle is considered solved if the following conditions hold: The pieces are arranged into a grid with $$$n$$$ rows and $$$m$$$ columns. For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece. Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.
|
For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).
|
The test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 800 |
train_022.jsonl
|
4b6f7f740038c4bd7b5c96425fc0c4a7
|
256 megabytes
|
["3\n1 3\n100000 100000\n2 2"]
|
PASSED
|
T = input()
for _ in xrange(T):
n, m = map(int, raw_input().split())
if n > 2 and m > 2:
print "NO"
else:
if (n == 2 and m > 2) or (m == 2 and n > 2):
print "NO"
else:
print "YES"
|
1588775700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2 4\n4 3\n1 3\n2 1\n1 1\n1 2\n31623 14130"]
|
f8335c59cd05988c8053f138c4df06aa
| null |
Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows. The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.
|
For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_103.jsonl
|
57942d47c8abf07a8d4e261bbf1d221b
|
256 megabytes
|
["7\n11\n14\n5\n4\n1\n2\n1000000000"]
|
PASSED
|
t = int(input())
def main() :
n = int(input())
if n==1 :
return("1 1")
else :
k = int(n**0.5)
if k*k==n :
k=k-1
pojok = k*k+k+1
if n<=pojok :
baris = k+n-pojok+1
kolom = k+1
else :
baris = k+1
kolom = k-n+pojok+1
return(str(baris)+" "+str(kolom))
R = []
for _ in range(t) :
R.append(main())
for ans in R :
print(ans)
|
1629297300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4", "24000", "-1"]
|
4dce15ff1446b5af2c5b49ee2d30bbb8
|
NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially.
|
Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible.
|
Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible.
|
First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,000 |
train_020.jsonl
|
70c3b97d4d35c113382d265d2e48e5a4
|
256 megabytes
|
["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"]
|
PASSED
|
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import itertools
import sys, threading
import os
from io import BytesIO, IOBase
from types import GeneratorType
def is_it_local():
script_dir = str(os.getcwd()).split('/')
username = "dipta007"
return username in script_dir
def READ(fileName):
if is_it_local():
sys.stdin = open(f'./{fileName}', 'r')
# 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 not is_it_local():
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
def input1(type=int):
return type(input())
def input2(type=int):
[a, b] = list(map(type, input().split()))
return a, b
def input3(type=int):
[a, b, c] = list(map(type, input().split()))
return a, b, c
def input_array(type=int):
return list(map(type, input().split()))
def input_string():
s = input()
return list(s)
##############################################################
adj = {}
label = []
target = []
cost = []
data = []
def merge(a, b):
# node number, zero number, one number, correct, need zero, need one
tmp = [a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3], a[4] + b[4], a[5] + b[5]]
return tmp
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
to = f(*args, **kwargs)
if stack:
return to
else:
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
return to
to = stack[-1].send(to)
return wrappedfunc
@bootstrap
def dfs1(u, p):
global data, label, target, adj, cost
now = [
1,
1 if label[u] == 0 and label[u] != target[u] else 0,
1 if label[u] == 1 and label[u] != target[u] else 0,
1 if label[u] == target[u] else 0,
1 if target[u] == 0 and label[u] != target[u] else 0,
1 if target[u] == 1 and label[u] != target[u] else 0
]
if p != -1:
cost[u] = min(cost[u], cost[p])
if u in adj:
for v in adj[u]:
if v != p:
tmp = yield dfs1(v, u)
now = merge(now, tmp)
data[u] = now
yield now
res = 0
@bootstrap
def call(u, p):
global data, label, target, adj, cost, res
f_0, f_1 = 0, 0
if u in adj:
for v in adj[u]:
if v != p:
n_0, n_1 = yield call(v, u)
f_0 += n_0
f_1 += n_1
now = data[u]
can_be_fixed_zero = min(now[4], now[1]) - f_0
can_be_fixed_one = min(now[5], now[2]) - f_1
not_fixed = can_be_fixed_zero + can_be_fixed_one
res += not_fixed * cost[u]
yield f_0 + can_be_fixed_zero, f_1 + can_be_fixed_one
def main():
global data, label, target, adj, cost
n = input1()
data = [0 for _ in range(n+4)]
label = [0 for _ in range(n+4)]
target = [0 for _ in range(n+4)]
cost = [0 for _ in range(n+4)]
z, o, tz, to = 0, 0, 0, 0
for i in range(1, n+1):
cost[i], label[i], target[i] = input3()
z += (label[i] == 0)
o += (label[i] == 1)
tz += (target[i] == 0)
to += (target[i] == 1)
adj = {}
for i in range(n-1):
u, v = input2()
if u not in adj:
adj[u] = []
if v not in adj:
adj[v] = []
adj[u].append(v)
adj[v].append(u)
if (tz != z or o != to):
print(-1)
exit()
dfs1(1, -1)
# for i in range(1, n+1):
# print(data[i], cost[i])
global res
res = 0
call(1, -1)
print(res)
pass
if __name__ == '__main__':
# sys.setrecursionlimit(2**32//2-1)
# threading.stack_size(1 << 27)
# thread = threading.Thread(target=main)
# thread.start()
# thread.join()
# sys.setrecursionlimit(200004)
# READ('in.txt')
main()
|
1590935700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["2", "112"]
|
43d877e3e1c1fd8ee05dc5e5e3067f93
|
NoteIn the first test, there is only one mirror and it tells, that Creatnx is beautiful with probability $$$\frac{1}{2}$$$. So, the expected number of days until Creatnx becomes happy is $$$2$$$.
|
Creatnx has $$$n$$$ mirrors, numbered from $$$1$$$ to $$$n$$$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $$$i$$$-th mirror will tell Creatnx that he is beautiful with probability $$$\frac{p_i}{100}$$$ for all $$$1 \le i \le n$$$.Creatnx asks the mirrors one by one, starting from the $$$1$$$-st mirror. Every day, if he asks $$$i$$$-th mirror, there are two possibilities: The $$$i$$$-th mirror tells Creatnx that he is beautiful. In this case, if $$$i = n$$$ Creatnx will stop and become happy, otherwise he will continue asking the $$$i+1$$$-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the $$$1$$$-st mirror again. You need to calculate the expected number of days until Creatnx becomes happy.This number should be found by modulo $$$998244353$$$. Formally, let $$$M = 998244353$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.
|
Print the answer modulo $$$998244353$$$ in a single line.
|
The first line contains one integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the number of mirrors. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq 100$$$).
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_017.jsonl
|
d758adcba0dbcc2f1a20044052ecfef4
|
256 megabytes
|
["1\n50", "3\n10 20 50"]
|
PASSED
|
n=input()
l=map(int,raw_input().split())
num=0
p=1
for i in range(n):
num=(num+(p*pow(100,n-i,998244353))%998244353)%998244353
p=(p*l[i])%998244353
print (num*pow(p,998244351,998244353))%998244353
|
1575556500
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds
|
["6", "7", "0"]
|
75e6bc042f61d2dd61165866a13d1c6d
|
NoteIn the first sample the following subsequences are possible: If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())". If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()". If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()". If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()". If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()". If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()". The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
|
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met: It is not empty (that is n ≠ 0). The length of the sequence is even. First charactes of the sequence are equal to "(". Last charactes of the sequence are equal to ")". For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
|
Output one number — the answer for the task modulo 109 + 7.
|
The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,300 |
train_037.jsonl
|
fde78457fa8cf2cbc6248a002cdfffc7
|
256 megabytes
|
[")(()()", "()()()", ")))"]
|
PASSED
|
mod = 10 ** 9 + 7
fact, inv, invfact = [1, 1], [0, 1], [1, 1]
for i in range(2, 200200):
fact.append(fact[-1] * i % mod)
inv.append(inv[mod % i] * (mod - mod // i) % mod)
invfact.append(invfact[-1] * inv[-1] % mod)
def C(n, k):
if k < 0 or k > n:
return 0
return fact[n] * invfact[k] * invfact[n - k] % mod
s = input()
op, cl = 0, s.count(')')
ans = 0
for x in s:
if x == '(':
op += 1
cur = C(cl + op - 1, op)
ans += cur
else:
cl -= 1
print(ans % mod)
|
1489590300
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["3.500000000000", "4.958333333333", "1.750000000000"]
|
f70ac2c4e0f62f9d6ad1e003aedd86b2
|
NoteConsider the third test example. If you've made two tosses: You can get 1 in the first toss, and 2 in the second. Maximum equals to 2. You can get 1 in the first toss, and 1 in the second. Maximum equals to 1. You can get 2 in the first toss, and 1 in the second. Maximum equals to 2. You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value
|
Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.
|
Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4.
|
A single line contains two integers m and n (1 ≤ m, n ≤ 105).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_011.jsonl
|
05a23b579b77eff8fb269d6721c53d91
|
256 megabytes
|
["6 1", "6 3", "2 2"]
|
PASSED
|
n,m = map(int, input().split())
s=0
for i in range(n):
s+=(i+1)*(pow((i+1)/n,m)-pow(i/n,m))
print(s)
|
1406907000
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["YES\n0 1 1", "YES\n0 1 1 3 3", "NO"]
|
2354852d9cc911ac4a307dee5b75d6fc
|
NoteIn the first example case one can have a construction with 3 people, where 1 person has 2 parents.In the second example case one can use the following construction: Only person 1 is imbalanced, because one of their parents has 1 ancestor in total, and the other parent has 3 ancestors.
|
Ivan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in this structure are conveniently numbered from $$$1$$$ to $$$n$$$, and $$$s_i$$$ denotes the child of the person $$$i$$$ (and $$$s_i = 0$$$ for exactly one person who does not have any children).We say that $$$a$$$ is an ancestor of $$$b$$$ if either $$$a = b$$$, or $$$a$$$ has a child, who is an ancestor of $$$b$$$. That is $$$a$$$ is an ancestor for $$$a$$$, $$$s_a$$$, $$$s_{s_a}$$$, etc.We say that person $$$i$$$ is imbalanced in case this person has both parents specified, and the total number of ancestors of one of the parents is at least double the other. Ivan counted the number of imbalanced people in the structure, and got $$$k$$$ people in total. However, he is not sure whether he computed it correctly, and would like to check if there is at least one construction with $$$n$$$ people that have $$$k$$$ imbalanced people in total. Please help him to find one such construction, or determine if it does not exist.
|
If there are no constructions with $$$n$$$ people and $$$k$$$ imbalanced people, output NO. Otherwise output YES on the first line, and then $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \leq s_i \leq n$$$), which describes the construction and specify the child of each node (or 0, if the person does not have any children).
|
The input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 100\,000$$$, $$$0 \leq k \leq n$$$), the total number of people and the number of imbalanced people.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,800 |
train_065.jsonl
|
a139305188c4f2aa7b001886cf4cf79c
|
512 megabytes
|
["3 0", "5 1", "3 2"]
|
PASSED
|
from heapq import *
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def ng():
print("NO")
exit()
n, k = MI()
if (n,k)==(1,0):
print("YES")
print(0)
exit()
ans = [0] * n
popcnt = lambda x: bin(x).count("1")
if n & 1 == 0 or n < 2 * k + 3 or (popcnt(n + 1) > 1 and k == 0): ng()
u = 0
if popcnt(n + 1 - 2 * (k - 1)) == 1:
for v in range(1, 4): ans[v] = v // 2+1
k -= 1
if n - 4 < 2 * k + 3 or k==0 or n<11: ng()
ans[4] = 1
u = 4
#print(n, k, u, ans)
for _ in range(k - 1):
ans[u + 1] = ans[u + 2] = u+1
u += 2
#print(n, k, u, ans)
for v in range(1,n-u):ans[v+u]=(v-1)//2+u+1
print("YES")
print(*ans)
|
1595149200
|
[
"math",
"trees"
] |
[
0,
0,
0,
1,
0,
0,
0,
1
] |
|
1 second
|
["3 1 2 1\n6 5 2 5 3 1 2\n0\n9 4 1 2 10 4 1 2 1 5\n1 1"]
|
46c5ebf1ddf5547352e84ba0171eacbc
|
NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.
|
This is the hard version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$2n$$$ operations. It can be proved that it is always possible.
|
For each test case, output an integer $$$k$$$ ($$$0\le k\le 2n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.
|
The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,700 |
train_005.jsonl
|
669d8046b27ef2616d52afa1b5e15189
|
256 megabytes
|
["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1"]
|
PASSED
|
t = int(input())
for _ in range(t):
l = int(input())
a = input().rstrip()
b = input().rstrip()
ans = []
c = 0
if a[0]=='1':
c += 1
for i in range(len(a)-1):
if a[i+1] != a[i]:
ans.append(i+1)
c+= 1
bns = []
d = 0
if b[0]=='1':
d += 1
for i in range(len(b)-1):
if b[i+1] != b[i]:
bns.append(i+1)
d += 1
if c%2!=d%2:
ans += [l]
f = ans + bns[::-1]
print(len(f), *f)
|
1595342100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
1.5 seconds
|
["15", "30"]
|
ab23517c489717ac200821f1041368a2
| null |
In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his n sons-princes marry the brides with as big dowry as possible.In search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with m unmarried princesses. Receiving guests, Karl learned that the dowry of the i th princess is wi of golden coins. Although the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.Knowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.Help the king to organize the marriage of his sons in the most profitable way for the treasury.
|
Print the only integer — the maximum number of gold coins that a king can get by playing the right weddings.
|
The first line contains two integers n, m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ 200 000) — number of princes and princesses respectively. Each of following m lines contains three integers ai, bi, wi (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ wi ≤ 10 000) — number of princes, which i-th princess is ready to marry and the value of her dowry.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,500 |
train_079.jsonl
|
5dadc7361e08f7b582a1b8de124cc35c
|
512 megabytes
|
["2 3\n1 2 5\n1 2 1\n2 1 10", "3 2\n1 2 10\n3 2 20"]
|
PASSED
|
from sys import stdin
from itertools import repeat
def main():
n, m = map(int, stdin.readline().split())
dat = map(int, stdin.read().split(), repeat(10, 3 * m))
e = [(-dat[i*3+2], dat[i*3+1], dat[i*3]) for i in xrange(m)]
e.sort()
par = range(n + 1)
c = [1] * (n + 1)
st = []
po = st.pop
pu = st.append
ans = 0
for s, x, y in e:
while x != par[x]:
pu(x)
x = par[x]
while y != par[y]:
pu(y)
y = par[y]
if x == y:
if c[y]:
c[y] = 0
ans += s
else:
pu(x)
if c[y] or c[x]:
ans += s
c[y] &= c[x]
for z in st:
par[z] = y
del st[:]
print -ans
main()
|
1508151900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nNO\nNO\nYES"]
|
bdbd3420d9aa85b3143a87c5fa530f31
|
NoteFor the first and the second test case, the only possible combination is $$$[1]$$$ so there always will be a subsegment with $$$1$$$ animal but not with $$$2$$$ animals.
|
Theofanis decided to visit his uncle's farm. There are $$$s$$$ animals and $$$n$$$ animal pens on the farm. For utility purpose, animal pens are constructed in one row.Uncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one continuous segment of pens that has exactly $$$k$$$ animals in total.Moreover, a farm is ideal if it's lucky for any distribution without empty pens.Neither Theofanis nor his uncle knows if their farm is ideal or not. Can you help them to figure it out?
|
For each test case, print YES (case-insensitive), if the farm is ideal, or NO (case-insensitive) otherwise.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The first and only line of each test case contains three integers $$$s$$$, $$$n$$$, and $$$k$$$ ($$$1 \le s, n, k \le 10^{18}$$$; $$$n \le s$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,400 |
train_097.jsonl
|
880979acd4ec34ac767c86a05ce7a10a
|
256 megabytes
|
["4\n1 1 1\n1 1 2\n100 50 200\n56220 47258 14497"]
|
PASSED
|
import sys
input = sys.stdin.buffer.readline
def process(s, n, k):
if k==0 or k==s:
sys.stdout.write("YES\n")
return
if k > s:
sys.stdout.write("NO\n")
return
a = s % k
b = s//k
"""
Normally
a blocks of size b+1
corresponding to 0, 1, .., (a-1)
k-a blocks of size b
so s = k*b+a
However we also have s
so a+1 blocks of size b+1
corresponding to 0, 1, ..., a
and k-a-1 blocks of size b
However we remove 2 from
the 0-block
and 2 from the s-block
0, 1, 4, 5, 10
"""
if a==0:
blocks = [[a, b+1], [k-a-1, b], [1, b-3]]
else:
blocks = [[a-1, b+1], [k-a-1, b], [2, b-1]]
# print(blocks)
max_n = 0
for count, size in blocks:
if size > 0:
if size % 2==0:
max_n+=(count*size)//2
else:
max_n+=(count*(size+1))//2
if max_n >= n-1:
sys.stdout.write('NO\n')
else:
sys.stdout.write('YES\n')
t = int(input())
for i in range(t):
s, n, k = [int(x) for x in input().split()]
process(s, n, k)
|
1633705500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3", "0", "-1", "1"]
|
79b0794f81acc1c882649d96b1c7f8da
|
NoteIn the first example Polycarp should increase the first number on $$$1$$$, decrease the second number on $$$1$$$, increase the third number on $$$1$$$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $$$[25, 20, 15, 10]$$$, which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $$$[0, 3, 6, 9, 12]$$$, which is an arithmetic progression.
|
Polycarp likes arithmetic progressions. A sequence $$$[a_1, a_2, \dots, a_n]$$$ is called an arithmetic progression if for each $$$i$$$ ($$$1 \le i < n$$$) the value $$$a_{i+1} - a_i$$$ is the same. For example, the sequences $$$[42]$$$, $$$[5, 5, 5]$$$, $$$[2, 11, 20, 29]$$$ and $$$[3, 2, 1, 0]$$$ are arithmetic progressions, but $$$[1, 0, 1]$$$, $$$[1, 3, 9]$$$ and $$$[2, 3, 1]$$$ are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers $$$[b_1, b_2, \dots, b_n]$$$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $$$1$$$, an element can be increased by $$$1$$$, an element can be left unchanged.Determine a minimum possible number of elements in $$$b$$$ which can be changed (by exactly one), so that the sequence $$$b$$$ becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals $$$0$$$.
|
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
|
The first line contains a single integer $$$n$$$ $$$(1 \le n \le 100\,000)$$$ — the number of elements in $$$b$$$. The second line contains a sequence $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 10^{9})$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 1,500 |
train_044.jsonl
|
e7fb35a704ec1f46b5b168e7d759f335
|
256 megabytes
|
["4\n24 21 14 10", "2\n500 500", "3\n14 5 1", "5\n1 3 6 9 12"]
|
PASSED
|
import sys
n = raw_input()
a = map(int,raw_input().split())
ans = sys.maxint
if len(a) > 2:
check = [(0,0,0),
(1,0,1),
(0,1,1),
(-1,0,1),
(0,-1,1),
(1,-1,2),
(-1,1,2),
(1,1,2),
(-1,-1,2)]
for e in check:
diff = (a[1]+e[1]) - (a[0]+e[0])
chg = e[2]
state = [e[0],e[1]]
valid = True
for i in range(2,len(a)):
if a[i] - (a[i-1]+state[i-1]) - diff >= 2 or a[i] - (a[i-1]+state[i-1]) - diff <= -2:
valid = False
break
else:
state.append(diff - (a[i] - (a[i-1]+state[i-1])) )
chg += abs(a[i] - (a[i-1]+state[i-1]) - diff)
if valid:
ans = min(chg,ans)
else:
ans = 0
print -1 if ans == sys.maxint else ans
|
1526202300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n4 1 2\n2 3 3\n-1\n4\n1 2 4\n2 4 5\n2 3 3\n4 5 1"]
|
b6fb4d868e3f496466746f5e776ae2cc
| null |
You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, numbered from $$$1$$$ to $$$n$$$. You can perform the following operation no more than $$$3n$$$ times: choose three integers $$$i$$$, $$$j$$$ and $$$x$$$ ($$$1 \le i, j \le n$$$; $$$0 \le x \le 10^9$$$); assign $$$a_i := a_i - x \cdot i$$$, $$$a_j := a_j + x \cdot i$$$. After each operation, all elements of the array should be non-negative.Can you find a sequence of no more than $$$3n$$$ operations after which all elements of the array are equal?
|
For each test case print the answer to it as follows: if there is no suitable sequence of operations, print $$$-1$$$; otherwise, print one integer $$$k$$$ ($$$0 \le k \le 3n$$$) — the number of operations in the sequence. Then print $$$k$$$ lines, the $$$m$$$-th of which should contain three integers $$$i$$$, $$$j$$$ and $$$x$$$ ($$$1 \le i, j \le n$$$; $$$0 \le x \le 10^9$$$) for the $$$m$$$-th operation. If there are multiple suitable sequences of operations, print any of them. Note that you don't have to minimize $$$k$$$.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,000 |
train_012.jsonl
|
66e0e33abcefa54d09a178184e2270f8
|
256 megabytes
|
["3\n4\n2 16 4 18\n6\n1 2 3 4 5 6\n5\n11 19 1 1 3"]
|
PASSED
|
from collections import Counter, defaultdict, deque
import bisect
import heapq
from sys import stdin, stdout
from itertools import repeat
import math
import random
# sys.stdin = open('input')
def mod(x, y, mod):
re = 1
now = x
while y:
if y&1:
re *= now
re %= mod
y >>= 1
now = (now*now)%mod
return re
def inp(force_list=False):
re = map(int, raw_input().split())
if len(re) == 1 and not force_list:
return re[0]
return re
def inst():
return raw_input().strip()
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def ggcd(x, y):
if y:
return ggcd(y, x%y)
return x
MOD = int(1e9+7)
def my_main():
T = inp()
for _ in range(T):
n = inp()
ans = []
da = inp(True)
sm = sum(da)
if sm%n != 0:
print -1
continue
ta = sm / n
for i in range(2, n+1):
less = (i - da[i-1]%i)%i
ans.append("%d %d %d" %(1, i, less))
x = (da[i-1]+less)/i
ans.append("%d %d %d" %(i, 1, x))
for i in range(2, n+1):
ans.append("%d %d %d" %(1, i, ta))
print len(ans)
print '\n'.join(ans)
my_main()
|
1601219100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3\n5\n4\n28010\n110"]
|
f7cde36c9cd0131478a5e3b990c64084
|
NoteIn the first test case: At time $$$0$$$, the values of the nodes are $$$[1, 1, 1]$$$. At time $$$1$$$, the values of the nodes are $$$[0, 1, 1]$$$. At time $$$2$$$, the values of the nodes are $$$[0, 0, 1]$$$. At time $$$3$$$, the values of the nodes are $$$[0, 0, 0]$$$.So the answer is $$$3$$$. In the second test case: At time $$$0$$$, the values of the nodes are $$$[1, 0, 0, 0, 0]$$$. At time $$$1$$$, the values of the nodes are $$$[0, 1, 0, 0, 1]$$$. At time $$$2$$$, the values of the nodes are $$$[0, 0, 1, 0, 0]$$$. At time $$$3$$$, the values of the nodes are $$$[0, 0, 0, 1, 0]$$$. At time $$$4$$$, the values of the nodes are $$$[0, 0, 0, 0, 1]$$$. At time $$$5$$$, the values of the nodes are $$$[0, 0, 0, 0, 0]$$$. So the answer is $$$5$$$.In the third test case:The first moment of time when all $$$a_i$$$ become $$$0$$$ is $$$6\cdot 998244353 + 4$$$.
|
Cirno has a DAG (Directed Acyclic Graph) with $$$n$$$ nodes and $$$m$$$ edges. The graph has exactly one node that has no out edges. The $$$i$$$-th node has an integer $$$a_i$$$ on it.Every second the following happens: Let $$$S$$$ be the set of nodes $$$x$$$ that have $$$a_x > 0$$$. For all $$$x \in S$$$, $$$1$$$ is subtracted from $$$a_x$$$, and then for each node $$$y$$$, such that there is an edge from $$$x$$$ to $$$y$$$, $$$1$$$ is added to $$$a_y$$$.Find the first moment of time when all $$$a_i$$$ become $$$0$$$. Since the answer can be very large, output it modulo $$$998\,244\,353$$$.
|
For each test case, print an integer in a separate line — the first moment of time when all $$$a_i$$$ become $$$0$$$, modulo $$$998\,244\,353$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n, m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of vertices and edges in the graph. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the integer on vertices. Each line of the following $$$m$$$ lines contains two integers $$$x, y$$$ ($$$1 \leq x, y \leq n$$$), represent a directed edge from $$$x$$$ to $$$y$$$. It is guaranteed that the graph is a DAG with no multi-edges, and there is exactly one node that has no out edges. It is guaranteed that both sum of $$$n$$$ and sum of $$$m$$$ over all test cases are less than or equal to $$$10\,000$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,200 |
train_089.jsonl
|
dcd64739b98b3f8d94d45f90ba9d653e
|
256 megabytes
|
["5\n\n3 2\n\n1 1 1\n\n1 2\n\n2 3\n\n5 5\n\n1 0 0 0 0\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n1 5\n\n10 11\n\n998244353 0 0 0 998244353 0 0 0 0 0\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n5 6\n\n6 7\n\n7 8\n\n8 9\n\n9 10\n\n1 3\n\n7 9\n\n5 6\n\n1293 1145 9961 9961 1919\n\n1 2\n\n2 3\n\n3 4\n\n5 4\n\n1 4\n\n2 4\n\n6 9\n\n10 10 10 10 10 10\n\n1 2\n\n1 3\n\n2 3\n\n4 3\n\n6 3\n\n3 5\n\n6 5\n\n6 1\n\n6 2"]
|
PASSED
|
from sys import stdin, stdout
N = 998244353
def toposort(graph):
res, found = [], [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
res.append(~node)
elif not found[node]:
found[node] = 1
stack.append(~node)
stack += graph[node]
# cycle check
for node in res:
if any(found[nei] for nei in graph[node]):
return None
found[node] = 0
return res[::-1]
t = int(stdin.readline())
for _ in range(t):
n, m = [int(x) for x in stdin.readline().split()]
a = [int(x) for x in stdin.readline().split()]
in_neighbours = {i:set() for i in range(n)}
out_neighbours = {i:set() for i in range(n)}
for bar in range(m):
v, w = [int(x)-1 for x in stdin.readline().split()]
in_neighbours[w].add(v)
out_neighbours[v].add(w)
if max(a) == 0:
stdout.write('0\n')
else:
time = 0
success = False
for bar in range(n-1):
time += 1
delta = []
for v in range(n):
if a[v] == 0:
temp = 0
else:
temp = -1
for w in in_neighbours[v]:
if a[w] > 0:
temp += 1
delta.append(temp)
for v in range(n):
a[v] += delta[v]
if max(a) == 0:
success = True
break
if success:
stdout.write(str(time)+'\n')
else:
stack = toposort(out_neighbours)
for v in stack:
for w in out_neighbours[v]:
a[w] = (a[w]+a[v])%N
stdout.write(str((time+a[v])%N)+'\n')
|
1659276300
|
[
"math",
"graphs"
] |
[
0,
0,
1,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1\n-1\n-1\n2", "1\n-1\n-1\n2\n5\n-1", "13\n2\n9\n5\n-1"]
|
27a521d4d59066e50e870e7934d4b190
|
NoteIn the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2, 4), (1, 3), (0, 2), (1, 1), (2, 0), (3, 1), (2, 2), (1, 3), (0, 4). The ray will stop at the point (0, 4) after 12 seconds. It will reflect at the points (3, 3), (2, 4), (0, 2), (2, 0) and (3, 1).
|
There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print - 1 for such sensors.
|
Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or - 1 if this will never happen.
|
The first line of the input contains three integers n, m and k (2 ≤ n, m ≤ 100 000, 1 ≤ k ≤ 100 000) — lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1 ≤ xi ≤ n - 1, 1 ≤ yi ≤ m - 1) — coordinates of the sensors. It's guaranteed that no two sensors are located at the same point.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_063.jsonl
|
cf43eaa817548eba4715c30cc993ea58
|
256 megabytes
|
["3 3 4\n1 1\n1 2\n2 1\n2 2", "3 4 6\n1 1\n2 1\n1 2\n2 2\n1 3\n2 3", "7 4 5\n1 3\n2 2\n5 1\n5 3\n4 3"]
|
PASSED
|
n, m, k = map(int,input().split())
dm, dp = {}, {}
vis = {}
sensors = []
border = set()
for el in [(0, m), (n, 0), (0, 0), (n, m)]:
border.add(el)
for _ in range(k):
x, y = map(int, input().split())
if not (x - y) in dm:
dm[x - y] = []
dm[x - y].append((x, y))
if not (x + y) in dp:
dp[x + y] = []
dp[x + y].append((x, y))
vis[(x, y)] = -1
sensors.append((x,y))
x, y = 0, 0
time = 0
move = (1,1)
while True:
if move == (1,1):
v = min(n - x, m - y)
nxt = (x + v, y + v)
if nxt[0] == n:
move = (-1, 1)
else:
move = (1, -1)
if (x - y) in dm:
for sensor in dm[x - y]:
if vis[sensor] == -1:
#print('doing', sensor)
vis[sensor] = time + sensor[0] - x
time += v
elif move == (-1,-1):
v = min(x, y)
nxt = (x - v, y - v)
if nxt[0] == 0:
move = (1, -1)
else:
move = (-1, 1)
if (x - y) in dm:
for sensor in dm[x - y]:
if vis[sensor] == -1:
#print('doing', sensor)
vis[sensor] = time + x - sensor[0]
time += v
elif move == (-1,1):
v = min(x, m - y)
nxt = (x - v, y + v)
if nxt[0] == 0:
move = (1, 1)
else:
move = (-1, -1)
if (x + y) in dp:
for sensor in dp[x + y]:
if vis[sensor] == -1:
#print('doing', sensor)
vis[sensor] = time + x - sensor[0]
time += v
else:
v = min(n - x, y)
nxt = (x + v, y - v)
if nxt[0] == n:
move = (-1, -1)
else:
move = (1, 1)
if (x + y) in dp:
for sensor in dp[x + y]:
if vis[sensor] == -1:
#print('doing', sensor)
vis[sensor] = time + sensor[0] - x
time += v
if nxt in border:
break
else:
border.add(nxt)
x, y = nxt
#print('bum', x, y)
for i in range(k):
#print(sensors[i])
print(vis[sensors[i]])
|
1475928900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
3 seconds
|
["2\n5 10", "1\n10", "3\n2 3 4", "3\n42 13 37"]
|
0fd45a1eb1fc23e579048ed2beac7edd
|
NoteLet's consider the examples from the statement. In the first example, Monocarp pins the messages $$$5$$$ and $$$10$$$. if the first student reads the message $$$5$$$, the second student reads the messages $$$5$$$ and $$$10$$$, and the third student reads the messages $$$5$$$ and $$$10$$$, the number of students which have read their respective messages will be $$$2$$$; if the first student reads the message $$$10$$$, the second student reads the messages $$$5$$$ and $$$10$$$, and the third student reads the messages $$$5$$$ and $$$10$$$, the number of students which have read their respective messages will be $$$3$$$. So, the expected number of students which will read their respective messages is $$$\frac{5}{2}$$$. In the second example, Monocarp pins the message $$$10$$$. if the first student reads the message $$$10$$$, the second student reads the message $$$10$$$, and the third student reads the message $$$10$$$, the number of students which have read their respective messages will be $$$2$$$. So, the expected number of students which will read their respective messages is $$$2$$$. If Monocarp had pinned both messages $$$5$$$ and $$$10$$$, the expected number of students which read their respective messages would have been $$$2$$$ as well. In the third example, the expected number of students which will read their respective messages is $$$\frac{8}{3}$$$. In the fourth example, the expected number of students which will read their respective messages is $$$2$$$.
|
Monocarp is a tutor of a group of $$$n$$$ students. He communicates with them using a conference in a popular messenger.Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student $$$i$$$ to read the message $$$m_i$$$.Of course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise it will definitely be skipped by everyone.Unfortunately, even if a message is pinned, some students may skip it anyway. For each student $$$i$$$, Monocarp knows that they will read at most $$$k_i$$$ messages. Suppose Monocarp pins $$$t$$$ messages; if $$$t \le k_i$$$, then the $$$i$$$-th student will read all the pinned messages; but if $$$t > k_i$$$, the $$$i$$$-th student will choose exactly $$$k_i$$$ random pinned messages (all possible subsets of pinned messages of size $$$k_i$$$ are equiprobable) and read only the chosen messages.Monocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices $$$i$$$ that student $$$i$$$ reads the message $$$m_i$$$). Help him to choose how many (and which) messages should he pin!
|
In the first line, print one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of messages Monocarp should pin. In the second line, print $$$t$$$ distinct integers $$$c_1$$$, $$$c_2$$$, ..., $$$c_t$$$ ($$$1 \le c_i \le 2 \cdot 10^5$$$) — the indices of the messages Monocarp should pin. The messages can be listed in any order. If there are multiple answers, print any of them.
|
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students in the conference. Then $$$n$$$ lines follow. The $$$i$$$-th line contains two integers $$$m_i$$$ and $$$k_i$$$ ($$$1 \le m_i \le 2 \cdot 10^5$$$; $$$1 \le k_i \le 20$$$) — the index of the message which Monocarp wants the $$$i$$$-th student to read and the maximum number of messages the $$$i$$$-th student will read, respectively.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,000 |
train_098.jsonl
|
4a59cdfe0932d6b7a10853628c6b7652
|
512 megabytes
|
["3\n10 1\n10 2\n5 2", "3\n10 1\n5 2\n10 1", "4\n1 1\n2 2\n3 3\n4 4", "3\n13 2\n42 2\n37 2"]
|
PASSED
|
import io,os
import heapq
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def calculate_maximum(tot,dic,wmax,wkey):
n = len(dic)
if n<tot: return [-1,[]]
indexes = [i for i in range(n)]
for i,key in enumerate(wkey):
wmax[i] += dic[key][tot]
heap = []
for i in range(n):
heapq.heappush(heap,(wmax[i],wkey[i]))
if len(heap)>tot: heapq.heappop(heap)
tempans = 0
temppick = []
for i in range(tot):
ele = heapq.heappop(heap)
tempans += ele[0]
temppick.append(ele[1])
return [tempans*1.0/tot,temppick]
def main(t):
q = int(input())
dic = {}
store = {}
for i in range(q):
index, hr = map(int,input().split())
if index not in dic: dic[index] = [0]*21
dic[index][hr] += 1
# print(dic)
for key in dic:
for k in range(19,0,-1):
dic[key][k] = dic[key][k+1] + dic[key][k]
# print(dic)
wkey = []
for key in dic: wkey.append(key)
wmax = [0]*(len(wkey))
ans = 0
pick = []
for k in range(1,21):
[tempans,temppick] = calculate_maximum(k,dic,wmax,wkey)
if tempans>ans:
ans = tempans
pick = temppick
# else:
# break
# print(ans,pick)
# if 64217 in dic and dic[64217][12]==1 and 76864 in dic and dic[76864][3]==1:
# print(20)
# print(1523,47986,140077,129374,198572,113642,117770,184883,71059,2094,36452,193203,143563,78520,151265,188108,3411,165350,191396,110974)
print(len(pick))
print(" ".join(map(str,pick)))
T = 1#int(input())
t = 1
while t<=T:
main(t)
t += 1
|
1637573700
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
1 second
|
["2", "1", "Impossible", "1"]
|
ffdef277d0ff8e8579b113f5bd30f52a
|
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
|
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).
|
Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
|
The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,800 |
train_026.jsonl
|
058ccfdebd5a9712cf3f552d47330ca2
|
256 megabytes
|
["nolon", "otto", "qqqq", "kinnikkinnik"]
|
PASSED
|
s = input()
l = len(s)
c = s[0]
diff = False
for i in range(0,int(l/2)):
if s[i] != c:
diff = True
if not diff:
print('Impossible')
exit()
s_2 = s + s
for i in range(1,l):
is_palendrome = True
for j in range(int(l/2)):
if s_2[j + i] != s_2[i + l - j-1]:
is_palendrome = False
if is_palendrome and s_2[i:i+l] != s:
print(1)
exit()
print(2)
|
1550334900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["3", "1"]
|
63e130256e23bd0693c6a1bede5e937e
| null |
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, l + 1, l + 2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1 = 1, F2 = 1, Fn = Fn - 1 + Fn - 2 for n ≥ 3.Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.
|
Print a single integer — the residue from dividing the sought greatest common divisor by m.
|
The first line contains four space-separated integers m, l, r and k (1 ≤ m ≤ 109; 1 ≤ l < r ≤ 1012; 2 ≤ k ≤ r - l + 1). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
|
standard output
|
standard input
|
Python 2
|
Python
| 2,400 |
train_043.jsonl
|
44a15a661135a9b3ad098d554c01034b
|
256 megabytes
|
["10 1 8 2", "10 1 8 3"]
|
PASSED
|
def recfib(n,m):
if n==0: return (0,1,)
a, b = recfib(n / 2,m)
return ((b*b+a*a)%m, b*(2*a+b)%m) if n%2 else (a*((2*b)-a)%m, ((b*b+a*a))%m)
m,l,r,k = map(long, raw_input().split())
D = (r-l)/(k-1)
while D > 1 and (1+(r/D)-((l+D-1)/D))<k:
N = 1 + (r/D)
D -= ( ((N*D)-r) + (N-1) ) / N
print(recfib(D, m)[0])
|
1348500600
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2.0000000000", "-1", "0.5000000000"]
|
1c2fc9449989d14d9eb02a390f36b7a6
|
NoteIn sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.In sample test 2, you can use the device indefinitely.In sample test 3, we can charge the third device for 2 / 5 of a second, then switch to charge the second device for a 1 / 10 of a second.
|
You have n devices that you want to use simultaneously.The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
|
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
|
The first line contains two integers, n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109) — the number of devices and the power of the charger. This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1 ≤ ai, bi ≤ 100 000) — the power of the device and the amount of power stored in the device in the beginning.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,800 |
train_000.jsonl
|
64f5b4b8ec180aeaf58314d8bfe51fdf
|
256 megabytes
|
["2 1\n2 2\n2 1000", "1 100\n1 1", "3 5\n4 3\n5 2\n6 1"]
|
PASSED
|
n, p = map(int, raw_input().strip().split())
d = [None] * n
for i in range(n):
d[i] = map(int, raw_input().strip().split())
if p >= sum(map(lambda x:x[0], d)):
print -1
else:
d.sort(cmp=lambda x,y:1 if x[1] * y[0] > y[1] * x[0] else -1)
res = 1e100
a_s, b_s = 0.0, 0.0
for i in range(n):
a_s += d[i][0]
b_s += d[i][1]
if a_s <= p: continue
res = min(res, b_s * 1. / (a_s - p))
print "%.9f" % res
|
1492356900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
4 seconds
|
["2 1 4 3 \n1 2 \n3 4 2 1 5 \n3 2 1"]
|
5481863fd03c37cdcb7d6ee40f973cb9
| null |
Monocarp had a permutation $$$a$$$ of $$$n$$$ integers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once).Then Monocarp calculated an array of integers $$$b$$$ of size $$$n$$$, where $$$b_i = \left\lfloor \frac{i}{a_i} \right\rfloor$$$. For example, if the permutation $$$a$$$ is $$$[2, 1, 4, 3]$$$, then the array $$$b$$$ is equal to $$$\left[ \left\lfloor \frac{1}{2} \right\rfloor, \left\lfloor \frac{2}{1} \right\rfloor, \left\lfloor \frac{3}{4} \right\rfloor, \left\lfloor \frac{4}{3} \right\rfloor \right] = [0, 2, 0, 1]$$$.Unfortunately, the Monocarp has lost his permutation, so he wants to restore it. Your task is to find a permutation $$$a$$$ that corresponds to the given array $$$b$$$. If there are multiple possible permutations, then print any of them. The tests are constructed in such a way that least one suitable permutation exists.
|
For each test case, print $$$n$$$ integers — a permutation $$$a$$$ that corresponds to the given array $$$b$$$. If there are multiple possible permutations, then print any of them.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — 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 $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le n$$$). Additional constrains on the input: the sum of $$$n$$$ over test cases does not exceed $$$5 \cdot 10^5$$$; there exists at least one permutation $$$a$$$ that would yield this array $$$b$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_098.jsonl
|
3babb8db54ba1568e0011deb4af2f572
|
256 megabytes
|
["4\n\n4\n\n0 2 0 1\n\n2\n\n1 1\n\n5\n\n0 0 1 4 1\n\n3\n\n0 1 3"]
|
PASSED
|
import heapq
import sys
input = sys.stdin.readline
rounds=int(input())
for ii in range(rounds):
out=0
length=int(input())
arr=list(map(int,input().split()))
small=[]
for l in range(length):
if arr[l]==0:
small.append([l+2,length,l])
else:
little=(l+1)//(arr[l]+1)+1
big=(l+1)//arr[l]
small.append([little,big,l])
small.sort()
used=set()
out=[0]*length
p=1
hold=[]
heapq.heapify(hold)
ind=0
while p<length+1:
for j in range(ind,length):
if p>=small[j][0] and small[j][2] not in used:
heapq.heappush(hold,(small[j][1],small[j][2]))
used.add(small[j][2])
else:
ind=j
break
cur=heapq.heappop(hold)
out[cur[1]]=p
p+=1
for o in out:
print(o,end=' ')
print('')
|
1657290900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["Yes\n101000\n100001", "Yes\n10100\n10010", "No"]
|
ea620a8dbef506567464dcaddcc2b34f
|
NoteIn the first example, $$$x = 101000_2 = 2^5 + 2^3 = 40_{10}$$$, $$$y = 100001_2 = 2^5 + 2^0 = 33_{10}$$$, $$$40_{10} - 33_{10} = 7_{10} = 2^2 + 2^1 + 2^0 = 111_{2}$$$. Hence $$$x-y$$$ has $$$3$$$ ones in base-2.In the second example, $$$x = 10100_2 = 2^4 + 2^2 = 20_{10}$$$, $$$y = 10010_2 = 2^4 + 2^1 = 18$$$, $$$x - y = 20 - 18 = 2_{10} = 10_{2}$$$. This is precisely one 1.In the third example, one may show, that it's impossible to find an answer.
|
You are given three integers $$$a$$$, $$$b$$$, $$$k$$$.Find two binary integers $$$x$$$ and $$$y$$$ ($$$x \ge y$$$) such that both $$$x$$$ and $$$y$$$ consist of $$$a$$$ zeroes and $$$b$$$ ones; $$$x - y$$$ (also written in binary form) has exactly $$$k$$$ ones. You are not allowed to use leading zeros for $$$x$$$ and $$$y$$$.
|
If it's possible to find two suitable integers, print "Yes" followed by $$$x$$$ and $$$y$$$ in base-2. Otherwise print "No". If there are multiple possible answers, print any of them.
|
The only line contains three integers $$$a$$$, $$$b$$$, and $$$k$$$ ($$$0 \leq a$$$; $$$1 \leq b$$$; $$$0 \leq k \leq a + b \leq 2 \cdot 10^5$$$) — the number of zeroes, ones, and the number of ones in the result.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_109.jsonl
|
158e3bd13e626daa40efa4dd7f3ebc86
|
512 megabytes
|
["4 2 3", "3 2 1", "3 2 5"]
|
PASSED
|
try:
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as Cntr
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect, insort
from time import perf_counter
from fractions import Fraction
import copy
from copy import deepcopy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def A2(n,m): return [[0]*m for i in range(n)]
def A(n):return [0]*n
# sys.setrecursionlimit(int(pow(10,6)))
# from sys import stdin
# input = stdin.buffer.readline
# I = lambda : list(map(int,input().split()))
# import sys
# input=sys.stdin.readline
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
except:
pass
a,b,k = L()
if b==1 or a==0:
if k==0:
print("Yes")
print("1"*b+"0"*a)
print("1"*b+"0"*a)
else:
print("No")
exit()
if k>a+b-2:
print("No")
exit()
print("Yes")
A = [1]*b+[0]*a
B = [1]*b+[0]*a
K = [0]*(a+b)
cnt = k
i=b-1
last = a+b-1
while(cnt and i):
final = min(i+cnt,last)
B[i]=0
B[final]=1
cnt -= final-i
last=i
i-=1
print(*A,sep="")
print(*B,sep="")
|
1614071100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1 0 1 0 0", "4 3 2 1 0"]
|
5a146d9d360228313006d54cd5ca56ec
|
NoteIn the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
|
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
|
Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
|
The first line contains single integer n (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers written in the vertices. The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 ≤ pi ≤ n, 1 ≤ wi ≤ 109) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1). It is guaranteed that the given graph is a tree.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_016.jsonl
|
c82fabffe6d157144eb9e897b2f1a629
|
256 megabytes
|
["5\n2 5 1 4 6\n1 7\n1 1\n3 5\n3 6", "5\n9 7 8 6 5\n1 1\n2 1\n3 1\n4 1"]
|
PASSED
|
import sys
import threading
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
e = {}
g = [[] for i in range(n)]
d = [0]*(n+5)
ans = [0]*n
p = [0]*(n+5)
for i in range(n-1):
c, w = map(int, input().split())
c-= 1
g[c].append(i+1)
e[i+1] = w
def dfs(i, h):
global ans, a, e, g, d, p
p[h]=0
for j in g[i]:
d[h+1] = d[h]+e[j]
dfs(j, h+1)
x = bisect_left(d, d[h]-a[i], 0, h+1)
#print(x-1, i, h, d[h], d[h], a[i])
if x>=0:
p[x-1]-=1
p[h-1]+=p[h]+1
ans[i]=p[h]
def solve():
global ans
dfs(0, 0)
print(' '.join(map(str, ans)))
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
|
1479918900
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["5.0000000000", "4.7142857143"]
|
620a9baa531f0c614cc103e70cfca6fd
|
NoteIn the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
|
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
|
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
|
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,900 |
train_025.jsonl
|
e7e932d739db0522d3114f2c1d99ae6b
|
256 megabytes
|
["5 10 1 2 5", "3 6 1 2 1"]
|
PASSED
|
#!/usr/bin/python3
import sys
sys.setrecursionlimit(10 ** 9)
def bscheck(n, l, v1, v2, k, t):
while True:
if k > n:
k = n
if n == 0:
return True
if l / v2 > t:
return False
# v2 * tx + v1 * (t - tx) = l
# (v2 - v1) * tx = l - v1 * t
tx = (l - v1 * t) / (v2 - v1)
ty = (tx * v2 - tx * v1) / (v1 + v2)
_n = n - k
_l = l - tx * v1 - ty * v1
_t = t - tx - ty
n = _n
l = _l
t = _t
n, l, v1, v2, k = map(int, input().split())
lt, rt = 0, 1791791791
for i in range(100):
mid = (lt + rt) / 2
if bscheck(n, l, v1, v2, k, mid):
rt = mid
else:
lt = mid
print(rt)
|
1469205300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["16", "24"]
|
6992db71923a01211b5073ee0f8a193a
|
NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24.
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist.
|
On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator.
|
The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,900 |
train_028.jsonl
|
244ee45df1ec1d287197caab255065a1
|
256 megabytes
|
["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"]
|
PASSED
|
from sys import stdin, stdout
import re
from random import randrange
from pprint import PrettyPrinter
pprint = PrettyPrinter(width=55).pprint
def is_lucky(num):
return re.fullmatch("[47]+", num) is not None
gr = None
def topo_order(u):
res = [(u, None, None)]
i = 0
while i < len(res):
u, p, _ = res[i]
i += 1
for v, c in gr[u]:
if v != p:
res.append((v, u, c))
return reversed(res)
def main():
global gr
n = int(stdin.readline())
# n = 4000
gr = [[] for i in range(n)]
for _ in range(n - 1):
s = stdin.readline().split()
u, v = int(s[0]) - 1, int(s[1]) - 1
c = is_lucky(s[-1])
# u, v = randrange(n), randrange(n)
# c = randrange(2) == 1
gr[u].append((v, c))
gr[v].append((u, c))
topo = list(topo_order(0))
tree_size = [1 for i in range(n)]
for u, p, _ in topo:
if p is not None:
tree_size[p] += tree_size[u]
dp_up, dp_down = [0 for i in range(n)], [0 for i in range(n)]
for u, p, cost in topo:
if p is not None:
dp_up[p] += tree_size[u] if cost else dp_up[u]
for u, p, cost in reversed(topo):
if p is not None:
dp_down[u] += tree_size[0] - tree_size[u] if cost else dp_down[p] + dp_up[p] - dp_up[u]
ans = sum(((u + v) * (u + v - 1) for u, v in zip(dp_up, dp_down)))
print(ans)
if __name__ == "__main__":
main()
|
1314633600
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["-1\n-4\n3\n12"]
|
3a45b6acdcf3800d1cb4ef8ac96ed4cf
|
NoteLet $$$f(i, j) = i \cdot j - k \cdot (a_i | a_j)$$$.In the first test case, $$$f(1, 2) = 1 \cdot 2 - k \cdot (a_1 | a_2) = 2 - 3 \cdot (1 | 1) = -1$$$. $$$f(1, 3) = 1 \cdot 3 - k \cdot (a_1 | a_3) = 3 - 3 \cdot (1 | 3) = -6$$$. $$$f(2, 3) = 2 \cdot 3 - k \cdot (a_2 | a_3) = 6 - 3 \cdot (1 | 3) = -3$$$. So the maximum is $$$f(1, 2) = -1$$$.In the fourth test case, the maximum is $$$f(3, 4) = 12$$$.
|
You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ and an integer $$$k$$$. Find the maximum value of $$$i \cdot j - k \cdot (a_i | a_j)$$$ over all pairs $$$(i, j)$$$ of integers with $$$1 \le i < j \le n$$$. Here, $$$|$$$ is the bitwise OR operator.
|
For each test case, print a single integer — the maximum possible value of $$$i \cdot j - k \cdot (a_i | a_j)$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ ($$$2 \le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le \min(n, 100)$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,700 |
train_087.jsonl
|
94e29cff4e92f511067e34ac4ff4ad6e
|
256 megabytes
|
["4\n3 3\n1 1 3\n2 2\n1 2\n4 3\n0 1 2 3\n6 6\n3 2 0 0 5 6"]
|
PASSED
|
import sys
from collections import deque
input = lambda: sys.stdin.readline().rstrip()
write = lambda: sys.stdout.write()
def driver():
T = int(input())
for _ in range(T):
x, y = deque([int(g) for g in input().split()])
maxi = -1000000000
item = deque([int(h) for h in input().split()])
for i in range(max(0, x - 150), x):
for j in range(i + 1, x):
ans = ((i + 1) * (j + 1)) - y * (item[i] | item[j])
maxi = max(maxi, ans)
sys.stdout.write(str(maxi)+"\n")
if __name__ == '__main__':
driver()
|
1627569300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2 7 1 3 6 5 4\n7 1 5 4 6 2 3", "-1"]
|
6b398790adbd26dd9af64e9086e38f7f
|
NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
|
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally: There is no road between a and b. There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
|
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d. Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
|
The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively. The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,600 |
train_029.jsonl
|
c8510bfa3202763e2eb9e78d27022af9
|
256 megabytes
|
["7 11\n2 4 7 3", "1000 999\n10 20 30 40"]
|
PASSED
|
n, k = input().split(' ')
n = int(n)
k = int(k)
a,b,c,d = input().split(' ')
a,b,c,d = int(a),int(b),int(c),int(d)
if k <= n:
print(-1)
exit()
if n == 4:
print(-1)
exit()
city = list(range(1,n+1))
road = [a,c]
for i in range(len(city)):
if city[i] not in (a,b,c,d): road.append(city[i])
road += [d,b]
t = ''
print(' '.join("{0}".format(t) for t in road))
road = [c,a] + road[2:n-2] + [b,d]
print(' '.join("{0}".format(t) for t in road))
|
1462633500
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
10 seconds
|
["BC23\nR23C55"]
|
910c0e650d48af22fa51ab05e8123709
| null |
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
|
Write n lines, each line should contain a cell coordinates in the other numeration system.
|
The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_001.jsonl
|
9bd7e1fbe00260b45a7638c7cd3bc5e2
|
64 megabytes
|
["2\nR23C55\nBC23"]
|
PASSED
|
m = {}
for k in range(26):
m[chr(65+k)] = 1+k
for abcdd in range(int(raw_input())):
a = raw_input()
for k in range(len(a)):
if a[k].isdigit():
a, b = a[:k], a[k:]
break
if b.isdigit():
n = 0
for k in a:
n = n * 26 + m[k]
print 'R' + b + 'C' + str(n)
else:
c, b = b.split('C')
a = ''
b = int(b)
while b:
a = chr(65+(b-1)%26) + a
b = int((b-1) / 26)
print a + c
|
1266580800
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
5 seconds
|
["162", "102"]
|
ee32db0f67954ed0eccae1429819f4d7
| null |
You are given $$$n$$$ segments on the coordinate axis. The $$$i$$$-th segment is $$$[l_i, r_i]$$$. Let's denote the set of all integer points belonging to the $$$i$$$-th segment as $$$S_i$$$.Let $$$A \cup B$$$ be the union of two sets $$$A$$$ and $$$B$$$, $$$A \cap B$$$ be the intersection of two sets $$$A$$$ and $$$B$$$, and $$$A \oplus B$$$ be the symmetric difference of $$$A$$$ and $$$B$$$ (a set which contains all elements of $$$A$$$ and all elements of $$$B$$$, except for the ones that belong to both sets).Let $$$[\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]$$$ be an array where each element is either $$$\cup$$$, $$$\oplus$$$, or $$$\cap$$$. Over all $$$3^{n-1}$$$ ways to choose this array, calculate the sum of the following values:$$$$$$|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|$$$$$$In this expression, $$$|S|$$$ denotes the size of the set $$$S$$$.
|
Print one integer — the sum of $$$|(((S_1\ \mathbin{op}_1\ S_2)\ \mathbin{op}_2\ S_3)\ \mathbin{op}_3\ S_4)\ \dots\ \mathbin{op}_{n-1}\ S_n|$$$ over all possible ways to choose $$$[\mathbin{op}_1, \mathbin{op}_2, \dots, \mathbin{op}_{n-1}]$$$. Since the answer can be huge, print it modulo $$$998244353$$$.
|
The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$). Then, $$$n$$$ lines follow. The $$$i$$$-th of them contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 3 \cdot 10^5$$$).
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,300 |
train_089.jsonl
|
3b8e9b7f182f5f2df6f60cabd91f646e
|
512 megabytes
|
["4\n3 5\n4 8\n2 2\n1 9", "4\n1 9\n3 5\n4 8\n2 2"]
|
PASSED
|
import cProfile
import sys
import io
import os
import traceback
from collections import deque
from itertools import accumulate
# region IO
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = io.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(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip('\r\n')
def read_int_list():
return list(map(int, input().split()))
def read_int_tuple():
return tuple(map(int, input().split()))
def read_int():
return int(input())
# endregion
# region local test
if 'AW' in os.environ.get('COMPUTERNAME', ''):
test_no = 1
# f = open(os.path.dirname(__file__) + f'\\in{test_no}.txt', 'r')
f = open('inputs')
def input():
return f.readline().rstrip("\r\n")
# endregion
class SegmentTree():
__slots__ = ['n', 'oper', 'e', 'log', 'size', 'data']
def __init__(self, n, oper, e):
self.n = n
self.oper = oper
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.data = [list(e) for _ in range(2 * self.size)]
# def _update(self, k):
# self.oper(self.data[k], self.data[2 * k], self.data[2 * k + 1])
def build(self, arr):
# assert len(arr) <= self.n
for i in range(self.n):
t = self.data[self.size + i]
t[0], t[1], t[2], t[3] = arr[i]
for i in range(self.size - 1, 0, -1):
# self._update(i)
self.oper(self.data[i], self.data[2 * i], self.data[2 * i + 1])
def set(self, p, x):
# assert 0 <= p < self.n
p += self.size
# self.data[p] = x
t = self.data[p]
t[0], t[1], t[2], t[3] = x
for i in range(self.log):
p >>= 1
# self._update(p)
self.oper(self.data[p], self.data[2 * p], self.data[2 * p + 1])
MOD = 998244353 # 1000000007
N = 300000 + 32
pos = [[] for _ in range(N)]
ZERO = (3, 0, 1, 2) # [3, 0], [1, 2]
ONE = (1, 2, 1, 2) # [1, 2], [1, 2]
E = (1, 0, 0, 1) # [1, 0], [0, 1]
def OPER(tn, fn, gn):
tn[0] = (fn[0] * gn[0] % MOD + fn[1] * gn[2] % MOD) % MOD
tn[1] = (fn[0] * gn[1] % MOD + fn[1] * gn[3] % MOD) % MOD
tn[2] = (fn[2] * gn[0] % MOD + fn[3] * gn[2] % MOD) % MOD
tn[3] = (fn[2] * gn[1] % MOD + fn[3] * gn[3] % MOD) % MOD
n = read_int()
def main():
st = SegmentTree(n - 1, OPER, E)
st.build([ZERO for _ in range(n)])
book = [[] for _ in range(N)]
m = 0
for i in range(n):
l, r = read_int_tuple()
book[l].append((1, i))
book[r + 1].append((0, i))
if m < r + 1: m = r + 1
cur = res = 0
for i in range(m):
for c, j in book[i]:
if j == 0: cur = c
else: st.set(j - 1, ONE if c else ZERO)
res += st.data[1][cur * 2 + 1]
res %= MOD
print(res)
main()
# cProfile.run("main()")
# n = read_int()
#
# def main():
# def matmul(k, i, j):
# u1, u2, u3, u4 = tree1[i], tree2[i], tree3[i], tree4[i]
# v1, v2, v3, v4 = tree1[j], tree2[j], tree3[j], tree4[j]
# tree1[k] = (u1 * v1 % mod + u2 * v3 % mod) % mod
# tree2[k] = (u1 * v2 % mod + u2 * v4 % mod) % mod
# tree3[k] = (u3 * v1 % mod + u4 * v3 % mod) % mod
# tree4[k] = (u3 * v2 % mod + u4 * v4 % mod) % mod
# return
#
# def update(i, x):
# i += l1
# if x:
# tree1[i], tree2[i] = 2, 2
# tree3[i], tree4[i] = 1, 1
# else:
# tree1[i], tree2[i] = 2, 0
# tree3[i], tree4[i] = 1, 3
# i //= 2
# while i:
# matmul(i, 2 * i, 2 * i + 1)
# i //= 2
# return
#
# mod = 998244353
# m = 3 * pow(10, 5) + 5
# l1 = pow(2, n.bit_length())
# l2 = 2 * l1
# tree1, tree2 = [1] * l2, [0] * l2
# tree3, tree4 = [0] * l2, [1] * l2
# for i in range(l1, l1 + n - 1):
# tree1[i], tree2[i] = 2, 0
# tree3[i], tree4[i] = 1, 3
# for i in range(l1 - 1, 0, -1):
# matmul(i, 2 * i, 2 * i + 1)
# x = [[] for _ in range(m + 1)]
# for i in range(n):
# l, r = read_int_tuple()
# x[l].append(n - i - 1)
# x[r + 1].append(n - i - 1)
# now = [0] * n
# ans = 0
# for i in range(m + 1):
# for j in x[i]:
# now[j] ^= 1
# if j < n - 1:
# update(j, now[j])
# u1, u2 = tree1[1], tree2[1]
# if now[-1]:
# v1, v2 = 1, 0
# else:
# v1, v2 = 0, 1
# ans += u1 * v1 % mod + u2 * v2 % mod
# ans %= mod
# ans %= mod
# print(ans)
#
# cProfile.run("main()")
|
1666017300
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
|
2 seconds
|
["Yes\n3 3 2 1 0", "No", "Yes\n-1 -1"]
|
39e4bae5abbc0efac5316bec0d540665
|
NoteSample 1:23 + 23 + 22 + 21 + 20 = 8 + 8 + 4 + 2 + 1 = 23Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.Answers like (4, 1, 1, 1, 0) do not have the minimum y value.Sample 2:It can be shown there does not exist a sequence with length 2.Sample 3:Powers of 2:If x > 0, then 2x = 2·2·2·...·2 (x times).If x = 0, then 2x = 1.If x < 0, then .Lexicographical order:Given two different sequences of the same length, (a1, a2, ... , ak) and (b1, b2, ... , bk), the first one is smaller than the second one for the lexicographical order, if and only if ai < bi, for the first i where ai and bi differ.
|
Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one. To be more clear, consider all integer sequence with length k (a1, a2, ..., ak) with . Give a value to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.For definitions of powers and lexicographical order see notes.
|
Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence. It is guaranteed that the integers in the answer sequence fit the range [ - 1018, 1018].
|
The first line consists of two integers n and k (1 ≤ n ≤ 1018, 1 ≤ k ≤ 105) — the required sum and the length of the sequence.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_008.jsonl
|
c7ec006127bc6f8e5c08be3eb9f0beae
|
256 megabytes
|
["23 5", "13 2", "1 2"]
|
PASSED
|
import math
x, k = map(int, input().split())
kori = k
a = bin(x)
# s = a[2:len(a)]
qtz = 0;
s = []
for i in range(2, len(a)):
if a[i] == "1":
k-=1
s.append(1)
else:
qtz+=1
s.append(0)
v = []
for i in range(len(s)):
if s[i] != 0:
v.append((len(s)-1)-i)
# else:
# v.append("x")
# print(qtz, k)
if k < 0:
print("No")
exit()
else:
tam = len(s)
# print(tam)
print("Yes")
# print(k, s)
if k > 0:
p = 0
#diminui o y máximo
while(1):
# print(p, s[p], len(s))
if tam - 1 <= p:
s.append(0)
if s[p] > k:
break
else:
k-= s[p]
s[p+1] += s[p]*2
s[p] = 0
p+=1
#se k ainda for maior que zero
if k > 0:
j = len(s)-1
while k > 0:
while s[j] == 0:
j-=1
s[j] -= 1
if j == len(s)-1:
s.append(2)
j+=1
else:
s[j+1] += 2
j+=1
k-=1
# print(s)
v = []
for i in range(len(s)):
for j in range(s[i]):
v.append((tam-1) -i)
print(*v)
else:
v = []
for i in range(len(s)):
for j in range(s[i]):
v.append(len(s)-1 -i)
print(*v)
|
1516372500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["5\n1 8 6"]
|
1e0148d417f80b995cac18c2f4cea32e
|
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices $$$1, 5, 6$$$ then the path between $$$1$$$ and $$$5$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 5)$$$, the path between $$$1$$$ and $$$6$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 6)$$$ and the path between $$$5$$$ and $$$6$$$ consists of edges $$$(4, 5), (4, 6)$$$. The union of these paths is $$$(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$$$ so the answer is $$$5$$$. It can be shown that there is no better answer.
|
You are given an unweighted tree with $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices $$$a, b, c$$$ on this tree such that the number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$ is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.
|
In the first line print one integer $$$res$$$ — the maximum number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$. In the second line print three integers $$$a, b, c$$$ such that $$$1 \le a, b, c \le n$$$ and $$$a \ne, b \ne c, a \ne c$$$. If there are several answers, you can print any.
|
The first line contains one integer number $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. Next $$$n - 1$$$ lines describe the edges of the tree in form $$$a_i, b_i$$$ ($$$1 \le a_i$$$, $$$b_i \le n$$$, $$$a_i \ne b_i$$$). It is guaranteed that given graph is a tree.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,000 |
train_022.jsonl
|
7fe5ed1ab433407e763996b788053068
|
256 megabytes
|
["8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8"]
|
PASSED
|
import sys
input = sys.stdin.readline
from collections import *
def bfs(sta):
dist = [-1]*n
dist[sta] = 0
par = [-1]*n
q = deque([sta])
while q:
v = q.popleft()
for nv in G[v]:
if dist[nv]==-1:
dist[nv] = dist[v]+1
par[nv] = v
q.append(nv)
return dist, par
def mbfs():
dist = [-1]*n
l = [b]
while par[l[-1]]!=-1:
l.append(par[l[-1]])
q = deque([])
for li in l:
dist[li] = 0
q.append(li)
while q:
v = q.popleft()
for nv in G[v]:
if dist[nv]==-1:
dist[nv] = dist[v]+1
q.append(nv)
return dist
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n-1):
u, v = map(int, input().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
d1, _ = bfs(0)
M = 0
for i in range(n):
if d1[i]>M:
M = d1[i]
a = i
d2, par = bfs(a)
M1 = 0
for i in range(n):
if d2[i]>M1:
M1 = d2[i]
b = i
d3 = mbfs()
if d3==[0]*n:
for i in range(n):
if i!=a and i!=b:
print(M1)
print(a+1, b+1, i+1)
exit()
M2 = 0
for i in range(n):
if d3[i]>M2:
M2 = d3[i]
c = i
print(M1+M2)
print(a+1, b+1, c+1)
|
1579703700
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
3 seconds
|
["2\n-\n2\n+", "6\n++-\n2\n+-+"]
|
d39359344dc38b3c94c6d304880804b4
| null |
Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans.Help Vasya find the plans.
|
The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them.
|
The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,900 |
train_039.jsonl
|
e6d0b4aa4d1e9bbaddb958342e70f834
|
256 megabytes
|
["2 2 1\n1 1 2\n2 2 1", "6 6 3\n2 2 6\n1 4 5\n2 3 4\n1 4 1\n1 3 1\n2 2 3"]
|
PASSED
|
I = lambda:map(int, raw_input().split())
n, m, s = I()
E = [I() for i in range(m)]
w = ['+'] * sum(a[0] == 2 for a in E)
e = [[] for i in range(n)]
v, s, p = [0] * n, s - 1, 0
for i in range(m):
E[i][1] -= 1
E[i][2] -= 1
if E[i][0] == 2:
e[E[i][1]].append([E[i][2], p * 2 + 1])
e[E[i][2]].append([E[i][1], p * 2])
p += 1
else:
e[E[i][1]].append([E[i][2], -1])
q, v[s] = [s], 1
while q:
x = q.pop()
for y in e[x]:
if not v[y[0]]:
v[y[0]] = 1
q.append(y[0])
if y[1] != -1:
w[y[1] / 2] = ['-', '+'][y[1] % 2]
print sum(v)
print ''.join(w)
v = [0] * n
q, v[s] = [s], 1
while q:
x = q.pop()
for y in e[x]:
if y[1] != -1:
w[y[1] / 2] = ['+', '-'][y[1] % 2]
elif not v[y[0]]:
v[y[0]] = 1
q.append(y[0])
print sum(v)
print ''.join(w)
|
1508573100
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["2\n4\n2\n7\n4"]
|
19a3247ef9d10563db821ca19b0f9004
|
NoteThe following are the promising substrings for the first three test cases in the example: $$$s[1 \dots 2]$$$="+-", $$$s[2 \dots 3]$$$="-+"; $$$s[1 \dots 2]$$$="-+", $$$s[2 \dots 3]$$$="+-", $$$s[1 \dots 5]$$$="-+---", $$$s[3 \dots 5]$$$="---"; $$$s[1 \dots 3]$$$="---", $$$s[2 \dots 4]$$$="---".
|
This is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string $$$s$$$ are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++".
|
For each test case, print a single number: the number of the promising non-empty substrings of string $$$s$$$. Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$.
|
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Then the descriptions of test cases follow. Each test case of input data consists of two lines. The first line consists of the number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$): the length of $$$s$$$. The second line of the test case contains the string $$$s$$$ of length $$$n$$$, consisting only of characters "+" and "-". It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 2,100 |
train_105.jsonl
|
e7954c49622720cbf6a1cfb96c101187
|
256 megabytes
|
["5\n\n3\n\n+-+\n\n5\n\n-+---\n\n4\n\n----\n\n7\n\n--+---+\n\n6\n\n+++---"]
|
PASSED
|
import sys
def Print( m ):
for r in m:
print( r )
print()
def Solve( size, s ):
cntM = 0
delta = [ 0 ]
for idx in range( size ):
c = s[idx]
if c == '+':
cntM -= 1
else :
cntM += 1
delta.append( cntM )
minDelta = min( delta )
maxDelta = max( delta )
sol3 = 0
collecteds = { key : 0 for key in range( minDelta, maxDelta + 1) }
collecteds[0] = 1
sums1 = { key:0 for key in range( minDelta - 3, maxDelta + 1) }
sums1[ 0 ] = 1
for i in range( 1, size + 1 ):
k = delta[i]
#print( '\n'*2, k )
#print( 'col', collecteds )
#print( 'sum ', dict( sorted(sums.items() )) )
#print( 'sum1', dict( sorted(sums1.items())[3:] ) )
#print( 'sum[k] and sum1[k]', k, sums[k], sums1[k] )
sol3 += sums1[ k - 3 ] + collecteds[ k ]
collecteds[ k ] += 1
sums1[ k ] = sums1[ k - 3 ] + collecteds[ k ]
return sol3
def main():
input = sys.stdin
if len( sys.argv ) >= 2:
input = open( sys.argv[1], 'r' )
n = int( input.readline().strip() )
for i in range( n ):
input.readline()
s = input.readline().strip()
print( Solve( len( s ), s ) )
if __name__ == "__main__":
main()
|
1648737300
|
[
"math",
"strings"
] |
[
0,
0,
0,
1,
0,
0,
1,
0
] |
|
2 seconds
|
["4 3 6 2", "42", "1 1"]
|
71dc07f0ea8962f23457af1d6509aeee
| null |
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.
|
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
|
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_033.jsonl
|
e5831c25389a89dbda88183639885ac5
|
256 megabytes
|
["4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2", "1\n42", "2\n1 1 1 1"]
|
PASSED
|
def getDictionary(myList):
myDict = {}
for i in range(0, len(myList)):
if (myList[i] in myDict):
myDict[myList[i]] = myDict[myList[i]] + 1;
else:
myDict[myList[i]] = 1;
return myDict
def counting(sizeOfMother, myDict):
winTable = []
for i in range(0, sizeOfMother):
x = next(iter(myDict.keys()))
# Usun ten element
if (myDict[x] > 1):
myDict[x] = myDict[x] - 1;
else:
del myDict[x]
for j in range(0, len(winTable)):
gcd = searchNWD(x, winTable[j])
# Usun ten element
if (myDict[gcd] <= 2):
del myDict[gcd]
else:
myDict[gcd] = myDict[gcd] - 2;
winTable.append(x)
return winTable
def searchNWD(a, b):
temporary = 0
while(a != 0) and (b != 0):
if(a > b):
a = a % b
else:
b = b % a
if(a > 0):
return a
else:
return b
######################
sizeOfMotherG = int(input())
numberInMotherG = list(map(int, input().split()))
numberInMotherG.sort(reverse=True)
myDictG = getDictionary(numberInMotherG)
w = counting(sizeOfMotherG, myDictG)
for i in range(0, sizeOfMotherG):
print(w[i], end=" ")
|
1443890700
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["2\n0\n100\n0\n3"]
|
e6c91f6872c4dd845cb7a156aacab7c7
| null |
You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You have to choose a positive integer $$$d$$$ and paint all elements into two colors. All elements which are divisible by $$$d$$$ will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $$$d$$$ which yields a beautiful coloring, or report that it is impossible.
|
For each testcase print a single integer. If there is no such value of $$$d$$$ that yields a beautiful coloring, print $$$0$$$. Otherwise, print any suitable value of $$$d$$$ ($$$1 \le d \le 10^{18}$$$).
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements of the array. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_087.jsonl
|
63640673ff7c24fa3e4638234cddd0c7
|
256 megabytes
|
["5\n5\n1 2 3 4 5\n3\n10 5 15\n3\n100 10 200\n10\n9 8 2 6 6 2 8 6 5 4\n2\n1 3"]
|
PASSED
|
def GCD(divisor,num):
if num == 0:
return divisor
else:
return GCD(num , divisor % num)
def solve(array):
even_divisor = 0
odd_divisor = 0
for index in range (0 , len(array)):
if index % 2 == 0 :
even_divisor = GCD(even_divisor , array[index])
else :
odd_divisor = GCD(odd_divisor , array[index])
ok = True
index = 0
while index < len(array) :
if array [index] % odd_divisor == 0 :
ok = False
break;
index += 2
if ok :
return odd_divisor
ok = True
index = 1
while index < len(array):
if array[index] % even_divisor == 0:
ok = False
break;
index += 2
if ok:
return even_divisor
return 0
n=int(input())
array=[]
for i in range(n) :
s = int(input())
x = list(map(int, input().split()))
array.append(x)
for i in array:
print(solve(i))
|
1639492500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["3", "3"]
|
c35102fa418cbfdcb150b52d216040d9
|
NoteHere are the heights of some valid castles: n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...] n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots occupied) The first list for both cases is the optimal answer, 3 spots are occupied in them.And here are some invalid ones: n = 5, H = 2, [3, 2, 0, ...], [2, 3, 0, ...], [1, 0, 2, 2, ...] n = 6, H = 8, [2, 2, 2, 0, ...], [6, 0, ...], [1, 4, 1, 0...], [2, 2, 1, 0, ...]
|
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: h1 ≤ H: no sand from the leftmost spot should go over the fence; For any |hi - hi + 1| ≤ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; : you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.
|
Print the minimum number of spots you can occupy so the all the castle building conditions hold.
|
The only line contains two integer numbers n and H (1 ≤ n, H ≤ 1018) — the number of sand packs you have and the height of the fence, respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_007.jsonl
|
9030d418648a4c6a426f8fc18204cacc
|
256 megabytes
|
["5 2", "6 8"]
|
PASSED
|
n, H = map(int, input().split())
l = 1
r = n
while l < r:
mid = int((l + r) / 2)
ans = 0
if mid <= H:
ans = int(mid * (mid + 1) // 2)
pass
else :
R = int(mid - (H - 1))
Len = int(R - 2)
ans = ans + int(H * (H - 1) // 2)
tmp = int(R / 2)
#print("%d %d %d" % (R, Len, tmp))
ans = ans + (H + H + tmp - 1) * tmp + (R - tmp * 2) * (H + tmp)
pass
#print((l, r, mid, int(mid * (mid + 1) // 2)))
if ans >= n:
r = mid
else : l = mid + 1
pass
print("%d" % l)
|
1526913900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["1", "-1", "2"]
|
51ad613842de8eff6226c97812118b61
|
NoteIn the first example you can select $$$2$$$ and $$$5$$$ and the array becomes $$$[7, 6, 8]$$$.In the second example you can only obtain arrays $$$[1, 1]$$$, $$$[3, 3]$$$ and $$$[0]$$$ which are all non-decreasing.In the third example you can select $$$1$$$ and $$$2$$$ and the array becomes $$$[3, 4, 6, 20]$$$. Then you can, for example, select $$$3$$$ and $$$4$$$ and the array becomes $$$[7, 6, 20]$$$, which is no longer non-decreasing.
|
Arkady owns a non-decreasing array $$$a_1, a_2, \ldots, a_n$$$. You are jealous of its beauty and want to destroy this property. You have a so-called XOR-gun that you can use one or more times.In one step you can select two consecutive elements of the array, let's say $$$x$$$ and $$$y$$$, remove them from the array and insert the integer $$$x \oplus y$$$ on their place, where $$$\oplus$$$ denotes the bitwise XOR operation. Note that the length of the array decreases by one after the operation. You can't perform this operation when the length of the array reaches one.For example, if the array is $$$[2, 5, 6, 8]$$$, you can select $$$5$$$ and $$$6$$$ and replace them with $$$5 \oplus 6 = 3$$$. The array becomes $$$[2, 3, 8]$$$.You want the array no longer be non-decreasing. What is the minimum number of steps needed? If the array stays non-decreasing no matter what you do, print $$$-1$$$.
|
Print a single integer — the minimum number of steps needed. If there is no solution, print $$$-1$$$.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the initial length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that $$$a_i \le a_{i + 1}$$$ for all $$$1 \le i < n$$$.
|
standard output
|
standard input
|
Python 2
|
Python
| null |
train_003.jsonl
|
d87b1149bf8218f23d77e1a905b1311c
|
256 megabytes
|
["4\n2 5 6 8", "3\n1 2 3", "5\n1 2 4 6 20"]
|
PASSED
|
from sys import stdin
def main():
n = int(stdin.readline())
a = map(int, stdin.readline().split())
for i in xrange(n - 1):
x = a[i] ^ a[i+1]
if (i and x < a[i-1]) or (i + 2 < n and x > a[i+2]):
print 1
return
d = [[0] * n for i in xrange(n)]
for i in xrange(n):
d[i][i] = a[i]
for j in xrange(i + 1, n):
d[i][j] = d[i][j-1] ^ a[j]
ans = n
for i in xrange(n):
for j in xrange(i):
for k in xrange(i, n):
if d[j][i-1] > d[i][k]:
t = i - j - 1 + k - i
if ans > t:
ans = t
if ans >= n:
ans = -1
print ans
main()
|
1606633500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1.5 seconds
|
["5", "60"]
|
d38c18b0b6716cccbe11eab7b4df8c3a
| null |
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is $$$n$$$ km. Let's say that Moscow is situated at the point with coordinate $$$0$$$ km, and Saratov — at coordinate $$$n$$$ km.Driving for a long time may be really difficult. Formally, if Leha has already covered $$$i$$$ kilometers since he stopped to have a rest, he considers the difficulty of covering $$$(i + 1)$$$-th kilometer as $$$a_{i + 1}$$$. It is guaranteed that for every $$$i \in [1, n - 1]$$$ $$$a_i \le a_{i + 1}$$$. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from $$$1$$$ to $$$n - 1$$$ may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty $$$a_1$$$, the kilometer after it — difficulty $$$a_2$$$, and so on.For example, if $$$n = 5$$$ and there is a rest site in coordinate $$$2$$$, the difficulty of journey will be $$$2a_1 + 2a_2 + a_3$$$: the first kilometer will have difficulty $$$a_1$$$, the second one — $$$a_2$$$, then Leha will have a rest, and the third kilometer will have difficulty $$$a_1$$$, the fourth — $$$a_2$$$, and the last one — $$$a_3$$$. Another example: if $$$n = 7$$$ and there are rest sites in coordinates $$$1$$$ and $$$5$$$, the difficulty of Leha's journey is $$$3a_1 + 2a_2 + a_3 + a_4$$$.Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are $$$2^{n - 1}$$$ different distributions of rest sites (two distributions are different if there exists some point $$$x$$$ such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate $$$p$$$ — the expected value of difficulty of his journey.Obviously, $$$p \cdot 2^{n - 1}$$$ is an integer number. You have to calculate it modulo $$$998244353$$$.
|
Print one number — $$$p \cdot 2^{n - 1}$$$, taken modulo $$$998244353$$$.
|
The first line contains one number $$$n$$$ ($$$1 \le n \le 10^6$$$) — the distance from Moscow to Saratov. The second line contains $$$n$$$ integer numbers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6$$$), where $$$a_i$$$ is the difficulty of $$$i$$$-th kilometer after Leha has rested.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,000 |
train_006.jsonl
|
ad03c90f3bc92096a151071fb4a1de1d
|
256 megabytes
|
["2\n1 2", "4\n1 3 3 7"]
|
PASSED
|
a = int(input())
b = list(map(int,input().split()))
c = b[0]%998244353
d = b[0]%998244353
for i in range(1,a):
c = (2*c + d + b[i])%998244353
d = (2*d + b[i])%998244353
print(c)
|
1531578900
|
[
"probabilities",
"math"
] |
[
0,
0,
0,
1,
0,
1,
0,
0
] |
|
2 seconds
|
["YES\nNO\nYES\nNO"]
|
bf89bc12320f635cc121eba99c542444
|
NoteIn the first test case, regardless of the strategy of his friends, Vlad can win by going to room $$$4$$$. The game may look like this: The original locations of Vlad and friends. Vlad is marked in green, friends — in red. Locations after one unit of time. End of the game. Note that if Vlad tries to reach the exit at the room $$$8$$$, then a friend from the $$$3$$$ room will be able to catch him.
|
The only difference with E2 is the question of the problem..Vlad built a maze out of $$$n$$$ rooms and $$$n-1$$$ bidirectional corridors. From any room $$$u$$$ any other room $$$v$$$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited $$$k$$$ friends to play a game with them.Vlad starts the game in the room $$$1$$$ and wins if he reaches a room other than $$$1$$$, into which exactly one corridor leads.Friends are placed in the maze: the friend with number $$$i$$$ is in the room $$$x_i$$$, and no two friends are in the same room (that is, $$$x_i \neq x_j$$$ for all $$$i \neq j$$$). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play).In other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play.
|
Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be "YES" if Vlad can guarantee himself a victory and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" will all be recognized as positive answers).
|
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The input contains an empty string before each test case. The first line of the test case contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2\cdot 10^5$$$) — the number of rooms and friends, respectively. The next line of the test case contains $$$k$$$ integers $$$x_1, x_2, \dots, x_k$$$ ($$$2 \le x_i \le n$$$) — numbers of rooms with friends. All $$$x_i$$$ are different. The next $$$n-1$$$ lines contain descriptions of the corridors, two numbers per line $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — numbers of rooms that connect the $$$j$$$ corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test is not greater than $$$2\cdot10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,700 |
train_093.jsonl
|
14aba60c00471c41a7eab00823af4f35
|
256 megabytes
|
["4\n\n8 2\n5 3\n4 7\n2 5\n1 6\n3 6\n7 2\n1 7\n6 8\n\n3 1\n2\n1 2\n2 3\n\n3 1\n2\n1 2\n1 3\n\n3 2\n2 3\n3 1\n1 2"]
|
PASSED
|
# RANK1ZEN; 3966 PEAK NA FLEX SUPPORT; Battlenet ID: Knuckles#11791
# region -----------------------------------------------------------------------------------------|
# oooo+oshdy+/smooyNMNNMMMmo/::----/dNsomMMMNNMy/::--::/mNoodNdmdo/:-://////::::::::.
# ooooyNMMMyssNyosmMMMMMMNs+::----::++//+oooooo/::----:/ys+oNNdMMo/:-/+mmdy+///::::::.
# ooooNMMMdyoNdoosNmmdyhyo/::------:::::::::::::-------::::/+++so/:::/+dMMNhydosso+///.``````
# oo/yNmMms+oyo///++///:::::-.------------------------------::::::::-:/odmNhyNsdMNmmy+/......
# o//oooo+/-:::::::::::::::---------------------.---------------:::-.::://+++yohMMMMNs+-.....
# +:::::::--::::::::::--::-.-::::::::----------.-:----:-----------:---:-::::::/ohhNMNo+-.....
# ::::::::.-:::::::::-:::-`.:::::::::-:::::::----::::::--::::::-::::d:---::::::://+os//-`.`..
# --------.:::::::--:::::. -::::::::--::::::--o/:::::::-::::::::::-yNs-:.::::::::::::::-..`..
# --------.:-::::-::::::- `::::::::-:::::::-:ym:::::::-:::::::::::+NMN+---:::::::::::::-.....
# --------.-----::::::::. .:://///::////:::+dMy//////:////////:::/mMMMm/:-:::::::::::::--....
# --------.----:::::::::``://////:///////+yNMM+++++//++++/////://hmmNNNd::-::::::::::::--....
# --------.----::::::::-``://++//+++++++ymmNMd+oo+++ooo++++++/++dNmdhhhys:-::::::::::::-:`...
# --------.----::::::::-``//++//++++++hNMMMMMoso++ooooooooo++o+dmNNNMMMMMm+://:::::://::/....
# --------:----::::::::-``////++++++/--+smNNhsooosssssoooo+oosmNMMMMMMMMMMN///////////-:/....
# -------/o-----:::::::-``://+++:. :NMydhohhooosssssssso+osodMNMNhyssyyhdmMo++++++++++./+....
# -------sd-----:::::::-`.:/oo/.://.-hddMMh+ossssssssss+soyNms/.` `:- ` `:++++/++++/ /+-.-.
# -------ym/-----:::::::/shhyh:/ymddo./mdysssssssssoyyossmMMh- .mMhdNds:ooo/ooooo- ++---.
# -------hhy----------:-sNNNNmhysyssoyysssoossssoshmyosdMMMMs ..///`-hysMMh/oo/ooooo/ `oo----
# ----`-..od/---::::::::oNNNNNNNNmdysoooooooooyhmNdsymMMMMMMm:/oydds+:ymmMhoo+oooooo` `oo----
# ----``- `-.---:::::::+dddddhyo++++oooosyhmNMNhshNMMMMMMMMMNmmhhyo+sydNmoo++ooooo. -oo----
# ----- `` ----:::::::ooooooosssyhhdNNNMMNdyydNMMmMMMMMMMMNNNNmNmmmNmmoohsoooo+. :++.---
# -----. `----:::::-mNNNNmNNMMMMMMMNmdhhdNMMMMMMMMMMMMMMNMNNmNmmmmmhshs:ooo/` `/+:----
# ------` .::::::::-yMMMMNNNNmmddhyhdNNMMMMMMMMMMMMMMMMMMMMNNNNNmmNh+-`/o+- .//--::-
# .------` -::-::::::osssssyhhdmNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMh` -/-` ://--::-
# `.-----` ---------yNNNMMMMMMMMNNmmmmmmNNNMMMMMMMMMMMMMMMMMMMMMh. `. . `:::--::-
# /` `-----` `--:-----+MMMMMMMMMMMh++++++++ooosyhNMMMMMMMMMMMMMMMy` `- -::--::::
# o+. `.---` `-::-----mMMMMMMMMMMNy+ssyyyyso++/+dMMMMMMMMMMMMMN+` -. .:::-:::::
# -//-` `.--.` `-------oMMMMMMMMMMMMNmdddmmmmmhdNMMMMMMMMMMMMmo. `:. `:::-::::::
# :-``` `..` .------ymNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNmy/` -:. -:::-::::::
# ooo+//:-.` ` .-----:ddddmNMMMMMMMMMMMMMMMMMMMMMMMNho:` -::` .///-:::::::
# oooooo+++- `-:::-+ddddhddmNMMMMMMMMMMMMMMNdy+-` `-:::` `////-:::::::
# oooooo++: .::::.+dddddddhddmmMMMMNds+-` `.-:::::` `/+++-::::::::
# oooooo+: `:/// `sdmddddddddhdy-` .-::::::::: /ooo/-::::::/:
# ----..../hNMMMMNNNmyyhdddyhmmmmdddmmmmmmmNmy- `.-+hmdsmmNmmmmhydmmmhs/.+NNNMh-...------:/+y
# --....+mMMMMMNNNmyydmmhosddmmdoyhymmmmmmmm+``-/shmmhsddmmmmmmmdsydmmmmmyodNNMNy.`...----:+s
# -...omMMNNNNNNNyydmhyosdmmmmyohs/hmmmmmmm/-:ohmmNmhymhsdmmmsddmdhsddmmdhhdNNMMMNs-`....-:+o
# ..+dMNNNmdmmmhshhyys:hdmmmdohdyymNNmmmmmmdddmmmhsdommmohdmmdohddddshdmmmmdhmMMMMMNh/....:/o
# :dNdNNNmmdydsyysyy+sdysdmssddsdNNNmmmmdmmmdmmm:.-hdmddhoddddd+hddddsyddmmmmhhdNMMMMMd+.`-/o
# NNy+Nmmmmmdoyyhy/+hdmddh+shdsdNNmmmmhydds:hmm:``.ydmmddyoddddh+ysdddyyddddmdddyhdmNMMMNy//o
# +.`ommmmmh+yhhs+ydddddh-+ydohmNNmmmyyhs-`-mmo``..ymmmmmdssdddm+yysdddsshddddddddhyydNMMMMNd
# ``-mmmmmy/ydyoyddmdddy.-yhoydhmmmmohs-```+Nd.....smNmmdddosdddh:h+yddhssdddddddddmdhydmNMMM
# `.dNmmmoshysydmdddddy.`+dysdhsNNd/+-..```hNs.....+mmmmyhdd+sddm/hohshhhoydddhddddmmmmdyhNMM
# `yNmmmsysoyddmmdddmd.`.hdomhsmNd-``.``.:-mN:``..`.mmmmmddddoodm+hoddsyhdohddsoydmmmmmmmhhMM
# +NNNmsooysosddmddddo``:mohNodNm-````.-+o:Nm. -`.``smmmmmmmmmo:s/oodmdsydd/ohdh+/shmmmmmmdNM
# NNmhyosoy+hdddddddd...oh/Nh+Nm:````-+oso:md`-o/```-mmmmmmmmmmh:`-/ddhdyymy.-odmy/:odmddmNNM
# yoo+yhdmhydmdddmddy`::hosNohNs```./oymNd:mh`shs/. `smmdsmmmmmNm/-`+s+/syymo`.:ymNs-/yy+dNMM
# y/ooNNNm+/ydddmmmdh-/sd/dN+dN-`./ohmMMMN/my:NMMmy:`.hds+:odNNNNy`/-.-.-/++m/`.-/dNh--+//mMM
# :`:/so+:.:dmmmmmmmdo:hy+NN/mh.-+ohmmmddd:y+oNMMMMmy/:hs/+.-+hNN/-Nmy:...../d-``-:smh....oMM
# ` ---..``-mmmmmmmdyy.y+yNN.d/ohmNNNNmmdd+o-:oodMMMMNy/y::+.`.:o`yMMMmh+:...:/```--+dy..-/mM
# - ---.-h+.dmmmmmdmho++/dMm -`:/:://ososy+/:oNNNMMMMMMmos-:/-. `+ymNNmdhy+:-` ..`-:/ho.-+hM
# -`---:mMd-dmmmmmdmmms/`++- ./-++hmMMMMMMMMNs+.s+-` ``.-/syhhso+:.````::/o.-+yN
# -`-:-:NMMssmmmmmmdmmNh+./-.-`. `` /-..:-sMMMMMMMMMMMMd:ohyo:.`-//:--:+yhhs/-.` .:::.-+yh
# /-./:-+NMm-dmmdddddmmmmho-om- ://s+ /Nddmmo:MMMMMMMMMMMMMh``-::/:.`-osyyso.:.-:...-:....+sy
# :-.:/:-/Nm-+mmmmddddmmmmmhosy.ssy++yNMMMMMN/mMMMMMMMMMMMy.` .. -yNNmy....::.`:-.-``/hM
# `-::-+mmohmmmddddddddmmmdy+yNMMMMMMMMMMMdoNNNNNNNNMMMy`.`.. sd: `+MNo.--.`://`..---`-hM
# :::-.` ``:dMyymmmdddddddddddddysymNMMMMMMMMNyodmdmmmmNNNy/oo::.oMMmhdmy-...:.`:/:`-//:-``hM
# `` `...-oy:ymmmhsddddddddhdhyysyhmNMMMNNNmyddddsydmmNNhhyshNMMMMMN+.``:.`.`:/-://///:.:y
# .://:..-:-.`yNNd+-ohdddddddho+ssssshmNNNNmmdddh`-ydmNNMMMMMMMMMMh-...`.:- :://::///:/ss
# ./++/--::`:-. `hNNm+`.odmmmdddhsosyso+osdNNNmmmmh`.hmNMMMMMMMMMMMs..---.`.-. -.-::::-:/+yh
# -+///--:::`---. .dNNN+ -sdmdmdddhyshNdy+/ohNNNmdy:yNNMMMMMMMMMMN+..--:::::-. .--`.-//-:+yd
# /::::`-:::-`-`/ `-mMMm-` .ohmmdddddysdNNho/+ymdhdMMMMMMMMMMMMMN/..---:::::/:-:-..`.----:yd
# h:::-``.----`.:``.+NNNo`` -/yddmmdddyyNMMdo-oNMMMMMMMMMMMMMMd:.----::::::/-:///:.``..``:y
# Ms---.`...--.:.`:o:mMNd``` -//:osshdddyoyNNNy`sMMMMMMMMMMMMNs..---:::::::/::////+:` :/:--.
# sNh/-.````` .`./oo/yNMN-``` :+++/:+/:ydddo+dmNy-MMMMMMMMMNdo-.---:::::::://:///+++/ ./++o+
# -omMh/. ./++++:hNNN: `` :oooo+///./hddoyNMN/MMMMMNmy+-.---::::::://///////+++/.. ./+oyh
# `-:smmo:+o+osss+/:-mNNs` ` `///+ooo+-: -hmm/dMMsMNho/-.---:::::::///////////+++/--/+`/++oys
# endregion---------------------------------------------------------------------------------------|
import sys
from heapq import *
from bisect import *
from collections import *
from math import ceil, floor, log, sqrt, gcd
mod = 1000000007
mod9 = 998244353
MX = 200003
nl = "\n"
def file_io():
sys.stdin = open(r"", "r")
sys.stdout = open(r"", "w")
def re(data=str): return data(sys.stdin.readline().rstrip())
def mp(data=str): return map(data, sys.stdin.readline().split())
def solve(tc):
re()
n, k = mp(int)
x = list(mp(int))
G = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = mp(int)
G[u - 1].append(v - 1)
G[v - 1].append(u - 1)
Q = deque([])
colour = [0] * n
def bfs(start):
for i in x:
Q.append(i - 1)
colour[i - 1] = 2
Q.append(0)
colour[0] = 1
while (Q):
cur = Q.popleft()
for nxt in G[cur]:
if not colour[nxt]:
colour[nxt] = colour[cur]
Q.append(nxt)
bfs(0)
for i in range(1, n):
if len(G[i]) == 1 and colour[i] == 1:
print("YES"); return
print("NO")
return None
def main():
# file_io()
tests = 1; tests = re(int)
for tc in range(1, tests + 1): solve(tc)
if __name__ == "__main__":
main()
|
1637850900
|
[
"trees"
] |
[
0,
0,
0,
0,
0,
0,
0,
1
] |
|
1 second
|
["10\n4975\n38\n0\n0"]
|
20dd260775ea71b1fb5b42bcac90a6f2
|
NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total.
|
There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?
|
For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.
|
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the quantity of candies in each box.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_106.jsonl
|
2360f6064ac5af26395eaef07e640a70
|
256 megabytes
|
["5\n\n5\n\n1 2 3 4 5\n\n6\n\n1000 1000 5 1000 1000 1000\n\n10\n\n1 2 3 5 1 2 7 9 13 5\n\n3\n\n8 8 8\n\n1\n\n10000000"]
|
PASSED
|
test_cases = int(input())
for i in range(test_cases):
l = int(input())
arr = list(map(int, input().split()))
arr.sort()
print(sum(arr) - (arr[0]*l))
|
1652193900
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["3 0", "5 5 3 2 0", "1"]
|
75d05c16baaba4b17ad6a9c1dd641bc0
| null |
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.SaMer wishes to create more cases from the test case he already has. His test case has an array $$$A$$$ of $$$n$$$ integers, and he needs to find the number of contiguous subarrays of $$$A$$$ that have an answer to the problem equal to $$$k$$$ for each integer $$$k$$$ between $$$1$$$ and $$$n$$$ (inclusive).
|
Output $$$n$$$ space-separated integers, the $$$k$$$-th integer should be the number of contiguous subarrays of $$$A$$$ that have an answer to the problem equal to $$$k$$$.
|
The first line of input contains a single integer $$$n$$$ ($$$1 \leq n \leq 5000$$$), the size of the array. The second line contains $$$n$$$ integers $$$a_1$$$,$$$a_2$$$,$$$\dots$$$,$$$a_n$$$ ($$$-10^8 \leq a_i \leq 10^8$$$), the values of the array.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,100 |
train_044.jsonl
|
b41f474e2dc386ff02d7e818c0795b3a
|
256 megabytes
|
["2\n5 5", "5\n5 -4 2 1 8", "1\n0"]
|
PASSED
|
#n=input()
#l=map(int, raw_input().split())
#pr=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973]
#pp=[pr[i]*pr[i] for i in xrange(len(pr))]
#sqf={}
#for i in xrange(n):
# j=0
# if l[i] in sqf:
# l[i]=sqf[l[i]]
# zz=l[i]
# while pp[j]<=abs(l[i]) and l[i]!=0:
# while abs(l[i])%pp[j]==0:
# l[i]/=pp[j]
# j+=1
# sqf[zz]=l[i]
primes = map(int, '''
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069
1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223
1229 1231 1237 1249 1259 1277 1279 1283 1289 1291 1297 1301 1303 1307 1319 1321 1327 1361 1367 1373
1381 1399 1409 1423 1427 1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499 1511
1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607 1609 1613 1619 1621 1627 1637 1657
1663 1667 1669 1693 1697 1699 1709 1721 1723 1733 1741 1747 1753 1759 1777 1783 1787 1789 1801 1811
1823 1831 1847 1861 1867 1871 1873 1877 1879 1889 1901 1907 1913 1931 1933 1949 1951 1973 1979 1987
1993 1997 1999 2003 2011 2017 2027 2029 2039 2053 2063 2069 2081 2083 2087 2089 2099 2111 2113 2129
2131 2137 2141 2143 2153 2161 2179 2203 2207 2213 2221 2237 2239 2243 2251 2267 2269 2273 2281 2287
2293 2297 2309 2311 2333 2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411 2417 2423
2437 2441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543 2549 2551 2557 2579 2591 2593 2609 2617
2621 2633 2647 2657 2659 2663 2671 2677 2683 2687 2689 2693 2699 2707 2711 2713 2719 2729 2731 2741
2749 2753 2767 2777 2789 2791 2797 2801 2803 2819 2833 2837 2843 2851 2857 2861 2879 2887 2897 2903
2909 2917 2927 2939 2953 2957 2963 2969 2971 2999 3001 3011 3019 3023 3037 3041 3049 3061 3067 3079
3083 3089 3109 3119 3121 3137 3163 3167 3169 3181 3187 3191 3203 3209 3217 3221 3229 3251 3253 3257
3259 3271 3299 3301 3307 3313 3319 3323 3329 3331 3343 3347 3359 3361 3371 3373 3389 3391 3407 3413
3433 3449 3457 3461 3463 3467 3469 3491 3499 3511 3517 3527 3529 3533 3539 3541 3547 3557 3559 3571
3581 3583 3593 3607 3613 3617 3623 3631 3637 3643 3659 3671 3673 3677 3691 3697 3701 3709 3719 3727
3733 3739 3761 3767 3769 3779 3793 3797 3803 3821 3823 3833 3847 3851 3853 3863 3877 3881 3889 3907
3911 3917 3919 3923 3929 3931 3943 3947 3967 3989 4001 4003 4007 4013 4019 4021 4027 4049 4051 4057
4073 4079 4091 4093 4099 4111 4127 4129 4133 4139 4153 4157 4159 4177 4201 4211 4217 4219 4229 4231
4241 4243 4253 4259 4261 4271 4273 4283 4289 4297 4327 4337 4339 4349 4357 4363 4373 4391 4397 4409
4421 4423 4441 4447 4451 4457 4463 4481 4483 4493 4507 4513 4517 4519 4523 4547 4549 4561 4567 4583
4591 4597 4603 4621 4637 4639 4643 4649 4651 4657 4663 4673 4679 4691 4703 4721 4723 4729 4733 4751
4759 4783 4787 4789 4793 4799 4801 4813 4817 4831 4861 4871 4877 4889 4903 4909 4919 4931 4933 4937
4943 4951 4957 4967 4969 4973 4987 4993 4999 5003 5009 5011 5021 5023 5039 5051 5059 5077 5081 5087
5099 5101 5107 5113 5119 5147 5153 5167 5171 5179 5189 5197 5209 5227 5231 5233 5237 5261 5273 5279
5281 5297 5303 5309 5323 5333 5347 5351 5381 5387 5393 5399 5407 5413 5417 5419 5431 5437 5441 5443
5449 5471 5477 5479 5483 5501 5503 5507 5519 5521 5527 5531 5557 5563 5569 5573 5581 5591 5623 5639
5641 5647 5651 5653 5657 5659 5669 5683 5689 5693 5701 5711 5717 5737 5741 5743 5749 5779 5783 5791
5801 5807 5813 5821 5827 5839 5843 5849 5851 5857 5861 5867 5869 5879 5881 5897 5903 5923 5927 5939
5953 5981 5987 6007 6011 6029 6037 6043 6047 6053 6067 6073 6079 6089 6091 6101 6113 6121 6131 6133
6143 6151 6163 6173 6197 6199 6203 6211 6217 6221 6229 6247 6257 6263 6269 6271 6277 6287 6299 6301
6311 6317 6323 6329 6337 6343 6353 6359 6361 6367 6373 6379 6389 6397 6421 6427 6449 6451 6469 6473
6481 6491 6521 6529 6547 6551 6553 6563 6569 6571 6577 6581 6599 6607 6619 6637 6653 6659 6661 6673
6679 6689 6691 6701 6703 6709 6719 6733 6737 6761 6763 6779 6781 6791 6793 6803 6823 6827 6829 6833
6841 6857 6863 6869 6871 6883 6899 6907 6911 6917 6947 6949 6959 6961 6967 6971 6977 6983 6991 6997
7001 7013 7019 7027 7039 7043 7057 7069 7079 7103 7109 7121 7127 7129 7151 7159 7177 7187 7193 7207
7211 7213 7219 7229 7237 7243 7247 7253 7283 7297 7307 7309 7321 7331 7333 7349 7351 7369 7393 7411
7417 7433 7451 7457 7459 7477 7481 7487 7489 7499 7507 7517 7523 7529 7537 7541 7547 7549 7559 7561
7573 7577 7583 7589 7591 7603 7607 7621 7639 7643 7649 7669 7673 7681 7687 7691 7699 7703 7717 7723
7727 7741 7753 7757 7759 7789 7793 7817 7823 7829 7841 7853 7867 7873 7877 7879 7883 7901 7907 7919
7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039 8053 8059 8069 8081 8087 8089 8093 8101 8111
8117 8123 8147 8161 8167 8171 8179 8191 8209 8219 8221 8231 8233 8237 8243 8263 8269 8273 8287 8291
8293 8297 8311 8317 8329 8353 8363 8369 8377 8387 8389 8419 8423 8429 8431 8443 8447 8461 8467 8501
8513 8521 8527 8537 8539 8543 8563 8573 8581 8597 8599 8609 8623 8627 8629 8641 8647 8663 8669 8677
8681 8689 8693 8699 8707 8713 8719 8731 8737 8741 8747 8753 8761 8779 8783 8803 8807 8819 8821 8831
8837 8839 8849 8861 8863 8867 8887 8893 8923 8929 8933 8941 8951 8963 8969 8971 8999 9001 9007 9011
9013 9029 9041 9043 9049 9059 9067 9091 9103 9109 9127 9133 9137 9151 9157 9161 9173 9181 9187 9199
9203 9209 9221 9227 9239 9241 9257 9277 9281 9283 9293 9311 9319 9323 9337 9341 9343 9349 9371 9377
9391 9397 9403 9413 9419 9421 9431 9433 9437 9439 9461 9463 9467 9473 9479 9491 9497 9511 9521 9533
9539 9547 9551 9587 9601 9613 9619 9623 9629 9631 9643 9649 9661 9677 9679 9689 9697 9719 9721 9733
9739 9743 9749 9767 9769 9781 9787 9791 9803 9811 9817 9829 9833 9839 9851 9857 9859 9871 9883 9887
9901 9907 9923 9929 9931 9941 9949 9967 9973 10007 '''.split())
sqf = {}
def squarefree_part(n):
"returns the squarefree part of a number. keeps the sign of the number if it's negative, and returns 0 for 0"
global sqf
if n in sqf:
return sqf[n]
if n == 0:
return 0
n_orig = n
for p in primes:
if p*p > abs(n):
sqf[n_orig] = n
return n
while n % p == 0 and (n/p) % p == 0:
n /= p
n /= p
line1 = raw_input()
line2 = raw_input()
n = int(line1)
l = map(int, line2.split())
l = map(squarefree_part, l)
d,k={0:0},1
for i in xrange(n):
if l[i] not in d:
d[l[i]]=k
k+=1
l[i]=d[l[i]]
ct,tmp=[0]*(n+2),[0]*(n+2)
for i in xrange(n):
k=0
for j in xrange(i,n):
ss=l[j]
if tmp[ss]==0 and ss!=0:
k+=1
tmp[ss]=1
ct[k]+=1
for j in xrange(i,n):
tmp[l[j]] = 0
print ct[0]+ct[1],
for i in ct[2:-1]:print i,
|
1525791900
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
1 second
|
["1001", "32"]
|
14c37283d16cb3aa8dd8fc7ea8f1096d
| null |
Given an array $$$a$$$, consisting of $$$n$$$ integers, find:$$$$$$\max\limits_{1 \le i < j \le n} LCM(a_i,a_j),$$$$$$where $$$LCM(x, y)$$$ is the smallest positive integer that is divisible by both $$$x$$$ and $$$y$$$. For example, $$$LCM(6, 8) = 24$$$, $$$LCM(4, 12) = 12$$$, $$$LCM(2, 3) = 6$$$.
|
Print one integer, the maximum value of the least common multiple of two elements in the array $$$a$$$.
|
The first line contains an integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the elements of the array $$$a$$$.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 2,900 |
train_017.jsonl
|
6f15819de120d5fa08b2af49cab75436
|
256 megabytes
|
["3\n13 35 77", "6\n1 2 4 8 16 32"]
|
PASSED
|
import sys
from fractions import gcd
input = sys.stdin.readline
n = int(input())
A = map(int, input().split())
divisors = [[] for _ in range(10**5+2)]
mobius = [1 for _ in range(10**5+2)]
for i in range(1,10**5+1):
for j in range(i,10**5+1,i):
divisors[j].append(i)
for i in range(1,10**5+1):
for d in divisors[i]:
if d == 1: continue
if i % (d**2) == 0 or mobius[i] == 0: mobius[i] = 0
elif len(divisors[i]) == 2: mobius[i] = -1
else: mobius[i] = mobius[d] * mobius[i / d]
numbers = set(A)
for i in A:
for d in divisors[i]:
numbers.add(d)
numbers = sorted(list(numbers), reverse=True)
stack = []
cnt = [0] * (10**5+2)
for i in numbers:
stack.append(i)
for d in divisors[i]:
cnt[d] += 1
ans = 0
for x in numbers:
num_co_prime = sum(cnt[d] * mobius[d] for d in divisors[x])
while num_co_prime > 0:
a = stack.pop()
for d in divisors[a]:
cnt[d] -= 1
if gcd(a,x) > 1:
continue
ans = max(a*x,ans)
num_co_prime-=1
print ans
|
1578665100
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
1 second
|
["2\n1 0\n1 3", "0"]
|
4a50c4147becea13946272230f3dde6d
|
NoteIn the first example, you can solve the problem in two operations: Swap the prefix of the first string with length 1 and the prefix of the second string with length 0. After this swap, you'll have strings ab and bbb. Swap the prefix of the first string with length 1 and the prefix of the second string with length 3. After this swap, you'll have strings bbbb and a. In the second example, the strings are already appropriate, so no operations are needed.
|
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be minimized.
|
The first line should contain a single integer n (0 ≤ n ≤ 5·105) — the number of operations. Each of the next n lines should contain two space-separated integers ai, bi — the lengths of prefixes of s and t to swap, respectively. If there are multiple possible solutions, you can print any of them. It's guaranteed that a solution with given constraints exists.
|
The first line contains a string s (1 ≤ |s| ≤ 2·105). The second line contains a string t (1 ≤ |t| ≤ 2·105). Here |s| and |t| denote the lengths of s and t, respectively. It is guaranteed that at least one of the strings contains at least one a letter and at least one of the strings contains at least one b letter.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,800 |
train_017.jsonl
|
f77d6d60de956907fe5e3250711dadbc
|
256 megabytes
|
["bab\nbb", "bbbb\naaa"]
|
PASSED
|
from sys import exit
def blokovi(x):
ret = [0]
for i in range(len(x) - 1):
if x[i] != x[i + 1]:
ret.append(i + 1)
return ret + [len(x)]
s = input()
t = input()
ss = blokovi(s)
tt = blokovi(t)
if s[-1] == 'a':
s += 'b'
else:
s += 'a'
if t[-1] == 'a':
t += 'b'
else:
t += 'a'
def greedy(x, y, rev=False):
i, j = len(x) - 1, len(y) - 1
swaps = []
while True:
while i >= 0 and x[i] == 'a':
i -= 1
while j >= 0 and y[j] == 'b':
j -= 1
if i < 0 and j < 0:
break
x, y = y, x
if rev:
swaps.append((j + 1, i + 1))
else:
swaps.append((i + 1, j + 1))
i, j = j, i
return swaps
def solve(x, y):
p = greedy(x, y)
q = greedy(y, x, True)
if len(p) < len(q):
return p
return q
probao = set()
total = len(ss) + len(tt)
sol = solve(s[:-1], t[:-1])
for b, i in enumerate(ss):
for c in range((2 * b + len(tt) - len(ss)) // 2 - 2, (2 * b + len(tt) - len(ss) + 1) // 2 + 3):
if 0 <= c < len(tt):
j = tt[c]
bs = b + len(tt) - c - 1
bt = c + len(ss) - b - 1
if abs(bs - bt) > 2:
continue
proba = (bs, bt, s[i], t[j])
if proba in probao:
continue
probao.add(proba)
s2 = t[:j] + s[i:-1]
t2 = s[:i] + t[j:-1]
if i + j > 0:
if i + j == len(s) + len(t) - 2:
cand = solve(t2, s2)
else:
cand = [(i, j)] + solve(s2, t2)
else:
cand = solve(s2, t2)
if len(cand) < len(sol):
sol = cand
print(len(sol))
for i, j in sol:
print(i, j)
|
1532938500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
5 seconds
|
["56"]
|
a6ca373007dc86193721b52bf35f5af8
|
NoteThe following explanation assumes $$$b = [2, 1]$$$ and $$$c=[2, 3, 4]$$$ (as in the sample).Examples of arrays $$$a$$$ that are not good: $$$a = [3, 2, 3]$$$ is not good because $$$a_1 > c_1$$$; $$$a = [0, -1, 3]$$$ is not good because $$$a_2 < 0$$$. One possible good array $$$a$$$ is $$$[0, 2, 4]$$$. We can show that no operation has any effect on this array, so $$$F(a, b) = a_1 = 0$$$.Another possible good array $$$a$$$ is $$$[0, 1, 4]$$$. In a single operation with $$$i = 1$$$, we set $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ and $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. So, after a single operation with $$$i = 1$$$, $$$a$$$ becomes equal to $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. We can show that no operation has any effect on this array, so $$$F(a, b) = -\frac{1}{2}$$$.
|
This is the easy version of the problem. The only difference is that in this version $$$q = 1$$$. You can make hacks only if both versions of the problem are solved.There is a process that takes place on arrays $$$a$$$ and $$$b$$$ of length $$$n$$$ and length $$$n-1$$$ respectively. The process is an infinite sequence of operations. Each operation is as follows: First, choose a random integer $$$i$$$ ($$$1 \le i \le n-1$$$). Then, simultaneously set $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ and $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ without any rounding (so values may become non-integer). See notes for an example of an operation.It can be proven that array $$$a$$$ converges, i. e. for each $$$i$$$ there exists a limit $$$a_i$$$ converges to. Let function $$$F(a, b)$$$ return the value $$$a_1$$$ converges to after a process on $$$a$$$ and $$$b$$$.You are given array $$$b$$$, but not array $$$a$$$. However, you are given a third array $$$c$$$. Array $$$a$$$ is good if it contains only integers and satisfies $$$0 \leq a_i \leq c_i$$$ for $$$1 \leq i \leq n$$$.Your task is to count the number of good arrays $$$a$$$ where $$$F(a, b) \geq x$$$ for $$$q$$$ values of $$$x$$$. Since the number of arrays can be very large, print it modulo $$$10^9+7$$$.
|
Output $$$q$$$ integers, where the $$$i$$$-th integer is the answer to the $$$i$$$-th query, i. e. the number of good arrays $$$a$$$ where $$$F(a, b) \geq x_i$$$ modulo $$$10^9+7$$$.
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$). The second line contains $$$n$$$ integers $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$). The third line contains $$$n-1$$$ integers $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$). The fourth line contains a single integer $$$q$$$ ($$$q=1$$$). The fifth line contains $$$q$$$ space separated integers $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,700 |
train_092.jsonl
|
ed9a76a4f4822e2bab009c9afaae44c4
|
256 megabytes
|
["3\n2 3 4\n2 1\n1\n-1"]
|
PASSED
|
def putin():
return map(int, input().split())
def sol():
n = int(input())
C = list(putin())
B = list(putin())
q = int(input())
x = int(input())
min_arr = [x]
min_part_sums = [x]
part_sums = [C[0]]
for i in range(1, n):
part_sums.append(part_sums[-1] + C[i])
for elem in B:
min_arr.append(min_arr[-1] + elem)
min_part_sums.append(min_arr[-1] + min_part_sums[-1])
for i in range(n):
if min_part_sums[i] > part_sums[i]:
return 0
if min_part_sums[0] > C[0]:
return 0
answer = [1] * (part_sums[0] - max(0, min_part_sums[0]) + 1)
for k in range(1, n):
new_answer = [0] * (part_sums[k] - max(0, min_part_sums[k]) + 1)
cnt = 1
window = answer[-1]
new_answer[-1] = window
while cnt <= len(new_answer) - 1:
cnt += 1
if cnt <= len(answer):
window += answer[-cnt]
if C[k] + 1 < cnt:
window -= answer[C[k] + 1 - cnt]
new_answer[-cnt] = window
answer = new_answer.copy()
m = 10 ** 9 + 7
return sum(answer) % m
print(sol())
|
1624635300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n1 0\n2 0", "1\n0 1"]
|
14ad30e33bf8cad492e665b0a486008e
|
NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
|
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
|
In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.
|
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_003.jsonl
|
25c48b28e0b8a426282835b0866fcf9e
|
256 megabytes
|
["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"]
|
PASSED
|
from collections import deque
n = int(input())
process = deque()
vs = []
for i in range(n):
d, s = map(int, input().split())
if d == 1:
process.append(i)
vs.append((d, s))
edges = []
while process:
a = process.popleft()
d, s = vs[a]
if d == 0:
continue
dd, ss = vs[s]
vs[s] = (dd - 1, ss ^ a)
if dd == 2:
process.append(s)
edges.append((a, s))
print(len(edges))
for a, b in edges:
print(a,b)
|
1421053200
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["4", "4"]
|
0f8ad0ea2befbbe036fbd5e5f6680c21
|
NoteIn the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.
|
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions: The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1). No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q). All elements of the sequence are good integers. Find the length of the longest good sequence.
|
Print a single integer — the length of the longest good sequence.
|
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_007.jsonl
|
e7abb1a8a03e90e76ee27274635721a3
|
256 megabytes
|
["5\n2 3 4 6 9", "9\n1 2 3 5 6 7 8 9 10"]
|
PASSED
|
n = 100001
m = int(input())
div = [[] for _ in range(n)]
div[1] = [1]
for i in range(2, n):
if not div[i]:
div[i] = [i]
for j in range(2 * i, n, i):
div[j].append(i)
a = list(map(int, input().rstrip().split()))
dp = [0] * (n + 1)
for i in a:
x = max(dp[j] for j in div[i]) + 1
for j in div[i]:
dp[j] = x
print(max(dp))
|
1358686800
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["1\n10\n22"]
|
fa11eb753c2cae620c139030f5ca5850
|
NoteIn the first test case, we can swap person $$$4$$$ and person $$$1$$$ (who are adjacent) in the initial configuration and get the order $$$[4, 2, 3, 1]$$$ which is equivalent to the desired one. Hence in this case a single swap is sufficient.
|
There are $$$n$$$ people, numbered from $$$1$$$ to $$$n$$$, sitting at a round table. Person $$$i+1$$$ is sitting to the right of person $$$i$$$ (with person $$$1$$$ sitting to the right of person $$$n$$$).You have come up with a better seating arrangement, which is given as a permutation $$$p_1, p_2, \dots, p_n$$$. More specifically, you want to change the seats of the people so that at the end person $$$p_{i+1}$$$ is sitting to the right of person $$$p_i$$$ (with person $$$p_1$$$ sitting to the right of person $$$p_n$$$). Notice that for each seating arrangement there are $$$n$$$ permutations that describe it (which can be obtained by rotations).In order to achieve that, you can swap two people sitting at adjacent places; but there is a catch: for all $$$1 \le x \le n-1$$$ you cannot swap person $$$x$$$ and person $$$x+1$$$ (notice that you can swap person $$$n$$$ and person $$$1$$$). What is the minimum number of swaps necessary? It can be proven that any arrangement can be achieved.
|
For each test case, print the minimum number of swaps necessary to achieve the desired order.
|
Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 10\,000$$$) — the number of test cases. The descriptions of the $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 200\,000$$$) — the number of people sitting at the table. The second line contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, $$$p_i \ne p_j$$$ for $$$i \ne j$$$) — the desired final order of the people around the table. The sum of the values of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| -1 |
train_085.jsonl
|
f0a1d0101ac35c51b72032a4aea9cba5
|
256 megabytes
|
["3\n\n4\n\n2 3 1 4\n\n5\n\n5 4 3 2 1\n\n7\n\n4 1 6 5 3 7 2"]
|
PASSED
|
import sys
input = sys.stdin.readline
class SegmentTree:
def __init__(self, data, default=0, func=lambda x, y: x + y):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def clear(self, i):
if i >= self._size:
self.data[i] = 0
if self.data[i]:
self.data[i] = 0
self.clear(i + i)
self.clear(i + i + 1)
SZ = 200005
ST = SegmentTree([0] * (2 * SZ))
t = int(input())
out = []
for _ in range(t):
n = int(input())
l = list(map(int, input().split()))
p = [0] * n
for i in range(n):
p[l[i] - 1] = i
res = 0
for i in range(n - 1):
l = p[i]
r = p[i + 1]
if r < l:
r += SZ
seen = ST.query(l, r)
tot = (p[i + 1] - p[i] - 1) % n
res += (i + 1) * (tot - seen)
#print(tot, seen)
ST[p[i]] = 1
ST[p[i] + SZ] = 1
out.append(res)
ST.clear(1)
#print(ST)
print('\n'.join(map(str, out)))
|
1650798300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["? 0000\n\n? 1110\n\n? 1111\n\n? 1101\n\n! 7"]
|
003b7257b35416ec93f189cb29e458e6
|
NoteHere is the graph of the example, satisfying $$$l_i=i$$$.
|
As for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $$$n$$$ stations with $$$m$$$ bidirectional tracks connecting them. The $$$i$$$-th track has length $$$l_i$$$ ($$$1\le l_i\le 10^6$$$). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than $$$2m$$$ queries. The input of the simulator is a string $$$s$$$ of length $$$m$$$, consisting of characters 0 and/or 1. The simulator will assume the $$$i$$$-th track functional if $$$s_i=$$$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.
| null |
The first and only line of input contains two integers $$$n,m$$$ ($$$2 \leq n \leq 200$$$, $$$1\le m \le 500$$$) — the number of stations and tracks.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_091.jsonl
|
d95e7973957489e08018b96a05bdbdb4
|
256 megabytes
|
["5 4\n\n0\n\n5\n\n9\n\n7"]
|
PASSED
|
def ask(ii):
aa = [0]*m
for i in ii: aa[i] = 1
print("? ", *aa, sep="", flush=True)
return int(input())
n, m = map(int, input().split())
ll = []
for i in range(m):
ll.append(ask([i]))
il = sorted(enumerate(ll), key=lambda x: x[1])
ans = il[0][1]
ii = [il[0][0]]
for i, l in il[1:]:
ii.append(i)
r = ask(ii)
if l == r-ans:
ans = r
else:
ii.pop()
print("!", ans, flush=True)
|
1654266900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["YES\nYES\nNO\nYES"]
|
6e6356adb23da0dfa38834a0e157524c
| null |
You are given an array $$$a$$$ of $$$n$$$ positive integers.You can use the following operation as many times as you like: select any integer $$$1 \le k \le n$$$ and do one of two things: decrement by one $$$k$$$ of the first elements of the array. decrement by one $$$k$$$ of the last elements of the array. For example, if $$$n=5$$$ and $$$a=[3,2,2,1,4]$$$, then you can apply one of the following operations to it (not all possible options are listed below): decrement from the first two elements of the array. After this operation $$$a=[2, 1, 2, 1, 4]$$$; decrement from the last three elements of the array. After this operation $$$a=[3, 2, 1, 0, 3]$$$; decrement from the first five elements of the array. After this operation $$$a=[2, 1, 1, 0, 3]$$$; Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.
|
For each test case, output on a separate line: YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations. NO, otherwise. The letters in the words YES and NO can be outputed in any case.
|
The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 30000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing one integer $$$n$$$ ($$$1 \le n \le 30000$$$) — the number of elements in the array. The second line of each test case contains $$$n$$$ integers $$$a_1 \ldots a_n$$$ ($$$1 \le a_i \le 10^6$$$). The sum of $$$n$$$ over all test cases does not exceed $$$30000$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_004.jsonl
|
d0612e48f0888fb311666dc7b62a70c0
|
256 megabytes
|
["4\n3\n1 2 1\n5\n11 7 9 6 8\n5\n1 3 1 3 1\n4\n5 2 1 10"]
|
PASSED
|
t = int(input())
for i in range(t):
n = int(input())
a = [0] + list(map(int, input().split()))
ans = [a[i] - a[i-1] for i in range(1, n+1)]
result = 0
for i in range(1, n):
if ans[i] < 0:
result = result + (-1)*ans[i]
if result <= a[1]:
print("YES")
else:
print("NO")
|
1604327700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
0.5 seconds
|
["108.395919545675"]
|
fd92081afd795789b738009ff292a25c
| null |
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.A "star" figure having n ≥ 5 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.
|
Output one number — the star area. The relative error of your answer should not be greater than 10 - 7.
|
The only line of the input contains two integers n (5 ≤ n < 109, n is prime) and r (1 ≤ r ≤ 109) — the number of the star corners and the radius of the circumcircle correspondingly.
|
standard output
|
standard input
|
Python 3
|
Python
| 2,100 |
train_019.jsonl
|
eb113dd3b5571bfd534005991d451e00
|
64 megabytes
|
["7 10"]
|
PASSED
|
import math
n, r = map(int, input().split())
a = math.pi / n
b = a / 2
print(r * math.sin(b) / math.sin(math.pi - a - b) * math.sin(a) * r * n)
|
1455807600
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
1 second
|
["3", "1", "0"]
|
2be73aa00a13be5274cf840ecd3befcb
|
NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.
|
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.
|
Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.
|
The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns. The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,100 |
train_001.jsonl
|
8b52ffbf0852fbb099c83c2c6a81cf5a
|
256 megabytes
|
["3\n5 6\n8 9\n10 3", "2\n6 5\n5 6", "6\n5 9\n1 3\n4 8\n4 5\n23 54\n12 32"]
|
PASSED
|
from copy import deepcopy
def f(n, m):
return abs(n - m)
n = int(input())
mas = []
L = 0
R = 0
for i in range(n):
l, r = map(int, input().split())
mas.append((l, r))
L += l
R += r
sum = f(L, R)
old = deepcopy(sum)
new = deepcopy(old)
#print(L, R)
for i in range(n):
L -= mas[i][0]
R -= mas[i][1]
L += mas[i][1]
R += mas[i][0]
#print(L, R)
if f(L, R) > new:
ans = i
new = f(L, R)
L -= mas[i][1]
R -= mas[i][0]
L += mas[i][0]
R += mas[i][1]
if new - old == 0:
print(0)
else:
print(ans + 1)
|
1477922700
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\nNO\nNO\nYES\nYES\nYES\nYES"]
|
78f25e2bc4ff22dbac94f72af68a745f
|
NoteOne possible casting sequence of the first test case is shown below: Void Absorption $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$. Lightning Strike $$$60-10=50$$$. Void Absorption $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$. Void Absorption $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$. Lightning Strike $$$27-10=17$$$. Lightning Strike $$$17-10=7$$$. Lightning Strike $$$7-10=-3$$$.
|
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of $$$x$$$ initially. When its hit point goes to $$$0$$$ or under $$$0$$$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells. Void Absorption Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will become $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Here $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ denotes $$$h$$$ divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by $$$10$$$. Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will be lowered to $$$h-10$$$.Due to some reasons Kana can only cast no more than $$$n$$$ Void Absorptions and $$$m$$$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.
|
If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).
|
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. For each test case the only line contains three integers $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$) — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.
|
standard output
|
standard input
|
PyPy 2
|
Python
| 900 |
train_001.jsonl
|
134edbe2dba84432cdd1bf3d7310f3d9
|
256 megabytes
|
["7\n100 3 4\n189 3 4\n64 2 3\n63 2 3\n30 27 7\n10 9 1\n69117 21 2"]
|
PASSED
|
import atexit, io, sys
# A stream implementation using an in-memory bytes
# buffer. It inherits BufferedIOBase.
buffer = io.BytesIO()
sys.stdout = buffer
# print via here
@atexit.register
def write():
sys.__stdout__.write(buffer.getvalue())
for _ in range(input()):
x,n,m=map(int,raw_input().split())
p=0
while(n):
y=x/2+10
if x<=y:
break
else:
x=y
n-=1
if (x+9)/10<=m:
print "YES"
else:
print "NO"
|
1586961300
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["NO", "YES\n8 * 7 = 56\n6 * 5 = 30\n3 - 4 = -1\n1 - 2 = -1\n30 - -1 = 31\n56 - 31 = 25\n25 + -1 = 24"]
|
1bd1a7fd2a07e3f8633d5bc83d837769
| null |
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?
|
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes). If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.
|
The first line contains a single integer n (1 ≤ n ≤ 105).
|
standard output
|
standard input
|
Python 2
|
Python
| 1,500 |
train_002.jsonl
|
cbddec7a8c3aa62a8596bba43292afea
|
256 megabytes
|
["1", "8"]
|
PASSED
|
a=input()
if(a<4):
print "NO"
elif(a==4):
print "YES"
print "4 * 3 = 12"
print "2 * 1 = 2"
print "12 * 2 = 24"
elif(a==5):
print "YES"
print "5 - 3 = 2"
print "2 + 1 = 3"
print "2 * 3 = 6"
print "6 * 4 = 24"
elif(a>5):
print "YES"
print "6 * 4 = 24"
print "3 - 2 = 1"
print "1 - 1 = 0"
print "0 * 5 = 0"
if(a>6):
for i in range(7,a+1):
print "0 * "+str(i)+" = 0"
print "24 + 0 = 24"
|
1411218000
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["2\n-1\n0\n3\n2"]
|
8ca8317ce3f678c99dc746cb9b058993
|
NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome.
|
Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.
|
For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,200 |
train_106.jsonl
|
541454725187f77fba935aedfe1b20e8
|
256 megabytes
|
["5\n8\nabcaacab\n6\nxyzxyz\n4\nabba\n8\nrprarlap\n10\nkhyyhhyhky"]
|
PASSED
|
import os, sys
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")
#mod = 10 ** 9 + 7
'''
def get(l,idx,avgl,avgr,n):
if n==1:
return False
if idx==n-1:
return False
print(avgl,idx,avgr)
if avgl==avgr:
return True
return get(l,idx+1,(avgl*idx+l[idx])/(idx+1),(avgr*(n-idx)-l[idx])/(n-idx-1),n) or get(l,idx+1,avgl,avgr,n)
l=[1,2,3,4,5,6,7,8] #list(map(int,input().split()))
s=sum(l)
n=len(l)
print(get(l,0,0,s/n,n))
'''
for _ in range(int(input())):
n=int(input())
l=list(input())
i=0
j=n-1
f=0
while i<j:
if l[i]==l[j]:
i+=1
j-=1
continue
else:
f=1
break
if f==1:
if n==2:
print(1)
continue
left=0
right=0
ti=i
tj=j
while ti<tj:
if l[ti]!=l[tj]:
if l[j]==l[tj]:
tj-=1
else:
break
else:
left=1
leftreq=l[j]
break
ti=i
tj=j
while ti<tj:
if l[ti]!=l[tj]:
if l[i]==l[ti]:
ti+=1
else:
break
else:
right=1
rightreq=l[i]
break
if left==0 and right==0:
if ti==tj:
print(1)
continue
else:
print(-1)
continue
ans=float('inf')
if left==1:
f=0
c=0
i=0
j=n-1
while i<j:
if l[i]==l[j]:
i+=1
j-=1
else:
if l[i]==leftreq:
i+=1
c+=1
elif l[j]==leftreq:
j-=1
c+=1
else:
f=1
break
if f==0:
ans=min(ans,c)
if right==1:
f=0
c=0
i=0
j=n-1
while i<j:
if l[i]==l[j]:
i+=1
j-=1
else:
if l[i]==rightreq:
i+=1
c+=1
elif l[j]==rightreq:
j-=1
c+=1
else:
f=1
break
if f==0:
ans=min(ans,c)
if ans==float('inf'):
print(-1)
continue
print(ans)
else:
print(0)
|
1635069900
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["2\n3"]
|
63108f3cc494df3c7bb62381c03801b3
|
NoteIn the first test case, the initial array contains elements $$$[6, 8, 4, 2]$$$. Element $$$a_4=2$$$ in this array is adjacent to $$$a_4=2$$$ (since $$$\frac{lcm(2, 2)}{gcd(2, 2)}=\frac{2}{2}=1=1^2$$$) and $$$a_2=8$$$ (since $$$\frac{lcm(8,2)}{gcd(8, 2)}=\frac{8}{2}=4=2^2$$$). Hence, $$$d_4=2$$$, and this is the maximal possible value $$$d_i$$$ in this array.In the second test case, the initial array contains elements $$$[12, 3, 20, 5, 80, 1]$$$. The elements adjacent to $$$12$$$ are $$$\{12, 3\}$$$, the elements adjacent to $$$3$$$ are $$$\{12, 3\}$$$, the elements adjacent to $$$20$$$ are $$$\{20, 5, 80\}$$$, the elements adjacent to $$$5$$$ are $$$\{20, 5, 80\}$$$, the elements adjacent to $$$80$$$ are $$$\{20, 5, 80\}$$$, the elements adjacent to $$$1$$$ are $$$\{1\}$$$. After one second, the array is transformed into $$$[36, 36, 8000, 8000, 8000, 1]$$$.
|
Let us call two integers $$$x$$$ and $$$y$$$ adjacent if $$$\frac{lcm(x, y)}{gcd(x, y)}$$$ is a perfect square. For example, $$$3$$$ and $$$12$$$ are adjacent, but $$$6$$$ and $$$9$$$ are not.Here $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$, and $$$lcm(x, y)$$$ denotes the least common multiple (LCM) of integers $$$x$$$ and $$$y$$$.You are given an array $$$a$$$ of length $$$n$$$. Each second the following happens: each element $$$a_i$$$ of the array is replaced by the product of all elements of the array (including itself), that are adjacent to the current value. Let $$$d_i$$$ be the number of adjacent elements to $$$a_i$$$ (including $$$a_i$$$ itself). The beauty of the array is defined as $$$\max_{1 \le i \le n} d_i$$$. You are given $$$q$$$ queries: each query is described by an integer $$$w$$$, and you have to output the beauty of the array after $$$w$$$ seconds.
|
For each query output a single integer — the beauty of the array at the corresponding moment.
|
The first input 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 3 \cdot 10^5$$$) — the length of the array. The following line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — array elements. The next line contain a single integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. The following $$$q$$$ lines contain a single integer $$$w$$$ each ($$$0 \le w \le 10^{18}$$$) — the queries themselves. It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 1,900 |
train_084.jsonl
|
0b5434ac898e94510e93f67531bd6ba9
|
256 megabytes
|
["2\n4\n6 8 4 2\n1\n0\n6\n12 3 20 5 80 1\n1\n1"]
|
PASSED
|
import sys, random
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); inf=10**18
LI = lambda : list(map(int, input().split()))
def debug(_l_):
for s in _l_.split():
print(f"{s}={eval(s)}", end=" ")
print()
def dlist(*l, fill=0):
if len(l)==1:
return [fill]*l[0]
ll = l[1:]
return [dlist(*ll, fill=fill) for _ in range(l[0])]
def hurui(n):
"""線形篩
pl: 素数のリスト
mpf: iを割り切る最小の素因数
"""
pl = []
mpf = [None]*(n+1)
for d in range(2,n+1):
if mpf[d] is None:
mpf[d] = d
pl.append(d)
for p in pl:
if p*d>n or p>mpf[d]:
break
mpf[p*d] = p
return pl, mpf
from collections import defaultdict
def factor(num):
d = defaultdict(int)
if num==1:
d.update({})
return d
while num>1:
d[mpf[num]] += 1
num //= mpf[num]
return d
def fs(num):
f = factor(num)
ans = [1]
for k,v in f.items():
tmp = []
for i in range(len(ans)):
val = 1
for _ in range(v):
val *= k
ans.append(ans[i]*val)
return ans
pl, mpf = hurui(1000100)
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
c = {}
for v in a:
f = factor(v)
k = tuple(sorted([kk for kk,vv in f.items() if vv%2]))
c.setdefault(k,0)
c[k] += 1
ans0 = max(c.values())
nc = {}
for k in c.keys():
if c[k]%2==0:
nk = tuple()
else:
nk = k
nc.setdefault(nk, 0)
nc[nk] += c[k]
ans1 = max(nc.values())
q = int(input())
for i in range(q):
w = int(input())
if w==0:
print(ans0)
else:
print(ans1)
|
1609857300
|
[
"number theory",
"math",
"graphs"
] |
[
0,
0,
1,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2\n1\n2\n0"]
|
130fd7f40d879e25b0bff886046bf699
|
NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:
|
Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which two planks of length at least $$$k+1$$$ — the base of the ladder; $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps. You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?
|
Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.
|
The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 900 |
train_002.jsonl
|
a17acec868989cd3e7169b864141978b
|
256 megabytes
|
["4\n4\n1 3 1 3\n3\n3 3 2\n5\n2 3 3 4 2\n3\n1 1 2"]
|
PASSED
|
t=int((input()))
l2=[]
for i in range(t):
n=int(input())
l1=[int(a) for a in input().split()]
max1=0
max2=0
for k in range(n):
if(l1[k]>=max1):
max2=max1
max1=l1[k]
elif(l1[k]>max2):
max2=l1[k]
else:
continue
c=0
for k in range(n):
if(l1[k]<=max1):
c+=1
if(c-2<max2):
l2.append(c-2)
else:
l2.append(max2-1)
for i in range(t):
print(l2[i])
|
1563806100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["4\n-1\n0\n-1"]
|
61bbe7bc4698127511a0bdbc717e2526
|
NoteConsider the first test.In the first test case, you can act like this (the vertex to which the operation is applied at the current step is highlighted in purple): It can be shown that it is impossible to make a tree beautiful in fewer operations.In the second test case, it can be shown that it is impossible to make a tree beautiful.In the third test case, the tree is already beautiful.
|
The girl named Masha was walking in the forest and found a complete binary tree of height $$$n$$$ and a permutation $$$p$$$ of length $$$m=2^n$$$.A complete binary tree of height $$$n$$$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $$$n$$$. The picture below shows the complete binary tree for $$$n=2$$$.A permutation is an array consisting of $$$n$$$ different integers from $$$1$$$ to $$$n$$$. For example, [$$$2,3,1,5,4$$$] is a permutation, but [$$$1,2,2$$$] is not ($$$2$$$ occurs twice), and [$$$1,3,4$$$] is also not a permutation ($$$n=3$$$, but there is $$$4$$$ in the array).Let's enumerate $$$m$$$ leaves of this tree from left to right. The leaf with the number $$$i$$$ contains the value $$$p_i$$$ ($$$1 \le i \le m$$$).For example, if $$$n = 2$$$, $$$p = [3, 1, 4, 2]$$$, the tree will look like this: Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order.In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees).For example, if Masha applies this operation to the root of the tree discussed above, it will take the following form: Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful.
|
For each test case in a separate line, print the minimum possible number of operations for which Masha will be able to make the tree beautiful or -1, if this is not possible.
|
The first line contains single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. In each test case, the first line contains an integer $$$m$$$ ($$$1 \le m \le 262144$$$), which is a power of two — the size of the permutation $$$p$$$. The second line contains $$$m$$$ integers: $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le m$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,300 |
train_084.jsonl
|
64ac2d97b70a65370b059664439d2ced
|
256 megabytes
|
["4\n\n8\n\n6 5 7 8 4 3 1 2\n\n4\n\n3 1 4 2\n\n1\n\n1\n\n8\n\n7 8 4 3 1 2 6 5"]
|
PASSED
|
def greater(a ,b):
if len(a) > len(b): return True
if len(a) < len(b): return False
for i in range(len(a)):
if a[i] > b[i]:
return True
elif a[i] < b[i]:
return False
return False
for _ in range(int(input())):
f = False
n = int(input())
a = input().split()
for i in range(0,n-1,2):
if abs(int(a[i+1]) - int(a[i])) != 1:
print(-1)
f = True
break
if f: continue
count = 0
while len(a) > 1:
# print(a)
copy = []
for i in range(0, len(a)-1, 2):
if greater(a[i], a[i+1]):
count += 1
copy.append(a[i+1] + a[i])
else:
copy.append(a[i] + a[i+1])
a = copy[:]
terms = 1
ind = 0
till = 10
ans = a[0]
for i in range(1,n+1):
if i == till:
till *= 10
terms += 1
if i != int(ans[ind:ind+terms]):
f = True
break
ind += terms
if f: print(-1)
else: print(count)
|
1665498900
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
1 second
|
["2\n3 4\n1 4\n4\n1 2\n2 2\n2 4\n5 4\n1\n5 1", "1\n1 1\n1\n1 2\n1\n1 3", "1\n1 1\n1\n2 2\n1\n3 1"]
|
29476eefb914b445f1421d99d928fd5a
|
NoteRooks arrangements for all three examples (red is color $$$1$$$, green is color $$$2$$$ and blue is color $$$3$$$).
|
Ivan is a novice painter. He has $$$n$$$ dyes of different colors. He also knows exactly $$$m$$$ pairs of colors which harmonize with each other.Ivan also enjoy playing chess. He has $$$5000$$$ rooks. He wants to take $$$k$$$ rooks, paint each of them in one of $$$n$$$ colors and then place this $$$k$$$ rooks on a chessboard of size $$$10^{9} \times 10^{9}$$$.Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.Ivan wants his arrangement of rooks to have following properties: For any color there is a rook of this color on a board; For any color the set of rooks of this color is connected; For any two different colors $$$a$$$ $$$b$$$ union of set of rooks of color $$$a$$$ and set of rooks of color $$$b$$$ is connected if and only if this two colors harmonize with each other.Please help Ivan find such an arrangement.
|
Print $$$n$$$ blocks, $$$i$$$-th of them describes rooks of $$$i$$$-th color. In the first line of block print one number $$$a_{i}$$$ ($$$1 \le a_{i} \le 5000$$$) — number of rooks of color $$$i$$$. In each of next $$$a_{i}$$$ lines print two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, \,\, y \le 10^{9}$$$) — coordinates of the next rook. All rooks must be on different cells. Total number of rooks must not exceed $$$5000$$$. It is guaranteed that the solution exists.
|
The first line of input contains $$$2$$$ integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le min(1000, \,\, \frac{n(n-1)}{2})$$$) — number of colors and number of pairs of colors which harmonize with each other. In next $$$m$$$ lines pairs of colors which harmonize with each other are listed. Colors are numbered from $$$1$$$ to $$$n$$$. It is guaranteed that no pair occurs twice in this list.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_025.jsonl
|
9c035837e10c647a0aa1649a7ade52d4
|
256 megabytes
|
["3 2\n1 2\n2 3", "3 3\n1 2\n2 3\n3 1", "3 1\n1 3"]
|
PASSED
|
n, m = list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
final = [[] for _ in range(n + 1)]
seen = {}
for _ in range(m):
a, b = list(map(int, input().split()))
if a > b:
a,b = b,a
seen[a] = True
seen[b] = True
G[a].append(b)
step = 1
for i in range(1, n + 1):
hrmny = G[i]
if i not in seen:
final[i].append((step, i))
step += 1
for h in hrmny:
final[i].append((step, i))
final[h].append((step, h))
step += 1
for i in range(1, n + 1):
f = final[i]
print(len(f))
print('\n'.join(map(lambda a: '{} {}'.format(*a), f)))
|
1540398900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["17", "4"]
|
a9473e6ec81c10c4f88973ac2d60ad04
|
NoteFor the first test case, here's how a circular value of $$$17$$$ is obtained:Pick the number at index $$$3$$$. The sum of adjacent elements equals $$$17$$$. Delete $$$7$$$ and $$$10$$$ from the circle and replace $$$2$$$ with $$$17$$$.Note that the answer may not fit in a $$$32$$$-bit integer.
|
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!You are given $$$n$$$ nonnegative integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle, where $$$n$$$ must be odd (ie. $$$n-1$$$ is divisible by $$$2$$$). Formally, for all $$$i$$$ such that $$$2 \leq i \leq n$$$, the elements $$$a_{i - 1}$$$ and $$$a_i$$$ are considered to be adjacent, and $$$a_n$$$ and $$$a_1$$$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.Help Danny find the maximum possible circular value after some sequences of operations.
|
Output the maximum possible circular value after applying some sequence of operations to the given circle.
|
The first line contains one odd integer $$$n$$$ ($$$1 \leq n < 2 \cdot 10^5$$$, $$$n$$$ is odd) — the initial size of the circle. The second line contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$0 \leq a_{i} \leq 10^9$$$) — the initial numbers in the circle.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,100 |
train_001.jsonl
|
5730229839b896fb668424c586bd0a78
|
256 megabytes
|
["3\n7 10 2", "1\n4"]
|
PASSED
|
## necessary imports
import sys
input = sys.stdin.readline
# from math import ceil, floor, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1;
return x;
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
## gcd function
def gcd(a,b):
if b == 0:
return a;
return gcd(b, a % b);
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k;
res = 1;
for i in range(k):
res = res * (n - i);
res = res / (i + 1);
return int(res);
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
if hi == None:
hi = len(a);
while lo < hi:
mid = (lo+hi)//2;
if a[mid] < x:
lo = mid+1;
else:
hi = mid;
return lo;
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b;
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret;
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()));
def float_array():
return list(map(float, input().strip().split()));
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n = int(input()); a = int_array();
odd_ = []; even_ = [];
a += a; odd = even = 0;
for i in range(2 * n):
if i & 1:
odd += a[i];
odd_.append(odd);
else:
even += a[i];
even_.append(even);
x = (n + 1) // 2; ans = 0;
for i in range(x - 1, len(even_)):
if i == x - 1:
ans = max(ans, even_[i]);
else:
ans = max(ans, even_[i] - even_[i - x]);
for i in range(x - 1, len(odd_)):
if i == x - 1:
ans = max(ans, odd_[i]);
else:
ans = max(ans, odd_[i] - odd_[i - x]);
print(ans);
|
1594479900
|
[
"games"
] |
[
1,
0,
0,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["3\n1\n1"]
|
16c4160d1436206412ce51315cb6140b
|
NoteIn the first test case, there is only one tree with the given visiting order: In the second test case, there is only one tree with the given visiting order as well: In the third test case, an optimal tree with the given visiting order is shown below:
|
Monocarp had a tree which consisted of $$$n$$$ vertices and was rooted at vertex $$$1$$$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty(): k = q.pop() # retrieve the first vertex from the queue a.append(k) # append k to the end of the sequence in which vertices were visited for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order $$$a$$$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all root's children are $$$1$$$.Help Monocarp to find any tree with given visiting order $$$a$$$ and minimum height.
|
For each test case print the minimum possible height of a tree with the given visiting order $$$a$$$.
|
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$; $$$a_1 = 1$$$) — the order in which the vertices were visited by the BFS algorithm. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,600 |
train_018.jsonl
|
c6512aa0f0df7821a149c814cbe660c9
|
256 megabytes
|
["3\n4\n1 4 3 2\n2\n1 2\n3\n1 2 3"]
|
PASSED
|
for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
d,c = [0]*n,0
for i in range(1,n):
if l[i-1] > l[i]:
c += 1
d[i] = d[c] + 1
print(d[n-1])
'''
5
1 2 5 4 3
'''
|
1603809300
|
[
"trees",
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
1
] |
|
2 seconds
|
["3\n2\n2", "401\n4\n3"]
|
b56e70728d36c41134c39bd6ad13d059
|
NoteIn the first example the three ways to split the message are: a|a|b aa|b a|ab The longest substrings are "aa" and "ab" of length 2.The minimum number of substrings is 2 in "a|ab" or "aa|b".Notice that "aab" is not a possible splitting because the letter 'a' appears in a substring of length 3, while a1 = 2.
|
Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1 = 2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1 = 2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions: How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109 + 7. What is the maximum length of a substring that can appear in some valid splitting? What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".
|
Print three lines. In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109 + 7. In the second line print the length of the longest substring over all the ways. In the third line print the minimum number of substrings over all the ways.
|
The first line contains an integer n (1 ≤ n ≤ 103) denoting the length of the message. The second line contains the message s of length n that consists of lowercase English letters. The third line contains 26 integers a1, a2, ..., a26 (1 ≤ ax ≤ 103) — the maximum lengths of substring each letter can appear in.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,700 |
train_030.jsonl
|
a633f0f9026dbd51819f8731f8cb8762
|
256 megabytes
|
["3\naab\n2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "10\nabcdeabcde\n5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"]
|
PASSED
|
n=int(input())
s=input()
l=list(map(int,input().split()))
dp=[0]*(n+2)
mn=[10**4]*(n+2)
dp[0]=dp[n+1]=1
mn[0]=1
mn[n+1]=0
mod=10**9+7
maxx=1
for i in range(1,n):
cur=10**4
for j in range(i,-1,-1):
c=ord(s[j])-ord('a')
cur=min(cur,l[c])
if cur<(i-j+1):
break
dp[i]=(dp[i]+dp[j-1])%mod
mn[i]=min(mn[i],mn[j-1]+1)
maxx=max(maxx,i-j+1)
#print(dp)
print(dp[n-1])
print(maxx)
print(mn[n-1])
|
1486487100
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["12330", "1115598"]
|
b4cd60296083ee2ae8a560209433dcaf
| null |
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally, if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$; if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$, your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.
|
Print the answer modulo $$$998\,244\,353$$$.
|
The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,800 |
train_024.jsonl
|
5f978c9edc3021dcd5c96aedb1cf1f43
|
256 megabytes
|
["3\n12 3 45", "2\n123 456"]
|
PASSED
|
import sys
from collections import deque
IS_LOCAL = False
def read_one(dtype=int):
return dtype(input())
def read_multiple(f, dtype=int):
return f(map(dtype, input().split()))
def swap(x, y):
return y, x
def main():
n = 3
a = [12, 3, 45]
if not IS_LOCAL:
n = read_one()
a = read_multiple(list)
d = 998_244_353
s, k = 0, 1
tot = n
z = 0
while tot > 0:
zeroed = 0
for i in range(n):
if a[i] == 0:
continue
t = a[i] % 10
a[i] //= 10
if a[i] == 0:
zeroed += 1
s = (s + t * z * k * 2) % d
s = (s + t * tot * k * k * 11) % d
k *= 10
z += k * zeroed
tot -= zeroed
print(s)
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == 'True':
IS_LOCAL = True
main()
|
1563374100
|
[
"number theory",
"math"
] |
[
0,
0,
0,
1,
1,
0,
0,
0
] |
|
2 seconds
|
["2 3", "6 4 1 4 2"]
|
2c51fa9ddc72caaebb29dd65a2db030e
| null |
There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i.Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.
|
Output n - 1 numbers — new representation of the road map in the same format.
|
The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_006.jsonl
|
a731f2543ab28ad2e2d56ebc1ccc9e44
|
256 megabytes
|
["3 2 3\n2 2", "6 2 4\n6 1 2 4 2"]
|
PASSED
|
import sys
import os
import string
(n,r1,r2)=[int(x) for x in raw_input().split()]
line=[int(x) for x in raw_input().split()]
fa=[0]*(n+1)
j=0
for i in xrange(1,n+1):
if (i==r1):
continue;
fa[i]=line[j]
j+=1
ans=fa[:]
p=r2
while p!=r1:
ans[fa[p]]=p
p=fa[p]
ans[r2]=-1
for t in [str(x) for x in ans if x>0]:
print t,
|
1286802000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["2", "11"]
|
bd7b85c0204f6b36dc07f8a96fc36161
|
NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
|
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
|
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
|
The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 1,400 |
train_018.jsonl
|
f51dde9ddf8a351a16c54a1d9bc2c5a4
|
256 megabytes
|
["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"]
|
PASSED
|
points = []
row_count = int(input())
for _ in range(row_count):
rawLine = input().split()
points.append([int(rawLine[0]),int(rawLine[1])])
total = 0
for i in range(2):
points.sort(key= lambda x : x[i])
previous = 1
for j in range(1,row_count+1):
if j != row_count and points[j][i] == points[j-1][i]:
previous += 1
else:
total += (previous*(previous-1))/2
previous = 1
points.sort(key= lambda x : (x[0],x[1]))
previous = 1
for j in range(1,row_count+1):
if j != row_count and points[j][0] == points[j-1][0] and points[j][1] == points[j-1][1]:
previous += 1
else:
total -= (previous*(previous-1))/2 # Duplicates
previous = 1
print(int(total))
|
1457342700
|
[
"geometry"
] |
[
0,
1,
0,
0,
0,
0,
0,
0
] |
|
3 seconds
|
["4\n10\n4\n0"]
|
afcd41492158e68095b01ff1e88c3dd4
|
NoteIn the first test case of the example, the optimal sequence of moves can be as follows: before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$; choose $$$c=6$$$; now $$$a=[40, 3, 40, 3, 20, 1]$$$; choose $$$c=40$$$; now $$$a=[20, 3, 20, 3, 20, 1]$$$; choose $$$c=20$$$; now $$$a=[10, 3, 10, 3, 10, 1]$$$; choose $$$c=10$$$; now $$$a=[5, 3, 5, 3, 5, 1]$$$ — all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.
|
There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).
|
For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).
|
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_000.jsonl
|
df0e2ae03513f2b9280e19a1df6c8d84
|
256 megabytes
|
["4\n6\n40 6 40 3 20 1\n1\n1024\n4\n2 4 8 16\n3\n3 1 7"]
|
PASSED
|
a = int(input())
for i in range(a):
f = int(input())
k = list(map(int, input().split()))
l = set()
ch = 0
lol = 0
for i in range(len(k)):
lol = k[i]
while lol % 2 == 0:
l.add(lol)
lol /= 2
print(len(l))
|
1576321500
|
[
"number theory"
] |
[
0,
0,
0,
0,
1,
0,
0,
0
] |
|
2 seconds
|
["abcda", "abc"]
|
94278e9c55f0fc82b48145ebecbc515f
|
NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.
|
Print on the single line the lexicographically minimal lucky string whose length equals n.
|
The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,100 |
train_014.jsonl
|
8c22943d44ee2f025a7662ac65bf3b5f
|
256 megabytes
|
["5", "3"]
|
PASSED
|
import sys
n = int(sys.stdin.readline())
s = 'abcd'
if n < 4:
print s[:n]
else:
print s * (n/4) + s[:n%4]
|
1314633600
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
2 seconds
|
["4", "2", "1"]
|
4c2d804bb2781abfb43558f8b2c6424f
|
NoteIn the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
|
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
|
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
|
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_019.jsonl
|
970b06772d12071fc6967ac39b74625d
|
256 megabytes
|
["4\n1 1 1 1", "5\n1 3 2 3 4", "6\n1 3 3 1 3 2"]
|
PASSED
|
n = int(input())
a = sorted(list(map(int,input().split())))
min1 = a[0];min2 = a[1];min3 = a[2]
t = True
if(min1 == min2 and min2 == min3):
cnt = 0
for i in a:
if i == min1:
cnt += 1
cnt = cnt * (cnt-1) * (cnt-2)
print(cnt // 6)
t = False
if(min1 == min2 and t):
cnt12 = 0
cnt3 = 0
for i in a:
if i == min1:
cnt12 += 1
if i == min3:
cnt3 += 1
print((cnt12 * (cnt12 - 1) // 2 ) * cnt3)
if(min1 == min3 and t):
cnt13 = 0
cnt2 = 0
for i in a:
if i == min1:
cnt13 += 1
if i == min2:
cnt2 += 1
print((cnt13 * (cnt13 - 1) // 2 ) * cnt2)
if(min3 == min2 and t):
cnt32 = 0
cnt1 = 0
for i in a:
if i == min3:
cnt32 += 1
if i == min1:
cnt1 += 1
print((cnt32 * (cnt32 - 1) // 2 ) * cnt1)
if(min1 != min2 and min2 != min3 and min1 != min3):
cnt1 = 0;cnt2 = 0;cnt3 = 0
for i in a:
if i == min1:cnt1+=1
if i == min2:cnt2+=1
if i == min3:cnt3+=1
print(cnt1*cnt2*cnt3)
|
1497539100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2", "-1", "3"]
|
fbfc333ad4b0a750f654a00be84aea67
|
NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.
|
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.
|
Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output - 1.
|
The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,600 |
train_003.jsonl
|
c17bef9e474f953bf3699980a800e06d
|
256 megabytes
|
["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"]
|
PASSED
|
import Queue as qq
def bfs(start, target):
LIMIT = 5000000
distances = [float('inf')] * LIMIT
visited = [False] * LIMIT
queue = qq.Queue()
queue.put(start)
visited[start] = True
distances[start] = 0
while not queue.empty():
top = queue.get()
for adjacent in xrange(len(matriz[top])):
if matriz[top][adjacent] != target and not visited[adjacent]:
distances[adjacent] = distances[top] + 1
visited[adjacent] = True
queue.put(adjacent)
return distances[n - 1]
n, m = map(int, raw_input().split())
matriz = [[1 for i in xrange(n)] for j in xrange(n)]
for x in xrange(m):
i, j = map(int, raw_input().split())
i -= 1
j -= 1
matriz[i][j] = 2
matriz[j][i] = 2
res = bfs(0, matriz[0][n - 1])
if res == float('inf'):
print -1
else:
print res
|
1448382900
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
1 second
|
["40\n34\n0"]
|
92bf30e66f4d5ddebb697d2fa4fa0689
|
NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is $$$2 \cdot 5 + 3 \cdot 10 = 40$$$.In second query you have to ell one hamburgers and two chicken burgers. Your income is $$$1 \cdot 10 + 2 \cdot 12 = 34$$$.In third query you can not create any type of burgers because because you have only one bun. So your income is zero.
|
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $$$b$$$ buns, $$$p$$$ beef patties and $$$f$$$ chicken cutlets in your restaurant. You can sell one hamburger for $$$h$$$ dollars and one chicken burger for $$$c$$$ dollars. Calculate the maximum profit you can achieve.You have to answer $$$t$$$ independent queries.
|
For each query print one integer — the maximum profit you can achieve.
|
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains three integers $$$b$$$, $$$p$$$ and $$$f$$$ ($$$1 \le b, ~p, ~f \le 100$$$) — the number of buns, beef patties and chicken cutlets in your restaurant. The second line of each query contains two integers $$$h$$$ and $$$c$$$ ($$$1 \le h, ~c \le 100$$$) — the hamburger and chicken burger prices in your restaurant.
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_008.jsonl
|
34afe74637c7894790adfd36cdd0d9ef
|
256 megabytes
|
["3\n15 2 3\n5 10\n7 5 2\n10 12\n1 100 100\n100 100"]
|
PASSED
|
n = int(input())
for i in range(n):
b,p,f=map(int,input().split())
h,c=map(int,input().split())
p1=h*(min(b//2,p))+c*(min(f,max(0,(b-2*p)//2)))
p2=c*(min(b//2,f))+h*(min(p,max(0,(b-2*f)//2)))
print(max(p1,p2))
|
1566484500
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
2 seconds
|
["2\nMasha\nPetya", "3\nLesha\nPasha\nVanya"]
|
b0301a2d79a1ec126511ed769ec0b743
| null |
When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.
|
The first output line should contain the single number k — the number of people in the sought team. Next k lines should contain the names of the sought team's participants in the lexicographical order. If there are several variants to solve the problem, print any of them. Petya might not be a member of the sought team.
|
The first line contains two integer numbers n (1 ≤ n ≤ 16) — the number of volunteers, and m () — the number of pairs that do not get on. Next n lines contain the volunteers' names (each name is a non-empty string consisting of no more than 10 uppercase and/or lowercase Latin letters). Next m lines contain two names — the names of the volunteers who do not get on. The names in pair are separated with a single space. Each pair of volunteers who do not get on occurs exactly once. The strings are case-sensitive. All n names are distinct.
|
standard output
|
standard input
|
Python 2
|
Python
| 1,500 |
train_018.jsonl
|
d90430691737d4a09ec876fdb32075b3
|
256 megabytes
|
["3 1\nPetya\nVasya\nMasha\nPetya Vasya", "3 0\nPasha\nLesha\nVanya"]
|
PASSED
|
import itertools
def check(combination, enemies):
for a in combination:
for b in combination:
if a != b:
if (a, b) in enemies or (b, a) in enemies:
return False
return True
def main():
n, m = map(int, raw_input().split())
names = [raw_input() for i in xrange(n)]
enemies = set([tuple(raw_input().split()) for i in xrange(m)])
for size in reversed(xrange(1, n + 1)):
for combination in itertools.combinations(names, size):
if check(combination, enemies):
print size
for x in sorted(combination):
print x
return
if __name__ == '__main__':
main()
|
1315494000
|
[
"graphs"
] |
[
0,
0,
1,
0,
0,
0,
0,
0
] |
|
2 seconds
|
["1.154700538379 1.632993161855", "70710.678118654752"]
|
6f8a1a138ea2620f2013f426e29e4d98
|
NoteDefinition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle.
|
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area? Illustration to the first example.
|
The output should contain n - 1 real numbers x1, x2, ..., xn - 1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0 < x1 < x2 < ... < xn - 1 < h must hold. Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .
|
The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 105).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,200 |
train_006.jsonl
|
c79f8bfd21d48d89311a3e7af2d24353
|
256 megabytes
|
["3 2", "2 100000"]
|
PASSED
|
n,h = map(int,input().split())
for x in range(1,n):
print("%.10f"%(h*(x/n)**0.5),end=' ')
|
1494668100
|
[
"geometry",
"math"
] |
[
0,
1,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["15\n15\n0\n299998\n340\n5\n5"]
|
f9287ed16ef943006ffb821ba3678545
|
Note In the first test case they can stick to the following plan: Megan (red circle) moves to the cell $$$(7, 3)$$$. Then she goes to the cell $$$(1, 3)$$$, and Stanley (blue circle) does the same. Stanley uses the portal in that cell (cells with portals are grey) to get to the cell $$$(7, 3)$$$. Then he moves to his destination — cell $$$(7, 5)$$$. Megan also finishes her route and goes to the cell $$$(1, 5)$$$. The total energy spent is $$$(2 + 6) + (2 + 1 + 2) + (2)= 15$$$, which is our final answer.
|
Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $$$n$$$ rows and $$$m$$$ columns. Stanley and Megan can move to an adjacent cell using $$$1$$$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $$$1$$$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $$$(1, 1)$$$) to the lower-right cell (cell with coordinates $$$(n, m)$$$), whilst Megan needs to get from the lower-left cell (cell with coordinates $$$(n, 1)$$$) to the upper-right cell (cell with coordinates $$$(1, m)$$$).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.
|
For each test case print a single integer on a new line – 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 only line in the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 800 |
train_082.jsonl
|
08c2c4ab815526d60a728551ec88b1ea
|
256 megabytes
|
["7\n\n7 5\n\n5 7\n\n1 1\n\n100000 100000\n\n57 228\n\n1 5\n\n5 1"]
|
PASSED
|
# codeforces 816
# prob A
from math import floor
from math import ceil
def solve(n, m):
if m == n == 1:
return 0
if m < n:
return m * 2 - 1 + n - 1
else:
return n * 2 - 1 + m - 1
num = int(input())
for i in range(num):
n, m = map(int, input().split())
print(solve(n, m))
|
1661006100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["YES\ncbabac\nYES\naab\nYES\nzaza\nYES\nbaa\nNO\nYES\nnutforajarofatuna"]
|
e2dc3de62fc45c7e9ddb92daa5c5d8de
|
NoteThe first test case is described in the statement.In the second test case, we can make either "aab" or "aba". But "aba" is a palindrome, so "aab" is the only correct answer.In the third test case, "zaza" and "zzaa" are correct answers, but not "azza".In the fourth test case, "baa" is the only correct answer.In the fifth test case, we can only make "aa", which is a palindrome. So the answer is "NO".In the sixth test case, "anutforajaroftuna" is a palindrome, but inserting 'a' elsewhere is valid.
|
A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.There is a string $$$s$$$. You must insert exactly one character 'a' somewhere in $$$s$$$. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose $$$s=$$$ "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.
|
For each test case, if there is no solution, output "NO". Otherwise, output "YES" followed by your constructed string of length $$$|s|+1$$$ on the next line. If there are multiple solutions, you may print any. You can print each letter of "YES" and "NO" in any case (upper or lower).
|
The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The only line of each test case contains a string $$$s$$$ consisting of lowercase English letters. The total length of all strings does not exceed $$$3\cdot 10^5$$$.
|
standard output
|
standard input
|
PyPy 3-64
|
Python
| 800 |
train_100.jsonl
|
ab1dbb8d79f77a098164763fec2327e7
|
256 megabytes
|
["6\ncbabc\nab\nzza\nba\na\nnutforajaroftuna"]
|
PASSED
|
n = int(input())
while n > 0:
s = input()
if "a" + s != s[::-1] + "a":
print("YES")
print("a" + s)
elif s + "a" != "a" + s[::-1]:
print("YES")
print(s + "a")
else:
print("NO")
n -= 1
|
1617460500
|
[
"strings"
] |
[
0,
0,
0,
0,
0,
0,
1,
0
] |
|
3 seconds
|
["2\n3\n4\n1"]
|
ff0b041d54755984df3706aae78d8ff2
|
NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$.
|
A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$.
|
For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$.
|
Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$).
|
standard output
|
standard input
|
Python 3
|
Python
| 1,500 |
train_110.jsonl
|
b4a412dd3d11f90220e9c676d2d67545
|
256 megabytes
|
["4\n\n7\n\n11\n\n240\n\n17179869184"]
|
PASSED
|
from collections import deque
powerful = [1]
for i in range(2, 16):
powerful.append( i * powerful[-1] )
powerful.append(4)
for i in range(3, 41):
powerful.append( 2 * powerful[-1] )
powerful.sort(reverse=True)
for tcase in range(int(input())):
q = deque()
n, k, i = int(input()), 0, 0
while n > 0:
while i < len(powerful) and powerful[i] > n: i += 1
while i < len(powerful) and n - powerful[i] < 2 * powerful[i]:
q.append((n - powerful[i], k+1, i+1))
i += 1
n, k, i = q.popleft()
print(k)
|
1646408100
|
[
"math"
] |
[
0,
0,
0,
1,
0,
0,
0,
0
] |
|
1 second
|
["1.916666666666666666666666666667"]
|
977aef0dfcf65b60bfe805757057aa73
| null |
You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: Pick a random segment (continuous subsequence) from l to r. All segments are equiprobable. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above.
|
Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
|
The first line contains a single integer n (1 ≤ n ≤ 100 000) — the length of the permutation. The second line contains n distinct integers from 1 to n — elements of the permutation.
|
standard output
|
standard input
|
PyPy 3
|
Python
| 2,400 |
train_076.jsonl
|
a93f478b0633e05e0cef9e3684cc2c7f
|
256 megabytes
|
["3\n2 3 1"]
|
PASSED
|
# Python3 program to count inversions using
# Binary Indexed Tree
# Returns sum of arr[0..index]. This function
# assumes that the array is preprocessed and
# partial sums of array elements are stored
# in BITree[].
def getSum( BITree, index):
sum = 0 # Initialize result
# Traverse ancestors of BITree[index]
while (index > 0):
# Add current element of BITree to sum
sum += BITree[index]
# Move index to parent node in getSum View
index -= index & (-index)
return sum
# Updates a node in Binary Index Tree (BITree)
# at given index in BITree. The given value
# 'val' is added to BITree[i] and all of its
# ancestors in tree.
def updateBIT(BITree, n, index, val):
# Traverse all ancestors and add 'val'
while (index <= n):
# Add 'val' to current node of BI Tree
BITree[index] += val
# Update index to that of parent
# in update View
index += index & (-index)
# Returns count of inversions of size three
def getInvCount(arr, n):
invcount = 0 # Initialize result
# Find maximum element in arrays
maxElement = max(arr)
# Create a BIT with size equal to
# maxElement+1 (Extra one is used
# so that elements can be directly
# be used as index)
BIT = [0] * (maxElement + 1)
for i in range(1, maxElement + 1):
BIT[i] = 0
for i in range(n - 1, -1, -1):
invcount += getSum(BIT, arr[i] - 1)
updateBIT(BIT, maxElement, arr[i], 1)
return invcount
def getInvCountAdv(arr, n):
invcount = 0 # Initialize result
# Find maximum element in arrays
maxElement = max(arr)
# Create a BIT with size equal to
# maxElement+1 (Extra one is used
# so that elements can be directly
# be used as index)
BIT = [0] * (maxElement + 1)
for i in range(1, maxElement + 1):
BIT[i] = 0
for i in range(n - 1, -1, -1):
invcount += (i + 1) * getSum(BIT, arr[i] - 1)
updateBIT(BIT, maxElement, arr[i], n-i)
return invcount
# Driver code
n = int(input())
a = list(map(int,input().split()))
InvCount = getInvCount(a, n)
InvCountAdv = getInvCountAdv(a,n)
thirdSum = 0
for i in range(1,n+1):
thirdSum += i * (i - 1) * (n- i + 1) / 2
print(InvCount - InvCountAdv / (n * (n + 1)) * 2 + thirdSum / (n * (n + 1)))
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
1482165300
|
[
"probabilities"
] |
[
0,
0,
0,
0,
0,
1,
0,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.