contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
listlengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
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"
] |
from collections import deque
import sys
n,m,k = map(int,sys.stdin.readline().split())
a = list(map(int,sys.stdin.readline().split()))
g = [[] for _ in range(n+1)]
for _ in range(m):
x,y = map(int,sys.stdin.readline().split())
g[x].append(y)
g[y].append(x)
def bfs(start):
hold = [0]*(n+1)
visited = [False]*(n+1)
q = deque()
q.append(start)
h = 0
while len(q)>0:
for _ in range(len(q)):
node = q.popleft()
visited[node] = True
hold[node] = h
for child in g[node]:
if not(visited[child]):
visited[child] = True
q.append(child)
h+=1
return hold
x = bfs(1) #dis 1 to i
y = bfs(n) #dis i to n
arr = sorted([(x[i]-y[i],i) for i in a])
pref,ans = -1e9,-1e9
for v,node in arr:
ans = max(ans,pref+y[node])
pref = max(pref,x[node])
print(min(x[n],ans+1))
|
py
|
1285
|
A
|
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
|
[
"math"
] |
a= int(input())
b = input()
print(a+1)
|
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"
] |
n, m = map(int,input().split())
s = input().split()
t = input().split()
q = int(input())
for z in range(q):
x = int(input()) - 1
print(s[x % n] + t[x % m])
|
py
|
1316
|
D
|
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters — UU, DD, LL, RR or XX — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103) — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
|
[
"constructive algorithms",
"dfs and similar",
"graphs",
"implementation"
] |
from collections import deque
def bfs(i,j):
q=deque([(i,j)])
while q:
i,j=q.popleft()
for a,b,d in [(i+1,j,'U'),(i-1,j,'D'),(i,j+1,'L'),(i,j-1,'R')]:
if a==-1 or a==n or b==-1 or b==n or v[a][b]:
continue
if m[a][b]==m[i][j]:
v[a][b]=d
q.append((a,b))
n=int(input())
m=[[None]*n for _ in range(n)]
v=[[False]*n for _ in range(n)]
for i in range(n):
r=[int(i) for i in input().split()]
for j in range(n):
a,b=r[2*j]-1,r[2*j+1]-1
m[i][j]=(a,b)
for i in range(n):
for j in range(n):
if m[i][j]==(i,j):
v[i][j]="X"
bfs(i,j)
if m[i][j]==(-2,-2):
for a,b,nxt,prev in [(i+1,j,'D','U'),(i-1,j,'U','D'),(i,j+1,'R','L'),(i,j-1,'L','R')]:
if a==-1 or a==n or b==-1 or b==n:
continue
if m[a][b]==(-2,-2):
v[i][j],v[a][b]=nxt,prev
break
else:
print("INVALID")
exit()
for i in range(n):
for j in range(n):
if v[i][j]==False:
print("INVALID")
exit()
print('VALID')
print('\n'.join([''.join(x) for x in v]))
|
py
|
1311
|
F
|
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
|
[
"data structures",
"divide and conquer",
"implementation",
"sortings"
] |
from sys import stdin
input=lambda :stdin.readline()[:-1]
class segtree():
def __init__(self,init,func,ide):
self.n=len(init)
self.func=func
self.ide=ide
self.size=1<<(self.n-1).bit_length()
self.tree=[self.ide for i in range(2*self.size)]
for i in range(self.n):
self.tree[self.size+i]=init[i]
for i in range(self.size-1,0,-1):
self.tree[i]=self.func(self.tree[2*i], self.tree[2*i|1])
def update(self,k,x):
k+=self.size
self.tree[k]=x
k>>=1
while k:
self.tree[k]=self.func(self.tree[2*k],self.tree[k*2|1])
k>>=1
def get(self,i):
return self.tree[i+self.size]
def query(self,l,r):
l+=self.size
r+=self.size
l_res=self.ide
r_res=self.ide
while l<r:
if l&1:
l_res=self.func(l_res,self.tree[l])
l+=1
if r&1:
r-=1
r_res=self.func(self.tree[r],r_res)
l>>=1
r>>=1
return self.func(l_res,r_res)
def debug(self,s=10):
print([self.get(i) for i in range(min(self.n,s))])
n=int(input())
x=list(map(int,input().split()))
v=list(map(int,input().split()))
s=sorted(list(set(x)))
d={}
m=len(s)
for i in range(m):
d[s[i]]=i
seg1=segtree([0]*m,lambda x,y:x+y,0)
seg2=segtree([0]*m,lambda x,y:x+y,0)
vx=[(v[i],x[i]) for i in range(n)]
vx.sort()
ans=0
for vi,xi in vx:
i=d[xi]
ans+=seg1.query(0,i)*xi-seg2.query(0,i)
seg1.update(i,1)
seg2.update(i,xi)
print(ans)
|
py
|
1303
|
C
|
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO
|
[
"dfs and similar",
"greedy",
"implementation"
] |
import string
def solve():
G=int(input())
for H in range(G):
E=input().strip();A=[];A.append(E[0]);C=0;D=set(A);F=False
for B in E[1:]:
if C>0 and B==A[C-1]:C-=1
elif C<len(A)-1 and B==A[C+1]:C+=1
elif C==len(A)-1 and B not in D:A.append(B);D.add(B);C+=1
elif C==0 and B not in D:A=[B]+A;D.add(B)
else:F=True
if F:print('NO')
else:
print('YES')
for B in string.ascii_lowercase:
if B not in D:A.append(B)
print(''.join(A))
if __name__=='__main__':solve()
|
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"
] |
from sys import stdin
class disjoinSet(object):
def __init__(self,n):
self.father = [x for x in range(0,n+1)]
self.rank = [0 for x in range(0,n+1)]
def setOf(self, x):
if(self.father[x] != x):
self.father[x] = self.setOf(self.father[x])
return self.father[x]
def Merge(self,x,y):
xR = self.setOf(x)
yR = self.setOf(y)
if(xR == yR):
return
if self.rank[xR] < self.rank[yR]:
self.father[xR] = yR
size[yR] += size[xR]
elif self.rank[xR] > self.rank[yR]:
self.father[yR] = xR
size[xR] += size[yR]
else:
self.father[yR] = xR
size[xR] += size[yR]
self.rank[xR] +=1
def LessSize(x):
return min(size[dsu.setOf(x)],size[dsu.setOf(x+k)])
def Solve(i):
global ans
cant = col[i][0]
if cant == 2:
x = col[i][1]
y = col[i][2]
if S[i] == 1:
if dsu.setOf(x) == dsu.setOf(y):
return
ans -=LessSize(x) + LessSize(y)
dsu.Merge(x,y)
dsu.Merge(x+k,y+k)
ans +=LessSize(y)
else:
if dsu.setOf(x) == dsu.setOf(y+k):
return
ans -=LessSize(x)+LessSize(y)
dsu.Merge(x,y+k)
dsu.Merge(x+k,y)
ans +=LessSize(y)
elif cant == 1:
x = col[i][1]
if S[i] == 1:
if dsu.setOf(x) == dsu.setOf(0):
return
ans -=LessSize(x)
dsu.Merge(x,0)
ans +=LessSize(x)
else:
if dsu.setOf(x+k) == dsu.setOf(0):
return
ans -=LessSize(x)
dsu.Merge(x+k,0)
ans +=LessSize(x)
n,k = map(int,input().split())
S = [1]+list(map(int,list(stdin.readline().strip())))
dsu = disjoinSet(k*2+1)
col = [[0 for _ in range(3)] for _ in range(n+2)]
size = [0 for _ in range(k*2+1)]
ans = 0
for i in range(1,k+1):
c = stdin.readline()
c = int(c)
conjunto = [1]+list(map(int,list(stdin.readline().split())))
for j in range(1,len(conjunto)):
x = conjunto[j]
col[x][0] = col[x][0]+1
col[x][col[x][0]] = i
for i in range(1,k+1):
size[i]=1
size[0]=3*10e5
for i in range(1,n+1):
Solve(i)
print(ans)
|
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"
] |
import math
def __gcd(a,b):
return (a if b == 0 else __gcd(b,a % b))
def phi(val):
ret = 1
for i in range(2,int(math.sqrt(val)) + 1):
if val % i == 0:
c = 0
while val % i == 0:
val //= i
c += 1
ret *= (i - 1)
for j in range(1,c):
ret *= i
if val > 1:
ret *= (val - 1)
return ret
for _ in range(int(input())):
a,m = map(int,input().split())
g = __gcd(a,m)
print(phi(m // g))
|
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):
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
|
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"
] |
print(sum([1/i for i in range(1,int(input())+1)]))
|
py
|
1141
|
A
|
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
|
[
"implementation",
"math"
] |
import sys
a,b=map(int,input().split())
cnt=0
if(b==a):
print(0)
sys.exit()
if(b==0 or a==0):
print(-1)
sys.exit()
if(a>b):
print(-1)
sys.exit()
divi=b//a
while(divi%2==0):
divi=divi//2
cnt+=1
while(divi%3==0):
divi=divi//3
cnt+=1
if(b%a!=0):
cnt=-1
if(divi==1):
print(cnt)
else:
print(-1)
|
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((1 << (bit + 2)) - 2 - (a[i] % mod), Max)
ones += mem[hi] - mem[lo - 1] - (lo <= a[i] % mod <= hi)
ones >>= 1
ans |= (1 << bit) * (ones & 1)
for i in range(min(mod * 2, Max + 1)): mem[i] = 0
out.append(ans)
print('\n'.join(map(str, out)))
|
py
|
1323
|
B
|
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2
1 0 1
1 1 1
OutputCopy4
InputCopy3 5 4
1 1 1
1 1 1 1 1
OutputCopy14
NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
|
[
"binary search",
"greedy",
"implementation"
] |
import math
def functie_divizori(numar):
dictionar={}
matrice=[]
if numar==1:
a=[1]*2
a.append(0)
a.append(0)
matrice.append(a)
else:
for j in range(1,math.floor(numar**(1/2))+1):
# print("j=",j)
if numar%j==0:
tupleta=[]
# print(dictionar)
tupleta.append(j)
tupleta.append(numar//j)
tupleta.append(0)
tupleta.append(0)
matrice.append(tupleta)
tupleta=[]
if numar//j!=j:
tupleta=[]
tupleta.append(numar//j)
tupleta.append(j)
tupleta.append(0)
tupleta.append(0)
matrice.append(tupleta)
return matrice
n,m,k=list(map(int, input().split()))
#cazuri=int(input())
vector_a=list(map(int,input().split()))
vector_b=list(map(int,input().split()))
#print(functie_divizori(2))
#n=int(input())
#n,m=list(map(int,input().split()))
#bloc=list(map(int, input().split()))
#bloc.sort()
# bloc=bloc[::-1]
#print(functie_divizori(9))
tupleta_a=functie_divizori(k)
#tupleta_b=functie_divizori(k)
#print("aa",tupleta_a)
suma_a=0
suma_b=0
for i in range(n):
if vector_a[i]==1:
suma_a+=1
else:
# print("i=",i)
for jj in range(len(tupleta_a)):
if tupleta_a[jj][0]<=suma_a:
tupleta_a[jj][2]=tupleta_a[jj][2]+suma_a+1-tupleta_a[jj][0]
suma_a=0
#print("l=",len(tupleta_a))
if suma_a>0:
for jj in range(len(tupleta_a)):
#print("jj=",jj)
if tupleta_a[jj][0]<=suma_a:
tupleta_a[jj][2]=tupleta_a[jj][2]+suma_a+1-tupleta_a[jj][0]
for i in range(m):
if vector_b[i]==1:
suma_b+=1
else:
# print("i=",i)
for jj in range(len(tupleta_a)):
if tupleta_a[jj][1]<=suma_b:
tupleta_a[jj][3]=tupleta_a[jj][3]+suma_b+1-tupleta_a[jj][1]
suma_b=0
if suma_b>0:
for jj in range(len(tupleta_a)):
if tupleta_a[jj][1]<=suma_b:
tupleta_a[jj][3]=tupleta_a[jj][3]+suma_b+1-tupleta_a[jj][1]
answ=0
for i in range(len(tupleta_a)):
answ+=tupleta_a[i][2]*tupleta_a[i][3]
# answ+=tupleta_b[i][2]*tupleta_b[i][3]
#print(tupleta_a)
#print(tupleta_b)
print(answ)
|
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
if __name__=="__main__":
n,m=sys.stdin.readline().strip().split(" ")
n=int(n)
m=int(m)
part=int((n-1)**0.5+1)
d={}
e={}
for i in range(m):
x,y=sys.stdin.readline().strip().split(" ")
y=int(y)
x=int(x)
if x not in e:
e[x]=[]
if y not in e:
e[y]=[]
e[x].append(y)
e[y].append(x)
stack_queue=[]
stack_queue.append((1,0,-1,0, 0))
tp=0
res=[]
cnt={}
while (len(stack_queue)>0) :#and cnt>-1:
# cnt-=1
now=stack_queue.pop()
x,h,fa,r, idone=now
if x not in d:
d[x]=h
tmpp=h%(part-1)
cnt[tmpp]=cnt.get(tmpp,0)+1
if r==0:
for i1 in range(idone,len(e[x])):
i=e[x][i1]
if fa==i:
continue
if i in d:
if d[x]-d[i]+1 >= part:
tp=i
res.append(str(x))
break
else:
continue
stack_queue.append((x, h,fa,1,i1))
if tp ==0:
stack_queue.append((i, h+1, x, 0, 0))
break
continue
if r==1:
i=e[x][idone]
if tp>0:
res.append(str(x))
if x ==tp:
tp=-1
if tp==0:
stack_queue.append((x, h,fa,0,idone+1))
if len(res)>0:
print(2)
print (len(res))
print (" ".join(res))
else:
target=-1
for i in cnt:
if cnt[i]>=part:
target=i
break
tmppart=part
for i in d:
#aprint (d,i,target)
if (d[i]%(tmppart-1))!=target:
continue
if part>0:
part-=1
res.append(str(i))
else:
break
print(1)
print (" ".join(res))
|
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, random
input = lambda : sys.stdin.readline().rstrip()
write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18
LI = lambda : list(map(int, input().split())); II=lambda : int(input())
def debug(_l_):
for s in _l_.split():
print(f"{s}={eval(s)}", end=" ")
print()
def dlist(*l, fill=0):
if len(l)==1:
return [fill]*l[0]
ll = l[1:]
return [dlist(*ll, fill=fill) for _ in range(l[0])]
n = int(input())
xy = [LI() for _ in range(n)]
xy.append(xy[0])
if n%2==0:
for i in range(n//2):
px,py = xy[i+1][0]-xy[i][0], xy[i+1][1] - xy[i][1]
qx,qy = xy[n//2+i+1][0]-xy[n//2+i][0], xy[n//2+i+1][1] - xy[n//2+i][1]
# print(px,py,qx,qy)
if px==-qx and py==-qy:
pass
else:
print("No")
break
else:
print("Yes")
else:
print("No")
|
py
|
1292
|
A
|
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
|
[
"data structures",
"dsu",
"implementation"
] |
#! /bin/env python3
# perhaps... Life is full of puzzles
def main():
n, q = map(int, input().split(' '))
v = [[0 for i in range(n+5)] \
for j in range(3)]
# solve
c = 0
for _ in range(q):
x, y = map(int, input().split(' '))
s = v[x][y]
cnt = 0
l, r = max(1, y-1), min(n, y+1)
for i in range(l, r+1):
if v[3-x][i] == 1: cnt += 1
c += cnt if s == 0 else -cnt
v[x][y] ^= 1
print("Yes" if c == 0 else "No")
main()
|
py
|
1315
|
A
|
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
|
[
"implementation"
] |
def solve():
for _ in range(int(input())):
a, b, x, y = map(int, input().split())
num1 = x * b
num2 = y * a
num3 = (a - x - 1) * b
num4 = (b - y - 1) * a
print(max(num1, num2, num3, num4))
solve()
|
py
|
1299
|
A
|
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
|
[
"brute force",
"greedy",
"math"
] |
import random
def transformare_baza(numar,baza):
vector_transformare=[0]*40
transformare=""
while numar>=baza:
rest=numar%baza
numar=numar//baza
transformare+=str(rest)
transformare+=str(numar)
noua_baza=transformare[::-1]
nou_string=(40-len(noua_baza))*'0'
noua_baza=nou_string+noua_baza
for j in range(40):
vector_transformare[j]=noua_baza[j]
return noua_baza
def bitwise_xor(a,b):
stringul_1=transformare_baza(a,2)
stringul_2=transformare_baza(b,2)
lungime=max(len(stringul_1), len(stringul_2))
raspunsul=0
#print(stringul_1,stringul_2)
str_answ=[0]*40
# print('lungime=', lungime)
#print(str_answ)
for i in range(0,lungime):
# print(i,str_answ)
j=lungime-1-i
if len(stringul_1)>i and len(stringul_2)>i:
if stringul_1[len(stringul_1)-1-i]!= stringul_2[len(stringul_2)-1-i]:
raspunsul+=2**(i)
str_answ[39-i]='1'
elif len(stringul_1)>i and stringul_1[len(stringul_1)-1-i]=='1':
raspunsul+=2**(i)
str_answ[39-i]='1'
elif len(stringul_2)>i and stringul_2[len(stringul_2)-1-i]=='1':
raspunsul+=2**(i)
str_answ[39-i]='1'
#print(str_answ)
str_answ=str_answ[::-1]
return str_answ
def bitwise_or(a,b):
stringul_1=transformare_baza(a,2)
stringul_2=transformare_baza(b,2)
lungime=max(len(stringul_1), len(stringul_2))
raspunsul=0
#print(stringul_1,stringul_2)
str_answ=[0]*40
# print('lungime=', lungime)
#print(stringul_1,stringul_2)
#print(str_answ)
#print("l1=",len(stringul_1), "l2=",len(stringul_2))
for i in range(0,lungime):
# print(i,str_answ)
j=lungime-1-i
#print(i,"aici?",stringul_2[len(stringul_2)-1-i])
if len(stringul_1)>i and len(stringul_2)>i:
if stringul_1[len(stringul_1)-1-i]!='0' or '0'!= stringul_2[len(stringul_2)-1-i]:
raspunsul+=2**(i)
str_answ[39-i]='1'
elif len(stringul_1)>i and stringul_1[len(stringul_1)-1-i]=='1' :
raspunsul+=2**(i)
str_answ[39-i]='1'
elif len(stringul_2)>i and stringul_2[len(stringul_2)-1-i]=='1' :
raspunsul+=2**(i)
str_answ[39-i]='1'
#print("aici")
#print(*str_answ)
return raspunsul
#n,m,k=list(map(int, input().split()))
#cazuri=int(input())
cate=0
care=-1
tupla=[]
for tt in range(1):
matrice=[]
n=int(input())
bloc=list(map(int,input().split()))
for i in range(n):
matrice.append(transformare_baza(bloc[i],2))
posibil=0
care=-1
for i in range(40):
posibil=0
partial=-1
for j in range(n):
if matrice[j][i]=='1' :
# print(j,i,posibil,partial)
if posibil==0:
posibil=1
partial=j
#print("care",bloc[care],j)
else:
posibil=-1
j=n+1
break
if posibil==1:
care=partial
#print("care=",care)
j=n+1
i=41
break
#print("care=",care)
#if care>-1:
# print(bloc[care],end=' ')
# print(*bloc[0:care],end=' ')
# print(*bloc[care+1:n])
# else:
# print(*bloc)
# print(matrice)
if care>-1:
print(bloc[care],end=' ')
print(*bloc[0:care],end=' ')
print(*bloc[care+1:n])
else:
print(*bloc)
|
py
|
1315
|
C
|
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
|
[
"greedy"
] |
for i in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
a=[]
i=0
t=0
while(len(a)!=(2*n)):
if(t==0):
r=arr[i]
a.append(arr[i])
if (r+1 not in arr) and (r+1 not in a):
a.append(r+1)
i+=1
t=0
else:
r+=1
t=1
b=[]
for i in a:
b.append(i)
c=[]
b.sort()
for i in range(2*n):
c.append(i+1)
if b!=c :
print(-1)
else:
print(*a)
|
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"
] |
for _ in range(int(input())):
N,K = map(int,input().split())
A = list(map(int,input().split()))
check = [0]*101
ans = 'Yes'
for i in A:
for b in range(61,-1,-1):
if K**b<=i:
i -= K**b
check[b] += 1
if i!=0:
ans = "No"
break
for i in check:
if i>=2:
ans = "No"
break
print(ans)
|
py
|
1325
|
B
|
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?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. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
|
[
"greedy",
"implementation"
] |
t=int(input())
for _ in range(t):
n=int(input())
a=set(map(int,input().split()))
print(len(a))
|
py
|
1294
|
C
|
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.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 nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823
|
[
"greedy",
"math",
"number theory"
] |
t = int(input())
#prime sieve
MAX = 32000 #sqrt(10**9)
primeSieve = [True]*MAX
primes = []
primeSieve[0] = primeSieve[1] = False
for i in range(2,MAX):
if primeSieve[i] == True:
primes.append(i)
for j in range(i*i, MAX, i):
primeSieve[j] = False
for _ in range(t):
n = int(input())
nums = []
i = 0
while i<len(primes) and n > 1:
if n%primes[i] == 0:
nums.append(primes[i])
n //= primes[i]
if len(nums) == 2:
break
if n%(primes[i]**2) == 0:
nums.append(primes[i]**2)
n //= primes[i]**2
break
i += 1
if len(nums) >=2 and n not in nums+[1]:
print("YES")
print(*nums,n)
else:
print("NO")
|
py
|
1301
|
A
|
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
|
[
"implementation",
"strings"
] |
import sys
import math
from collections import defaultdict,Counter,deque
input = sys.stdin.readline
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
def WRITE(out):
return print('\n'.join(map(str, out)))
def WS(out):
return print(' '.join(map(str, out)))
def WNS(out):
return print(''.join(map(str, out)))
'''
101
110
1011
a+b = a xor b + 2*(a and b)
1
11
10
11
11
1
100
101
11011111101010010
'''
def solve():
t = II()
for _ in range(t):
a = I().strip()
b = I().strip()
c = I().strip()
valid = True
for i in range(len(a)):
if not (c[i] == a[i] or c[i] == b[i]):
valid = False
break
print("YES" if valid else "NO")
solve()
|
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"
] |
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)]
def solve():
s, t = I(), I()
n, m = len(s), len(t)
for x in range(m+1):
t1, t2 = t[:x], t[x:]
dp = [[-1] * (x+1) for _ in range(n+1)]
dp[0][0] = 0
for i in range(n):
for j in range(x+1):
if dp[i][j] < 0:
continue
if j < len(t1) and s[i] == t1[j]:
dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j])
if dp[i][j] < len(t2) and s[i] == t2[dp[i][j]]:
dp[i+1][j] = max(dp[i+1][j], dp[i][j] + 1)
dp[i+1][j] = max(dp[i+1][j], dp[i][j])
if dp[n][x] + x == m:
return print("YES")
print("NO")
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
|
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
input = sys.stdin.buffer.readline
from collections import deque
def countingSort(arr, exp1):
n = len(arr)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n):
index = arr[i] // exp1
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp1
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
i = 0
for i in range(0, len(arr)):
arr[i] = output[i]
def radixSort(arr):
max1 = max(arr)
exp = 1
while max1 / exp >= 1:
countingSort(arr, exp)
exp *= 10
N = int(input())
a = list(map(int, input().split()))
res = 0
radixSort(a)
for k in range(max(a).bit_length(), -1, -1):
z = 1 << k
c = 0
j = jj = jjj = N - 1
for i in range(N):
while j >= 0 and a[i] + a[j] >= z: j -= 1
while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1
while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1
c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj)
res += z * (c & 1)
for i in range(N): a[i] = min(a[i] ^ z, a[i])
a.sort()
#print(res, a, c)
print(res)
|
py
|
1285
|
D
|
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.
|
[
"bitmasks",
"brute force",
"dfs and similar",
"divide and conquer",
"dp",
"greedy",
"strings",
"trees"
] |
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def binary(n):
return bin(n)[2:]
def calculate_answer(numbers, position):
# If we check all the bits, return 0
if position < 0:
return 0
off = []
on = []
# Check if the bit in position is on or off for every number
for n in numbers:
if (n >> position) & 1 == 0:
off.append(n)
else:
on.append(n)
# Check if the lists are empty to recursively call the function in the next bit
if len(off) == 0:
return calculate_answer(on, position - 1)
elif len(on) == 0:
return calculate_answer(off, position - 1)
# Return the minimum between the two lists and add it to 2^bit
return min(calculate_answer(off, position - 1), calculate_answer(on, position - 1)) + 2 ** position
n = inp()
a = inlt()
# Transform list into binary and obtain the longest binary number to know how many bits we need to check
b = [binary(i) for i in a]
longest = len(max(b, key=len))
print(calculate_answer(a, longest - 1))
|
py
|
1301
|
E
|
E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1≤n,m≤500,1≤q≤3⋅105)(1≤n,m≤500,1≤q≤3⋅105) — the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1≤r1≤r2≤n,1≤c1≤c2≤m)(1≤r1≤r2≤n,1≤c1≤c2≤m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
OutputCopy16
4
4
4
0
InputCopy6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
OutputCopy36
4
16
16
16
InputCopy8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
OutputCopy64
0
16
4
16
4
36
0
NotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.
|
[
"binary search",
"data structures",
"dp",
"implementation"
] |
import io, os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n,m,q=map(int,input().split())
C=[input().strip() for i in range(n)]
ATABLE=[[0]*m for i in range(n)]
for i in range(n-1):
for j in range(m-1):
if C[i][j]==82 and C[i+1][j]==89 and C[i][j+1]==71 and C[i+1][j+1]==66:
for l in range(1,5000):
if 0<=i-l and 0<=j-l and i+l+1<n and j+l+1<m:
True
else:
break
flag=1
for k in range(i-l,i+1):
if C[k][j-l]!=82:
flag=0
break
if C[k][j+l+1]!=71:
flag=0
break
if flag==0:
break
for k in range(j-l,j+1):
if C[i-l][k]!=82:
flag=0
break
if C[i+l+1][k]!=89:
flag=0
break
if flag==0:
break
for k in range(i+1,i+l+2):
if C[k][j-l]!=89:
flag=0
break
if C[k][j+l+1]!=66:
flag=0
break
if flag==0:
break
for k in range(j+1,j+l+2):
if C[i-l][k]!=71:
flag=0
break
if C[i+l+1][k]!=66:
flag=0
break
if flag==0:
break
ATABLE[i][j]=l
#for i in range(n):
# print(ATABLE[i])
Sparse_table1 = [[ATABLE[i]] for i in range(n)]
for r in range(n):
for i in range(m.bit_length()-1):
j = 1<<i
B = []
for k in range(len(Sparse_table1[r][-1])-j):
B.append(max(Sparse_table1[r][-1][k], Sparse_table1[r][-1][k+j]))
Sparse_table1[r].append(B)
#for i in range(n):
# print(Sparse_table1[i])
Sparse_table2 = [[[[Sparse_table1[i][j][k] for i in range(n)]] for k in range(len(Sparse_table1[0][j]))] for j in range(m.bit_length())]
for d in range(m.bit_length()):
for c in range(len(Sparse_table1[0][d])):
for i in range(n.bit_length()-1):
#print(d,c,Sparse_table2[d][c])
j = 1<<i
B = []
for k in range(len(Sparse_table2[d][c][-1])-j):
B.append(max(Sparse_table2[d][c][-1][k], Sparse_table2[d][c][-1][k+j]))
Sparse_table2[d][c].append(B)
#print("!",B)
for query in range(q):
r1,c1,r2,c2=map(int,input().split())
r1-=1
c1-=1
r2-=1
c2-=1
if r1==r2 or c1==c2:
print(0)
continue
OK=0
rd=(r2-r1).bit_length()-1
cd=(c2-c1).bit_length()-1
NG=1+max(Sparse_table2[cd][c1][rd][r1],Sparse_table2[cd][c1][rd][r2-(1<<rd)],Sparse_table2[cd][c2-(1<<cd)][rd][r1],Sparse_table2[cd][c2-(1<<cd)][rd][r2-(1<<rd)])
#print(r1,r2,c1,c2)
while NG-OK>1:
mid=(NG+OK)//2
rr1=r1+mid-1
cc1=c1+mid-1
rr2=r2-mid+1
cc2=c2-mid+1
#print("!",NG,OK,mid,rr1,rr2,cc1,cc2)
if rr1>=rr2 or cc1>=cc2:
NG=mid
continue
rd=(rr2-rr1).bit_length()-1
cd=(cc2-cc1).bit_length()-1
#print(rr1,rr2,cc1,cc2,mid,cd,rd)
#print(Sparse_table2[cd][cc1][rd][rr1],Sparse_table2[cd][cc2-(1<<cd)][rd][rr2-(1<<rd)])
if mid<=max(Sparse_table2[cd][cc1][rd][rr1],Sparse_table2[cd][cc1][rd][rr2-(1<<rd)],Sparse_table2[cd][cc2-(1<<cd)][rd][rr1],Sparse_table2[cd][cc2-(1<<cd)][rd][rr2-(1<<rd)]):
OK=mid
else:
NG=mid
sys.stdout.write(str((OK*2)**2)+"\n")
|
py
|
1304
|
E
|
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
|
[
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] |
import sys
# Testing out some really weird behaviours in pypy
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, begin, end):
depth = (end - begin).bit_length() - 1
return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)])
class LCA:
def __init__(self, root, graph):
self.time = [-1] * len(graph)
self.path = [-1] * len(graph)
P = [-1] * len(graph)
t = -1
dfs = [root]
while dfs:
node = dfs.pop()
self.path[t] = P[node]
self.time[node] = t = t + 1
for nei in graph[node]:
if self.time[nei] == -1:
P[nei] = node
dfs.append(nei)
self.rmq = RangeQuery(self.time[node] for node in self.path)
def __call__(self, a, b):
if a == b:
return a
a = self.time[a]
b = self.time[b]
diff = ((b - a) >> 31) & (b - a)
a += diff
b -= diff
return self.path[self.rmq.query(a, b)]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
root = 0
lca = LCA(root, coupl)
depth = [-1]*n
depth[root] = 0
bfs = [root]
for node in bfs:
for nei in coupl[node]:
if depth[nei] == -1:
depth[nei] = depth[node] + 1
bfs.append(nei)
def dist(a,b):
for _ in range(0): pass
c = lca(a,b)
return depth[a] + depth[b] - 2 * depth[c]
q = inp[ii]; ii += 1
out = []
for _ in range(q):
x = inp[ii] - 1; ii += 1
y = inp[ii] - 1; ii += 1
a = inp[ii] - 1; ii += 1
b = inp[ii] - 1; ii += 1
k = inp[ii]; ii += 1
dists = [dist(a,b), dist(a,x) + dist(y,b) + 1, dist(a,y) + dist(x,b) + 1]
#dist(a,b) + dist(b,x) # this line makes everything 2 s faster for no reason
for d in dists:
if d - k & 1 == 0 and d <= k:
out.append('YES')
break
else:
out.append('NO')
print('\n'.join(out))
|
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
input = sys.stdin.buffer.readline
def process(A, S, k):
n = len(A)
p = len(S[0])
pairs = []
for x in range(2**p-1, -1, -1):
b = sum(map(int, bin(x)[2:]))
for j in range(p):
if x&(2**j)==0:
pairs.append([x, j, b])
A2 = []
for i in range(n):
row = [A[i]]
for j in range(p):
row.append(S[i][j])
A2.append(row)
A2.sort(reverse=True)
aud_sum = 0
for i in range(k):
aud_sum+=A2[i][0]
d = [aud_sum for i in range(2**p)]
# print(A2)
for i in range(n):
# print(A2[i], d, "Before")
for x, j, b in pairs:
entry1 = d[x]+A2[i][j+1]
"""
we are currently using
the first k+b things one way or another
"""
if i <= k+b:
entry1-=A2[i][0]
entry1+=A2[k+b][0]
# print(x, j, b, entry1)
d[x+2**j] = max(d[x+2**j], entry1)
# print(d, "After")
print(d[2**p-1])
n, p, k = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
S = []
for i in range(n):
row = [int(x) for x in input().split()]
S.append(row)
process(A, S, k)
|
py
|
1311
|
F
|
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
|
[
"data structures",
"divide and conquer",
"implementation",
"sortings"
] |
class BIT:
def __init__(self, n):
self.n = n
self.bit = [0]*(self.n+1) # 1-indexed
def init(self, init_val):
for i, v in enumerate(init_val):
self.add(i, v)
def add(self, i, x):
# i: 0-indexed
i += 1 # to 1-indexed
while i <= self.n:
self.bit[i] += x
i += (i & -i)
def sum(self, i, j):
# return sum of [i, j)
# i, j: 0-indexed
return self._sum(j) - self._sum(i)
def _sum(self, i):
# return sum of [0, i)
# i: 0-indexed
res = 0
while i > 0:
res += self.bit[i]
i -= i & (-i)
return res
def lower_bound(self, x):
s = 0
pos = 0
depth = self.n.bit_length()
v = 1 << depth
for i in range(depth, -1, -1):
k = pos + v
if k <= self.n and s + self.bit[k] < x:
s += self.bit[k]
pos += v
v >>= 1
return pos
def __str__(self): # for debug
arr = [self.sum(i,i+1) for i in range(self.n)]
return str(arr)
n = int(input())
X = list(map(int, input().split()))
V = list(map(int, input().split()))
Y = set(V)
Y = list(Y)
Y.sort()
toid = {}
for i, y in enumerate(Y):
toid[y] = i
A = []
for x, v in zip(X, V):
v = toid[v]
A.append((x, v))
A.sort(key=lambda x: x[0])
N = len(toid)
bitCnt = BIT(N+1)
bitSum = BIT(N+1)
ans = 0
for x, v in A:
ans += x*bitCnt.sum(0, v+1)-bitSum.sum(0, v+1)
bitCnt.add(v, 1)
bitSum.add(v, x)
print(ans)
|
py
|
1301
|
A
|
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
|
[
"implementation",
"strings"
] |
I=input
exec(int(I())*"print('NYOE S'[all(y in x for*x,y in zip(I(),I(),I()))::2]);")
|
py
|
1311
|
C
|
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.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.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
|
[
"brute force"
] |
# Thank God that I'm not you.
from collections import Counter, deque
import heapq
import itertools
import math
import random
import sys
from types import GeneratorType;
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def primeFactors(n):
counter = Counter();
while n % 2 == 0:
counter[2] += 1;
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
counter[i] += 1;
n = n / i
if (n > 2):
counter[n] += 1;
return counter;
input = sys.stdin.readline;
m = (10**9 + 7)
def mod_inv(n,m):
n=n%m
return pow(n,m-2,m)
def nCr(n,r,m):
numerator=1
for i in range(r):
numerator=(numerator*(n-i))%m
denomenator=1
for i in range(2,r+1):
denomenator=(denomenator*i)%m
return (numerator*mod_inv(denomenator,m))%m
t = int(input())
result = []
for _ in range(t):
n, m = map(int, input().split())
string = input().rstrip()
positions = list(map(int, input().split()))
def solve():
positions.sort();
prefixSum = [0 for i in range(len(string))];
hashMap = Counter(string)
for idx in positions:
idx -= 1;
right = idx + 1
prefixSum[0] += 1;
if right < len(prefixSum):
prefixSum[right] -= 1;
for i in range(1, len(prefixSum)):
prefixSum[i] += prefixSum[i - 1]
for i, char in enumerate(string):
hashMap[char] += prefixSum[i]
res = []
for char in "abcdefghijklmnopqrstuvwxyz":
res.append(hashMap[char])
return res;
print(*solve())
# print(result)
|
py
|
1305
|
E
|
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] |
import math
n,m=map(int,input().split())
good=1
if n%2==0:
if m>(n/2)*(n/2-1):
print(-1)
good=0
if n%2==1:
if m>((n-1)/2)**2:
print(-1)
good=0
arr=[]
leftover=0
if good==1:
if n==1:
print(1)
else:
if int(math.sqrt(m))*(int(math.sqrt(m))+1)<=m:
k=2*int(math.sqrt(m))+2
leftover=m-int(math.sqrt(m))*(int(math.sqrt(m))+1)
else:
k=2*int(math.sqrt(m))+1
leftover=m-int(math.sqrt(m))**2
for i in range(k):
arr.append(i+1)
if leftover>0:
arr.append(arr[k-1]+arr[k-2*leftover])
zzz=(arr[len(arr)-1]+1)*2+1
thing=arr[len(arr)-1]+1
if n-len(arr)>0:
add=n-len(arr)
for i in range(add):
arr.append(zzz)
zzz+=thing
print(*arr)
|
py
|
1312
|
B
|
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
|
[
"constructive algorithms",
"sortings"
] |
t = int(input())
for _ in range(t):
n = input()
a = list(map(lambda x: int(x), input().split()))
a.sort()
a = list(reversed(a))
for i in a:print(i , end=" " if len(a) > 1 else "")
print("")
|
py
|
1295
|
C
|
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
|
[
"dp",
"greedy",
"strings"
] |
def solve():
s, t = input(), input()
st1, st2 = set(s), set(t)
for k in st2:
if k not in st1:
print(-1); return
n, m = len(s), len(t)
dp = [[n]*26 for _ in range(n+1)]
for i in range(n-1, -1, -1):
dp[i] = dp[i+1][:]
dp[i][ord(s[i])-ord('a')] = i
vis = [False]*m
ans = 0
for i in range(m):
if not vis[i]:
j = 0
while j < n and i < m:
if dp[j][ord(t[i])-97] == n: break
j = dp[j][ord(t[i])-97]+1
vis[i] = True
while i < m and vis[i]: i += 1
ans += 1
print(ans)
for _ in range(int(input())):
solve()
|
py
|
1294
|
E
|
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
|
[
"greedy",
"implementation",
"math"
] |
import sys
import io, os
input = sys.stdin.buffer.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
A = [list(map(int, input().split())) for i in range(n)]
#B = [[0]*m for i in range(n)]
#for i in range(n):
#for j in range(m):
#B[i][j] = i*m+j
#print(B)
for i in range(n):
for j in range(m):
A[i][j] -= 1
ans = 0
from collections import Counter
for j in range(m):
C = Counter()
for i in range(n):
if A[i][j]%m != j:
continue
else:
q, r = divmod(A[i][j], m)
if 0 <= q < n:
if q <= i:
C[i-q] += 1
else:
C[n+i-q] += 1
temp = n
for k, v in C.items():
temp = min(temp, k+n-v)
ans += temp
print(ans)
|
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())
a = list(map(int , input().split()))
b = list(map(int , input().split()))
k = 0
k1 = 0
for i in range(0 , len(a)):
if a[i] > b[i]:
k += 1
if a[i] < b[i]:
k1 += 1
if k == 0:
print(-1)
exit()
k1 = k1 // k + 1
print(k1)
|
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())
c=False
c=set()
rez=0
h=[]
for i in range (n):
l=input()
if l[::-1] in c:
c.remove(l[::-1])
h.append(l)
rez+=2*m
else:
c.add(l)
s=rez//m//2-1
t=None
for i in c:
if i[::-1] == i:
rez+=m
t=i
break
print(rez)
for i in h:
print(i, end="")
if t!=None:
print(t,end="")
while s>=0:
print(h[s][::-1],end="")
s-=1
|
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"
] |
from sys import stdin
input = stdin.readline
for case in range(int(input())):
n, m = map(int, input().split())
prev_min, prev_max, prev_t, ans = m, m, 0, True
for line in range(n):
t, l, h = map(int, input().split())
theo_min, theo_max = prev_min - (t - prev_t), prev_max + (t - prev_t)
if theo_min > h or theo_max < l: ans = False
prev_min, prev_max, prev_t = max(l, theo_min), min(h, theo_max), t
print('yEs') if ans else print('nO')
|
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
input = sys.stdin.buffer.readline
from collections import deque
def countingSort(arr, exp1):
n = len(arr)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n):
index = arr[i] // exp1
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = arr[i] // exp1
output[count[index % 10] - 1] = arr[i]
count[index % 10] -= 1
i -= 1
i = 0
for i in range(0, len(arr)):
arr[i] = output[i]
def radixSort(arr):
max1 = max(arr)
exp = 1
while max1 / exp >= 1:
countingSort(arr, exp)
exp *= 10
N = int(input())
a = list(map(int, input().split()))
res = 0
radixSort(a)
for k in range(max(a).bit_length(), -1, -1):
z = 1 << k
c = 0
j = jj = jjj = N - 1
for i in range(N):
while j >= 0 and a[i] + a[j] >= z: j -= 1
while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1
while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1
c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj)
res += z * (c & 1)
for i in range(N): a[i] = min(a[i] ^ z, a[i])
radixSort(a)
#print(res, a, c)
print(res)
|
py
|
1323
|
A
|
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
|
[
"brute force",
"dp",
"greedy",
"implementation"
] |
for _ in[0]*int(input()):
n=input()
a=[*map(int,input().split())]
if a[0]%2==0: print('1\n1')
elif n=='1': print(-1)
elif a[1]%2==0: print('1\n2')
else: print('2\n1 2')
|
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"
] |
from collections import deque,Counter,OrderedDict
from math import *
import sys
import random
from bisect import *
from functools import reduce
from sys import stdin
from heapq import *
import copy
import os
import sys
from io import BytesIO, IOBase
# 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
def gcd(x,y):
while y:x,y=y,x%y
return x
n = int(input())
s = input()
left,right = s.count('('),s.count(')')
if n%2==1 or (left!=right):
print(-1)
sys.exit()
bal=0
ans=0
for i in s:
bp=bal
if i=='(':bal+=1
else:bal-=1
if bal<0 or bp<0:
ans+=1
print(ans)
|
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 heapq
import sys
input = sys.stdin.buffer.readline
def process(A, T):
d = {}
n = len(A)
for i in range(n):
a = A[i]
t = T[i]
if a not in d:
d[a] = []
d[a].append(t)
curr = []
curr_S = 0
m = min(d)
answer = 0
L = sorted(d)
n2 = len(L)
for i in range(n2):
m = L[i]
for x in d[m]:
curr_S+=x
heapq.heappush(curr, -1*x)
while len(curr) > 0 and ((i+1 < n2 and m < L[i+1]) or (i==n2-1)):
entry = heapq.heappop(curr)
entry = entry*-1
curr_S-=entry
answer+=(curr_S)
m+=1
return answer
n = int(input())
A = [int(x) for x in input().split()]
T = [int(x) for x in input().split()]
print(process(A, T))
|
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"
] |
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
r = list(map(int, input().split()))
b = list(map(int, input().split()))
c1, c2 = 0, 0
for i, j in zip(r, b):
if not i ^ j:
continue
if i:
c1 += 1
else:
c2 += 1
if not c1:
ans = -1
else:
ans = 0
while ans * c1 <= c2:
ans += 1
print(ans)
|
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"
] |
# 13:58-
import sys
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
l,r = float('inf'),-1
m = 0
cur = 0
for i in range(N):
if A[i]!=-1:
cur = A[i]
if i-1>=0:
if A[i-1]==-1:
l = min(l,A[i])
r = max(r,A[i])
else:
m = max(m, abs(A[i]-A[i-1]))
if i+1<N:
if A[i+1]==-1:
l = min(l,A[i])
r = max(r,A[i])
else:
m = max(m, abs(A[i]-A[i+1]))
m = max(m, (r-l-1)//2+1)
if r!=-1:
cur = (l+r)//2
print(m,cur)
|
py
|
1288
|
C
|
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
|
[
"combinatorics",
"dp"
] |
mod=int(1e9+7)
def read():
return [int(i) for i in input().split()]
def main():
n,m=read()
dp=[[0 for i in range(n+2)] for i in range(n+2)]
for i in range(1,n+1):
for j in range(i,n+1):
dp[i][j]=1
for _ in range(m-1):
for i in range(1,n+1):
for j in range(n,i-1,-1):
dp[i][j]=(dp[i][j]+dp[i][j+1]+dp[i-1][j]-dp[i-1][j+1]+mod)%mod
ans=0
for i in range(1,n+1):
for j in range(i,n+1):
ans=(ans+dp[i][j])%mod
print(ans)
main()
|
py
|
1313
|
C2
|
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"data structures",
"dp",
"greedy"
] |
import sys
from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import heapify, heappush, heappop
#sys.setrecursionlimit(10**5)
from functools import lru_cache
#@lru_cache(None)
#======================================================#
input = lambda: sys.stdin.readline()
I = lambda: int(input().strip())
S = lambda: input().strip()
M = lambda: map(int,input().strip().split())
L = lambda: list(map(int,input().strip().split()))
#======================================================#
#======================================================#
def factorial_inverse():
mod=10**9+7
upto=(10**5)*3+1
nfactorial=[1 for i in range(upto)]
ninverse=[1 for i in range(upto)]
finverse=[1 for i in range(upto)]
for i in range(2,upto):
nfactorial[i]=(nfactorial[i-1]*i)%mod
ninverse[i]=(-(mod//i)*ninverse[mod%i])%mod
finverse[i]=(finverse[i-1]*ninverse[i])%mod
return nfactorial,finverse
def nCk(n,k):
if n<0 or k<0:
return 0
if k>n:
return 0
return ((nfactorial[n]*finverse[k]%mod)*finverse[n-k])%mod
#======================================================#
def primelist():
L = [False for i in range((10**10)+1)]
primes = [False for i in range((10**10)+1)]
for i in range(2,(10**10)+1):
if not L[i]:
primes[i]=True
for j in range(i,(10**10)+1,i):
L[j]=True
return primes
def isPrime(n):
p = primelist()
return p[n]
#======================================================#
def bst(arr,x):
low,high = 0,len(arr)-1
ans = -1
while low<=high:
mid = (low+high)//2
#if arr[mid]==x:
# return mid
if arr[mid]<=x:
low = mid+1
else:
high = mid-1
ans = mid
return ans
def factors(x):
l1 = []
l2 = []
for i in range(1,int(sqrt(x))+1):
if x%i==0:
if (i*i)==x:
l1.append(i)
else:
l1.append(i)
l2.append(x//i)
for i in range(len(l2)//2):
l2[i],l2[len(l2)-1-i]=l2[len(l2)-1-i],l2[i]
return l1+l2
#======================================================#
def power(n,x):
if x==0:
return 1
k = (10**9)+7
if n==1:
return 1
if x==1:
return n
ans = power(n,x//2)
if x%2==0:
return (ans*ans)%k
return (ans*ans*n)%k
#======================================================#
def f():
b = [[a[0],1]]
c = a[0]
for i in range(1,n):
if b[-1][0]==a[i]:
b[-1][1]+=1
c+=a[i]
elif b[-1][0]<a[i]:
b.append([a[i],1])
c+=a[i]
else:
t = 1
while b:
if b[-1][0]<a[i]:
break
else:
c-=b[-1][0]*b[-1][1]
t+=b[-1][1]
b.pop()
b.append([a[i],t])
c+=a[i]*t
l.append(c)
n = I()
a = L()
l = [a[0]]
f()
ans = l
a.reverse()
l = [a[0]]
f()
l.reverse()
a.reverse()
res = 0
for i in range(1,n):
if (ans[i]+l[i]-a[i])>(ans[res]+l[res]-a[res]):
res = i
pp = [0 for i in range(n)]
pp[res]=a[res]
for i in range(res+1,n):
pp[i] = min(a[i],pp[i-1])
for i in range(res-1,-1,-1):
pp[i] = min(a[i],pp[i+1])
print(*pp)
|
py
|
1301
|
A
|
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
|
[
"implementation",
"strings"
] |
result=""
for i in range(0,int(input())):
a=input()
b=input()
c=input()
flag=True
n=0
for k in range(0,len(a)):
if (a[k]==c[k]) or (b[k]==c[k]):
n+=1
elif (a[k]==b[k]):
n+=2
else:
flag=False
break
if flag and n<=len(a):
result+="YES\n"
else:
result+="NO\n"
print(result.rstrip("\n"))
|
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 math
import random
#n,m,k=list(map(int, input().split()))
#cazuri=int(input())
n,a,b,k=list(map(int,input().split()))
bloc=list(map(int,input().split()))
#n=500000
#bloc=[]
#for z in range(n):
# bloc.append(random.randint(1,10**9))
cate=0
suma=a+b
resturi=[]
for i in range(n):
rest=bloc[i]%suma
if rest>0 and rest<=a:
cate+=1
else:
if rest==0:
rest=suma
# print("i=",bloc[i],rest)
resturi.append(math.ceil((rest-a)/a))
#print(resturi)
resturi.sort()
for j in resturi:
if k>=j:
cate+=1
k-=j
else:
break
print(cate)
|
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"
] |
from collections import defaultdict, deque
import heapq
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
ans = [0] * (n - 1)
d = defaultdict(lambda : 0)
d[s] = r
while q:
i = q.popleft()
for j, c in G[i]:
if not ans[c]:
d[i] %= r
d[i] += 1
ans[c] = d[i]
d[j] = d[i]
q.append(j)
return ans
n, k = map(int, input().split())
G = [[] for _ in range(n + 1)]
for i in range(n - 1):
x, y = map(int, input().split())
G[x].append((y, i))
G[y].append((x, i))
h = []
for i in range(1, n + 1):
heapq.heappush(h, (-len(G[i]), i))
for _ in range(k):
l, i = heapq.heappop(h)
r, i = heapq.heappop(h)
r *= -1
ans = bfs(1)
print(r)
print(*ans)
|
py
|
1294
|
E
|
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
|
[
"greedy",
"implementation",
"math"
] |
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
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 gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
mod = int(1e9) + 7
def power(k, n):
if n == 0:
return 1
if n % 2:
return (power(k, n - 1) * k) % mod
t = power(k, n // 2)
return (t * t) % mod
def totalPrimeFactors(n):
count = 0
if (n % 2) == 0:
count += 1
while (n % 2) == 0:
n //= 2
i = 3
while i * i <= n:
if (n % i) == 0:
count += 1
while (n % i) == 0:
n //= i
i += 2
if n > 2:
count += 1
return count
# #MAXN = int(1e7 + 1)
# # spf = [0 for i in range(MAXN)]
#
#
# def sieve():
# spf[1] = 1
# for i in range(2, MAXN):
# spf[i] = i
# for i in range(4, MAXN, 2):
# spf[i] = 2
#
# for i in range(3, mt.ceil(mt.sqrt(MAXN))):
# if (spf[i] == i):
# for j in range(i * i, MAXN, i):
# if (spf[j] == j):
# spf[j] = i
#
#
# def getFactorization(x):
# ret = 0
# while (x != 1):
# k = spf[x]
# ret += 1
# # ret.add(spf[x])
# while x % k == 0:
# x //= k
#
# return ret
# Driver code
# precalculating Smallest Prime Factor
# sieve()
def main():
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int, input().split())))
ans = 0
for j in range(m):
t = [n+i for i in range(n)]
for i in range(n):
f = a[i][j] - (j + 1)
if f % m == 0:
f //= m
if 0 <= f < n:
if f <= i:
t[(i - f)] -= 1
else:
t[(i + 1) + (n - 1 - f)] -= 1
ans+=min(t)
print(ans)
return
if __name__ == "__main__":
main()
|
py
|
1313
|
C1
|
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"brute force",
"data structures",
"dp",
"greedy"
] |
n = int(input())
nums = list(map(int, input().split()))
ans = float('-inf')
idx = 0
for piv in range(len(nums)):
tot = nums[piv]
m = tot
for i in range(piv-1, -1, -1):
m = min(m, nums[i])
tot += m
m = nums[piv]
for i in range(piv+1, len(nums)):
m = min(m, nums[i])
tot += m
if tot > ans:
ans = tot
idx = piv
m = nums[idx]
for i in range(idx-1, -1, -1):
m = min(m, nums[i])
nums[i] = m
m = nums[idx]
for i in range(idx+1, len(nums)):
m = min(m, nums[i])
nums[i] = m
print(' '.join([str(i) for i in nums]))
|
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"
] |
t = int(input())
for i in range(t):
n, g, b = map(int, input().split())
ng = (n + 1) // 2
tg = ng // g * (b + g)
if ng % g == 0:
tg -= b
else:
tg += ng % g
print(max(n, tg))
|
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"
] |
import sys, collections, math,bisect
input = sys.stdin.readline
n = int(input())
s = input().rstrip('\n')
max_v = 0
dp = [0] * 26
ans = [0] * n
for i in range(n):
temp = 0
for j in range(26):
if j > ord(s[i]) - ord('a'):
temp = max(dp[j],temp)
ans[i] = temp + 1
max_v = max(max_v,temp + 1)
dp[ord(s[i]) - ord('a')] = max(dp[ord(s[i]) - ord('a')],temp + 1)
print(max_v)
print(*ans)
|
py
|
1305
|
E
|
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] |
# https://codeforces.com/problemset/problem/1305/E
def gen_sequence(size, balance):
result = []
for i in range(1, size + 1):
triple_count = (i - 1) >> 1
if triple_count <= balance:
result.append(i)
balance -= triple_count
else:
break
if len(result) == size and balance > 0:
return [-1]
if balance > 0:
result.append(2 * (result[-1] - balance) + 1)
delta = result[-1] + 1
while len(result) < size:
value = result[-1] + delta
if value % 2 == 0:
value += 1
result.append(value)
return result
if __name__ == '__main__':
size, balance = map(int, input().split())
for x in gen_sequence(size, balance):
print(x, end=' ')
print()
|
py
|
1295
|
C
|
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3
|
[
"dp",
"greedy",
"strings"
] |
import math
from collections import Counter, deque
from sys import stdout
import time
from math import factorial, log, gcd
import sys
from decimal import Decimal
import heapq
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():
s = IS()
n = len(s)
t = IS()
alphabet = set(s)
if alphabet | set(t) != alphabet:
print(-1)
return
suf_m = dict([(i, [-1] * n) for i in alphabet])
suf_m[s[-1]][-1] = n - 1
for i in range(n - 2, -1, -1):
el = s[i]
for a in alphabet:
if a != el:
suf_m[a][i] = suf_m[a][i + 1]
else:
suf_m[el][i] = i
idx = -1
op = 0
for i in range(len(t)):
el = t[i]
idx = suf_m[el][idx + 1]
if idx == n - 1:
op += 1
idx = -1
elif idx == -1:
op += 1
idx = suf_m[el][0]
if idx != -1:
op += 1
print(op)
if __name__ == '__main__':
for _ in range(II()):
main()
# main()
|
py
|
1323
|
A
|
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
|
[
"brute force",
"dp",
"greedy",
"implementation"
] |
for _ in range(int(input())):
n = int(input())
lis = list(map(int,input().split()))
summ = 0
oc=0
for i in range(n):
if lis[i]%2==0:
oc=0
print(1,i+1,sep = "\n")
break
else:
oc+=1
if oc==2:
print(2)
print(i,i+1)
break
else:
print(-1)
|
py
|
1313
|
C1
|
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"brute force",
"data structures",
"dp",
"greedy"
] |
import sys
import math
from collections import *
from functools import cmp_to_key
mod=998244353
def get_ints():
return map(int, sys.stdin.readline().strip().split())
#test=int(input())
#while test:
#test-=1
n=int(input())
a=list(get_ints())
t=-float("inf")
f=[0 for i in range(n)]
for i in range(n):
res={}
s=0
res[i]=a[i]
s+=a[i]
for j in range(i-1,-1,-1):
if a[j]<=res[j+1]:
res[j]=a[j]
else:
res[j]=res[j+1]
s+=res[j]
for j in range(i+1,n):
if a[j]<=res[j-1]:
res[j]=a[j]
else:
res[j]=res[j-1]
s+=res[j]
if s>t:
t=s
for k in res.keys():
f[k]=res[k]
[print(i,end=' ') for i in f]
print()
|
py
|
1286
|
B
|
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2
|
[
"constructive algorithms",
"data structures",
"dfs and similar",
"graphs",
"greedy",
"trees"
] |
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict,deque
def bfs(node):
vis[node]=1
q=deque([node])
order.append(node)
while q:
cur=q.popleft()
for j in edge[cur]:
if vis[j]==0:
child[cur].append(j)
vis[j]=1
order.append(j)
q.append(j)
def dfs(node):
vis[node]=1
stack=[node]
while stack:
cur=stack.pop()
ans[cur-1]=lis[arr[cur]]
lis.remove(ans[cur-1])
for j in edge[cur]:
if vis[j]==0:
vis[j]=1
stack.append(j)
n=int(input())
edge=defaultdict(list)
child=defaultdict(list)
root=-1
arr=[-1]*(n+1)
for i in range(n):
p,c=list(map(int,input().split()))
arr[i+1]=c
if p!=0:
edge[p].append(i+1)
edge[i+1].append(p)
else:
root=i+1
subTreeSize=[1]*(n+1)
vis=[0]*(n+1)
order=[]
bfs(root)
order.reverse()
for i in range(n):
for j in child[order[i]]:
subTreeSize[order[i]]+=subTreeSize[j]
x=0
for i in range(1,n+1):
if arr[i]>subTreeSize[i]-1:
x+=1
break
if x==1:
print("NO")
else:
print("YES")
lis=[]
for i in range(n):
lis.append(i+1)
vis=[0]*(n+1)
ans=[-1]*n
dfs(root)
print(" ".join(str(x) for x in ans))
|
py
|
1295
|
A
|
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11
|
[
"greedy"
] |
for i in range(int(input())):
a = int(input())
if(a%2==0):
print("1"*(a//2))
else:
print('7'+'1'*((a-3)//2))
|
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"
] |
for _ in range(int(input())):
n, m = list(map(int, input().split(' ')))
a = sum(list(map(int, input().split(' '))))
print(a) if a < m else print(m)
|
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"
] |
for _ in range(int(input())):
length = int(input())
odd = 0
for number in input().split():
if int(number) & 1:
odd += 1
if odd == 0:
print('NO')
elif odd == length and not length & 1:
print('NO')
else:
print('YES')
|
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"
] |
print(sum(1/(i+1)for i in range(int(input()))))
|
py
|
1311
|
E
|
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.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 only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:
|
[
"brute force",
"constructive algorithms",
"trees"
] |
for tests in range(int(input())):
n, d = map(int,input().split())
upper_bound, lower_bound, lv = n * (n - 1) // 2, 0, 0
for i in range(1, n + 1):
if not(i & (i - 1)):
lv += 1
lower_bound += lv - 1
if not(d in range(lower_bound, upper_bound + 1)):
print("NO")
else:
bad = [False] * n
depth = list(range(n))
count_child = [1] * n
count_child[n - 1] = 0
current_depth = upper_bound
parent = list(range(-1,n-1))
while current_depth > d:
v, p = -1, -1
for i in range(n):
if not(bad[i]) and count_child[i] == 0 and (v == -1 or depth[i] < depth[v]):
v = i
for i in range(n):
if count_child[i] < 2 and depth[i] == depth[v] - 2 and (p == -1 or depth[i] > depth[p]):
p = i
if p == -1:
bad[v] = True
continue
count_child[parent[v]] -= 1
depth[v] -= 1
count_child[p] += 1
parent[v] = p
current_depth -= 1
print("YES")
print(*((parent[i] + 1) for i in range(1,n)))
|
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
# Se leen los datos
n = input()
arr = [ int(i) for i in input().split()]
#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
print(ans)
|
py
|
13
|
E
|
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3
|
[
"data structures",
"dsu"
] |
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
p = list(map(int, input().split()))
BLOCK_LENGTH = 400
block = [i//BLOCK_LENGTH for i in range(n)]
jumps = [0] * n
end = [0] * n
for i in range(n - 1, -1, -1):
nex = i + p[i]
if nex >= n:
jumps[i] = 1
end[i] = i + n
elif block[nex] > block[i]:
jumps[i] = 1
end[i] = nex
else:
jumps[i] = jumps[nex] + 1
end[i] = end[nex]
out = []
for _ in range(m):
#print(jumps)
#print(end)
#print(block)
s = input().strip()
if s[0] == '0':
_,a,b = s.split()
a = int(a) - 1
b = int(b)
p[a] = b
i = a
while i >= 0 and block[i] == block[a]:
nex = i + p[i]
if nex >= n:
jumps[i] = 1
end[i] = i + n
elif block[nex] > block[i]:
jumps[i] = 1
end[i] = nex
else:
jumps[i] = jumps[nex] + 1
end[i] = end[nex]
i -= 1
else:
_,a = s.split()
curr = int(a) - 1
jmp = 0
while curr < n:
jmp += jumps[curr]
curr = end[curr]
out.append(str(curr - n + 1)+' '+str(jmp))
print('\n'.join(out))
|
py
|
1311
|
E
|
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.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 only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:
|
[
"brute force",
"constructive algorithms",
"trees"
] |
t=int(input())
import math as m
def print_tree(l):
t=[{'p':None, 'c':[]} for i in range(sum(l))]
l2={i:[] for i in range(len(l))}
j=0
for i in range(sum(l)):
l2[j].append(i+1)
if len(l2[j])==l[j]:
j+=1
for i in range(1,len(l)):
p=0
for n in l2[i]:
pi=l2[i-1][p]
t[n-1]['p']=pi
t[pi-1]['c'].append(n)
if len(t[pi-1]['c'])==2:
p+=1
for i in range(1, len(t)):
print(t[i]['p'], end=' ')
print()
for _ in range(t):
n, d = map(int, input().split())
k=m.floor(m.log2(n))
maxd=n*(n-1)//2
mind=k*2**(k+1)-2**(k+1)+2+k*(n-2**(k+1)+1)
if (d<mind) or (d>maxd):
print("NO")
continue
l=[1 for i in range(n)]
s=maxd
lowest=1
highest=n-1
while (s>d):
diff=s-d
if (diff>highest-lowest):
l[highest]-=1
l[lowest]+=1
s-=(highest-lowest)
highest-=1
if l[lowest-1]*2==l[lowest]:
lowest+=1
else:
level=highest-diff
l[level]+=1
l[highest]-=1
s-=diff
print("YES")
print_tree(l)
|
py
|
1295
|
E
|
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2
|
[
"data structures",
"divide and conquer"
] |
import sys
readline = sys.stdin.readline
from itertools import accumulate
class Lazysegtree:
#RAQ
def __init__(self, A, intv, initialize = True, segf = min):
#区間は 1-indexed で管理
self.N = len(A)
self.N0 = 2**(self.N-1).bit_length()
self.intv = intv
self.segf = segf
self.lazy = [0]*(2*self.N0)
if initialize:
self.data = [intv]*self.N0 + A + [intv]*(self.N0 - self.N)
for i in range(self.N0-1, 0, -1):
self.data[i] = self.segf(self.data[2*i], self.data[2*i+1])
else:
self.data = [intv]*(2*self.N0)
def _ascend(self, k):
k = k >> 1
c = k.bit_length()
for j in range(c):
idx = k >> j
self.data[idx] = self.segf(self.data[2*idx], self.data[2*idx+1]) \
+ self.lazy[idx]
def _descend(self, k):
k = k >> 1
idx = 1
c = k.bit_length()
for j in range(1, c+1):
idx = k >> (c - j)
ax = self.lazy[idx]
if not ax:
continue
self.lazy[idx] = 0
self.data[2*idx] += ax
self.data[2*idx+1] += ax
self.lazy[2*idx] += ax
self.lazy[2*idx+1] += ax
def query(self, l, r):
L = l+self.N0
R = r+self.N0
Li = L//(L & -L)
Ri = R//(R & -R)
self._descend(Li)
self._descend(Ri - 1)
s = self.intv
while L < R:
if R & 1:
R -= 1
s = self.segf(s, self.data[R])
if L & 1:
s = self.segf(s, self.data[L])
L += 1
L >>= 1
R >>= 1
return s
def add(self, l, r, x):
L = l+self.N0
R = r+self.N0
Li = L//(L & -L)
Ri = R//(R & -R)
while L < R :
if R & 1:
R -= 1
self.data[R] += x
self.lazy[R] += x
if L & 1:
self.data[L] += x
self.lazy[L] += x
L += 1
L >>= 1
R >>= 1
self._ascend(Li)
self._ascend(Ri-1)
def binsearch(self, l, r, check, reverse = False):
L = l+self.N0
R = r+self.N0
Li = L//(L & -L)
Ri = R//(R & -R)
self._descend(Li)
self._descend(Ri-1)
SL, SR = [], []
while L < R:
if R & 1:
R -= 1
SR.append(R)
if L & 1:
SL.append(L)
L += 1
L >>= 1
R >>= 1
if reverse:
for idx in (SR + SL[::-1]):
if check(self.data[idx]):
break
else:
return -1
while idx < self.N0:
ax = self.lazy[idx]
self.lazy[idx] = 0
self.data[2*idx] += ax
self.data[2*idx+1] += ax
self.lazy[2*idx] += ax
self.lazy[2*idx+1] += ax
idx = idx << 1
if check(self.data[idx+1]):
idx += 1
return idx - self.N0
else:
for idx in (SL + SR[::-1]):
if check(self.data[idx]):
break
else:
return -1
while idx < self.N0:
ax = self.lazy[idx]
self.lazy[idx] = 0
self.data[2*idx] += ax
self.data[2*idx+1] += ax
self.lazy[2*idx] += ax
self.lazy[2*idx+1] += ax
idx = idx << 1
if not check(self.data[idx]):
idx += 1
return idx - self.N0
N = int(readline())
P = list(map(lambda x:int(x)-1 , readline().split()))
Pinv = [None]*N
for i in range(N):
Pinv[P[i]] = i
A = list(map(int, readline().split()))
dp = A[:-1]
for i in range(1, N-1):
dp[i] += dp[i-1]
inf = 1<<60
ans = dp[0]
dp = Lazysegtree(dp, inf, initialize = True, segf = min)
N0 = dp.N0
cnt = 0
for i in range(N):
a = A[Pinv[i]]
p = Pinv[i]
dp.add(p, N0, -2*a)
cnt += a
ans = min(ans, cnt + dp.query(0, N0))
print(ans)
|
py
|
1285
|
A
|
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
|
[
"math"
] |
a=input()
print(len(input())+1)
|
py
|
1304
|
D
|
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
|
[
"constructive algorithms",
"graphs",
"greedy",
"two pointers"
] |
import sys
input = sys.stdin.readline
t = int(input())
ans = []
for _ in range(t):
n, s = input().rstrip().split()
n = int(n)
s = list(s)
x = [0]
for i in range(n - 1):
if s[i] == ">":
x.append(i + 1)
x.append(n)
p = [0] * n
u = 1
for i in range(len(x) - 2, -1, -1):
for j in range(x[i], x[i + 1]):
p[j] = u
u += 1
ans.append(" ".join(map(str, p)))
p = []
u, v = n - len(x) + 2, n - len(x) + 3
p.append(u)
u -= 1
for i in reversed(s):
if i == "<":
p.append(u)
u -= 1
else:
p.append(v)
v += 1
p.reverse()
ans.append(" ".join(map(str, p)))
sys.stdout.write("\n".join(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
|
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())
for i in range(t):
n = int(input())
*a, = map(int, input().split())
*b, = map(int, input().split())
a.sort()
b.sort()
print(*a)
print(*b)
|
py
|
1312
|
B
|
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5
|
[
"constructive algorithms",
"sortings"
] |
##############################
# author: oneku #
# trying to solve problems #
##############################
# Bismillah
import sys
import os
from functools import reduce
from io import BytesIO, IOBase
from typing import List
from bisect import bisect, bisect_left, bisect_right
# from typing import List
BUFFER_SIZE = 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, BUFFER_SIZE))
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, **kwargs):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFFER_SIZE))
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)
fast_input = lambda: sys.stdin.readline().rstrip("\r\n")
read_int = lambda: int(fast_input())
read_ints = lambda: map(int, fast_input().split())
read_list_int = lambda: list(map(int, fast_input().split()))
read_str = lambda: str(fast_input())
read_strs = lambda: map(str, fast_input().split())
read_list_str = lambda: list(map(str, fast_input().split()))
output = lambda *value: sys.stdout.write(' '.join(map(str, value)) + '\n')
MOD = 32_768
'''
'''
MOD = 10 ** 9 + 7
def solve() -> None:
n = read_int()
nums = sorted(read_list_int(), reverse=True)
output(*nums)
return
'''
5 3 2 3 5
'''
def main() -> None:
# solve()
for _ in range(read_int()):
solve()
if __name__ == '__main__':
main()
|
py
|
1287
|
B
|
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
|
[
"brute force",
"data structures",
"implementation"
] |
n=int(input().split()[0])
s=set()
r=0
for _ in[0]*n:
t=*map(ord,input()),
for x in s:r+=(*(u^(u!=v)*(66^v)for u,v in zip(x,t)),)in s
s|={t}
print(r//2)
|
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"
] |
for i in range(int(input())):
a,b,p=map(int, input().split())
ro=str(input())
road=list(ro)
l=len(road)
node=[]
bol=(road[-1]=="A")
if bol:
cou=0
node.append([l-1,1])
else:
cou=1
node.append([l-1,0])
for j in range(l-1,0,-1):
if road[j-1]==road[j]:
pass
else:
node.append([j,cou])
cou=abs(cou-1)
if road[0]!=road[1]:
node.append([0,abs(node[0][1]-1)])
if len(node)>=2 and node[0]==node[1]:
node.pop(0)
if len(node)>=2 and node[0][0]==node[1][0]:
node.pop(0)
summ=0
boll=True
for x in range(len(node)):
summ+=[b,a][node[x][1]]
if summ>p:
t=x
boll=False
break
if boll:
print(1)
else:
print(node[t][0]+1)
|
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())
for _ in range(T):
n = int(input())
A = sorted(list(map(int, input().split())))
B = sorted(list(map(int, input().split())))
print(*A)
print(*B)
|
py
|
1304
|
E
|
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
|
[
"data structures",
"dfs and similar",
"shortest paths",
"trees"
] |
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()]
debug = lambda *x: print(*x, file=sys.stderr)
ceil1 = lambda a, b: (a + b - 1) // b
Mint, Mlong = 2 ** 31 - 1, 2 ** 63 - 1
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 subtree(self, root):
queue, visit = deque([root]), array('b', [0] * (self.n + 1))
self.level = array('i', [0] * (self.n + 1))
self.par, visit[root] = array('i', [-1] * (self.n + 1)), True
while queue:
s = queue.popleft()
for i1 in self.gdict[s]:
if not visit[i1]:
queue.append(i1)
visit[i1], self.level[i1] = True, self.level[s] + 1
self.par[i1] = s
def lca_preprocess(self, root):
self.subtree(root)
self.lev = 18
self.table = [array('i', [-1] * (self.n + 1)) for _ in range(self.lev)]
self.table[0] = self.par
for i in range(1, self.lev):
for node in range(1, self.n + 1):
if self.table[i - 1][node] != -1:
self.table[i][node] = self.table[i - 1][self.table[i - 1][node]]
def lca(self, u, v):
if self.level[v] < self.level[u]:
u, v = v, u
diff = self.level[v] - self.level[u]
for i in range(self.lev):
if (diff >> i) & 1:
v = self.table[i][v]
if u == v: return u
for i in range(self.lev - 1, -1, -1):
if self.table[i][u] != self.table[i][v]:
u, v = self.table[i][u], self.table[i][v]
return self.table[0][u]
def get_dist(u, v):
return g.level[u] + g.level[v] - g.level[g.lca(u, v)] * 2
for _ in range(tests):
n = int(input())
g = graph(n)
for i in range(n - 1):
u, v = inp(int)
g.add_edge(u, v)
g.lca_preprocess(1)
for i in range(int(input())):
x, y, a, b, k = inp(int)
ans = 0
for d in [get_dist(a, b), get_dist(a, x) + 1 + get_dist(y, b), get_dist(a, y) + 1 + get_dist(x, b)]:
ans |= d <= k and (k - d) & 1 == 0
out.append(['no', 'yes'][ans])
print('\n'.join(map(str, out)))
|
py
|
1141
|
E
|
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1
|
[
"math"
] |
from sys import stdin
from math import ceil
inp = stdin.readline
h, n = map(int, inp().split())
arr = [int(x) for x in inp().split()]
change = sum(arr)
ma = 0
count = 0
poi = []
hp = []
for i, c in enumerate(arr):
count += c
if count < ma:
poi.append(i)
hp.append(count)
ma = count
if change >= 0 and h + ma > 0:
print(-1)
else:
if change >= 0 or h + ma <= 0:
x = 0
else:
x = ceil((-ma-h)/change)
h += x*change
for i, c in enumerate(hp):
if h + c <= 0:
print(poi[i] + x*n + 1)
break
|
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"
] |
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,m,k = map(int,input().split())
if k > 4*n*m-2*m-2*n:
print('NO')
exit()
print('YES')
if n == 1:
step = [(m-1,'R'),(m-1,'L')]
elif m == 1:
step = [(n-1,'D'),(n-1,'U')]
else:
v,v1 = [(n-1,'RLD'),(n-1,'RLU')],(1,'R')
step = [(n-1,'RLD')]
for i in range(m-1):
step.append(v1)
if i != m-2:
step.append(v[not i%2])
else:
z = list(v[not i%2])
z[1] = z[1][2:]
step.append(tuple(z))
if m&1:
step.append((n-1,'U'))
else:
step.append((n-1,'D'))
v,v1 = [(n-1,'D'),(n-1,'U')],(1,'L')
for i in range(m-1):
step.append(v1)
step.append(v[(m-i-1)%2])
fin = []
ans = 0
for i in step:
ans += len(i[1])*i[0]
if ans > k:
ans -= len(i[1])*i[0]
if k-ans >= len(i[1]):
fin.append(((k-ans)//len(i[1]),i[1]))
z = (k-ans)%len(i[1])
if z:
fin.append((1,i[1][:z]))
break
fin.append(i)
print(len(fin))
for i in fin:
print(*i)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
|
py
|
1323
|
A
|
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
|
[
"brute force",
"dp",
"greedy",
"implementation"
] |
import os
os.system("cls") # clear screen
# Debug mode (color output green)
if os.getcwd().endswith("codeforces_py"):
from colorama import Fore, Style
import builtins
def print(*args, **kwargs):
builtins.print(Fore.GREEN, end="")
builtins.print(*args, **kwargs)
builtins.print(Style.RESET_ALL, end="")
########################################################
t = int(input())
for T in range(t):
n = int(input())
arr = list(map(int, input().split()))
evenVal = False
oddIDs = []
evenID = 0
for i, x in enumerate(arr):
if x % 2 == 0:
evenVal = True
evenID = i+1
break
else:
oddIDs.append(i+1)
if not evenVal and len(oddIDs) < 2:
print(-1)
elif evenVal:
print(1)
print(evenID)
else:
print(2)
print(oddIDs[0], oddIDs[1])
|
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"
] |
import sys
import math
from collections import defaultdict,Counter,deque
input = sys.stdin.readline
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
def WRITE(out):
return print('\n'.join(map(str, out)))
'''
AXXXB
AXXXA
BXXXA
BXXXB
()
()() (())
()()()
(()())
()(())
(())()
((()))
7
3
007
4
1000
5
00000
3
103
4
2020
9
123456789
30
001678294039710047203946100020
1
2
3
4
lcm(a,b) = (a*b)/gcd(a,b)
lcm(1,b) = b/1
lcm(2,b) = 2b/gcd(2,b)
lcm(3,b) = 3b/gcd(3,b)
1
2 1
1 3 2
2 1 4 3 = 2 + 2 + 12 + 12 = 28
2 4 1 3 =
1 2 3 4 5
1 3 2 5 4 = 1 + 6 + 6 + 20 + 20 = 53
2 1 4 5 3 = 2 + 2 + 12 + 20 + 15
'''
t = II()
for _ in range(t):
n = II()
nums = LII()
total = 0
ans = 0
for num in nums:
if num == 0:
total += 1
ans += 1
else:
total += num
print(ans + int(total==0))
|
py
|
1313
|
C2
|
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"data structures",
"dp",
"greedy"
] |
# ЛАсСД 6 - Небоскребы
def up_east(aaa,n):
st=[0]
bbb=[0]*(n+2)
xxx=[0]
for i in range (1,n+1):
a=aaa[i]
if a>=aaa[st[-1]] :
bbb[i]=bbb[i-1]+a
else:
while a<aaa[st[-1]] : #st всегда не пуст!!!
j=st.pop()
j=st[-1]
bbb[i]=bbb[j]+a*(i-j)
st.append(i)
if a>=aaa[i-1] and a>aaa[i+1] :
xxx.append(i)
st.clear()
return bbb,xxx
def down_east(aaa,n):
st=[n+1]
bbb=[0]*(n+2)
for i in range (n,0,-1):
a=aaa[i]
b=aaa[st[-1]]
if a>=b :
bbb[i]=bbb[i+1]+a
else:
while a<aaa[st[-1]] : #st всегда не пуст!!!
j=st.pop()
j=st[-1]
bbb[i]=bbb[j]+a*(j-i)
st.append(i)
st.clear()
return bbb
N=int(input())
AAA=list(map(int,('0 '+input()).split()))
AAA.append(0)
UpE,XXX=up_east(AAA,N)
DwE=down_east(AAA,N)
rb=0
for x in XXX :
r=UpE[x]+DwE[x]-AAA[x]
if r>rb:
rb=r
y=x
for i in range(y-1,0,-1):
AAA[i]=min(AAA[i],AAA[i+1])
for j in range(y+1,N+1,):
AAA[j]=min(AAA[j-1],AAA[j])
for a in AAA[1:-1]:
print(a,end=' ')
|
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"
] |
import sys
import math
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 4 + 5)
test = False
mod1, mod2 = 10 ** 9 + 7, 998244353
inf = 10 ** 16 + 5
lim = 10 ** 5 + 5
def test_case():
x0, y0, ax, ay, bx, by = map(int, input().split())
xs, ys, t = map(int, input().split())
x, y = [x0], [y0]
while x[-1] <= (xs + t - bx) / ax and y[-1] <= (ys + t - by) / ay:
x.append(x[-1] * ax + bx)
y.append(y[-1] * ay + by)
res = 0
for i in range(len(x)):
for j in range(len(x)):
l, r = abs(x[i] - xs) + abs(y[i] - ys), abs(x[j] - x[i]) + abs(y[j] - y[i])
if l + r <= t:
res = max(res, abs(j - i) + 1)
print(res)
t = 1
if test:
t = int(input())
for _ in range(t):
# print(f"Case #{_+1}: ", end='')
test_case()
|
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
input = sys.stdin.buffer.readline
from collections import deque
def radix_sort(a):
l = len(a)
mx = max(a)
m = 0
while mx > 0:
mx = mx // 10
m += 1
for i in range (m):
b = [[] for _ in range (10)]
e = pow(10, i)
for j in a:
num = (j//e)%10
b[num].append(j)
a *= 0
for l in b:
a += l
N = int(input())
a = list(map(int, input().split()))
res = 0
radix_sort(a)
for k in range(max(a).bit_length(), -1, -1):
z = 1 << k
c = 0
j = jj = jjj = N - 1
for i in range(N):
while j >= 0 and a[i] + a[j] >= z: j -= 1
while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1
while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1
c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj)
res += z * (c & 1)
for i in range(N): a[i] = min(a[i] ^ z, a[i])
a.sort()
#print(res, a, c)
print(res)
|
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 math
n = int(input())
for i in range(1,int(n**0.5)+1):
if n%i==0:
if math.gcd(n//i,i) == 1:
res = i
print(res,n//res)
|
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"
] |
# ======== author: kuanc (@kuantweets) | created: 08/04/22 01:25:01 ======== #
from sys import stdin, stderr, stdout, setrecursionlimit
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
from itertools import accumulate, combinations, permutations, product
from functools import lru_cache, cmp_to_key, reduce
from heapq import heapify, heappush, heappop, heappushpop, heapreplace
from pypyjit import set_param
set_param("max_unroll_recursion=-1")
# setrecursionlimit(300005)
INF = 1 << 60
MOD = 998244353 + 1755654
input = lambda: stdin.readline().rstrip("\r\n")
dbg = lambda *A, **M: stderr.write("\033[91m" + \
M.get("sep", " ").join(map(str, A)) + M.get("end", "\n") + "\033[0m")
# ============================ START OF MY CODE ============================ #
def bootstrap(f):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if isinstance(to, type((lambda: (yield))())):
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
stack = []
return wrappedfunc
def solve(_tc):
@bootstrap
def dfs(node, prev):
C[node] = 1 if A[node] == 1 else -1
for neigh in adj[node]:
if neigh == prev:
continue
yield dfs(neigh, node)
C[node] += max(0, C[neigh])
yield
@bootstrap
def dfs2(node, prev):
for neigh in adj[node]:
if neigh == prev:
continue
C[neigh] += max(0, C[node] - max(0, C[neigh]))
yield dfs2(neigh, node)
yield
N = int(input())
A = list(map(int, input().split()))
adj = defaultdict(list)
for _ in range(N - 1):
a, b = map(int, input().split())
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
C = [0 for _ in range(N)]
dfs(0, -1)
dfs2(0, -1)
print(*C)
if __name__ == "__main__":
# _tcs = int(input())
for _tc in range(1, vars().get("_tcs", 1) + 1):
dbg("=== Case {} ===".format(str(_tc).rjust(2)))
solve(_tc)
|
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
input = sys.stdin.buffer.readline
from functools import reduce
def __flatten(A):
return reduce(lambda x, y: x+y, A)
def radix(a):
digits = len(str(max(a)))
for i in range (digits):
b = [[] for _ in range (10)]
e = pow(10, i)
for j in a:
num = (j//e)%10
b[num].append(j)
a = __flatten(b)
return(a)
N = int(input())
a = list(map(int, input().split()))
res = 0
a = radix(a)
for k in range(max(a).bit_length(), -1, -1):
z = 1 << k
c = 0
j = jj = jjj = N - 1
for i in range(N):
while j >= 0 and a[i] + a[j] >= z: j -= 1
while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1
while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1
c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj)
res += z * (c & 1)
for i in range(N): a[i] = min(a[i] ^ z, a[i])
a.sort()
#print(res, a, c)
print(res)
|
py
|
1296
|
B
|
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.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 separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111
|
[
"math"
] |
import sys
import math
import bisect
import heapq
import string
from collections import defaultdict,Counter,deque
def I():
return input()
def II():
return int(input())
def MII():
return map(int, input().split())
def LI():
return list(input().split())
def LII():
return list(map(int, input().split()))
def GMI():
return map(lambda x: int(x) - 1, input().split())
def LGMI():
return list(map(lambda x: int(x) - 1, input().split()))
def WRITE(out):
return print('\n'.join(map(str, out)))
def WS(out):
return print(' '.join(map(str, out)))
def WNS(out):
return print(''.join(map(str, out)))
'''
b > a
gcd(b,a) == 1
n = 1000
b => (2,n+1)
a = n-b
if gcd(a,b) == 1:
cnt += 1
print(cnt)
< 10 = x
10 = 11
12 = 12
...
18 = 19
19 = 21
...
100 // 10 = 10 cashback
spent 100, 10 cashback = 1 -> 111
28
10
10
10
19
ans = 0
digits = [1, 9
digits = [1, 10]
ans = 10
ans = 20
[1,9,9]
100
[1,10,9]
200
[1,10,19]
219
199
0,10,9 100
0,0,19 200
0,0,0,2 219
'''
# sys.stdin = open("backforth.in", "r")
# sys.stdout = open("backforth.out", "w")
def solve():
t = II()
for _ in range(t):
s = I().strip()
digits = [0] * len(s)
for i,num in enumerate(s):
digits[i] = int(num)
ans = 0
for i in range(len(digits)-1):
digits[i+1] += digits[i]
ans += digits[i] * (10 ** (len(digits) - 1 - i))
new_digits = []
for d in str(digits[-1]):
new_digits.append(int(d))
# print(new_digits)
for i in range(len(new_digits)):
if i+1 < len(new_digits):
new_digits[i+1] += new_digits[i]
ans += new_digits[i] * (10 ** (len(new_digits) - 1 - i))
# print(new_digits)
ans += new_digits[-1] // 10
print(ans)
solve()
|
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 = sys.stdin.readline
from heapq import heappop, heappush
for _ in range(int(input())):
n = int(input())
s = input()[:-1]
h = []
for i in range(n):
heappush(h, (s[i:] + s[:i][::-1], i+1) if (n-i) & 1 else (s[i:] + s[:i], i+1))
a, b = heappop(h)
print(a)
print(b)
|
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 collections import deque, defaultdict
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
visit = [0] * (n + 1)
visit[s] = 1
parent[s] = -1
e[s] = -1
while q:
i = q.popleft()
for j, c in G[i]:
if not visit[j]:
visit[j] = 1
q.append(j)
parent[j] = i
e[j] = c
return
n = int(input())
G = [[] for _ in range(n + 1)]
for i in range(n - 1):
x, y = map(int, input().split())
G[x].append((y, i))
G[y].append((x, i))
m = int(input())
se = set()
d = defaultdict(lambda : [])
for _ in range(m):
a, b, g = map(int, input().split())
d[g].append((a, b))
se.add(g)
se = list(se)
se.sort(reverse = True)
parent = [-1] * (n + 1)
e = [-1] * (n + 1)
f = [0] * (n - 1)
for i in se:
for a, b in d[i]:
ok = 0
bfs(a)
u = b
while a ^ u:
if not f[e[u]] or f[e[u]] == i:
f[e[u]] = i
ok = 1
u = parent[u]
if not ok:
f = [-1]
break
if not ok:
f = [-1]
break
if ok:
for i in range(n - 1):
if not f[i]:
f[i] = 114514
print(*f)
|
py
|
1284
|
D
|
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
|
[
"binary search",
"data structures",
"hashing",
"sortings"
] |
import sys
input = lambda: sys.stdin.readline().rstrip()
ke = 133333333
pp = 1000000000001003
def rand():
global ke
ke = ke ** 2 % pp
return ((ke >> 10) % (1<<20)) + (1<<20)
N = int(input())
W = [rand() for _ in range(N)]
AL, AR, BL, BR = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
AL.append(a)
AR.append(b)
BL.append(c)
BR.append(d)
def chk(L, R):
S = sorted(list(set(L + R)))
D = {s:i for i, s in enumerate(S)}
L = [D[a] for a in L]
R = [D[a] for a in R]
X = [0] * 200200
for i, l in enumerate(L):
X[l] += W[i]
for i in range(1, 200200):
X[i] += X[i-1]
s = 0
for i, r in enumerate(R):
s += X[r] * W[i]
return s
print("YES" if chk(AL, AR) == chk(BL, BR) else "NO")
|
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
|
1320
|
A
|
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
|
[
"data structures",
"dp",
"greedy",
"math",
"sortings"
] |
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
b = list(map(int, input().split()))
l = pow(10, 6)
s = [0] * l
for i in range(n):
s[b[i] - i] += b[i]
ans = max(s)
print(ans)
|
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"
] |
from sys import stdin
input=lambda :stdin.readline()[:-1]
n,a,b,k=map(int,input().split())
h=list(map(int,input().split()))
ans=0
c=[]
for i in h:
r=i%(a+b)
if 0<r<=a:
ans+=1
continue
if r==0:
r+=a+b
c.append((r+a-1)//a-1)
c.sort()
for i in c:
if k>=i:
ans+=1
k-=i
print(ans)
|
py
|
1311
|
F
|
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3
1 3 2
-100 2 3
OutputCopy3
InputCopy5
2 1 4 3 5
2 2 2 3 4
OutputCopy19
InputCopy2
2 1
-3 0
OutputCopy0
|
[
"data structures",
"divide and conquer",
"implementation",
"sortings"
] |
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
input=lambda:sys.stdin.readline().strip('\n')
mis=lambda:map(int,input().split())
ii=lambda:int(input())
#sys.setrecursionlimit(5*(10 ** 3))
class ft:
def __init__(self, n):
self.n = n
self.a = [0] * (n+1)
def update(self, i, val):
i += 1
while i <= self.n:
self.a[i] += val
i += i & (-i)
def query(self, i):
r = 0
i += 1
while i > 0:
r += self.a[i]
i -= i & -i
return r
N = ii()
X = list(mis())
V = list(mis())
XV = list(zip(X, V))
XV.sort()
V.sort()
fw_cnt = ft(N)
fw_sum = ft(N)
ans = 0
for i, (x, v) in enumerate(XV):
pos = bisect_right(V, v) - 1
ans += x*fw_cnt.query(pos) - fw_sum.query(pos)
fw_cnt.update(pos, 1)
fw_sum.update(pos, x)
print(ans)
|
py
|
1288
|
C
|
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
|
[
"combinatorics",
"dp"
] |
n, m = list(map(int, input().split()))
MOD = 10**9 + 7
# since indexes are 0 based, we will use n+1 and m+1 in the dp arrays.
dp_a = [[0 for _ in range(n)] for _ in range(m)]
dp_b = [[0 for _ in range(n)] for _ in range(m)]
# setting the base state
for j in range(0, n):
dp_a[0][j] = 1
# populating the dp_a table
for i in range(1, m):
for j in range(0, n):
dp_a[i][j] += dp_a[i][j - 1] + dp_a[i - 1][j]
dp_a[i][j] %= MOD
# populating the dp_b table
for i in range(0, m):
for j in range(0, n):
dp_b[i][j] += dp_b[i][j - 1] + dp_a[i][j]
dp_b[i][j] %= MOD
# calculating the final result
ans = 0
for j in range(0, n):
# If last element of array a is j, then array be has n-j numbers avalilable.
ans += (dp_a[m-1][j] * dp_b[m-1][n-j-1]) %MOD
ans %= MOD
print(ans%MOD)
|
py
|
1285
|
A
|
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
|
[
"math"
] |
'''
Case 1: All L is ignored
Case 2: All R is ignored
LRLR
Range from [-2,2]
positions = 2--2 + 1
Count R and L
print(R+L + 1)
'''
n=int(input())
s = input().strip()
L = 0
R = 0
for c in s:
if c == "L":
L += 1
else:
R += 1
print(R + L + 1)
|
py
|
1313
|
C1
|
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
|
[
"brute force",
"data structures",
"dp",
"greedy"
] |
import os,sys
from random import randint, shuffle
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate, permutations
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split()))
# for _ in range(int(input())):
# a, b, c = list(map(int, input().split()))
# ans = 0
# for i in range(1 << 7):
# x = y = z = 0
# cnt = 0
# for j in range(7):
# if i >> j & 1:
# cnt += 1
# if j == 0:
# x += 1
# elif j == 1:
# y += 1
# elif j == 2:
# z += 1
# elif j == 3:
# x += 1
# y += 1
# elif j == 4:
# x += 1
# z += 1
# elif j == 5:
# y += 1
# z += 1
# else:
# x += 1
# y += 1
# z += 1
# if x <= a and y <= b and z <= c:
# ans = max(ans, cnt)
# print(ans)
# for _ in range(int(input())):
# n, x, y = list(map(int, input().split()))
n = int(input())
a = list(map(int, input().split()))
mx = 0
ans = []
for i in range(n):
b = a[:]
l = i - 1
r = i + 1
while l >= 0:
b[l] = min(b[l], b[l + 1])
l -= 1
while r < n:
b[r] = min(b[r], b[r - 1])
r += 1
tot = sum(b)
if tot > mx:
mx = tot
ans = b
print(*ans)
|
py
|
1320
|
A
|
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
|
[
"data structures",
"dp",
"greedy",
"math",
"sortings"
] |
import sys
from bisect import bisect_right, bisect_left
import os
import sys
from io import BytesIO, IOBase
from math import factorial, floor, sqrt, inf
from collections import defaultdict
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()
return(s[:len(s) - 1])
def invr():
return(map(int,input().split()))
def insr2():
s = input()
return(s.split(" "))
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
n = inp()
arr = inlt()
cnt = defaultdict(int)
for i in range(n):
cnt[arr[i]-i] += arr[i]
print(max(cnt.values()))
|
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"
] |
from heapq import heapify, heappop, heappush
from itertools import cycle
from math import sqrt,ceil
import os
import sys
from collections import defaultdict,deque
from io import BytesIO, IOBase
# prime = [True for i in range(5*10**5 + 1)]
# def SieveOfEratosthenes(n):
# p = 2
# while (p * p <= n):
# # If prime[p] is not changed, then it is a prime
# if (prime[p] == True):
# # Update all multiples of p
# for i in range(p ** 2, n + 1, p):
# prime[i] = False
# p += 1
# prime[0]= False
# prime[1]= False
# SieveOfEratosthenes(5*10**5)
# print(sum(el==True for el in prime))
# MOD = 998244353
# nmax = (2*(10**5))+2
# fact = [1] * (nmax+1)
# for i in range(2, nmax+1):
# fact[i] = fact[i-1] * i % MOD
# inv = [1] * (nmax+1)
# for i in range(2, nmax+1):
# inv[i] = pow(fact[i], MOD-2, MOD)
# def C(n, m):
# return fact[n] * inv[m] % MOD * inv[n-m] % MOD if 0 <= m <= n else 0
# import sys
# import math
# mod = 10**7+1
# LI=lambda:[int(k) for k in input().split()]
# input = lambda: sys.stdin.readline().rstrip()
# IN=lambda:int(input())
# S=lambda:input()
# r=range
# fact=[i for i in r(mod)]
# for i in reversed(r(2,int(mod**0.5))):
# i=i**2
# for j in range(i,mod,i):
# if fact[j]%i==0:
# fact[j]//=i
from collections import Counter
from functools import lru_cache
from collections import deque
def main():
for _ in range(int(input())):
n,m=map(int,input().split())
if m==0:
print(0)
elif m==n:
print(n*(n+1)//2)
else :
zero=n-m
tot=m+1
per=zero//tot
res=n*(n+1)//2
res-=tot*(per*(per+1)//2)
rem=zero-per*tot
res-=rem*(per+1)
print(res)
# class SegmentTree:
# def __init__(self, data, default=0, func=max):
# self._default = default
# self._func = func
# self._len = len(data)
# self._size = _size = 1 << (self._len - 1).bit_length()
# self.data = [default] * (2 * _size)
# self.data[_size:_size + self._len] = data
# for i in reversed(range(_size)):
# self.data[i] = func(self.data[i + i], self.data[i + i + 1])
# def __delitem__(self, idx):
# self[idx] = self._default
# def __getitem__(self, idx):
# return self.data[idx + self._size]
# def __setitem__(self, idx, value):
# idx += self._size
# self.data[idx] = value
# idx >>= 1
# while idx:
# self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
# idx >>= 1
# def __len__(self):
# return self._len
# def query(self, start, stop):
# """func of data[start, stop)"""
# start += self._size
# stop += self._size
# if start==stop:
# return self._default
# res_left = res_right = self._default
# while start < stop:
# if start & 1:
# res_left = self._func(res_left, self.data[start])
# start += 1
# if stop & 1:
# stop -= 1
# res_right = self._func(self.data[stop], res_right)
# start >>= 1
# stop >>= 1
# return self._func(res_left, res_right)
# def __repr__(self):
# return "SegmentTree({0})".format(self.data)
# import bisect,math
# ---------------------------------------------------------
# class SortedList():
# BUCKET_RATIO = 50
# REBUILD_RATIO = 170
# def __init__(self,buckets):
# buckets = list(buckets)
# buckets = sorted(buckets)
# self._build(buckets)
# def __iter__(self):
# for i in self.buckets:
# for j in i: yield j
# def __reversed__(self):
# for i in reversed(self.buckets):
# for j in reversed(i): yield j
# def __len__(self):
# return self.size
# def __contains__(self,x):
# if self.size == 0: return False
# bucket = self._find_bucket(x)
# i = bisect.bisect_left(bucket,x)
# return i != len(bucket) and bucket[i] == x
# def __getitem__(self,x):
# if x < 0: x += self.size
# if x < 0: raise IndexError
# for i in self.buckets:
# if x < len(i): return i[x]
# x -= len(i)
# raise IndexError
# def _build(self,buckets=None):
# if buckets is None: buckets = list(self)
# self.size = len(buckets)
# bucket_size = int(math.ceil(math.sqrt(self.size/self.BUCKET_RATIO)))
# tmp = []
# for i in range(bucket_size):
# t = buckets[(self.size*i)//bucket_size:(self.size*(i+1))//bucket_size]
# tmp.append(t)
# self.buckets = tmp
# def _find_bucket(self,x):
# for i in self.buckets:
# if x <= i[-1]:
# return i
# return i
# def add(self,x):
# # O(√N)
# if self.size == 0:
# self.buckets = [[x]]
# self.size = 1
# return True
# bucket = self._find_bucket(x)
# bisect.insort(bucket,x)
# self.size += 1
# if len(bucket) > len(self.buckets) * self.REBUILD_RATIO:
# self._build()
# return True
# def remove(self,x):
# # O(√N)
# if self.size == 0: return False
# bucket = self._find_bucket(x)
# i = bisect.bisect_left(bucket,x)
# if i == len(bucket) or bucket[i] != x: return False
# bucket.pop(i)
# self.size -= 1
# if len(bucket) == 0: self._build()
# return True
# def lt(self,x):
# # less than < x
# for i in reversed(self.buckets):
# if i[0] < x:
# return i[bisect.bisect_left(i,x) - 1]
# def le(self,x):
# # less than or equal to <= x
# for i in reversed(self.buckets):
# if i[0] <= x:
# return i[bisect.bisect_right(i,x) - 1]
# def gt(self,x):
# # greater than > x
# for i in self.buckets:
# if i[-1] > x:
# return i[bisect.bisect_right(i,x)]
# def ge(self,x):
# # greater than or equal to >= x
# for i in self.buckets:
# if i[-1] >= x:
# return i[bisect.bisect_left(i,x)]
# def index(self,x):
# # the number of elements < x
# ans = 0
# for i in self.buckets:
# if i[-1] >= x:
# return ans + bisect.bisect_left(i,x)
# ans += len(i)
# return ans
# def index_right(self,x):
# # the number of elements < x
# ans = 0
# for i in self.buckets:
# if i[-1] > x:
# return ans + bisect.bisect_right(i,x)
# ans += len(i)
# return ans
#--------------------------------------------------------------
# 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)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
|
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.