contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | def solve(arr,n):
k=0
flag=True
for i in range(n):
if(arr[i]<i):
break
k=i
for i in range(n-k):
if(arr[n-1-i]<i):
flag= False
break
return flag
t=int(input())
while(t>0):
n=int(input())
l=list(map(int,input().split()))
if(solve(l,n)):
print('YES')
else:
print('NO')
t-=1 | py |
1295 | D | D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00. | [
"math",
"number theory"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
def fact(n):
res=n
a=[]
i=2
while i*i<=res:
if res%i==0:
cnt=0
while res%i==0:
cnt+=1
res//=i
a.append((i,cnt))
i+=1
if res!=1:
a.append((res,1))
return a
import math
def solve():
x,m=map(int,input().split())
g=math.gcd(x,m)
m//=g
ans=m
for p,_ in fact(m):
ans=ans//p*(p-1)
print(ans)
for _ in range(int(input())):
solve() | py |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | for _ in range(int(input())):
a, b, c, n = map(int, input().split(' '))
coins = [a, b, c]
coins.sort()
coins_left = n - (coins[2] - coins[0]) - (coins[2] - coins[1])
if coins_left >= 0 and coins_left % 3 == 0:
print("YES")
else:
print("NO") | py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | from collections import Counter, deque, defaultdict
import math
from itertools import permutations, accumulate
from sys import *
from heapq import *
from bisect import bisect_left, bisect_right
from functools import cmp_to_key
from random import randint
xor = randint(10 ** 7, 10**8)
# https://docs.python.org/3/library/bisect.html
on = lambda mask, pos: (mask & (1 << pos)) > 0
lcm = lambda x, y: (x * y) // math.gcd(x,y)
rotate = lambda seq, k: seq[k:] + seq[:k] # O(n)
input = stdin.readline
'''
Check for typos before submit, Check if u can get hacked with Dict (use xor)
Observations/Notes:
'''
for _ in range(int(input())):
n, x = map(int, input().split())
s = input().strip()
ans = 0
curr = 0
seen_ans = False
if curr == x:
ans += 1
seen_ans = True
for char in s:
curr += (char == "0")
curr -= (char == '1')
if curr == x:
seen_ans = True
diff = curr
if curr == 0 and seen_ans:
print(-1)
continue
elif curr == 0:
print(0)
continue
# current_balance = x - (y * diff)
# y * diff = x - current_balance
# y = (x - current_balance) // diff
curr_balance = 0
for i in range(n):
curr_balance += (s[i] == "0")
curr_balance -= (s[i] == '1')
if (x - curr_balance) % diff == 0 and (x - curr_balance) // diff >= 0:
# print(i, "chec", (x - curr_balance) // diff)
ans += 1
print(ans) | py |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | import math
whatever = int(input())
for i in range(whatever):
test_case = input().split()
n = int(test_case[0])
g = int(test_case[1])
b = int(test_case[2])
if g > n:
print(n)
continue
total_days = 0
# goo_days = 0
ngood = math.ceil(n/2)
check = False
if ngood % g == 0:
check = True
divup = math.ceil(ngood / g)
divdown = ngood // g
#print(divup, divdown)
if check:
total_days += (divdown-1) * b
total_days += divdown * g
ngood -= divdown * g
else:
total_days += divdown * b
total_days += divdown * g
ngood -= divdown * g
total_days += ngood
if total_days < n:
print(n)
continue
print(total_days)
| py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | import math
import sys
import bisect
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
Mod = 1000000007
# t = int(input())
t=1
while t>0:
t-=1
#n = q(m+1) + r
n = int(input())
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
a1 = [0]*n
a2 = [0]*n
for i in range(n):
a1[i] = a[i]-b[i]
a2[i] = -a[i]+b[i]
ans = 0
for i in range(n):
if(a1[i]>a2[i]):
ans-=1
a2.sort()
for x in a1:
ans+=bisect.bisect_left(a2,x)
#find index of first elem eql or greater than x
print(ans//2)
| py |
1292 | B | B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that. | [
"brute force",
"constructive algorithms",
"geometry",
"greedy",
"implementation"
] | #OMM NAMH SHIVAY
#JAI SHREE RAM
import sys,math,heapq,queue
from collections import deque
from functools import cmp_to_key
fast_input=sys.stdin.readline
MOD=10**9+7
x0,y0,ax,ay,bx,by=map(int,fast_input().split())
xs,ys,t=map(int,fast_input().split())
temp=[[x0,y0]]
while True:
curx=ax*temp[-1][0]+bx
cury=ay*temp[-1][1]+by
if curx>=xs and cury>=ys and abs(curx-xs)+abs(cury-ys)>t:
break
temp.append([curx,cury])
ans=0
for i in range(len(temp)):
lastx,lasty=xs,ys
c=0
cur=0
for j in range(i,len(temp)):
cur+=abs(temp[j][0]-lastx)+abs(temp[j][1]-lasty)
if cur>t:
break
c+=1
lastx,lasty=temp[j][0],temp[j][1]
ans=max(ans,c)
for i in range(len(temp)-1,-1,-1):
lastx,lasty=xs,ys
c=0
cur=0
for j in range(i,-1,-1):
cur+=abs(temp[j][0]-lastx)+abs(temp[j][1]-lasty)
if cur>t:
break
c+=1
lastx,lasty=temp[j][0],temp[j][1]
ans=max(ans,c)
print(ans)
| py |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | import sys; import math;
CASE=0; rla=''
def solve() :
n=int(rla)
if n&1 :
for i in range(n) : a, b=map(int, input().split())
print("NO"); return
else :
x=[]; y=[]
for i in range(n>>1) :
a, b=map(int, input().split())
x.append(a); y.append(b)
flag=0
a, b=map(int, input().split())
for i in range(1, (n>>1)) :
c, d=map(int, input().split())
if c-a!=x[i-1]-x[i] or d-b!=y[i-1]-y[i] : flag=1
a=c; b=d
print("NO" if flag==1 else "YES")
while True :
rla=sys.stdin.readline()
cases=1
if not rla: break
if (rla=='\n')|(rla=='') : continue
if CASE==1 : cases=int(rla)
for cas in range(cases) :
solve()
| py |
1141 | C | C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1
| [
"math"
] | import sys
input = sys.stdin.readline
n = int(input())
w = list(map(int, input().split()))
x = n-1
l, r, d = 0, 0, 0
c = 0
q = [0]*n
for i, j in enumerate(w):
if c <= 0:
l1 = i
c = j
else:
c += j
if c > d:
d = c
l = l1
r = i + 1
if d == x:
q[l] = 1
for i in range(l+1, n):
q[i] = q[i-1] + w[i-1]
for i in range(l-1, -1, -1):
q[i] = q[i+1] - w[i]
if sorted(q) == list(range(1, n+1)):
print(' '.join(map(str, q)))
exit(0)
l0, r0, d0 = 0, 0, 0
c = 0
for i, j in enumerate(w):
if c >= 0:
l1 = i
c = j
else:
c += j
if c < d0:
d0 = c
l0 = l1
r0 = i + 1
if d0 == -x:
q[r0] = 1
for i in range(r0+1, n):
q[i] = q[i-1] + w[i-1]
for i in range(r0-1, -1, -1):
q[i] = q[i+1] - w[i]
if sorted(q) == list(range(1, n+1)):
print(' '.join(map(str, q)))
exit(0)
print(-1)
| py |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | import sys
input = sys.stdin.readline
from math import sqrt
n,m=map(int,input().split())
k=int(-(-sqrt(n)//1))
E=[[] for i in range(n+1)]
D=[0]*(n+1)
for i in range(m):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
D[x]+=1
D[y]+=1
Q=[(d,i+1) for i,d in enumerate(D[1:])]
import heapq
heapq.heapify(Q)
ANS=[]
USE=[0]*(n+1)
while Q:
d,i=heapq.heappop(Q)
if D[i]!=d or USE[i]==1:
continue
else:
if d>=k-1:
break
else:
ANS.append(i)
USE[i]=1
for to in E[i]:
if USE[to]==0:
USE[to]=1
for to2 in E[to]:
if USE[to2]==0:
D[to2]-=1
heapq.heappush(Q,(D[to2],to2))
#print(ANS)
if len(ANS)>=k:
print(1)
print(*ANS[:k])
sys.exit()
for i in range(1,n+1):
if USE[i]==0:
start=i
break
Q=[start]
ANS=[]
#print(USE)
while Q:
x=Q.pop()
USE[x]=1
ANS.append(x)
for to in E[x]:
if USE[to]==1:
continue
else:
USE[to]=1
Q.append(to)
break
for i in range(len(ANS)):
if ANS[-1] in E[ANS[i]]:
break
ANS=ANS[i:]
print(2)
print(len(ANS))
print(*ANS)
| py |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | """
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
from collections import defaultdict as dd, deque as dq
import math, string
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 10**9+7
"""
how many edges does each node have?
remove the nodes with the K most edges from consideration, then take the maximum of the remaining nodes
dfs through the tree, keeping track of the parent edge
if the count of a node is
"""
def solve():
N, K = getInts()
graph = dd(set)
count = [0]*N
edges = []
for n in range(N-1):
A, B = getInts()
A -= 1
B -= 1
graph[A].add(B)
graph[B].add(A)
count[A] += 1
count[B] += 1
edges.append((min(A,B),max(A,B)))
count2 = []
for i, a in enumerate(count):
count2.append((a,i))
count2.sort(key = lambda x: x[0])
ans = count2[N-K-1][0]
edge_D = dd(int)
visited = set()
@bootstrap
def dfs(node,col):
visited.add(node)
for neighbour in graph[node]:
if neighbour not in visited:
col += 1
col %= ans
edge_D[(min(node,neighbour),max(node,neighbour))] = col+1
yield dfs(neighbour,col)
yield
print(ans)
dfs(1,-1)
ans = [edge_D[(A,B)] for A, B in edges]
print(*ans)
return
#for _ in range(getInt()):
solve() | py |
1301 | B | B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33. | [
"binary search",
"greedy",
"ternary search"
] | t = int(input())
for i in range(t):
n = int(input())
res = 0
a = list(map(int, input().split()))
mina = float('inf')
maxa = 0
res = 0
for i in range(n):
if a[i] == -1:
if i > 0 and a[i-1] != -1:
mina = min(mina, a[i-1])
maxa = max(maxa, a[i-1])
if i < n-1 and a[i+1] != -1:
mina = min(mina, a[i+1])
maxa = max(maxa, a[i+1])
if mina == float('inf'):
print('{} {}'.format(0, 1))
else:
res = (maxa+mina)//2
ans = 0
for i in range(n):
if a[i] == -1:
a[i] = res
if i > 0:
ans = max(ans, abs(a[i]-a[i-1]))
print('{} {}'.format(ans, res))
| py |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | from itertools import permutations
import os
import sys
from io import BytesIO, IOBase
from fractions import Fraction
def main():
t=int(input())
for _ in range(t):
l=int(input())
h=input()
i=0
s=''
while i<len(h):
if int(h[i])%2==1:
s+=h[i]
if len(s)==2:
break
i+=1
if len(s)!=2:
print(-1)
else:
print(s)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main() | py |
1285 | F | F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32 | [
"binary search",
"combinatorics",
"number theory"
] | from math import gcd
max_val = 10**5+1
def solve(arr):
#Lista de Listas que contendrá los divisores de cada uno de los números en el intervalo [1,max_val]
div = [[] for _ in range(max_val)]
#Lista que contendrá el precalculo de la función de Mobius en el intervalo [1,max_val]
mu = [1 for _ in range(max_val)]
#precalculo de los divisores de cada numero en el intervalo [1,max_val]
for i in range(1,max_val):
for j in range(i,max_val,i):
div[j].append(i)
# Precalculo de los valores de la función de Mobius para todos los numeros del intervalo
for i in range(1,max_val):
for d in div[i]:
if d == 1:
continue
if i% (d**2) == 0 or mu[i] == 0:
mu[i] = 0
elif len(div[i]) == 2:
mu[i] = -1
else:
mu[i] = mu[d] * mu[i//d]
# obtener todos los divisores de los números a analizar, para evitar repetirlos, se añaden en un set
nums = set(arr)
for i in arr:
for d in div[i]:
nums.add(d)
#Ordena de mayor a menor los divisores
#creamos una pila donde...
#Creamos un array de frecuencia para contar la cantidad de divisores para cada numero
nums = sorted(list(nums), reverse=True)
stack = []
cnt = [0] * max_val
# calcular la cantidad de divisores de cada numero de la lista y añadir los numeros de la lista en una pila
for i in nums:
stack.append(i)
for d in div[i]:
cnt[d] += 1
# Variable que contendrá el mayot LCM
ans = 0
#Iterando desde el número mayor hasta el menor calcular la cantidad de coprimos en la lista
#Para esto se utiliza el principio de inclusión exclusión apoyandose en la fórmula de Mobius previamente calculada
#Mientras la cantidad de coprimos de un numero x sea mayor que 0 se eliminará el numero en la cima de la pila, se restan los divisores de dichoo número
# como son coprimos los elementos el gcd de ambos va a ser 1, luego, el lcm va a ser la multiplicación de estos
# si el lcm recién calculado maximiza la solución, se actualiza yu se continúna
for x in nums:
count_coprimes = sum(cnt[d] * mu[d] for d in div[x])
while count_coprimes > 0:
a = stack.pop()
for d in div[a]:
cnt[d] -= 1
if gcd(a,x) > 1:
continue
ans = max(a*x, ans)
count_coprimes -= 1
#Finalmente se retorna el lcm más grande
return ans
if __name__ == '__main__':
# Se leen los datos
n = input()
arr = [ int(i) for i in input().split()]
print(solve(arr))
| py |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | for t in range(int(input())):
n = int(input())
cord_list = []
for i in range(n):
x, y = map(int, input().split())
cord_list.append((x, y))
cord_list.sort()
r = 0
u = 0
fir = 0
sec = 0
ans = []
while cord_list:
r = abs(cord_list[0][0] - fir)
u = abs(cord_list[0][1] - sec)
ans.append('R' * r)
ans.append('U' * u)
if cord_list[0][0] < fir or cord_list[0][1] < sec:
print('NO')
break
fir = cord_list[0][0]
sec = cord_list[0][1]
del cord_list[0]
else:
print('YES')
print(''.join(ans))
| py |
1304 | B | B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0
InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string. | [
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"strings"
] | n, m = map(int,input().split())
t = []
ans = ans1 = ""
for i in range(n):
s= input()
r = s[::-1]
if r in t:
ans += r
elif s==r:
ans1 = s
t.append(s)
anss = ans+ans1+ans[::-1]
print(len(anss),anss,end="")
| py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | t = int(input())
for i in range(t):
n = int(input())
ll = list(map(int,input().split()))
ll = sorted(ll,reverse=True)
l1 = []
l2 = []
if n%2 == 0:
l1len = n+1
l2len = n-1
else:
l1len = n
l2len = n
for i in range(len(ll)):
if i % 2 == 0 and len(l1) < l1len:
l1.append(ll[i])
elif len(l2) < l2len:
l2.append(ll[i])
else:
l1.append(ll[i])
print(abs(l1[len(l1)//2] - l2[len(l2)//2])) | py |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | import math
def f():
l1 = input().split(' ')
l2 = input().split(' ')
n = int(l1[0])
x = int(l1[1])
am = 0
for i in range(n):
if int(l2[i]) == x:
print(1)
return 0
am = max(am, int(l2[i]))
if am > x:
print(2)
return 0
else:
print(math.ceil(x/am))
return 0
row = int(input())
for r in range(row):
f()
| py |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | t = int(input())
for i in range(t):
s = input()
s = list(s.split('R'))
maxim = 0
for i in s:
if len(i) > maxim:
maxim = len(i)
print(maxim + 1) | py |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] | '''
Hala Madrid!
https://www.zhihu.com/people/li-dong-hao-78-74
'''
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MI():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
#------------------------------FastIO---------------------------------
from bisect import *
from heapq import *
from collections import *
from functools import *
from itertools import *
from time import *
from random import *
from math import log, gcd, sqrt, ceil
'''
手写栈防止recursion limit
注意要用yield 不要用return
函数结尾要写yield None
'''
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
mod = 998244353
class Factorial:
def __init__(self, N, mod) -> None:
self.mod = mod
self.f = [1 for _ in range(N)]
self.g = [1 for _ in range(N)]
for i in range(1, N):
self.f[i] = self.f[i - 1] * i % self.mod
self.g[-1] = pow(self.f[-1], mod - 2, mod)
for i in range(N - 2, -1, -1):
self.g[i] = self.g[i + 1] * (i + 1) % self.mod
def comb(self, n, m):
return self.f[n] * self.g[m] % self.mod * self.g[n - m] % self.mod
def perm(self, n, m):
return self.f[n] * self.g[n - m] % self.mod
def catalan(self, n):
#TODO: check 2 * n < N#
return (self.comb(2 * n, n) - self.comb(2 * n, n - 1)) % self.mod
FACTORIAL = Factorial(200010, mod)
def solve():
n, m = MI()
if n == 2:
print(0)
else:
print(FACTORIAL.comb(m, n - 1) * (n - 2) % mod * pow(2, n - 3, mod) % mod)
for _ in range(1):solve() | py |
1312 | C | C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2. | [
"bitmasks",
"greedy",
"implementation",
"math",
"number theory",
"ternary search"
] | from collections import deque, defaultdict, Counter
from heapq import heappush, heappop, heapify
from math import inf, sqrt, ceil, log2
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
from typing import List
from bisect import bisect_left, bisect_right
import sys
import string
import random
input=lambda:sys.stdin.readline().strip('\n')
mis=lambda:map(int,input().split())
ii=lambda:int(input())
#sys.setrecursionlimit(2* 10 ** 5 + 1)
T = ii()
for _ in range(T):
N, K = mis()
A = list(mis())
seen = set()
ans = 'YES'
for a in A:
index = 0
while a > 0:
a, mod = divmod(a, K)
if mod > 1:
ans = 'NO'
break
elif mod == 1 and index in seen:
ans = 'NO'
break
elif mod == 1:
seen.add(index)
index += 1
if ans == 'NO':
break
print(ans)
| py |
1311 | B | B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES
| [
"dfs and similar",
"sortings"
] | for _ in range(int(input())):
n, m = map(int, input().split())
arr = list(map(int, input().split(' ')))
nums = list(map(int, input().split(' ')))
while True:
flag = False
for i in range(m):
if arr[nums[i] - 1] > arr[nums[i]]:
arr[nums[i] - 1], arr[nums[i]] = arr[nums[i]], arr[nums[i] - 1]
flag = True
if not flag: break
ans = 'YES'
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
ans = 'NO'
break
print(ans)
| py |
1305 | B | B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations. | [
"constructive algorithms",
"greedy",
"strings",
"two pointers"
] | s = list(input())
ans = []
while True:
temp = []
l = 0
r = len(s) - 1
while l < r:
while l < r and s[l] != "(":
l += 1
while l < r and s[r] != ")":
r -= 1
if l < r and s[l] == "(" and s[r] == ")":
s[l] = "0"
s[r] = "0"
l += 1
r -= 1
temp.extend([l, r+2])
if not temp:
break
ans.append(sorted(temp))
new_s = []
for ch in s:
if ch != "0":
new_s.append(ch)
s = new_s
print(len(ans))
for a in ans:
print(len(a))
print(*a) | py |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] |
n,m,p = tuple(map(int,input().split()))
a = list(map(int,input().split()))
b = list(map(int,input().split()))
i =0
while i<n:
if a[i]%p != 0:
break
i+=1
j =0
while j<m:
if b[j]%p != 0:
break
j+=1
print(i+j)
| py |
1307 | D | D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. | [
"binary search",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"shortest paths",
"sortings"
] | import sys
from array import array
from collections import deque
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
out, tests = [], 1
class graph:
def __init__(self, n):
self.n = n
self.gdict = [array('i') for _ in range(n + 1)]
def add_edge(self, node1, node2):
self.gdict[node1].append(node2)
self.gdict[node2].append(node1)
def bfs_util(self, root):
visit, self.dist = array('b', [0] * (self.n + 1)), [0] * (self.n + 1)
queue, visit[root] = deque([root]), True
while queue:
s = queue.popleft()
for i1 in self.gdict[s]:
if visit[i1] == False:
queue.append(i1)
visit[i1], self.dist[i1] = True, self.dist[s] + 1
return self.dist
for _ in range(tests):
n, m, k = inp(int)
sp = array('i', inp(int))
g, ans = graph(n), 0
for i in range(m):
u, v = inp(int)
g.add_edge(u, v)
dist1 = g.bfs_util(1)
distn = g.bfs_util(n)
sor = array('i', sorted(range(k), key=lambda x: dist1[sp[x]] - distn[sp[x]]))
suf = 0
for ix in range(k - 2, -1, -1):
i, suf = sor[ix], max(suf, distn[sp[sor[ix + 1]]])
ans = max(ans, suf + dist1[sp[i]] + 1)
out.append(min(ans, dist1[n]))
print('\n'.join(map(str, out)))
| py |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc 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.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
input = sys.stdin.buffer.readline
def process_root(g, r):
start = [r]
seen = {r: 0}
parent = {r: None}
while len(start) > 0:
next_s = []
for x in start:
for y in g[x]:
if y not in seen:
seen[y] = seen[x]+1
parent[y] = x
next_s.append(y)
start = next_s
return seen, parent
def find_diameter(g):
for x in g:
break
seen, parent = process_root(g, x)
my_max = [0, x]
for y in seen:
if seen[y] > my_max[0]:
my_max = [seen[y], y]
a = my_max[1]
seen, parent = process_root(g, a)
my_max = [0, a]
for y in seen:
if seen[y] > my_max[0]:
my_max = [seen[y], y]
c = my_max[1]
L = [c]
while L[-1] != a:
x = parent[L[-1]]
L.append(x)
return L, parent
def process(G):
#we want three vertices a b c to maximize edges on paths between them
#if b is on path from a to c then we don't get helped.
#so none of them is on the path between the other two.
#say path from b to a intersects path from c to a at x
#a0 = a, a1, a2, a3, ..., ak = c
#x =ai , 0 < i < k
#a, c = diameter of tree
#b = longest branch off diameter?
g = {}
n = len(G)
for i in range(n):
a, b = G[i]
if a not in g:
g[a] = set([])
if b not in g:
g[b] = set([])
g[a].add(b)
g[b].add(a)
L, parent = find_diameter(g)
a, c = L[0], L[-1]
b = L[1]
L = set(L)
distance = {}
answer = [0, None]
for x in g:
if len(g[x])==1 and x != a and x != c:
L2 = [x]
while L2[-1] not in distance:
L2.append(parent[L2[-1]])
if L2[-1] in L:
distance[L2[-1]] = 0
break
L2.pop()
while len(L2) > 0:
x2 = L2.pop()
distance[x2] = distance[parent[x2]]+1
answer = max([distance[x], x], answer)
if answer[1] is None:
path_length = len(L)-1
return [path_length, a, b, c]
else:
b = answer[1]
path_length = len(L)-1+answer[0]
return [path_length, a, b, c]
n = int(input())
G = []
for i in range(n-1):
a, b = [int(x) for x in input().split()]
G.append([a, b])
path_length, a, b, c = process(G)
print(path_length)
print(f'{a} {b} {c}') | py |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | import collections
import math
def prime_range(n):
sieve = [0] * n
pid = {1: 0}
for i in range(2, n):
if not sieve[i]:
sieve[i] = i
pid[i] = len(pid)
for j in range(i * i, n, i):
if not sieve[j]:
sieve[j] = i
return sieve, pid
def odd_prime_factors(a, min_p_factor):
f = collections.Counter()
while a > 1:
x = min_p_factor[a]
f[x] ^= 1
a //= x
return [x for x in f if f[x]]
def shortest_cycle(root, g):
if not g[root]:
return math.inf
# -1 is faster than None (PyPy)
depth = [-1] * len(g)
depth[root] = 0
queue = collections.deque([(root, None)])
while queue:
u, parent = queue.popleft()
for v in g[u]:
if depth[v] is -1:
depth[v] = depth[u] + 1
queue.append((v, u))
elif v != parent:
return depth[u] + depth[v] + 1
return math.inf
min_p_factor, pid = prime_range(10**6 + 1)
input()
g = [[] for _ in range(len(pid))]
for x in map(int, input().split()):
f = odd_prime_factors(x, min_p_factor)
if not f:
print(1)
exit()
f.append(1)
u, v = pid[f[0]], pid[f[1]]
g[u].append(v)
g[v].append(u)
shortest = min(shortest_cycle(i, g) for i in range(169)) # pid[1009] == 169
print(shortest if math.isfinite(shortest) else -1)
| py |
1321 | A | A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | [
"greedy"
] | n = int(input())
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
total1 = sum(arr1)
total2 = sum(arr2)
count = 0
ones = 0
for i in range(len(arr1)):
if arr1[i] == 1 and arr2[i] == 0:
count += 1
elif arr1[i] == 1 and arr2[i] == 1:
ones += 1
needed = -1
if total1 > total2:
print(1)
exit()
if count >= 1 and total1 <= total2:
total2 = total2 - ones
needed = total2//count + 1
print(needed) | py |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
class LowestCommonAncestor:
""" <O(n), O(log(n))> """
def __init__(self, G: "隣接リスト", root: "根", parents):
from collections import deque
self.n = len(G)
self.tour = [0] * (2 * self.n - 1)
self.depth_list = [0] * (2 * self.n - 1)
self.id = [-1] * self.n
self.dfs(G, root, parents)
self._rmq_init(self.depth_list)
def _rmq_init(self, arr):
n = self.mod = len(arr)
self.seg_len = 1 << (n - 1).bit_length()
self.seg = [self.n * n] * (2 * self.seg_len)
seg = self.seg
for i, e in enumerate(arr):
seg[self.seg_len + i] = n * e + i
for i in range(self.seg_len - 1, 0, -1):
seg[i] = min(seg[2 * i], seg[2 * i + 1])
def _rmq_query(self, l, r):
"""最小値となるindexを返す"""
l += self.seg_len; r += self.seg_len
res = self.n * self.mod
seg = self.seg
while l < r:
if r & 1:
r -= 1
res = min(res, seg[r])
if l & 1:
res = min(res, seg[l])
l += 1
l >>= 1; r >>= 1
return res % self.mod
def dfs(self, G, root, parents):
""" 非再帰で深さ優先探索を行う """
id = self.id
tour = self.tour
depth_list = self.depth_list
v = root
it = [0] * self.n
visit_id = 0
depth = 0
while v != -1:
if id[v] == -1:
id[v] = visit_id
tour[visit_id] = v
depth_list[visit_id] = depth
visit_id += 1
g = G[v]
if it[v] == len(g):
v = parents[v]
depth -= 1
continue
if g[it[v]] == parents[v]:
it[v] += 1
if it[v] == len(g):
v = parents[v]
depth -= 1
continue
else:
child = g[it[v]]
it[v] += 1
v = child
depth += 1
else:
child = g[it[v]]
it[v] += 1
v = child
depth += 1
def lca(self, u: int, v: int) -> int:
""" u と v の最小共通祖先を返す """
l, r = self.id[u], self.id[v]
if r < l:
l, r = r, l
q = self._rmq_query(l, r + 1)
return self.tour[q]
def dist(self, u: int, v: int) -> int:
""" u と v の距離を返す """
lca = self.lca(u, v)
depth_u = self.depth_list[self.id[u]]
depth_v = self.depth_list[self.id[v]]
depth_lca = self.depth_list[self.id[lca]]
return depth_u + depth_v - 2 * depth_lca
n=int(input())
edge=[[] for i in range(n)]
edge_id={}
for i in range(n-1):
x,y=map(lambda x:int(x)-1,input().split())
edge[x].append(y)
edge[y].append(x)
edge_id[(x<<20)+y]=i
edge_id[(y<<20)+x]=i
par=[-1]*n
todo=[(0,-1)]
while todo:
v,p=todo.pop()
for u in edge[v]:
if p!=u:
par[u]=v
todo.append((u,v))
lca=LowestCommonAncestor(edge,0,par)
q=int(input())
c=[]
for i in range(q):
x,y,g=map(int,input().split())
c.append((g,x-1,y-1))
c.sort(reverse=True)
def find_pass(frm,to):
L=lca.lca(frm,to)
now=frm
pass1=[]
while now!=L:
p=par[now]
pass1.append(edge_id[(now<<20)+p])
now=p
now=to
pass2=[]
while now!=L:
p=par[now]
pass2.append(edge_id[(now<<20)+p])
now=p
return pass1+pass2[::-1]
color=[-1]*(n-1)
for g,x,y in c:
flag=False
for id in find_pass(x,y):
if color[id]==-1 or color[id]==g:
color[id]=g
flag=True
if not flag:
print(-1)
exit()
for i in range(n-1):
if color[i]==-1:
color[i]=10**6
print(*color) | py |
1141 | G | G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1 | [
"binary search",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"trees"
] | n, k = map(int, input().split(' '))
deg = [0] * n
neighbors = [[] for i in range(n)]
edges = []
for i in range(n - 1):
a, b = map(int, input().split(' '))
neighbors[a - 1].append(b - 1)
neighbors[b - 1].append(a - 1)
deg[a - 1] += 1
deg[b - 1] += 1
edges.append((a - 1, b - 1))
deg = list(sorted(deg))
r = deg[-(k + 1)]
print(r)
from collections import deque
colors = {}
q = deque()
q.append((None, 0))
while q:
par, node = q.popleft()
parcolor = None if par is None else colors[(par, node)]
color = 0 if parcolor != 0 else 1
deg = len(neighbors[node])
for neigh in neighbors[node]:
if neigh != par:
if deg > r:
colors[(node, neigh)] = 0 if parcolor is None else parcolor
else:
colors[(node, neigh)] = color
color += 1
if color == parcolor:
color += 1
q.append((node, neigh))
for a, b in edges:
if (a, b) in colors:
print(colors[(a, b)] + 1, end=' ')
else:
print(colors[(b, a)] + 1, end=' ')
| py |
1299 | B | B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements. | [
"geometry"
] | import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
def isParallel(p1a,p1b,p2a,p2b):
dx1=p1a[0]-p1b[0]
dy1=p1a[1]-p1b[1]
dx2=p2a[0]-p2b[0]
dy2=p2a[1]-p2b[1]
return dx1==dx2 and dy1==dy2
n=int(input())
xy=[] #[[x,y]]
for _ in range(n):
a,b=[int(z) for z in input().split()]
xy.append([a,b])
#YES if each line is parallel to another line
xy.sort(key=lambda z:(z[0],z[1])) #sort by x then y.
#xy[0] will match with xy[n-1],xy[1] will match with xy[n-2] etc.
if n%2==1:
print('NO')
else:
ans='YES'
for i in range(n//2):
p1a=xy[i]
p1b=xy[i+1]
j=n-1-i
p2a=xy[j-1]
p2b=xy[j]
if not isParallel(p1a,p1b,p2a,p2b):
ans='NO'
break
print(ans) | py |
1305 | A | A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100) — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000) — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement. | [
"brute force",
"constructive algorithms",
"greedy",
"sortings"
] | t=int(input())
while(t>0):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
b.sort()
for i in range(n):
print(a[i],end=" ")
print()
for i in range(n):
print(b[i],end=" ")
print()
t=t-1 | py |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | import math
a = int(input())
n = 0
for i in range(2,a):
x=a
while x:
n+=x%i
x//=i
b=math.gcd(n,a-2)
print(str(n//b)+'/'+str((a-2)//b)) | py |
1284 | C | C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32. | [
"combinatorics",
"math"
] | n, m = map(int, input().split())
f = [1]
for i in range(1, 250001):
f.append(f[-1] * i % m)
ans = 0
for i in range(1, n + 1):
ans += ((((f[i] * f[n-i]) % m)) * (n - i + 1) * (n - i + 1)) % m
#print(ans)
print(ans % m)
| py |
1316 | E | E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1. | [
"bitmasks",
"dp",
"greedy",
"sortings"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, p, k = map(int, input().split())
a = list(map(float, input().split()))
s = [tuple(map(float, input().split())) for _ in range(n)]
b = [(a[i], i) for i in range(n)]
b.sort(reverse = True)
pow2 = [1]
for _ in range(p):
pow2.append(2 * pow2[-1])
m = pow2[p]
dp0 = [-1.0] * m
dp0[0] = 0.0
dp = [-1.0] * m
c = [bin(i).count("1") for i in range(m)]
u = 0
for ai, i in b:
u += 1
si = s[i]
for j in range(m):
if dp0[j] < 0:
continue
cj = c[j]
dp0j = dp0[j]
if u - cj <= k:
dp[j] = max(dp[j], dp0j + ai)
else:
dp[j] = max(dp[j], dp0j)
for l in range(p):
pl = pow2[l]
if j & pl:
continue
dp[j ^ pl] = max(dp[j ^ pl], dp0j + si[l])
dp0, dp = dp, dp0
ans = int(dp0[-1])
print(ans) | py |
1290 | C | C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n) — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n) — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111. | [
"dfs and similar",
"dsu",
"graphs"
] | import sys
readline = sys.stdin.readline
class UF():
def __init__(self, num):
self.par = [-1]*num
self.weight = [0]*num
def find(self, x):
if self.par[x] < 0:
return x
else:
stack = []
while self.par[x] >= 0:
stack.append(x)
x = self.par[x]
for xi in stack:
self.par[xi] = x
return x
def union(self, x, y):
rx = self.find(x)
ry = self.find(y)
if rx != ry:
if self.par[rx] > self.par[ry]:
rx, ry = ry, rx
self.par[rx] += self.par[ry]
self.par[ry] = rx
self.weight[rx] += self.weight[ry]
return rx
N, K = map(int, readline().split())
S = list(map(int, readline().strip()))
A = [[] for _ in range(N)]
for k in range(K):
BL = int(readline())
B = list(map(int, readline().split()))
for b in B:
A[b-1].append(k)
cnt = 0
T = UF(2*K)
used = set()
Ans = [None]*N
inf = 10**9+7
for i in range(N):
if not len(A[i]):
Ans[i] = cnt
continue
kk = 0
if len(A[i]) == 2:
x, y = A[i]
if S[i]:
rx = T.find(x)
ry = T.find(y)
if rx != ry:
rx2 = T.find(x+K)
ry2 = T.find(y+K)
sp = min(T.weight[rx], T.weight[rx2]) + min(T.weight[ry], T.weight[ry2])
if x not in used:
used.add(x)
T.weight[rx] += 1
if y not in used:
used.add(y)
T.weight[ry] += 1
rz = T.union(rx, ry)
rz2 = T.union(rx2, ry2)
sf = min(T.weight[rz], T.weight[rz2])
kk = sf - sp
else:
rx = T.find(x)
ry2 = T.find(y+K)
sp = 0
if rx != ry2:
ry = T.find(y)
rx2 = T.find(x+K)
sp = min(T.weight[rx], T.weight[rx2]) + min(T.weight[ry], T.weight[ry2])
if x not in used:
used.add(x)
T.weight[rx] += 1
if y not in used:
used.add(y)
T.weight[ry] += 1
rz = T.union(rx, ry2)
rz2 = T.union(rx2, ry)
sf = min(T.weight[rz], T.weight[rz2])
kk = sf - sp
else:
if S[i]:
x = A[i][0]
rx = T.find(x)
rx2 = T.find(x+K)
sp = min(T.weight[rx], T.weight[rx2])
T.weight[rx] += inf
sf = min(T.weight[rx], T.weight[rx2])
kk = sf - sp
else:
x = A[i][0]
rx = T.find(x)
rx2 = T.find(x+K)
sp = min(T.weight[rx], T.weight[rx2])
T.weight[rx2] += inf
if x not in used:
used.add(x)
T.weight[rx] += 1
sf = min(T.weight[rx], T.weight[rx2])
kk = sf-sp
Ans[i] = cnt + kk
cnt = Ans[i]
print('\n'.join(map(str, Ans)))
| py |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | import math
# def sieve(n):
# arr = [True]*(n+1)
# arr[0] = False
# arr[1] = False
# for p in range(2,math.ceil(pow(n,0.5))):
# if arr[p] == False:
# continue
# for j in range(p*p,n+1,p):
# arr[j] = False
# res = []
# for p in range(2,n+1):
# if arr[p]:
# res.append(p)
# return res
def prime_factors(n):
arr = []
# make it odd
s = bin(n)[2:][::-1]
zero = 0
for e in s:
if e == '0':
zero += 1
else:
break
n = n >> zero
if zero >= 1:
arr.append(2)
for e in range(3,math.ceil(pow(n,0.5)) + 1,2):
if n%e == 0:
arr.append(e)
while n % e == 0:
n = n//e
if n > 1: arr.append(n)
return arr
# print(prime_factors(2*3*107*31*27*193))
def find(arr,e):
res = 0
for x in arr:
if x < e:
res += e - x
# print(e-x%e)
else:
res += min(x%e,e - x%e)
# print(min(x%e,e - x%e))
return res
import random
n = int(input())
arr = [int(x) for x in input().split()]
limit = min(8, n)
iterations = [x for x in range(n)]
random.shuffle(iterations)
iterations = iterations[:limit]
prime_list = set()
for i in iterations:
x = arr[i]
for d in [x-1,x,x+1]:
prime_list = prime_list.union(set(prime_factors(d)))
res = n
for prime in prime_list:
res = min(res,find(arr,prime))
print(res)
| py |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | import sys
input = sys.stdin.readline
n,m,p=map(int,input().split())
W=[tuple(map(int,input().split())) for i in range(n)]
A=[tuple(map(int,input().split())) for i in range(m)]
M=[tuple(map(int,input().split())) for i in range(p)]
Q=[[] for i in range(10**6+1)]
for x,y,c in M:
Q[x].append((c,y))
for x,c in W:
Q[x-1].append((c,0))
seg_el=1<<((10**6+1).bit_length())
SEGMAX=[-2147483648]*seg_el
for x,y in A:
SEGMAX[x-1]=max(SEGMAX[x-1],-y)
for i in range(seg_el-2,-1,-1):
SEGMAX[i]=max(SEGMAX[i+1],SEGMAX[i])
SEGMAX=[-2147483648]*(seg_el)+SEGMAX
for i in range(seg_el-1,0,-1):
SEGMAX[i]=max(SEGMAX[i*2],SEGMAX[(i*2)+1])
SEGADD=[0]*(2*seg_el)
def adds(l,r,x):
L=l+seg_el
R=r+seg_el
while L<R:
if L & 1:
SEGADD[L]+=x
L+=1
if R & 1:
R-=1
SEGADD[R]+=x
L>>=1
R>>=1
L=(l+seg_el)>>1
R=(r+seg_el-1)>>1
while L!=R:
if L>R:
SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)])
L>>=1
else:
SEGMAX[R]=max(SEGMAX[R*2]+SEGADD[R*2],SEGMAX[1+(R*2)]+SEGADD[1+(R*2)])
R>>=1
while L!=0:
SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)])
L>>=1
ANS=-2147483648
for i in range(10**6+1):
for c,y in Q[i]:
if y==0:
ANS=max(ANS,SEGMAX[1]-c)
else:
adds(y,seg_el,c)
print(ANS)
| py |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | n = int(input())
ans = 0
x = n
for i in range(n):
ans += 1 / x
x -= 1
print(ans) | py |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
if sum(a) % 2 == 1:
print("YES")
elif any((a[i] - a[j]) % 2 == 1 for i in range(n) for j in range(i+1, n)):
print("YES")
else:
print("NO")
| py |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | import sys
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
n = int(input())
s = input()
min_r = s
k = 1
for i in range(1, n):
if i % 2 == n % 2:
temp = s[i:] + s[:i]
else:
temp = s[i:] + s[:i][::-1]
if temp < min_r:
min_r = temp
k = i + 1
print(min_r)
print(k) | py |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | t=int(input())
op=[]
for i in range(t):
m,n=map(int,input().split(' '))
if m%n==0:
op.append('YES')
else:
op.append('NO')
for i in op:
print(i) | py |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc 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.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import random, sys, os, math, gc
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce, cmp_to_key
from itertools import accumulate, combinations, permutations, product
from heapq import nsmallest, nlargest, heapify, heappop, heappush
from io import BytesIO, IOBase
from copy import deepcopy
from bisect import bisect_left, bisect_right
from math import factorial, gcd
from operator import mul, xor
from types import GeneratorType
# if "PyPy" in sys.version:
# import pypyjit; pypyjit.set_param('max_unroll_recursion=-1')
# sys.setrecursionlimit(2*10**5)
BUFSIZE = 8192
MOD = 10**9 + 7
MODD = 998244353
INF = float('inf')
D4 = [(1, 0), (0, 1), (-1, 0), (0, -1)]
D8 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
class JumpOnTree:
def __init__(self, edges, root=0):
self.n = len(edges)
self.edges = edges
self.root = root
self.logn = (self.n - 1).bit_length()
self.depth = [-1] * self.n
self.depth[self.root] = 0
self.parent = [[-1] * self.n for _ in range(self.logn)]
self.dfs()
self.doubling()
def dfs(self):
stack = [self.root]
while stack:
u = stack.pop()
for v in self.edges[u]:
if self.depth[v] == -1:
self.depth[v] = self.depth[u] + 1
self.parent[0][v] = u
stack.append(v)
def doubling(self):
for i in range(1, self.logn):
for u in range(self.n):
p = self.parent[i - 1][u]
if p != -1:
self.parent[i][u] = self.parent[i - 1][p]
def lca(self, u, v):
du = self.depth[u]
dv = self.depth[v]
if du > dv:
du, dv = dv, du
u, v = v, u
d = dv - du
i = 0
while d > 0:
if d & 1:
v = self.parent[i][v]
d >>= 1
i += 1
if u == v:
return u
logn = (du - 1).bit_length()
for i in range(logn - 1, -1, -1):
pu = self.parent[i][u]
pv = self.parent[i][v]
if pu != pv:
u = pu
v = pv
return self.parent[0][u]
def jump(self, u, v, k):
if k == 0:
return u
p = self.lca(u, v)
d1 = self.depth[u] - self.depth[p]
d2 = self.depth[v] - self.depth[p]
if d1 + d2 < k:
return -1
if k <= d1:
d = k
else:
u = v
d = d1 + d2 - k
i = 0
while d > 0:
if d & 1:
u = self.parent[i][u]
d >>= 1
i += 1
return u
def dist(self, u, v):
return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)]
def solve():
n = II()
d = getGraph(n, n-1)
tree = JumpOnTree(d)
t1 = 0
c = 0
for i in range(1, n):
if tree.dist(0, i) > c:
c = tree.dist(0, i)
t1 = i
t2 = 0
c = 0
for i in range(n):
if tree.dist(t1, i) > c:
c = tree.dist(t1, i)
t2 = i
q = []
dist = [INF] * n
ans = [t1, t2]
while t1 != t2:
q.append(t1)
dist[t1] = 0
t1 = tree.jump(t1, t2, 1)
dist[t2] = 0
q.append(t2)
for i in q:
for j in d[i]:
if dist[j] > dist[i] + 1:
dist[j] = dist[i] + 1
q.append(j)
t = dist.index(max(dist))
t1, t2 = ans
while t in [t1, t2]:
t += 1
ans.append(t)
print(dist[t] + tree.dist(t1, t2))
print(*[i + 1 for i in ans])
def main():
t = 1
# t = II()
for _ in range(t):
solve()
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def bitcnt(n):
c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)
c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333)
c = (c & 0x0F0F0F0F0F0F0F0F) + ((c >> 4) & 0x0F0F0F0F0F0F0F0F)
c = (c & 0x00FF00FF00FF00FF) + ((c >> 8) & 0x00FF00FF00FF00FF)
c = (c & 0x0000FFFF0000FFFF) + ((c >> 16) & 0x0000FFFF0000FFFF)
c = (c & 0x00000000FFFFFFFF) + ((c >> 32) & 0x00000000FFFFFFFF)
return c
def lcm(x, y):
return x * y // gcd(x, y)
def lowbit(x):
return x & -x
def perm(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def comb(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def probabilityMod(x, y, mod):
return x * pow(y, mod-2, mod) % mod
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin = IOWrapper(sys.stdin)
# sys.stdout = IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def I():
return input()
def II():
return int(input())
def MI():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
def getGraph(n, m, directed=False):
d = [[] for _ in range(n)]
for _ in range(m):
u, v = LGMI()
d[u].append(v)
if not directed:
d[v].append(u)
return d
def getWeightedGraph(n, m, directed=False):
d = [[] for _ in range(n)]
for _ in range(m):
u, v, w = LII()
u -= 1; v -= 1
d[u].append((v, w))
if not directed:
d[v].append((u, w))
return d
if __name__ == "__main__":
main() | py |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | t = int(input())
for i in range(t):
k = int(input())
a = input()
angry = False
patient = 0
ans = 0
for j in range(len(a)):
if a[j] == 'A':
angry = True
ans = max(ans, patient)
patient = 0
elif a[j] == 'P' and angry:
patient += 1
ans = max(ans, patient)
print(ans)
| py |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | t = int(input())
for Cases in range(t):
n = int(input()); a = list(map(int,input().split()))
dp = [0]*(n); dp[0] = a[0]; rem = [0]*n
for i in range(1,n):
dp[i] = max(dp[i-1]+a[i],a[i])
if dp[i] == a[i]: rem[i] = i
elif dp[i] == dp[i-1]+a[i]: rem[i] = rem[i-1]
if sum(a) > max(dp): print("YES")
elif sum(a) == max(dp) and dp.count(sum(a)) == 1\
and sum(a) == dp[-1] and rem[-1] == 0: print("YES")
else: print("NO") | py |
1287 | A | A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry. | [
"greedy",
"implementation"
] | from itertools import groupby
for _ in range(int(input())):
input()
ans = 0
for i, (k, v) in enumerate(groupby(input())):
if i != 0 and k == "P":
ans = max(ans, sum(1 for _ in v))
print(ans)
| py |
1291 | F | F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 2n2k≤20 0002n2k≤20 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 2n2k≤20 0002n2k≤20 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"graphs",
"interactive"
] | from sys import stdout
class Mock:
def __init__(self, cap, a):
self.a, self.cap = a, cap
self.n, self.q = len(a), []
def ask(self, i):
result = self.a[i] in self.q
self.q.append(self.a[i])
if len(self.q) > self.cap:
self.q = self.q[1:]
return result
def reset(self):
self.q = []
def out(self, result):
print('!', result)
class IO:
def __init__(self):
self.n, self.cap = map(int, input().split())
def ask(self, i):
print('?', i + 1)
stdout.flush()
return input() == 'Y'
def reset(self):
print('R')
stdout.flush()
def out(self, result):
print('!', result)
def solve(io):
n, cap = io.n, io.cap
size = cap + 1 >> 1
count = n // size
removed = [False] * n
for d in range(1, count):
for r in range(min(d, count - d)):
for i in range(r, count, d):
for j in range(i * size, (i + 1) * size):
if not removed[j] and io.ask(j):
removed[j] = True
io.reset()
return removed.count(False)
# io = Mock(2, [1, 4, 1, 3])
# io.out(solve(io))
# io = Mock(8, [1, 2, 3, 4, 5, 6, 6, 6])
# io.out(solve(io))
io = IO()
io.out(solve(io)) | py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] |
def main():
n=int(input())
adj=[set() for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].add(v)
adj[v].add(u)
leaves=set()
for i in range(1,n+1):
if len(adj[i])==1:
leaves.add(i)
#Iteratively remove leaves. Each pair of leaves will eliminate 2 nodes.
while True:
u=leaves.pop()
v=leaves.pop()
u2=next(iter(adj[u]))
v2=next(iter(adj[v]))
# print('u:{} v:{} u2:{} v2:{} adj:{};'.format(u,v,u2,v2,adj))
adj[u2].remove(u)
adj[v2].remove(v)
if len(adj[u2])==1:leaves.add(u2)
if len(adj[v2])==1:leaves.add(v2)
w=queryInteractive(u,v)
if u==w or v==w or len(leaves)==0:
answerInteractive(w)
break
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# import sys
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
main() | py |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
# sys.setrecursionlimit(10000000)
inf = float('inf')
eps = 10 ** (-15)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
N = getN()
S = [ord(s) - ord('a') for s in input()]
S = [[S[i], i] for i in range(N)]
S.sort(key = lambda i:i[1], reverse = True)
S.sort(key = lambda i:i[0], reverse = True)
seg = [inf for i in range(27)]
ans = [0] * N
for _, ind in S:
c = 1
while seg[c] < ind:
c += 1
ans[ind] = c
seg[c] = min(seg[c], ind)
print(max(ans))
print(*ans) | py |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | I=input
exec(int(I())*"I();a=[*map(int,I().split())];s=a.count(0);print(s+(s+sum(a)==0));") | py |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | import sys
input = sys.stdin.readline
n, a, b, k = map(int, input().split())
w = list(map(int, input().split()))
d = []
x = a + b
for i in w:
if i % x == 0:
i = x
else:
i %= x
d.append(i)
d.sort()
c = 0
x = 0
for i in d:
x = i//a - (i%a==0)
if k >= x:
k -= x
c += 1
else:
break
print(c)
| py |
1311 | A | A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66. | [
"greedy",
"implementation",
"math"
] | for _ in range(int(input())):
a,b=map(int,input().split())
if a==b:
print(0)
elif ((b-a)%2==1 and a<b) or ((b-a)%2==0 and a>b):
print(1)
else:
print(2)
| py |
1303 | E | E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES
| [
"dp",
"strings"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
def solve():
s=input()
t=input()
ns=len(s)
nt=len(t)
inf=10**9
for i in range(nt):
t1=t[:i]
t2=t[i:]
n1=len(t1)
n2=len(t2)
dp=[-1]*(n1+1)
dp[0]=0
for j in range(ns):
ndp=[-1]*(n1+1)
for k in range(n1+1):
if dp[k]==-1:
continue
ndp[k]=max(ndp[k],dp[k])
if k!=n1 and s[j]==t1[k]:
ndp[k+1]=max(ndp[k+1],dp[k])
if dp[k]!=n2 and s[j]==t2[dp[k]]:
ndp[k]=max(ndp[k],dp[k]+1)
dp=ndp
if dp[n1]==n2:
print('YES')
return
print('NO')
for _ in range(int(input())):
solve() | py |
1290 | D | D. Coffee Varieties (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn cafés in this city, where nn is a power of two. The ii-th café produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,…,ana1,…,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the café cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30 00030 000 times.More formally, the memory of your friend is a queue SS. Doing a query on café cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 3n22k3n22k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It is guaranteed that 3n22k≤15 0003n22k≤15 000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the café cc, in a separate line output? ccWhere cc must satisfy 1≤c≤n1≤c≤n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30 00030 000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 3n22k3n22k queries of type ? or you asked more than 30 00030 000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1≤k≤n≤10241≤k≤n≤1024, kk and nn are powers of two).It must hold that 3n22k≤15 0003n22k≤15 000.The third line should contain nn integers a1,a2,…,ana1,a2,…,an, separated by spaces (1≤ai≤n1≤ai≤n).ExamplesInputCopy4 2
N
N
Y
N
N
N
N
OutputCopy? 1
? 2
? 3
? 4
R
? 4
? 1
? 2
! 3
InputCopy8 8
N
N
N
N
Y
Y
OutputCopy? 2
? 6
? 4
? 5
? 2
? 5
! 6
NoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5. | [
"constructive algorithms",
"graphs",
"interactive"
] | from sys import stdout
class Mock:
def __init__(self, cap, a):
self.a, self.cap = a, cap
self.n, self.q = len(a), []
def ask(self, i):
result = self.a[i] in self.q
self.q.append(self.a[i])
if len(self.q) > self.cap:
self.q = self.q[1:]
return result
def reset(self):
self.q = []
def out(self, result):
print('!', result)
class IO:
def __init__(self):
self.n, self.cap = map(int, input().split())
def ask(self, i):
print('?', i + 1)
stdout.flush()
return input() == 'Y'
def reset(self):
print('R')
stdout.flush()
def out(self, result):
print('!', result)
def solve(io):
n, cap = io.n, io.cap
size = cap + 1 >> 1
count = n // size
removed = [False] * n
for d in range(1, count):
for r in range(min(d, count - d)):
for i in range(r, count, d):
for j in range(i * size, (i + 1) * size):
if not removed[j] and io.ask(j):
removed[j] = True
io.reset()
return removed.count(False)
# io = Mock(2, [1, 4, 1, 3])
# io.out(solve(io))
# io = Mock(8, [1, 2, 3, 4, 5, 6, 6, 6])
# io.out(solve(io))
io = IO()
io.out(solve(io)) | py |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | import os
import time
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# endregion
def main():
u, v = map(int, input().split())
b = [0] * 61
possible = True
for i in range(60, -1, -1):
if (u & (1 << i)) < (v & (1 << i)):
if i-1 < 0:
possible = False
break
b[i-1] += 2
elif (u & (1 << i)) > (v & (1 << i)):
r = -1
for j in range(i, 61):
if b[j] >= 2:
r = j
break
if r == -1 or i-1 < 0:
possible = False
break
for j in range(r, i, -1):
b[j] -= 2
b[j-1] += 4
b[i] -= 1
b[i-1] += 2
elif (u & (1 << i)):
b[i] += 1
if not possible:
print(-1)
else:
ret = []
while max(b):
curr = 0
for i in range(61):
if b[i]:
curr |= (1 << i)
b[i] -= 1
ret.append(curr)
print(len(ret))
print(" ".join(str(c) for c in ret))
if __name__ == "__main__":
start_time = time.time()
main()
print(f'Execution time: {time.time() - start_time} s', file=sys.stderr)
| py |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | for _ in range(int(input())):
input()
a = list(map(int, input().split()))
s = sum(x or 1 for x in a)
print(a.count(0) + (s == 0))
| py |
1286 | A | A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. | [
"dp",
"greedy",
"sortings"
] | #from highlight import *
n = int(input())
p = list(map(int, input().split()))
remaining = set(range(1, n+1))
a = []
# 0 = even, 1 = odd, -1 = missing
for i in p:
if i == 0:
a.append(-1)
else:
remaining.remove(i)
if i % 2 == 0:
a.append(0)
else:
a.append(1)
n_odd = 0
n_even = 0
for i in remaining:
if i % 2 == 0:
n_even += 1
else:
n_odd += 1
dp = [
[
[[float("inf"), float("inf")] for _ in range(n_even+1)]
for _ in range(n_odd+1)
]
for __ in range(n+1)
]
# dp[index][num_odd_used][num_even_used][last_parity] => min complexity
dp[0][0][0] = [0, 0]
#print(a)
for index in range(1, n+1):
for num_odd_used in range(n_odd+1):
for num_even_used in range(n_even+1):
if a[index-1] == 0:
dp[index][num_odd_used][num_even_used] = [
min(dp[index-1][num_odd_used][num_even_used][0], dp[index-1][num_odd_used][num_even_used][1] + 1),
float("inf")
]
elif a[index-1] == 1:
dp[index][num_odd_used][num_even_used] = [
float("inf"),
min(dp[index-1][num_odd_used][num_even_used][0] + 1, dp[index-1][num_odd_used][num_even_used][1]),
]
else:
dp[index][num_odd_used][num_even_used] = [
min(dp[index-1][num_odd_used][num_even_used-1][0], dp[index-1][num_odd_used][num_even_used-1][1] + 1),
min(dp[index-1][num_odd_used-1][num_even_used][0] + 1, dp[index-1][num_odd_used-1][num_even_used][1]),
]
print(min(dp[n][n_odd][n_even])) | py |
1310 | A | A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications. | [
"data structures",
"greedy",
"sortings"
] | import sys
from collections import defaultdict
from heapq import heapify, heappush, heappop
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
t = list(map(int, sys.stdin.readline().split()))
# create a map that stores list of time for each value of a
umap = defaultdict(list)
for i in range(n):
umap[a[i]].append(t[i])
# maintain a priority queue that will store time of repeating values
# this will help us in retriving/deleting greatest time
pq = [] # max heap
heapify(pq)
heapsum = 0 # to store sum of heap
ans = 0
for num in sorted(set(a)):
if len(umap[num]) > 1 or len(pq) > 0: # either num repeats or pq is not empty
for val in umap[num]:
heappush(pq, -1*val) # store negative value since it's min heap
heapsum += val
# remove the largest time value
heapsum += pq[0]
heappop(pq)
# increment all the other values
temp = num
while len(pq) > 0:
temp += 1
ans += heapsum
if len(umap[temp]) > 0:
# the next num also contains many time value
# hence should be added in next iteration
break
else:
# remove the largest time value
heapsum += pq[0]
heappop(pq)
print(ans)
| py |
1293 | B | B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars. | [
"combinatorics",
"greedy",
"math"
] | n = int(input())
dollars = 0
for i in range(n):
dollars += (1 / n)
n -= 1
print(dollars) | py |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | n,m=map(int, input().split())
l=list(map(int, input().split()))
if n>m:
print(0)
else:
ans=1
for i in range(n):
for j in range(i+1,n):
ans=(ans*abs(l[i]-l[j]))%m
print(ans) | py |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | import sys
import math
from collections import Counter
#from decimal import *
import random
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"}
def transformare_baza(numar,baza):
transformare=""
while numar>=baza:
rest=numar%baza
numar=numar//baza
transformare+=str(rest)+"|"
transformare+=str(numar)
noua_baza=transformare[::-1]
noua_baza=transformare
return noua_baza
def prime_generator(nr_elemente_prime):
vector_prime=[-1]*nr_elemente_prime
vector_rasp=[0]*nr_elemente_prime
vector_prime[1]=1
vector_rasp[1]=1
#primes sieve
contor=2
for i in range(2,nr_elemente_prime):
if vector_prime[i]==-1:
vector_prime[i]=1
vector_rasp[contor]=i
contor=contor+1
for j in range(i+i,nr_elemente_prime,i):
if vector_prime[j]==-1:
vector_prime[j]=i
#print(i,j)
#print(vector_rasp)
set_prime=set(vector_rasp[2:len(vector_rasp)])
set_prime.remove(0)
return list(set_prime)
def cautare(poz,tupleta,lungime):
pornire=0
oprire=poz-1
centrare=(pornire+oprire)//2
# print("p=",pornire,"op=",oprire,"cen=",centrare)
while pornire+1<oprire:
centrare=(pornire+oprire)//2
while tupleta[centrare][2]>tupleta[poz][1] and pornire+1<oprire:
oprire=centrare
centrare=(pornire+oprire)//2
while tupleta[centrare][2]<=tupleta[poz][1] and pornire+1<oprire:
pornire=centrare
centrare=(pornire+oprire)//2
# print("cen=",centrare,pornire,oprire)
if tupleta[centrare][2]>tupleta[poz][1]:
centrare-=1
else:
if centrare+1<lungime:
if tupleta[centrare+1][2]<=tupleta[poz][1]:
centrare+=1
return centrare
dictionar_linii={}
dictionar_coloane={}
#z=int(input())
for contorr in range(1):
# empty_line=input()
n=int(input())
#n=1100
#k=int(input())
#n,m=list(map(int, input().split()))
stringul=input()
#bloc=list(map(int, input().split()))
answ=''
initial=stringul
j=26
while j>0:
valoare=j
posibil=1
while posibil==1:
#print("a=",answ,j)
posibil=0
answ=''
n=len(stringul)
for i in range(len(stringul)):
if stringul[i]!=alfabet_2[str(j)]:
answ+=stringul[i]
else:
if i==0:
if i+1<n:
if alfabet[stringul[i+1]]==valoare-1:
posibil=1
else:
answ+=stringul[i]
else:
posibil=0
answ+=stringul[i]
elif i==n-1:
if i-1>=0:
if alfabet[stringul[i-1]]==valoare-1:
posibil=1
else:
answ+=stringul[i]
else:
posibil=0
answ+=stringul[i]
else:
# print("aa",i)
if i+1<n:
if alfabet[stringul[i+1]]==valoare-1:
posibil=1
elif i-1>=0:
#print("xx",i)
if alfabet[stringul[i-1]]==valoare-1:
#print("gg")
posibil=1
else:
answ+=stringul[i]
elif i-1>=0:
if alfabet[stringul[i-1]]==valoare-1:
posibil=1
#print("aici")
else:
answ+=stringul[i]
#print("answ=",answ, j)
stringul=answ
j-=1
print(len(initial)-len(stringul))
| py |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | tests = int(input())
i = 0
while i < tests:
checker = False
len_of_number = int(input())
number = [int(x) for x in list(input())]
if len_of_number == 1:
print(-1)
elif sum(number) == 1:
print(-1)
else:
if sum(number)%2 == 0 and number[-1]%2 != 0:
number = [str(x) for x in number]
print(' '.join(number).replace(' ', ''))
else:
j = len_of_number - 1
while j > 0:
if number[j]%2 == 0:
number.pop(j)
#print(number)
#j -= 1
else:
#print(sum(number))
if sum(number)%2 == 0:
#print('is it worked&!')
number = [str(x) for x in number]
print(' '.join(number).replace(' ', ''))
break
else:
#print(number)
k = len(number) - 2
while k >= 0:
if number[k]%2 != 0:
number.pop(k)
number = [str(x) for x in number]
print(' '.join(number).replace(' ', ''))
checker = True
break
k -= 1
if checker == False:
j -= 1
else:
break
else:
print(-1)
i += 1 | py |
1285 | B | B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | [
"dp",
"greedy",
"implementation"
] | t = int(input())
def max_subarray(arr):
acc = 0
min_acc = 0
max_acc = float("-inf")
for num in arr:
acc += num
max_acc = max(max_acc, acc - min_acc)
min_acc = min(min_acc, acc)
return max_acc
for i in range(t):
n = int(input())
arr = list(map(int, input().split(" ")))
print("YES" if sum(arr) > max(max_subarray(arr[1:]), max_subarray(arr[:-1])) else "NO")
| py |
1322 | A | A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds. | [
"greedy"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
s = list(input().rstrip())
c = 0
for i in s:
c += 1 if i & 1 else -1
if c:
ans = -1
print(ans)
exit()
ans = 0
c = 0
now = 0
f = 0
for i in s:
c += 1
now += 1 if not i & 1 else -1
if now < 0:
f = 1
if not now and f:
ans += c
if not now:
c, f = 0, 0
print(ans) | py |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | import sys, math
import heapq
from collections import deque
input = sys.stdin.readline
hqp = heapq.heappop
hqs = heapq.heappush
# input
def ip(): return int(input())
def sp(): return str(input().rstrip())
def mip(): return map(int, input().split())
def msp(): return map(str, input().split().rstrip())
def lmip(): return list(map(int, input().split()))
def lmsp(): return list(map(str, input().split().rstrip()))
# gcd, lcm
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return x * y // gcd(x, y)
# prime
def isPrime(x):
if x <= 1: return False
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return False
return True
# Union Find
# p = [i for i in range(n + 1)]
def find(x):
if x == p[x]:
return x
q = find(p[x])
p[x] = q
return q
def union(x, y):
x = find(x)
y = find(y)
if x != y:
p[y] = x
def getPow(a, x):
ret = 1
while x:
if x & 1:
ret = (ret * a) % MOD
a = (a * a) % MOD
x >>= 1
return ret
def getInv(x):
return getPow(x, MOD - 2)
############### Main! ###############
ans = [0, 0]
def f(x):
global ans
b = [-1 for _ in range(1 << m)] # index
for i in range(n):
bit = 0
for j in range(m):
bit |= (0 if a[i][j] < x else 1) << j # not smaller than x: 1
b[bit] = i
for i in range(1 << m):
for j in range(1 << m):
if (i | j) == (1 << m) - 1 and b[i] != -1 and b[j] != -1:
ans = [b[i] + 1, b[j] + 1]
return True
return False
n, m = mip()
a = []
for i in range(n):
a.append(lmip())
lo = 0
hi = 10**9 + 234
while lo <= hi:
mid = (lo + hi) // 2
if f(mid):
lo = mid + 1
else:
hi = mid - 1
print(*ans)
######## Priest W_NotFoundGD ######## | py |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | import sys
from array import array
from bisect import *
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
tests, inf = 1, 10 ** 18
out = []
max_ = 10 ** 6 + 1
class range_sum:
def __init__(self, n, default, func):
self.tree, self.n, self.lazy, self.h = [0] * (2 * n), n, [0] * (n), 20
self.default, self.func = default, func
def apply(self, p, val):
self.tree[p] += val
if p < self.n:
self.lazy[p] += val
# fix applied nodes and down nodes
def build(self, p):
while p > 1:
p >>= 1
self.tree[p] = self.func(self.tree[p << 1], self.tree[(p << 1) + 1]) + self.lazy[p]
# push lazy operations
def push(self, p):
for s in range(self.h, 0, -1):
i = p >> s
if self.lazy[i]:
self.apply(i * 2, self.lazy[i])
self.apply(i * 2 + 1, self.lazy[i])
self.lazy[i] = 0
def update(self, l, r, val):
'''[l,r)'''
l += self.n
r += self.n
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l, val)
l += 1
if r & 1:
r -= 1
self.apply(r, val)
l >>= 1
r >>= 1
self.build(l0)
self.build(r0 - 1)
def query(self, l, r):
'''[l,r)'''
l += self.n
r += self.n
# apply lazy nodes
self.push(l)
self.push(r - 1)
res = self.default
while l < r:
if l & 1:
res = self.func(res, self.tree[l])
l += 1
if r & 1:
r -= 1
res = self.func(res, self.tree[r])
l >>= 1
r >>= 1
return res
for _ in range(tests):
n, m, p = inp(int)
att = array('i', [10 ** 9 + 1] * max_)
def_ = array('i', [10 ** 9 + 1] * max_)
mdef = array('i', [-1] * p)
matt = array('i', [-1] * p)
mcoin = array('i', [-1] * p)
adj = [array('i') for _ in range(max_)]
defs = array('i')
tree = range_sum(m, -10 ** 9, max)
for i in range(n):
a, ca = inp(int)
att[a] = min(att[a], ca)
for i in range(m):
b, cb = inp(int)
def_[b] = min(def_[b], cb)
for i in range(p):
mdef[i], matt[i], mcoin[i] = inp(int)
adj[mdef[i]].append(i)
for i in range(max_):
if def_[i] != 10 ** 9 + 1:
defs.append(i)
tree.update(len(defs) - 1, len(defs), -def_[i])
ans = -inf
for i in range(max_):
if att[i] != 10 ** 9 + 1:
ans = max(ans, tree.query(0, len(defs)) - att[i])
for j in adj[i]:
ix = bisect_right(defs, matt[j])
if ix < len(defs): tree.update(ix, len(defs), mcoin[j])
out.append(ans)
print('\n'.join(map(str, out)))
| py |
1293 | A | A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor. | [
"binary search",
"brute force",
"implementation"
] | 'https://codeforces.com/contest/1293/problem/A'
for _ in range(int(input())):
n,s,k=map(int,input().split())
num=list(map(int,input().split()))
for i in range(n):
left=s-i
right=s+i
if(left>=1 and left not in num):
print(i)
break
if(right<=n and right not in num):
print(i)
break
else: assert(False) | py |
1296 | D | D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6
| [
"greedy",
"sortings"
] | #! /bin/env python3
# please follow ATshayu
def main():
n, a, b, k = map(int, input().split(' '))
h = map(int, input().split(' '))
# solve
def ceil(a, b): return a//b if a%b == 0 else a//b+1
res = []
ans = 0
for ele in h:
x, r = ele//(a+b), ele%(a+b)
if r == 0: x -= 1
if 1 <= r and r <= a:
ans += 1
continue
r = ele - x*(a+b) - a
res.append(ceil(r, a))
res.sort()
for ele in res:
if ele > k: break
ans += 1
k -= ele
print(ans)
main() | py |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | liste = input().split()
size_problem=int(liste[0])
modulo=int(liste[1])
liste=input().split()
if size_problem>modulo:
print(0)
else:
liste = [eval(i) for i in liste]
liste.sort(reverse=True)
prod =1
for i in range (0,size_problem-1):
for j in range(i+1,size_problem):
prod*= liste[i]-liste[j]
prod= prod%modulo
if prod == 0:
break
print(prod)
| py |
1288 | E | E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] | [
"data structures"
] | n,m=map(int,input().split())
a=[int(i)-1 for i in input().split()]
ans1=[i+1 for i in range(n)]
ans2=[-1 for i in range(n)]
for i in set(a):
ans1[i]=1
N=1
while N<n+m:N<<=1
st=[0 for i in range(N<<1)]
pos=[i+m for i in range(n)]
for i in range(n):
st[i+N+m]=1
for i in range(N-1,0,-1):
st[i]=st[i<<1]+st[i<<1|1]
def up(i,v):
i+=N
st[i]=v
i>>=1
while i>0:
st[i]=st[i<<1]+st[i<<1|1]
i>>=1
def qr(l,r=N):
l+=N
r+=N
ans=0
while l<r:
if l&1:
ans+=st[l]
l+=1
if r&1:
r-=1
ans+=ans[r]
l>>=1
r>>=1
return(ans)
for j in range(m):
x=a[j]
i=pos[x]
ans2[x]=max(ans2[x],n-qr(i+1))
up(i,0)
pos[x]=m-1-j
up(pos[x],1)
for i in range(n):
x=pos[i]
ans2[i]=max(ans2[i],n-qr(x+1))
for i in range(n):
print(ans1[i],ans2[i]) | py |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | t=int(input())
for _ in range(t):
size=int(input())
path=input()
l,res=0,[-1]
min_length=size+1
pos_idx={(0,0):-1}
x,y=0,0
for r,go in enumerate(path):
if go=="L":
x-=1
elif go=="R":
x+=1
elif go=="U":
y+=1
else:
y-=1
if (x,y) in pos_idx:
if r-pos_idx[(x,y)]<min_length:
min_length=r-pos_idx[(x,y)]
res=[pos_idx[(x,y)]+2,r+1]
pos_idx[(x,y)]=r
print(*res)
| py |
1320 | D | D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5
11011
3
1 3 3
1 4 2
1 2 3
OutputCopyYes
Yes
No
| [
"data structures",
"hashing",
"strings"
] | import sys
input = sys.stdin.readline
n=int(input())
t=input().strip()
q=int(input())
ZEROS=[0]*n
ZERO_ONE=[]
ONECOUNT=[0]*n
ind=0
count=0
for i in range(n):
ZEROS[i]=ind
if t[i]=="0":
ind+=1
ONECOUNT[i]=count%2
ZERO_ONE.append(count%2)
count=0
else:
count+=1
ONECOUNT[i]=count
ZEROS.append(ind)
S=ZERO_ONE
LEN=len(S)
p=2
import random
mod=random.randint(10**8,10**9)*2+1
mod2=random.randint(10**8,10**9)*2+1
mod3=random.randint(10**8,10**9)*2+1
mod4=random.randint(10**8,10**9)*2+1
TABLE=[0]
TABLE2=[0]
TABLE3=[0]
TABLE4=[0]
for i in range(LEN):
TABLE.append(p*TABLE[-1]%mod+S[i]%mod) # テーブルを埋める
TABLE2.append(p*TABLE2[-1]%mod2+S[i]%mod2) # テーブルを埋める
TABLE3.append(p*TABLE3[-1]%mod3+S[i]%mod2) # テーブルを埋める
TABLE4.append(p*TABLE4[-1]%mod4+S[i]%mod4) # テーブルを埋める
def hash_ij(i,j): # [i,j)のハッシュ値を求める
return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod
def hash_ij2(i,j): # [i,j)のハッシュ値を求める
return (TABLE2[j]-TABLE2[i]*pow(p,j-i,mod2))%mod2
def hash_ij3(i,j): # [i,j)のハッシュ値を求める
return (TABLE3[j]-TABLE3[i]*pow(p,j-i,mod3))%mod3
def hash_ij4(i,j): # [i,j)のハッシュ値を求める
return (TABLE4[j]-TABLE4[i]*pow(p,j-i,mod4))%mod4
def zcount(l,LEN):
return ZEROS[l+LEN]-ZEROS[l]
def first_check(l,LEN):
if t[l]=="0":
return 0
else:
return (ZERO_ONE[ZEROS[l]]-ONECOUNT[l]+1)%2
def equalcheck(l1,l2,LEN):
f1,f2=ZEROS[l1]+1,ZEROS[l2]+1
if l1+LEN-1=="0":
la1=ZEROS[l1+LEN]
else:
la1=ZEROS[l1+LEN]-1
if l2+LEN-1=="0":
la2=ZEROS[l2+LEN]
else:
la2=ZEROS[l2+LEN]-1
if hash_ij(f1,la1+1)==hash_ij(f2,la2+1) and hash_ij2(f1,la1+1)==hash_ij2(f2,la2+1) and hash_ij3(f1,la1+1)==hash_ij3(f2,la2+1) and hash_ij4(f1,la1+1)==hash_ij4(f2,la2+1):
return "Yes"
else:
return "No"
for queries in range(q):
l1,l2,LEN=map(int,input().split())
l1-=1
l2-=1
#print(l1,l2,LEN)
if zcount(l1,LEN)!=zcount(l2,LEN):
print("No")
continue
if zcount(l1,LEN)==0:
print("Yes")
continue
if first_check(l1,LEN)!=first_check(l2,LEN):
print("No")
continue
if zcount(l1,LEN)==1:
print("Yes")
continue
print(equalcheck(l1,l2,LEN))
| py |
1303 | D | D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0
| [
"bitmasks",
"greedy"
] | def read():
return [int(i) for i in input().split()]
def solve():
[n,m]=read()
a=read()
a.sort()
nax=64
def cb(num,bit):
return (num>>bit)&1
if sum(a)<n:
print(-1)
return
ct=[0 for i in range(nax)]
for i in range(m):
for bit in range(nax):
if cb(a[i],bit):
ct[bit]+=1
ans = 0
for bit in range(nax-1):
if cb(n, bit) and ct[bit]==0:
j = bit
while ct[j]==0:
j+=1
ans += j-bit
ct[j]-=1
for k in range(bit+1,j):
ct[k]+=1
continue
if cb(n, bit):
ct[bit]-=1
ct[bit+1]+=ct[bit]//2
print(ans)
def main():
for i in range(int(input())):
solve()
main() | py |
1304 | C | C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied. | [
"dp",
"greedy",
"implementation",
"sortings",
"two pointers"
] | import sys
from bisect import bisect_right, bisect_left
import os
import sys
from io import BytesIO, IOBase
from math import factorial, floor, inf, ceil, gcd
from collections import defaultdict, deque, Counter
from functools import cmp_to_key
from heapq import heappop, heappush, heapify
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")
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(s)
def invr():
return(map(int,input().split()))
def insr2():
s = input()
return(s.split(" "))
###functions
##better sqrt with binary search (since f**k float precision for large nums)
def sqrt(num):
l, r = 0, 10**18 + 7
while r-l != 1:
mid = (l+r)//2
square = mid*mid
if square <= num:
l = mid
else:
r = mid
return l
### Calculate C(n, r) mod p, where p is prime (fast with precalculation)
def build_mod_inverses(n, r, p):
fact = [1] * (n + 1)
for i in range(1, n + 1):
fact[i] = i * fact[i - 1] % p
inv = [1] * (n + 1)
inv[n] = pow(fact[n], p - 2, p)
for i in range(n - 1, -1, -1):
inv[i] = (i + 1) * inv[i + 1] % p
return fact, inv
# fast C(n, r) mod p calculation using predefined fact and inv
def comb(n, r, p, fact, inv):
return fact[n] * inv[r] % p * inv[n - r] % p if n >= r >= 0 else 0
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i and i != 1:
divisors.append(n // i)
return divisors
def dfs(graph, vertex):
visited = set()
tree = []
deq = deque([vertex])
while deq:
vertex = deq.pop()
if vertex not in visited:
visited.add(vertex)
deq.extend(graph[vertex])
tree.append(vertex)
return tree
def find_in_sorted_list(elem, sorted_list):
# https://docs.python.org/3/library/bisect.html
'Locate the leftmost value exactly equal to x'
i = bisect_left(sorted_list, elem)
if i != len(sorted_list) and sorted_list[i] == elem:
return i
return -1
############ SEGMENT TREE ##############
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
############ DSU ##############
class DisjointSetUnion():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
self.group = n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
self.group -= 1
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return self.group
def all_group_members(self):
dic = {r:[] for r in self.roots()}
for i in range(self.n):
dic[self.find(i)].append(i)
return dic
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
###code
__ = inp()
for _ in range(__):
def solve():
n,m = inlt()
cur_time = 0
a,b = m,m
f = True
for i in range(n):
t, l, r = inlt()
a = max(l, a-(t-cur_time))
b = min(r, b+(t-cur_time))
cur_time = t
if a > b and f:
print('NO')
f = False
if f:
print('YES')
return
solve() | py |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | from __future__ import division, print_function
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
l = list(map(int, input().split()))
# not my solution, from: https://codeforces.com/contest/1299/submission/70653333
su = [l[0]]
cou = [-1, 0]
for k in range(1, n):
nd = 1
ns = l[k]
while len(cou) > 1 and su[-1] * (cou[-1] - cou[-2] + nd) > (su[-1] + ns) * (
cou[-1] - cou[-2]
):
nd += cou[-1] - cou[-2]
ns += su[-1]
su.pop()
cou.pop()
cou.append(k)
su.append(ns)
floats = []
for k in range(len(su)):
floats += [su[k] / (cou[k + 1] - cou[k])] * (cou[k + 1] - cou[k])
if True:
if False:
# 3244 ms, TLE on pypy3
# But 1044 ms on pypy2!!!
print("\n".join(map(str, floats)))
if False:
# 2028 ms
os.write(1, b"\n".join(str(x).encode() for x in floats))
if False:
# 1544 ms
# %-formatting for bytes, added in python 3.5: https://www.python.org/dev/peps/pep-0461/
os.write(1, b"\n".join(b"%.9f" % x for x in floats))
if False:
# 842 ms
# Format with ints instead to avoid float formatting
# This version is not generic! Doesn't handle negatives and wrong for stuff close to integers like x = 1.0 - 1e-10
os.write(1, b"\n".join(b"%d.%09d" % (x, (x - int(x)) * 1e9 + 0.5) for x in floats))
if False:
# 748 ms
# Same as above
ans = bytearray()
for x in floats:
i = int(x)
ans += b"%d.%09d\n" % (i, (x - i) * 1e9 + 0.5)
os.write(1, ans)
if True:
# Try to handle sign and overflows in the fractional part
# These edge cases are not exercised by this problem so I'm not sure if it's correct
def floatToBytes(x):
sign = b""
if x < 0.0:
sign = b"-"
x *= -1.0
whole = int(x)
frac = int((x - whole) * 1e9 + 0.5)
if frac >= 10 ** 9:
frac -= 10 ** 9
whole += 1
return b"%b%d.%09d" % (sign, whole, frac)
os.write(1, b'\n'.join(map(floatToBytes, floats)))
else:
# 670 ms
# Use that fact that most of the output are repeats (specific to this problem)
ans = bytearray()
for k in range(len(su)):
repeat = cou[k + 1] - cou[k]
x = su[k] / repeat
i = int(x)
ans += (b"%d.%09d\n" % (i, (x - i) * 1e9 + 0.5)) * repeat
os.write(1, ans)
| py |
1324 | F | F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33. | [
"dfs and similar",
"dp",
"graphs",
"trees"
] | import gc
import heapq
import itertools
import math
from collections import Counter, deque, defaultdict
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import threading
from heapq import *
from fractions import Fraction
import bisect
def S():
return sys.stdin.readline().split()
def I():
return [int(i) for i in sys.stdin.readline().split()]
def II():
return int(sys.stdin.readline())
def IS():
return sys.stdin.readline().replace('\n', '')
def main():
n = II()
a = I()
tree = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = I()
tree[u - 1].append(v - 1)
tree[v - 1].append(u - 1)
order = []
queue = deque([0])
p = [-1] * n
d = [-1 if i == 0 else 1 for i in a]
while queue:
v = queue.pop()
order.append(v)
for u in tree[v]:
if p[v] != u:
p[u] = v
queue.appendleft(u)
order = order[::-1]
up = [False] * n
for i in range(n - 1):
if d[order[i]] > 0:
up[order[i]] = True
d[p[order[i]]] += d[order[i]]
ans = [0] * n
ans[0] = d[0]
for i in range(n - 2, -1, -1):
idx = order[i]
if not up[idx]:
ans[idx] = max(d[idx], ans[p[idx]] + d[idx])
else:
ans[idx] = max(ans[p[idx]], d[idx])
print(*ans)
if __name__ == '__main__':
# for _ in range(II()):
# main()
main() | py |
1303 | B | B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good. | [
"math"
] | from collections import Counter, deque, defaultdict
import math
from itertools import permutations, accumulate
from sys import *
from heapq import *
from bisect import bisect_left, bisect_right
from functools import cmp_to_key
from random import randint
xor = randint(10 ** 7, 10**8)
# https://docs.python.org/3/library/bisect.html
on = lambda mask, pos: (mask & (1 << pos)) > 0
lcm = lambda x, y: (x * y) // math.gcd(x,y)
rotate = lambda seq, k: seq[k:] + seq[:k] # O(n)
input = stdin.readline
'''
Check for typos before submit, Check if u can get hacked with Dict (use xor)
Observations/Notes:
'''
for _ in range(int(input())):
n, g, b = map(int, input().split())
def poss(num):
want = (n // 2) + (n & 1)
full_cycles = num // (g + b)
remaining_good = min(g, num % (g + b))
remaining_bad = max(0, num % (g + b) - remaining_good)
want -= (full_cycles * g + remaining_good)
remain = 0
if want < 0:
remain = -want
want = 0
bad_want = n - ((n // 2) + (n & 1))
bad_want -= remain
return want == 0 and (full_cycles * b + remaining_bad) >= bad_want
l = 1; r = 10**18
best = -1
while l <= r:
mid = (l + r) // 2
if poss(mid):
r = mid - 1
best = mid
else:
l = mid + 1
print(best) | py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | import os
import 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")
import math
def solve():
n = int(input())
ans = -1
for i in range(1,int(n**(1/2)) + 1):
if n % i == 0 and math.gcd(i,n//i) ==1:
ans = i
print(ans,n//ans)
t = 1
for i in range(t):
solve()
| py |
1322 | B | B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102. | [
"binary search",
"bitmasks",
"constructive algorithms",
"data structures",
"math",
"sortings"
] | import sys
from array import array
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, []
for _ in range(1):
Max = 10 ** 7
n, a = int(input()), array('i', inp(int))
mem = array('i', [0] * (10 ** 7 + 10))
ans = 0
for bit in range(25):
mod, ones = 1 << (bit + 1), 0
for i in range(n): mem[a[i] % mod] += 1
for i in range(min(mod * 2, Max + 1)): mem[i] += mem[i - 1]
for i in range(n):
lo = max((1 << bit) - (a[i] % mod), 0)
if lo <= Max:
hi = min(mod - 1 - (a[i] % mod), Max)
ones += mem[hi] - mem[lo - 1] - (lo <= a[i] % mod <= hi)
lo = mod + (1 << bit) - (a[i] % mod)
if lo <= Max:
hi = min(mod * 2 - 2 - (a[i] % mod), Max)
ones += mem[hi] - mem[lo - 1] - (lo <= a[i] % mod <= hi)
ones >>= 1
ans |= (ones & 1) << bit
for i in range(min(mod * 2, Max + 1)): mem[i] = 0
out.append(ans)
print('\n'.join(map(str, out)))
| py |
1301 | D | D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running): | [
"constructive algorithms",
"graphs",
"implementation"
] | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
'''
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
'''
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
#t=int(input())
for _ in range (t):
#n=int(input())
n,m,k=map(int,input().split())
#a=list(map(int,input().split()))
#b=list(map(int,input().split()))
#s=input()
#n=len(s)
ans=[]
f,s=m-1,"R"
c=min(f,k)
if c==f and c:
ans.append([f,s])
k-=c
elif c:
ans.append([c,s])
k-=c
if k:
ans.append([1,s[:k]])
k=0
#print(ans)
f,s=m-1,"L"
c=min(f,k)
if c==f and c:
ans.append([f,s])
k-=c
elif c:
ans.append([c,s])
k-=c
if k:
ans.append([1,s[:k]])
k=0
for i in range (1,n):
if k:
ans.append([1,"D"])
k-=1
if k and m-1:
f,s=m-1,"R"
c=min(f,k)
if c==f and c:
ans.append([f,s])
k-=c
elif c:
ans.append([c,s])
k-=c
if k:
ans.append([1,s[:k]])
k=0
if k and m-1:
f,s=m-1,"UDL"
c=min(f,k//3)
#print(c,f,k)
if c==f and c:
ans.append([f,s])
k-=c*3
else:
if c:
ans.append([c,s])
k-=c*3
if k:
ans.append([1,s[:k]])
k=0
f,s=n-1,"U"
#print(k)
c=min(f,k)
if c==f and c:
ans.append([f,s])
k-=c
elif c:
ans.append([c,s])
k-=c
if k:
ans.append([1,s[:k]])
k=0
#print(ans)
if k:
print("NO")
else:
print("YES")
print(len(ans))
for i in ans:
print(*i) | py |
1313 | A | A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors. | [
"brute force",
"greedy",
"implementation"
] | def fonction(a,b,c):
som=0
if a>0 :
som+=1
a-=1
if b>0:
som+=1
b-=1
if c >0:
som+=1
c-=1
if a>0 and b>0:
som+=1
a-=1
b-=1
if a==b==0 and c>1:
som-=1
a+=1
b+=1
if a>0 and c>0 :
som+=1
a-=1
c-=1
if b>0 and c>0:
som+=1
b-=1
c-=1
if a >0 and b>0 and c>0:
som+=1
return som
t=int(input())
L=[]
for i in range(t):
a,b,c=[int(x) for x in input().split()]
L.append (fonction(a,b,c))
for k in L:
print(k) | py |
1315 | B | B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6
| [
"binary search",
"dp",
"greedy",
"strings"
] | def feasible(mid,a,b,s,p):
changes = 0
cost = 0
if mid<len(s)-1:
if s[mid]=="A":
cost+=a
else:
cost+=b
for i in range(mid+1,len(s)-1):
if i>0 and s[i]!=s[i-1]:
changes+=1
if s[i]=='A':
cost+=a
else:
cost+=b
if cost>p:
return False
if cost>p:
return False
return True
for _ in range(int(input())):
a,b,p = map(int,input().split())
s = input()
left = 0
right = len(s)-1
ans = len(s)-1
while left<=right:
mid = left + (right- left)//2
if feasible(mid,a,b,s,p):
ans = mid
right = mid-1
else:
left = mid+1
print(ans+1) | py |
1322 | C | C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11. | [
"graphs",
"hashing",
"math",
"number theory"
] | from collections import Counter
from sys import stdin
from math import gcd
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
n, m = map(int, input().split())
values = list(map(int, input().split()))
y_neigh = [[] for i in range(n)]
for i in range(m):
x, y = map(int, input().split())
y_neigh[y - 1].append(x - 1)
# group indices with the same neighboring set
'''
y_n = {}
for i in range(n):
nst = frozenset(y_neigh[i])
if nst != set():
if nst in y_n:
y_n[nst] += values[i]
else:
y_n[nst] = values[i]
'''
# using Counter here for faster read
y_n = Counter()
for i in range(n):
if y_neigh[i] != []:
y_n[hash(tuple(sorted(y_neigh[i])))] += values[i]
curr = 0
for g in y_n:
if g == hash(tuple()):
continue
curr = gcd(curr, y_n[g])
print (curr)
blank = input()
| py |
1301 | C | C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement. | [
"binary search",
"combinatorics",
"greedy",
"math",
"strings"
] | import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
ans = []
for _ in range(t):
n, m = map(int, input().split())
l = n - m
if l <= m + 1:
ans0 = n * (n + 1) // 2 - l
else:
x = l // (m + 1)
y = l % (m + 1)
ans0 = n * (n + 1) // 2
ans0 -= x * (x + 1) // 2 * (m + 1 - y)
ans0 -= (x + 1) * (x + 2) // 2 * y
ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans))) | py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | def pp(a,b,c):
i=0
j=1000000000
while i<=j:
# if b==-3:
m=(i+j)//2
x=b+m*c
# print(i,j,x,a,b,c)
if x==a:
return True
if x>a:
if c>0:
j=m-1
else:
i=m+1
else:
if c>0:
i=m+1
else:
j=m-1
return False
def ss(n,x,s):
ans=0
a=s.count('0')
b=n-a
p=0
q=0
for i in s:
if i=='0':
p+=1
else:
q+=1
if a==b and p-q==x:
return -1
if pp(x,p-q,a-b):
# print(p,q)
# break
ans+=1
if x==0:
if a==b:
return -1
ans+=1
return ans
for _ in range(int(input())):
n,x=map(int, input().split())
s=str(input())
print(ss(n,x,s)) | py |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | import time
import os,sys
from datetime import datetime
from math import floor,sqrt,gcd,factorial,ceil,log2
from collections import Counter,defaultdict as dd
import bisect
from itertools import chain
from collections import deque
from sys import maxsize as INT_MAX
from itertools import permutations
from collections import deque
from functools import lru_cache
import threading
from heapq import *
from functools import cmp_to_key
from io import BytesIO, IOBase
'''Dont use setrecursionlimit in pypy'''
sys.setrecursionlimit(int(1e9))
#threading.stack_size(0x2000000)
ONLINE_JUDGE,INF,mod=False,float('inf'),int(1e9)+7
if os.path.exists('D:\\vimstuff'):
ONLINE_JUDGE=True
sys.stdin=open('D:\\vimstuff\\inp.txt','r')
sys.stdout=open('D:\\vimstuff\\out.txt','w')
BUFSIZE: int = 8192
def readint():
return int(sys.stdin.readline())
def readstr():
return sys.stdin.readline()
def readlst():
return list(map(int, sys.stdin.readline().strip().split()))
def readmul():
return map(int, sys.stdin.readline().strip().split())
def mulfloat(): return map(float, sys.stdin.readline().strip().split())
def flush():
return sys.stdout.flush()
def power_two(x):
return (1<<x)
def lcm(a,b):
return a*b//gcd(a,b)
def countGreater(arr,n, k):
l = 0
r = n - 1
leftGreater = n
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
else:
l = m + 1
return (n - leftGreater)
def lower_bound(arr,n,val):
l,r=-1,n
while r>l+1:
m=int((l+r)>>1)
if arr[m]<val:
l=m
else:
r=m
return r
def upper_bound(arr,n,val):
l,r=-1,n
while r>l+1:
m=int((l+r)>>1)
if arr[m]<=val:
l=m
else:
r=m
return l
def binpow(a,n,mod):
res=1
while n:
if n&1:
res=(res*a)%mod
n-=1
a=(a*a)%mod
n=n>>1
return res
def printmat(l,seperate=True):
for i in range(0,len(l)):
if(seperate):
print(*l[i],sep=" ")
else:
print(*l[i],sep="")
def is_perfect_square(num):
#print(num)
temp = num**(0.5)
#print(temp)
return (temp//1)==temp
def find(res):
n1=res
while par[n1]!=n1:
par[n1]=par[par[n1]]
n1=par[n1]
return n1
def union(u,v):
p1,p2=find(u),find(v)
if p1==p2:
return 0
if(rank[p1]>rank[p2]):
p1,p2=p2,p1
par[p1]=p2
rank[p2]+=rank[p1]
return 1
#Fibonaci logn implementation gives current and next fibonnaci number
def fibonac(n):
if n==0:
return (0,1)
nb2,nb2p1=fibonac(n//2)
#print(nb2)
#print(nb2p1)
a=nb2*(2*nb2p1-nb2)
b=nb2p1*nb2p1+nb2*nb2
if n&1==0:
return (a,b)
else:
return (b,a+b)
def euler_totient(n):
res=n
for i in range(2,int(sqrt(n))+1):
if res%i==0:
while n%i==0:
n=n//i
res=res-res//i
if n>1:
res=res-res//n
return res
def custom_ceil(a,b):
return (a+b-1)//b
def iter_dfs(node,comp):
stk=[node]
vis=[False]*(comp+1)
while len(stk):
node=stk[-1]
vis[node]=True
stk=stk[:-1]
for child in graph[node]:
if child==comp:
return True
if vis[child]==False:
vis[child]=True
stk.append(child)
return False
'''
1. Implement after understanding properly don't do in vain.
2. Check corner cases.
3. Use python if there is recursion.
4. Use pypy if heavy loop,list slice.
5. If you don't want to alter string do not use list costly.
'''
def john_3_16():
n,x=readmul()
a=readlst()
mx=max(a)
if x in a:
print(1);return
print(max(2,ceil(x/mx)))
return
def main():
#tc=1
tc=readint()
start=time.time()
#cnt=1
while tc:
#john_3_16(cnt)
john_3_16()
tc-=1
#cnt+=1
if ONLINE_JUDGE:
print(f'{(time.time()-start)*1000}ms')
pass
main()
| py |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | for _ in range(int(input())):
n = int(input())
a = sorted([list(map(int, input().split())) for _ in range(n)])
if any(y1 < y0 for (_, y0), (_, y1) in zip(a, a[1:])):
print("NO")
else:
print("YES")
x = y = 0
for nx, ny in a:
print(end="R" * (nx - x) + "U" * (ny - y))
x, y = nx, ny
print()
| py |
1141 | B | B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all. | [
"implementation"
] | n = int(input())
a = [int(x) for x in input().split()][:n]
count, max = 0, 0
check1, loopEnded = False, False
start, end = 0, 0
for i in range(n):
if a[i] == 1:
count += 1
if check1 == False:
start += 1
if i == n - 1: loopEnded = True
else:
count = 0
check1 = True
if count > max: max = count
for i in reversed(range(n)):
if a[i] == 1 and loopEnded == False:
end += 1
else: break
if start + end > max: max = start + end
print(max)
| py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | from math import lcm, ceil
min = n = int(input())
sq = ceil(n ** 0.5) + 1
x = 1
while x < sq:
if n % x == 0:
y = n // x
if lcm(x, y) != n:
x += 1
continue
mx = max(x, y)
if mx < min:
min = mx
x += 1
print(n // mx, mx)
| py |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | #13B - Letter A
import math
r = lambda: map(int,input().split())
#Function to check if the lines cross
def cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def dot(a, b):
return a[0] * b[0] + a[1] * b[1]
# def l(v):
# return math.hypot(*v)
def on_line(a, b):
return dot(a, b) > 0 and cross(a, b) == 0 and abs(b[0]) <= abs(5 * a[0]) <= abs(4 * b[0]) and abs(b[1]) <= abs(5 * a[1]) <= abs(4 * b[1])
def is_A(a, b, c):
a, b = set(a), set(b)
if len(a & b) != 1:
return False
p1, = a & b
p2, p3 = a ^ b
v1 = (p2[0] - p1[0], p2[1] - p1[1])
v2 = (p3[0] - p1[0], p3[1] - p1[1])
if dot(v1, v2) < 0 or abs(cross(v1, v2)) == 0:
return False
v3 = (c[0][0] - p1[0], c[0][1] - p1[1])
v4 = (c[1][0] - p1[0], c[1][1] - p1[1])
return (on_line(v3, v1) and on_line(v4, v2)) or (on_line(v3, v2) and on_line(v4, v1))
for i in range(int(input())):
xa1, ya1, xa2, ya2 = r()
xb1, yb1, xb2, yb2 = r()
xc1, yc1, xc2, yc2 = r()
a, b, c = [(xa1, ya1), (xa2, ya2)], [(xb1, yb1), (xb2, yb2)], [(xc1, yc1), (xc2, yc2)]
print ("YES" if is_A(a, b, c) or is_A(a, c, b) or is_A(b, c, a) else "NO") | py |
1296 | F | F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1
| [
"constructive algorithms",
"dfs and similar",
"greedy",
"sortings",
"trees"
] | class HLD:
def __init__(self, g):
self.g = g
self.n = len(g)
self.parent = [-1]*self.n
self.size = [1]*self.n
self.head = [0]*self.n
self.preorder = [0]*self.n
self.k = 0
self.depth = [0]*self.n
for v in range(self.n):
if self.parent[v] == -1:
self.dfs_pre(v)
self.dfs_hld(v)
def dfs_pre(self, v):
g = self.g
stack = [v]
order = [v]
while stack:
v = stack.pop()
for u in g[v]:
if self.parent[v] == u:
continue
self.parent[u] = v
self.depth[u] = self.depth[v]+1
stack.append(u)
order.append(u)
# 隣接リストの左端: heavyな頂点への辺
# 隣接リストの右端: 親への辺
while order:
v = order.pop()
child_v = g[v]
if len(child_v) and child_v[0] == self.parent[v]:
child_v[0], child_v[-1] = child_v[-1], child_v[0]
for i, u in enumerate(child_v):
if u == self.parent[v]:
continue
self.size[v] += self.size[u]
if self.size[u] > self.size[child_v[0]]:
child_v[i], child_v[0] = child_v[0], child_v[i]
def dfs_hld(self, v):
stack = [v]
while stack:
v = stack.pop()
self.preorder[v] = self.k
self.k += 1
top = self.g[v][0]
# 隣接リストを逆順に見ていく(親 > lightな頂点への辺 > heavyな頂点 (top))
# 連結成分が連続するようにならべる
for u in reversed(self.g[v]):
if u == self.parent[v]:
continue
if u == top:
self.head[u] = self.head[v]
else:
self.head[u] = u
stack.append(u)
def for_each(self, u, v):
# [u, v]上の頂点集合の区間を列挙
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
l = max(self.preorder[self.head[v]], self.preorder[u])
r = self.preorder[v]
yield l, r # [l, r]
if self.head[u] != self.head[v]:
v = self.parent[self.head[v]]
else:
return
def for_each_edge(self, u, v):
# [u, v]上の辺集合の区間列挙
# 辺の情報は子の頂点に
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
if self.head[u] != self.head[v]:
yield self.preorder[self.head[v]], self.preorder[v]
v = self.parent[self.head[v]]
else:
if u != v:
yield self.preorder[u]+1, self.preorder[v]
break
def subtree(self, v):
# 頂点vの部分木の頂点集合の区間 [l, r)
l = self.preorder[v]
r = self.preorder[v]+self.size[v]
return l, r
def lca(self, u, v):
# 頂点u, vのLCA
while True:
if self.preorder[u] > self.preorder[v]:
u, v = v, u
if self.head[u] == self.head[v]:
return u
v = self.parent[self.head[v]]
class SegTree:
def __init__(self, init_val, ide_ele, segfunc):
self.n = len(init_val)
self.num = 2**(self.n-1).bit_length()
self.ide_ele = ide_ele
self.segfunc = segfunc
self.seg = [ide_ele]*2*self.num
# set_val
for i in range(self.n):
self.seg[i+self.num] = init_val[i]
# built
for i in range(self.num-1, 0, -1):
self.seg[i] = self.segfunc(self.seg[2*i], self.seg[2*i+1])
def update(self, k, x):
k += self.num
self.seg[k] = x
while k:
k = k >> 1
self.seg[k] = self.segfunc(self.seg[2*k], self.seg[2*k+1])
def query(self, l, r):
if r <= l:
return self.ide_ele
l += self.num
r += self.num
lres = self.ide_ele
rres = self.ide_ele
while l < r:
if r & 1:
r -= 1
rres = self.segfunc(self.seg[r], rres)
if l & 1:
lres = self.segfunc(lres, self.seg[l])
l += 1
l = l >> 1
r = r >> 1
res = self.segfunc(lres, rres)
return res
def __str__(self): # for debug
arr = [self.query(i,i+1) for i in range(self.n)]
return str(arr)
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
INF = 10**6
n = int(input())
edge = [[] for i in range(n)]
toid = {}
for i in range(n-1):
x, y = map(int, input().split())
x, y =x-1, y-1
edge[x].append(y)
edge[y].append(x)
toid[(x,y)] = i
toid[(y,x)] = i
m = int(input())
Q = []
for i in range(m):
a, b, g = map(int, input().split())
a, b = a-1, b-1
Q.append((a, b, g))
Q.sort(key=lambda x: -x[2])
hld = HLD(edge)
segMin = SegTree([INF]*n, INF, min)
segPos = SegTree(list(range(n)), -1, max)
for a, b, g in Q:
for l, r in hld.for_each_edge(a, b):
while segPos.query(l, r+1) != -1:
p = segPos.query(l, r+1)
segMin.update(p, g)
segPos.update(p, -1)
check = INF
for l, r in hld.for_each_edge(a, b):
check = min(check, segMin.query(l, r+1))
if check != g:
print(-1)
exit()
ans = [0]*(n-1)
for v in range(1, n):
i = hld.preorder[v]
p = hld.parent[v]
idx = toid[(p, v)]
f = segMin.query(i, i+1)
ans[idx] = f
print(*ans)
| py |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | for _ in range(int(input())):
n, x = map(int, input().split())
a = list(map(int, input().split()))
if x in a:
print(1)
else:
a = sorted(a)
i = 0
j = len(a)-1
f = 0
if x%2==0:
while i<=j:
m = (i+j)
if a[m]>=x//2:
print(2)
f = 1
break
else:
i = m+1
else:
while i<=j:
m = (i+j)
if a[m]>x//2:
f = 1
print(2)
break
else:
i = m+1
if f == 0:
p = 0
i = 0
while i<len(a) and a[i]<x:
if x%a[i]==0:
p = a[i]
i = i + 1
if p==0:
print((x//a[-1])+1)
else:
print(min(x//p,(x//a[-1])+1))
| py |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | t = int(input())
for _ in range(t):
n, m = map(int, input().split())
lst = [int(x) for x in input().split()][:n]
sum = 0
for i in range(n):
sum += lst[i]
print(min(m, sum))
| py |
1325 | F | F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample: | [
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy"
] | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
e = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n + 1)]
for u, v in e:
g[u].append(v)
g[v].append(u)
req = 1
while req * req < n:
req += 1
def dfs():
dep = [0] * (n + 1)
par = [0] * (n + 1)
st = [1]
st2 = []
while st:
u = st.pop()
if dep[u]:
continue
st2.append(u)
dep[u] = dep[par[u]] + 1
for v in g[u]:
if not dep[v]:
par[v] = u
st.append(v)
elif dep[u] - dep[v] + 1 >= req:
cyc = []
while u != par[v]:
cyc.append(u)
u = par[u]
return (None, cyc)
mk = [0] * (n + 1)
iset = []
while st2:
u = st2.pop()
if not mk[u]:
iset.append(u)
for v in g[u]:
mk[v] = 1
return (iset[:req], None)
iset, cyc = dfs()
if iset:
print(1)
print(*iset)
else:
print(2)
print(len(cyc))
print(*cyc)
| py |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | t = int(input())
t_c = [tuple(map(int, input().split())) for _ in range(t)]
for i in t_c:
l = None
if i[1] < 9 :
l = 0
elif int((tmp := len(str(i[1]))) * '9') <= i[1]:
l = tmp
else:
l = tmp - 1
print(i[0] * l) | py |
1300 | A | A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4. | [
"implementation",
"math"
] | t = int(input()) # t (1≤t≤104) — количество наборов входных данных
for i in range(t):
n = int(input())
#kr = input()
#kr =[int(x) for x in kr]
a = input() ; a = a.split()
a = [int(x) for x in a]
#s = input()
sm = sum(a)
kol = a.count(0)
if sm + kol == 0:
kol += 1
print( kol) | py |
1284 | A | A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal. | [
"implementation",
"strings"
] | # LUOGU_RID: 101844461
n, m = map(int, input().split())
s = input().split()
t = input().split()
for _ in range(int(input())):
x = int(input()) - 1
print(s[x % n] + t[x % m]) | py |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | import sys
for _ in range(int(sys.stdin.readline())):
a,b,c=map(int,sys.stdin.readline().split())
a1,b1,c1=a,b,c
count=10**9+7
for i in range(1,a*2+1):
for j in range(i,2*b+1,i):
for x in range(j,2*c+1,j):
y=abs(a-i)+abs(b-j)+abs(c-x)
if y<count:
a1=i
b1=j
c1=x
count=y
print(count)
print(a1,b1,c1)
| py |
1294 | F | F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc 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.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer. | [
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
input = sys.stdin.buffer.readline
def process_root(g, r):
start = [r]
seen = {r: 0}
parent = {r: None}
while len(start) > 0:
next_s = []
for x in start:
for y in g[x]:
if y not in seen:
seen[y] = seen[x]+1
parent[y] = x
next_s.append(y)
start = next_s
return seen, parent
def find_diameter(g):
for x in g:
break
seen, parent = process_root(g, x)
my_max = [0, x]
for y in seen:
if seen[y] > my_max[0]:
my_max = [seen[y], y]
a = my_max[1]
seen, parent = process_root(g, a)
my_max = [0, a]
for y in seen:
if seen[y] > my_max[0]:
my_max = [seen[y], y]
c = my_max[1]
L = [c]
while L[-1] != a:
x = parent[L[-1]]
L.append(x)
return L, parent
def process(G):
#we want three vertices a b c to maximize edges on paths between them
#if b is on path from a to c then we don't get helped.
#so none of them is on the path between the other two.
#say path from b to a intersects path from c to a at x
#a0 = a, a1, a2, a3, ..., ak = c
#x =ai , 0 < i < k
#a, c = diameter of tree
#b = longest branch off diameter?
g = {}
n = len(G)
for i in range(n):
a, b = G[i]
if a not in g:
g[a] = set([])
if b not in g:
g[b] = set([])
g[a].add(b)
g[b].add(a)
L, parent = find_diameter(g)
a, c = L[0], L[-1]
b = L[1]
L = set(L)
distance = {}
answer = [0, None]
for x in g:
if len(g[x])==1 and x != a and x != c:
L2 = [x]
while L2[-1] not in distance:
L2.append(parent[L2[-1]])
if L2[-1] in L:
distance[L2[-1]] = 0
break
L2.pop()
while len(L2) > 0:
x2 = L2.pop()
distance[x2] = distance[parent[x2]]+1
answer = max([distance[x], x], answer)
if answer[1] is None:
path_length = len(L)-1
return [path_length, a, b, c]
else:
b = answer[1]
path_length = len(L)-1+answer[0]
return [path_length, a, b, c]
n = int(input())
G = []
for i in range(n-1):
a, b = [int(x) for x in input().split()]
G.append([a, b])
path_length, a, b, c = process(G)
print(path_length)
print(f'{a} {b} {c}')
| py |
1316 | B | B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. | [
"brute force",
"constructive algorithms",
"implementation",
"sortings",
"strings"
] | from audioop import reverse
from sys import stdin, stdout
import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_arr(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
t = int(input())
while t:
t-=1
n = int(input())
s = get_string()
s1 = s
s2 = s
# print(s2)
ans = 0
for i in range(0,n):
if (n-i)%2==0:
s3 = s1[0:i]
s4 = s[i:n] + s3
if s4<s2:
ans = i
s2 = min(s2,s4)
# print(s[i:n])
# print(s3[::-1])
# print(s4)
else:
s3 = s1[0:i]
s4 = s[i:n] + s3[::-1]
if s4<s2:
ans = i
s2 = min(s2,s4)
# print(s[i:n])
# print(s3[::-1])
# print(s4)
print(s2)
print(ans+1)
| py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.