contest_id
stringclasses 33
values | problem_id
stringclasses 14
values | statement
stringclasses 181
values | tags
sequencelengths 1
8
| code
stringlengths 21
64.5k
| language
stringclasses 3
values |
---|---|---|---|---|---|
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | n = int(input())
s = input()
s = list(s)
cnt = 0
for i in range(25, -1, -1):
c = chr(97+i)
j = 0
while j < len(s):
if s[j] == c and (j != 0 and ord(s[j-1])+1 == ord(c) or j != len(s)-1 and ord(s[j+1])+1 == ord(c)):
s.pop(j)
cnt += 1
j = -1
j += 1
print(cnt) | 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 sys
readline = sys.stdin.readline
def accumulate2d(X):
N = len(X)
M = len(X[0])
for i in range(0, N):
for j in range(1, M):
X[i][j] += X[i][j-1]
for j in range(0, M):
for i in range(1, N):
X[i][j] += X[i-1][j]
return X
N, M, Q = map(int, readline().split())
table = [None]*100
table[ord('R')] = 0
table[ord('G')] = 1
table[ord('B')] = 2
table[ord('Y')] = 3
INF = 10**3
D = [[table[ord(s)] for s in readline().strip()] for _ in range(N)]
G = [[0]*M for _ in range(N)]
BS = 25
candi = []
geta = M
for i in range(N-1):
for j in range(M-1):
if D[i][j] == 0 and D[i][j+1] == 1 and D[i+1][j+1] == 2 and D[i+1][j] == 3:
G[i][j] = 1
nh, nw = i, j
while True:
k = G[nh][nw]
fh, fw = nh-k, nw-k
k2 = 2*(k+1)
kh = k+1
if fh < 0 or fw < 0 or N < fh+k2-1 or M < fw+k2-1:
break
if any(D[fh][j] != 0 for j in range(fw, fw+kh)) or\
any(D[j][fw] != 0 for j in range(fh, fh+kh)) or\
any(D[fh][j] != 1 for j in range(fw+kh, fw+k2)) or\
any(D[j][fw+k2-1] != 1 for j in range(fh, fh+kh)) or\
any(D[j][fw+k2-1] != 2 for j in range(fh+kh, fh+k2)) or\
any(D[fh+k2-1][j] != 2 for j in range(fw+kh, fw+k2)) or\
any(D[fh+k2-1][j] != 3 for j in range(fw, fw+kh)) or\
any(D[j][fw] != 3 for j in range(fh+kh, fh+k2)):
break
G[nh][nw] += 1
if G[nh][nw] > BS:
candi.append((nh, nw))
Gnum = [None] + [[[0]*M for _ in range(N)] for _ in range(BS)]
for h in range(N):
for w in range(M):
if G[h][w] > 0:
for k in range(1, min(BS, G[h][w])+1):
Gnum[k][h][w] = 1
Gnum = [None] + [accumulate2d(g) for g in Gnum[1:]]
Ans = [None]*Q
for qu in range(Q):
h1, w1, h2, w2 = map(lambda x: int(x)-1, readline().split())
res = 0
for k in range(min(BS, h2-h1+1, w2-w1+1), 0, -1):
hs, ws = h1+k-1, w1+k-1
he, we = h2-k, w2-k
if hs <= he and ws <= we:
cnt = Gnum[k][he][we]
if hs:
cnt -= Gnum[k][hs-1][we]
if ws:
cnt -= Gnum[k][he][ws-1]
if hs and ws:
cnt += Gnum[k][hs-1][ws-1]
if cnt:
res = k
break
for nh, nw in candi:
if h1 <= nh <= h2 and w1 <= nw <= w2:
res = max(res, min(nh-h1+1, h2-nh, nw-w1+1, w2-nw, G[nh][nw]))
Ans[qu] = 4*res**2
print('\n'.join(map(str, Ans))) | py |
1316 | A | A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105) — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m) — scores of the students.OutputFor each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m. | [
"implementation"
] | t = int(input())
for _ in range(t):
n, m = map(int, input().split())
score = [int(x) for x in input().split()][:n]
total = 0
for i in range(n): total += score[i]
print(min(m, total))
| py |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | n=int(input())
l=input()
r=input()
ldic={}
rdic={}
for i in range(n):
if l[i] in ldic:
ldic[l[i]].append(i)
else:
ldic[i]=[i]
for i in range(n):
if r[i] in rdic:
rdic[r[i]].append(i)
else:
rdic[r[i]]=[i]
li=[]
for i in range(n):
li.append([l[i],i])
li.sort()
nli=[]
c=0
for i in range(n):
if li[i][0]=="?":
c+=1
else:
break
nli=li[c:]+li[:c]
# print(nli)
# print(rdic)
ans=[]
visb=[0]*n
for i in range(n):
if nli[i][0]!="?":
if nli[i][0] in rdic and len(rdic[nli[i][0]])>0:
num=rdic[nli[i][0]][-1]
rdic[nli[i][0]].pop(-1)
ans.append([nli[i][1]+1,num+1])
else:
if "?" in rdic and len(rdic["?"])>0:
num=rdic["?"][-1]
rdic["?"].pop(-1)
ans.append([nli[i][1]+1,num+1])
else:
z=0
for j in rdic:
if j!="?" and len(rdic[j])>0:
num=rdic[j][-1]
rdic[j].pop(-1)
ans.append([nli[i][1]+1,num+1])
z=1
break
if z==0:
for j in rdic:
if j=="?" and len(rdic[j])>0:
num=rdic[j][-1]
rdic[j].pop(-1)
ans.append([nli[i][1]+1,num+1])
z=1
break
print(len(ans))
for i in ans:
print(*i)
| 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 sys
import math
from math import *
import builtins
input = sys.stdin.readline
def print(x, end='\n'):
sys.stdout.write(str(x) + end)
# IO helpers
def get_int():
return int(input())
def get_list_ints():
return list(map(int, input().split()))
def get_char_list():
s = input()
return list(s[:len(s) - 1])
def get_tuple_ints():
return tuple(map(int, input().split()))
def print_iterable(p):
print(" ".join(map(str, p)))
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return high
def find_gcd(x, y):
while(y):
x, y = y, x % y
return x
# Python3 program to calculate
# Euler's Totient Function
def phi(n):
# Initialize result as n
result = n;
# Consider all prime factors
# of n and subtract their
# multiples from result
p = 2;
while(p * p <= n):
# Check if p is a
# prime factor.
if (n % p == 0):
# If yes, then
# update n and result
while (n % p == 0):
n = int(n / p);
result -= int(result / p);
p += 1;
# If n has a prime factor
# greater than sqrt(n)
# (There can be at-most
# one such prime factor)
if (n > 1):
result -= int(result / n);
return result;
def main():
n=get_int()
for i in range(n):
[a,m]=get_list_ints()
g=find_gcd(a,m)
p2=m//g
ans=phi(p2)
print(ans)
pass
if __name__ == '__main__':
main()
| py |
1307 | B | B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109) — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0). | [
"geometry",
"greedy",
"math"
] | import sys
from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm, radians, tan, log2
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import heapify, heappush, heappop
#from sortedcontainers import SortedList
#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 bs(arr,x):
low,high = 0,len(arr)-1
ans = -1
while low<=high:
mid = (low+high)//2
if arr[mid]==x:
return mid
elif arr[mid]<x:
ans = mid
low = mid+1
else:
high = mid-1
return ans
def addd(arr,x):
t = bs(arr,x)
ans = []
if t!=0:
ans = arr[:t]
ans.append(x)
if t!=len(arr):
ans.extend(arr[t:])
return ans
#======================================================#
def factorial_inverse():
mod=10**9+7
upto=(10**3)*2+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
#ans = mid
else:
high = mid-1
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
#======================================================#
for _ in range(I()):
n,x = M()
a = L()
b = 0
f = False
for i in range(n):
if a[i]==x:
print(1)
f = True
break
if a[i]<x:
b = max(b,a[i])
if f:
continue
if b!=max(a):
print(2)
continue
ans = x//b
t = x%b
if t!=0:
ans+=1
print(ans)
| 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 array
import bisect
import heapq
import json
import math
import collections
import random
import re
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
import fractions
from typing import Tuple, List, Union
from queue import PriorityQueue
# sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque
big_prime = 135771883649879
################## pypy deep recursion handling ##############
# Author = @pajenegod
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
to = f(*args, **kwargs)
if stack:
return to
else:
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
return to
to = stack[-1].send(to)
return wrappedfunc
################## Graphs ###################
class Graphs:
def __init__(self):
self.graph = graphDict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def dfs_utility(self, nodes, visited_nodes, colors, parity, level):
global count
if nodes == 1:
colors[nodes] = -1
else:
if len(self.graph[nodes]) == 1 and parity % 2 == 0:
if q == 1:
colors[nodes] = 1
else:
colors[nodes] = -1
count += 1
else:
if parity % 2 == 0:
colors[nodes] = -1
else:
colors[nodes] = 1
visited_nodes.add(nodes)
for neighbour in self.graph[nodes]:
new_level = level + 1
if neighbour not in visited_nodes:
self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)
def dfs(self, node):
Visited = set()
color = collections.defaultdict()
self.dfs_utility(node, Visited, color, 0, 0)
return color
def bfs(self, node, f_node):
count = float("inf")
visited = set()
level = 0
if node not in visited:
queue.append([node, level])
visited.add(node)
flag = 0
while queue:
parent = queue.popleft()
if parent[0] == f_node:
flag = 1
count = min(count, parent[1])
level = parent[1] + 1
for item in self.graph[parent[0]]:
if item not in visited:
queue.append([item, level])
visited.add(item)
return count if flag else -1
return False
################### Tree Implementaion ##############
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(node, lis):
if node:
inorder(node.left, lis)
lis.append(node.data)
inorder(node.right, lis)
return lis
def leaf_node_sum(root):
if root is None:
return 0
if root.left is None and root.right is None:
return root.data
return leaf_node_sum(root.left) + leaf_node_sum(root.right)
def hight(root):
if root is None:
return -1
if root.left is None and root.right is None:
return 0
return max(hight(root.left), hight(root.right)) + 1
################## Union Find #######################
class UnionFind():
parents = []
sizes = []
count = 0
def __init__(self, n):
self.count = n
self.parents = [i for i in range(n)]
self.sizes = [1 for i in range(n)]
def find(self, i):
if self.parents[i] == i:
return i
else:
self.parents[i] = self.find(self.parents[i])
return self.parents[i]
def unite(self, i, j):
root_i = self.find(i)
root_j = self.find(j)
if root_i == root_j:
return
elif root_i < root_j:
self.parents[root_j] = root_i
self.sizes[root_i] += self.sizes[root_j]
else:
self.parents[root_i] = root_j
self.sizes[root_j] += self.sizes[root_i]
def same(self, i, j):
return self.find(i) == self.find(j)
def size(self, i):
return self.sizes[self.find(i)]
def group_count(self):
return len(set(self.find(i) for i in range(self.count)))
def answer(self, extra, p, q):
dic = collections.Counter()
for q in range(n):
dic[self.find(q)] = self.size(q)
hq = list(dic.values())
heapq._heapify_max(hq)
ans = -1
for z in range(extra + 1):
if hq:
ans += heapq._heappop_max(hq)
else:
break
return ans
#################################################
def rounding(n):
return int(decimal.Decimal(f'{n}').to_integral_value())
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0), [1]))
def p_sum(array):
return list(itertools.accumulate(array))
def base_change(nn, bb):
if nn == 0:
return [0]
digits = []
while nn:
digits.append(int(nn % bb))
nn //= bb
return digits[::-1]
def diophantine(a: int, b: int, c: int):
d, x, y = extended_gcd(a, b)
r = c // d
return r * x, r * y
@bootstrap
def extended_gcd(a: int, b: int):
if b == 0:
d, x, y = a, 1, 0
else:
(d, p, q) = yield extended_gcd(b, a % b)
x = q
y = p - q * (a // b)
yield d, x, y
######################################################################################
'''
Knowledge and awareness are vague, and perhaps better called illusions.
Everyone lives within their own subjective interpretation.
~Uchiha Itachi
'''
################################ <fast I/O> ###########################################
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, **kwargs):
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)
#############################################<I/O Region >##############################################
def inp():
return sys.stdin.readline().strip()
def map_inp(v_type):
return map(v_type, inp().split())
def list_inp(v_type):
return list(map_inp(v_type))
def interactive():
return sys.stdout.flush()
######################################## Solution ####################################
def primes_sieve1(limit):
limitn = limit + 1
primes = dict()
for i in range(2, limitn): primes[i] = True
for i in primes:
factors = range(i, limitn, i)
for f in factors[1:]:
primes[f] = False
return [i for i in primes if primes[i] == True]
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))
def n_sum(x):
return (x * (x + 1)) // 2
# for accurate division
def div(q, w):
return decimal.Decimal(q).__truediv__(decimal.Decimal(w))
# kickstart
def ks(case, value, is_arr=False):
if is_arr:
return f"""Case #{case + 1}: {" ".join([str(item) for item in value])}"""
return f"""Case #{case + 1}: {value}"""
"""
“What good are dreams, if all you do is work? There’s more to life than hitting the books, I hope you know.”
— Tamaki Suou
"""
for _ in range(int(inp())):
s = inp()
t = inp()
dic = collections.defaultdict(list)
for i, item in enumerate(s):
dic[item].append(i)
n = len(t) - 1
flag = 1
ans = 0
while n >= 0:
if t[n] not in dic:
flag = 0
break
last = dic[t[n]][-1]
ans += 1
while n >= 0:
n -= 1
if t[n] not in dic:
flag = 0
break
x = bisect.bisect_left(dic[t[n]], last)
x -= 1
temp = dic[t[n]][x]
if temp < last:
last = temp
else:
break
if not flag:
break
if flag:
print(ans)
else:
print(-1)
| 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"
] | def solve(n, l):
c = 0
for i in range(1, n):
c = max(c, abs(l[i] - l[i - 1]))
return c
t = int(input())
while(t):
n = int(input())
l = list(map(int, input().split()))
a = []
for i in range(n - 1):
if(l[i] != -1 and l[i + 1] == -1):
a.append(l[i])
elif(l[i + 1] != -1 and l[i] == -1):
a.append(l[i + 1])
if(not a):
print(0, 0)
else:
k = (max(a) + min(a) + 1) // 2
l = [k if i == -1 else i for i in l]
m = solve(n, l)
print(m, k)
t -= 1 | 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 heapq
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n = int(input())
A = [None]*n
B = [None]*n
events = dict()
events0 = dict()
for i in range(n):
sa,ea,sb,eb = map(int,input().split())
if sa not in events:
events[sa] = [[],[]]
if ea not in events:
events[ea] = [[],[]]
if sb not in events0:
events0[sb] = [[],[]]
if eb not in events0:
events0[eb] = [[],[]]
events[sa][1].append(i)
events[ea][0].append(i)
events0[sb][1].append(i)
events0[eb][0].append(i)
A[i] = (sa,ea)
B[i] = (sb,eb)
I = list(range(n))
I.sort(key=lambda i: A[i])
lo,hi = [],[]
to_remove_lo = {x:0 for x,_ in B}
to_remove_hi = {x:0 for _,x in B}
for t in sorted(events):
for i in events[t][1]:
sb,eb = B[i]
heapq.heappush(lo, -sb)
heapq.heappush(hi, eb)
while lo and to_remove_lo[-lo[0]]:
to_remove_lo[-heapq.heappop(lo)] -= 1
while hi and to_remove_hi[hi[0]]:
to_remove_hi[heapq.heappop(hi)] -= 1
# check
if -lo[0] > hi[0]:
print("NO")
exit()
for i in events[t][0]:
sb,eb = B[i]
to_remove_lo[sb] += 1
to_remove_hi[eb] += 1
I = list(range(n))
I.sort(key=lambda i: B[i])
lo,hi = [],[]
to_remove_lo = {x:0 for x,_ in A}
to_remove_hi = {x:0 for _,x in A}
for t in sorted(events0):
for i in events0[t][1]:
sa,ea = A[i]
heapq.heappush(lo, -sa)
heapq.heappush(hi, ea)
while lo and to_remove_lo[-lo[0]]:
to_remove_lo[-heapq.heappop(lo)] -= 1
while hi and to_remove_hi[hi[0]]:
to_remove_hi[heapq.heappop(hi)] -= 1
# check
if -lo[0] > hi[0]:
print("NO")
exit()
for i in events0[t][0]:
sa,ea = A[i]
to_remove_lo[sa] += 1
to_remove_hi[ea] += 1
print("YES")
| 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 math
def main():
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
ev = 0
ods = []
for i in range(n):
if (a[i] & 1) == 0:
ev = i + 1
else:
ods.append(i + 1)
if ev != 0:
print(1)
print(ev)
elif len(ods) >= 2:
print(2)
print(ods[0], ods[1])
else:
print(-1)
main()
| py |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] |
def main():
n = int(input())
a = readIntArr()
dp = [[-1 for _ in range(n)] for __ in range(n)]
# dp[l][r] = the value that a[l:r] can become
for l in range(n):
dp[l][l] = a[l]
for gap in range(2, n + 1):
for l in range(n):
r = l + gap - 1
if r == n:
break
for mid in range(l, r):
if dp[l][mid] != -1 and dp[l][mid] == dp[mid + 1][r]:
dp[l][r] = dp[l][mid] + 1
break
dp2 = [n] * n
for r in range(n):
for l in range(r + 1):
if l == 0:
prev = 0
else:
prev = dp2[l - 1]
if dp[l][r] != -1:
dp2[r] = min(dp2[r], prev + 1)
ans = dp2[n - 1]
print(ans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b):
print('? {} {}'.format(a, b))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | 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 io
import os
# PSA:
# The key optimization that made this pass was to avoid python big ints by using floats (which have integral precision <= 2^52)
# None of the other optimizations really mattered in comparison.
# Credit for this trick goes to pajenegod: https://codeforces.com/blog/entry/77309?#comment-622486
popcount = []
for mask in range(1 << 7):
popcount.append(bin(mask).count("1"))
maskToPos = []
for mask in range(1 << 7):
maskToPos.append([i for i in range(7) if mask & (1 << i)])
inf = float("inf")
def solve(N, P, K, audienceScore, playerScore):
scores = sorted(zip(audienceScore, playerScore), reverse=True)
scoresA = [0.0 for i in range(N)]
scoresP = [0.0 for i in range(7 * N)]
for i, (a, ps) in enumerate(scores):
scoresA[i] = float(a)
for j, p in enumerate(ps):
scoresP[7 * i + j] = float(p)
f = [-inf for mask in range(1 << P)]
nextF = [-inf for mask in range(1 << P)]
f[0] = scoresA[0]
for pos in range(P):
f[1 << pos] = scoresP[pos]
for n in range(1, N):
for mask in range(1 << P):
best = f[mask]
if n - popcount[mask] < K:
best += scoresA[n]
for pos in maskToPos[mask]:
best = max(best, scoresP[7 * n + pos] + f[mask - (1 << pos)])
nextF[mask] = best
f, nextF = nextF, f
return int(max(f))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, P, K = list(map(int, input().split()))
audienceScore = [int(x) for x in input().split()]
playerScore = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, P, K, audienceScore, playerScore)
print(ans)
| py |
1305 | C | C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10
8 5
OutputCopy3InputCopy3 12
1 4 5
OutputCopy0InputCopy3 7
1 4 9
OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7. | [
"brute force",
"combinatorics",
"math",
"number theory"
] | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
w = list(map(int, input().split()))
if n > m:
print(0)
else:
c = 1
for i in range(n):
for j in range(i+1, n):
c = c * (abs(w[i]-w[j])) % m
if c == 0:
print(c)
exit()
print(c)
| py |
1291 | B | B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened. | [
"greedy",
"implementation"
] | import sys
input = sys.stdin.readline
show = sys.stdout.write
for _ in range(int(input())):
n = int(input())
f = False
arr = list(map(int, input().split()))
i = 0
while i<n and arr[i] >= i:
i+=1
while i<n:
if arr[i-1]>arr[i]:
i+=1
continue
else:
arr[i] = arr[i-1] - 1
if arr[i] < 0:
break
i+=1
if i==n:
show("Yes\n")
else:
show("No\n")
| 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"
] | import math
n, m = map(int, input().split())
result = math.factorial(n+(2*m)-1)//(math.factorial(2*m)*math.factorial(n-1))
print(int(result) % (1000000007))
| py |
1290 | A | A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1) — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44. | [
"brute force",
"data structures",
"implementation"
] | 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])]
### セグメント木(はやい)
class SG:
def __init__(self, n, v=None):
self._n = n
self.geta = 0
x = 0
while (1 << x) < n:
x += 1
self._log = x
self._size = 1 << self._log
self._d = [ninf] * (2 * self._size)
if v is not None:
for i in range(self._n):
self._d[self._size + i] = v[i]
for i in range(self._size - 1, 0, -1):
self._update(i)
def _update(self, k):
self._d[k] = op(self._d[2 * k], self._d[2 * k + 1])
def update(self, p, x):
assert 0 <= p < self._n
# x -= self.geta
p += self._size
self._d[p] = x
for i in range(1, self._log + 1):
# self._update(p >> i)
k = p>>i
self._d[k] = op(self._d[2 * k], self._d[2 * k + 1])
def get(self, p):
assert 0 <= p < self._n
return self._d[p + self._size] # + self.geta
def check(self):
return [self.get(p) for p in range(self._n)]
def query(self, left, right):
# [l,r)の総和
assert 0 <= left <= right <= self._n
sml = ninf
smr = ninf
left += self._size
right += self._size
# 外側から計算していく(lは小さい側から, rは大きい側から)
while left < right:
if left & 1:
sml = op(sml, self._d[left])
left += 1
if right & 1:
right -= 1
smr = op(self._d[right], smr)
left >>= 1
right >>= 1
return op(sml, smr) # + self.geta
# def update_all(self, v):
# # 全体加算
# self.geta += v
def query_all(self):
return self._d[1] # + self.geta
def max_right(self, left, f):
"""f(op(a[l], a[l + 1], ..., a[r - 1])) = true となる最大の r
-> rはf(op(a[l], ..., a[r]))がFalseになる最小のr
"""
# assert 0 <= left <= self._n
# assert f(ninf)
if left == self._n:
return self._n
left += self._size
sm = ninf
first = True
while first or (left & -left) != left:
first = False
while left % 2 == 0:
left >>= 1
if not f(op(sm, self._d[left])):
while left < self._size:
left *= 2
if f(op(sm, self._d[left])):
sm = op(sm, self._d[left])
left += 1
return left - self._size
sm = op(sm, self._d[left])
left += 1
return self._n
def min_left(self, right, f):
"""f(op(a[l], a[l + 1], ..., a[r - 1])) = true となる最小の l
-> l は f(op(a[l-1] ,..., a[r-1])) が false になる最大の l
"""
# assert 0 <= right <= self._n
# assert f(ninf)
if right == 0:
return 0
right += self._size
sm = ninf
first = True
while first or (right & -right) != right:
first = False
right -= 1
while right > 1 and right % 2:
right >>= 1
if not f(op(self._d[right], sm)):
while right < self._size:
right = 2 * right + 1
if f(op(self._d[right], sm)):
sm = op(self._d[right], sm)
right -= 1
return right + 1 - self._size
sm = op(self._d[right], sm)
return 0
op = min
ninf = INF
t = II()
for _ in range(t):
n,m,k = LI()
k = min(k,m-1)
a = list(map(int, input().split()))
vs = []
for i in range(m):
v = max(a[i], a[i+(n-m+1)-1])
vs.append(v)
sg = SG(m, vs)
ans = sg.query(0,m)
for i in range(k+1):
ans = max(ans, sg.query(i, i+m-k))
print(ans) | py |
1324 | E | E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good. | [
"dp",
"implementation"
] | """
f[i][j], a[0,..,i-1], s[i] % h = j, maxscore
f[i][j] = max(f[i - 1][(j - a[i - 1]) % h],
f[i - 1][(j - a[i - 1] + 1) % h]) + (l <= j <= r)
"""
n, h, l, r = list(map(int, input().split()))
a = list(map(int, input().split()))
f = [[float('-inf')] * h for _ in range(n + 1)]
f[0][0] = 0
for i in range(1, n + 1):
for j in range(h):
f[i][j] = max(f[i - 1][(j - a[i - 1]) % h], f[i - 1][(j - a[i - 1] + 1) % h]) + int(l <= j <= r)
print(max(f[n])) | py |
1307 | A | A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Next 2t2t lines contain a description of test cases — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100) — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day. | [
"greedy",
"implementation"
] | R=lambda:map(int,input().split())
t,=R()
for _ in[0]*t:
n,d=R();r=i=0
for x in R():m=min(d,i*x);r+=m//i if i else x;d-=m;i+=1
print(r) | 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"
] | # aabb babb babb babb baba
# bbaa bbaa baaa baba baba
# baba aaba abba abaa abab
for _ in range(int(input())):
a1 = input()
a2 = input()
a3 = input()
flag = 0
for i in range(len(a1)):
if a1[i] != a3[i] and a2[i] != a3[i]:
flag = 1
break
if flag == 1:
print('NO')
else:
print('YES') | py |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10. | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
# Read input and build the graph
inp = [int(x) for x in sys.stdin.buffer.read().split()]; ii = 0
n = inp[ii]; ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
# Relabel to speed up n^2 operations later on
bfs = [0]
found = [0]*n
found[0] = 1
for node in bfs:
for nei in coupl[node]:
if not found[nei]:
found[nei] = 1
bfs.append(nei)
new_label = [0]*n
for i in range(n):
new_label[bfs[i]] = i
coupl = [coupl[i] for i in bfs]
for c in coupl:
c[:] = [new_label[x] for x in c]
##### DP using multisource bfs
DP = [0] * (n * n)
size = [1] * (n * n)
P = [-1] * (n * n)
# Create the bfs ordering
bfs = [root * n + root for root in range(n)]
for ind in bfs:
P[ind] = ind
for ind in bfs:
node, root = divmod(ind, n)
for nei in coupl[node]:
ind2 = nei * n + root
if P[ind2] == -1:
bfs.append(ind2)
P[ind2] = ind
del bfs[:n]
# Do the DP
for ind in reversed(bfs):
node, root = divmod(ind, n)
pind = P[ind]
parent = pind//n
# Update size of (root, parent)
size[pind] += size[ind]
# Update DP value of (root, parent)
DP[root * n + parent] = DP[pind] = max(DP[pind], DP[ind] + size[ind] * size[root * n + node])
print(max(DP[root * n + root] for root in range(n))) | 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"
] | from sys import stdin
input = stdin.readline
#google = lambda : print("Case #%d: "%(T + 1) , end = '')
inp = lambda : list(map(int,input().split()))
def answer():
for q in range(int(input())):
y = int(input())
y -= 1
ans = a[y % n] + b[y % m]
print(ans)
for T in range(1):
n , m = inp()
a = input().split()
b = input().split()
answer()
| py |
1325 | E | E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1≤n≤1051≤n≤105) — the length of aa.The second line contains nn integers a1a1, a2a2, ……, anan (1≤ai≤1061≤ai≤106) — the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInputCopy3
1 4 6
OutputCopy1InputCopy4
2 3 6 6
OutputCopy2InputCopy3
6 15 10
OutputCopy3InputCopy4
2 3 5 7
OutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence. | [
"brute force",
"dfs and similar",
"graphs",
"number theory",
"shortest paths"
] | from sys import stdin, exit
from collections import deque
N = int(input())
arr = list(map(int, stdin.readline().split()))
# sieve, prime list, dictionary of primes
# lp is largest prime
MAX = 1_000_005
pid = {1:0}
pr = []
lp = [0]*MAX
for i in range(2, MAX):
if not lp[i]:
lp[i] = i
pr.append(i)
pid[i] = len(pr)
for p in pr:
if p > lp[i] or i*p >= MAX:
break
lp[i*p] = p
g = [[] for i in range(len(pid))]
large_prime = 0
for x in arr:
new = []
while x > 1:
p, c = lp[x], 0
while lp[x] == p:
x //= p
c ^= 1
if c:
new.append(p)
if not len(new):
print (1)
exit()
L = max(new)
if L > large_prime:
large_prime = L
new += [1]*(2 - len(new))
u, v = pid[new[0]], pid[new[1]]
g[u].append(v)
g[v].append(u)
def bfs(s):
q = deque()
q.append((s, -1))
v = [-1]*len(pid)
v[s] = 0
while len(q):
c, p = q.pop()
for n in g[c]:
if v[n] != -1:
if n != p:
return v[c] + v[n] + 1
else:
v[n] = v[c] + 1
q.appendleft((n, c))
ans = N + 1
for i in range(len(pid)):
if i > 0 and pr[i - 1]**2 >= MAX:
break
ans = min(ans, bfs(i) or ans)
print (ans if ans <= N else -1)
| 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"
] | t=int(input())
for k in range(t):
n=int(input())
a=[*map(int,input().split())]
#print(a)
kt=False; kq=-1; s=[]
for i in range(n):
if a[i]%2==0 :
s.append(i+1)
kt=True
break
if kt :
print(len(s))
print(*s)
else :
for i in range(n):
if a[i]%2!=0 :
s.append(i+1)
if len(s) >1 : break
if len(s) <2 : print(-1)
else :
print(len(s))
print(*s) | 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"
] | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def solve(s,t):
if len(t) == 1:
if s.count(t[0]):
return 'YES'
return 'NO'
for i in range(1,len(t)):
dp = [[-1000]*(i+1) for _ in range(len(s)+1)]
dp[0][0] = 0
for j in range(len(s)):
dp[j+1] = dp[j][:]
for k in range(i+1):
if k != i and s[j] == t[k]:
dp[j+1][k+1] = max(dp[j+1][k+1],dp[j][k])
if abs(dp[j][k]+i) < len(t) and s[j] == t[dp[j][k]+i]:
dp[j+1][k] = max(dp[j+1][k],dp[j][k]+1)
for l in range(len(s)+1):
if dp[l][-1] == len(t)-i:
return 'YES'
return 'NO'
def main():
for _ in range(int(input())):
s = input().strip()
t = input().strip()
print(solve(s,t))
#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 |
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"
] | 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())):
# x, y, a, b = list(map(int, input().split()))
# if (y - x) % (a + b):
# print(-1)
# else:
# print((y - x) // (a + b))
n, m = list(map(int, input().split()))
st = set()
a = []
for _ in range(n):
s = input()
if s[::-1] in st:
st.remove(s[::-1])
a.append(s)
else:
st.add(s)
b = ''
for s in st:
if s == s[::-1]:
b = s
break
a = ''.join(a)
print(len(a) * 2 + len(b))
print(a + b + a[::-1])
| py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | # If you win, you live. You cannot win unless you fight.
from math import sin
from sys import stdin,setrecursionlimit
input=stdin.readline
import heapq
rd=lambda: map(lambda s: int(s), input().strip().split())
ri=lambda: int(input())
rs=lambda :input().strip()
from collections import defaultdict as unsafedict,deque,Counter as unsafeCounter
from bisect import bisect_left as bl, bisect_right as br
from random import randint
random = randint(1, 10 ** 9)
mod=998244353
def ceil(a,b):
return (a+b-1)//b
class myDict:
def __init__(self,func):
self.RANDOM = randint(0,1<<32)
self.default=func
self.dict={}
def __getitem__(self,key):
myKey=self.RANDOM^key
if myKey not in self.dict:
self.dict[myKey]=self.default()
return self.dict[myKey]
def get(self,key,default):
myKey=self.RANDOM^key
if myKey not in self.dict:
return default
return self.dict[myKey]
def __setitem__(self,key,item):
myKey=self.RANDOM^key
self.dict[myKey]=item
def getKeys(self):
return [self.RANDOM^i for i in self.dict]
def __str__(self):
return f'{[(self.RANDOM^i,self.dict[i]) for i in self.dict]}'
from math import prod
'''
x*ts+y==m
(m-y)%ts==0
type 2
x*ts-x==m
'''
for _ in range(ri()):
n,m=rd()
s=rs()
ts=s.count("0")-s.count("1")
if ts==0:
x=0
ans=0
for i in s:
if i=="0":
x+=1
else:
x-=1
if x==m:
ans+=1
if ans:
print(-1)
else:
print(0)
continue
ans=0
y=0
st=set()
if m==0:
st.add(-1)
for i in range(n):
if s[i]=="1":
y-=1
else:
y+=1
if (m-y)%ts==0:
if (m-y)//ts>=0:
st.add(((m-y)//ts,i))
ans+=1
print(len(st))
| py |
1141 | D | D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10
| [
"greedy",
"implementation"
] | import sys
def II(): return int(sys.stdin.readline())
def LI(): return [int(num) for num in sys.stdin.readline().split()]
def SI(): return sys.stdin.readline().rstrip()
from collections import defaultdict
k = II()
l = defaultdict(list)
r = defaultdict(list)
for ind, char in enumerate(zip(SI(), SI())):
l[char[0]].append(ind + 1)
r[char[1]].append(ind + 1)
# print(l)
# print(r)
pairs = []
def func(seek_from, where, flag):
for char in seek_from:
if char != '?' and char in where:
while seek_from[char] and where[char]:
if flag:
pairs.append([seek_from[char].pop(), where[char].pop()])
else:
pairs.append([where[char].pop(), seek_from[char].pop()])
if not where[char]:
del where[char]
# print(l)
# print(r)
func(l, r, 1)
func(r, l, 0)
# print(pairs)
def func2(where, seek_from, flag):
for char in seek_from:
if char != '?':
while where['?'] and seek_from[char]:
if flag:
pairs.append([where['?'].pop(), seek_from[char].pop()])
else:
pairs.append([seek_from[char].pop(), where['?'].pop()])
# print(l)
# print(r)
func2(l, r, 1)
func2(r, l, 0)
# print(pairs)
# print(l)
# print(r)
while l['?'] and r['?']:
pairs.append([l['?'].pop(), r['?'].pop()])
print(len(pairs))
for pair in pairs:
print(*pair)
# for char in seek_from:
# if char == '?' and char in where:
# while seek_from[char] and where[char]:
# pairs.append([seek_from[char].pop(), where[char].pop()])
# if not where[char]:
# del where[char]
#
# pairs = []
# for char in l:
# if char != '?' and char in r:
# nexus = min(l[char], r[char])
# pairs += nexus
# l[char] -= nexus
# r[char] -= nexus
# if not r[char]:
# del r[char]
#
#
# def func(where, from_counter):
# global pairs
# if '?' in where:
# for char in from_counter:
# if char != '?' and where['?']:
# nexus = min(from_counter[char], where['?'])
# pairs += nexus
# where['?'] -= nexus
#
| py |
1313 | B | B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place. | [
"constructive algorithms",
"greedy",
"implementation",
"math"
] | from sys import stdin
input = stdin.readline
def answer():
maxrank = min(n , x + y - 1)
if((x + y) <= n):
minrank = 1
else:
m = min(x , y)
if(m != n):minrank = (x + y + 1) - n
else:minrank = n
return [minrank , maxrank]
for T in range(int(input())):
n , x , y = map(int,input().split())
print(*answer())
| py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
def query(u , v):
print('?' , u , v , flush = True)
return int(input())
def dfs(p , prev):
yes = True
for i in child[p]:
if(done[i]):continue
if(i == prev):continue
yes = False
dfs(i , p)
if(yes):leafs.append(p)
def answer():
global done , leafs
done = [False for i in range(n + 1)]
r = 1
while(1):
leafs = []
dfs(r , 0)
if(leafs[0] == r):return r
if(len(leafs) == 1):
leafs.append(r)
r = query(leafs[0] , leafs[1])
if(r == leafs[0] or r == leafs[1]):
return r
done[leafs[0]] = True
done[leafs[1]] = True
for T in range(1):
n = int(input())
edges = []
child = [[] for i in range(n + 1)]
for i in range(n - 1):
u , v = inp()
edges.append([u , v])
child[u].append(v)
child[v].append(u)
print('!' , answer() , flush = True)
| 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"
] | q=int(input())
for i in range(q):
n, m=[int(k) for k in input().split()]
rho=[m, m]
last=0
c=[]
for j in range(n):
c.append([int(k) for k in input().split()])
for j in range(n):
w=c[j]
t=w[0]-last
rho=[rho[0]-t, rho[1]+t]
if rho[0]>w[2] or rho[1]<w[1]:
print("NO")
break
else:
rho=[max(rho[0], w[1]), min(rho[1], w[2])]
last=w[0]
#print(rho, t)
else:
print("YES") | py |
1296 | C | C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1
| [
"data structures",
"implementation"
] | for _ in range(int(input())):
n = int(input())
s = input()
d = dict()
d[(0, 0)] = 0
x, y = 0, 0
l, r = -1, n
for i, c in enumerate(s):
x += (1 if c == 'R' else 0) - (1 if c == 'L' else 0)
y += (1 if c == 'U' else 0) - (1 if c == 'D' else 0)
if (x, y) in d:
if i - d[(x, y)] + 1 < r - l + 1:
l, r = d[(x, y)], i
d[(x, y)] = i+1
if l == -1:
print(-1)
else:
print(l+1, r+1)
| 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"
] | import math
def primeFactors(n,arr):
while(n%2==0):
arr.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
arr.append(i)
n = n // i
if n > 2:
arr.append(n)
return arr
from collections import Counter
t=int(input())
while(t):
t-=1
n=int(input())
n1=n
arr1=[]
ct=[]
arr1=primeFactors(n,arr1)
arr=list(Counter(arr1).keys())
ct=list(Counter(arr1).values())
ans=[]
if(len(arr)>=3):
ans.append(arr[0]**(ct[0]))
ans.append(arr[1]**(ct[1]))
if(n//((arr[0]**(ct[0]))*(arr[1]**(ct[1]))) not in ans and n//((arr[0]**(ct[0]))*(arr[1]**(ct[1])))!=1):
ans.append(n//((arr[0]**(ct[0]))*(arr[1]**(ct[1]))))
print("YES")
print(*ans)
else:
print("NO")
else:
ans.append(int(arr[0]))
if(ct[0]-1>=2):
ans.append(int(arr[0]*arr[0]))
if(n/(arr[0]*arr[0]*arr[0])== n//(arr[0]*arr[0]*arr[0]) and n//(arr[0]*arr[0]*arr[0]) !=1):
if(n//(arr[0]*arr[0]*arr[0]) not in ans ):
ans.append(int(n//(arr[0]*arr[0]*arr[0])))
print("YES")
print(*ans)
else:
print("NO")
else:
print("NO")
else:
if(len(arr)==1):
print("NO")
else:
ans.append(int(arr[1]))
if(n/(arr[0]*arr[1])==n//(arr[0]*arr[1]) and n//(arr[0]*arr[1])!=1):
if(n//(arr[0]*arr[1]) not in ans):
ans.append(int(n//(arr[0]*arr[1])))
print("YES")
print(*ans)
else:
print("NO")
else:
print("NO") | py |
1324 | C | C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right. | [
"binary search",
"data structures",
"dfs and similar",
"greedy",
"implementation"
] | cases = int(input())
for c in range(cases):
jumps = input()
pos_r = []
pos_r.append(0)
for i in range(len(jumps)):
if (jumps[i] == 'R'):
pos_r.append(i+1)
pos_r.append(len(jumps) + 1)
r = 0
for h in range(len(pos_r) - 1):
r = max(r, pos_r[h+1]-pos_r[h])
print(r)
| py |
1312 | E | E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all. | [
"dp",
"greedy"
] | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
n = int(input())
a = list(map(int, input().split()))
dp = [[False]*(n+2) for i in range(n+2)]
dp2 = [[600]*(n+2) for i in range(n+2)]
for i in range(n):
dp[i][i] = a[i]
dp2[i][i] = 1
for diff in range(1, n):
for i in range(n-diff):
for j in range(i, i+diff):
if dp[i][j] == dp[j+1][i+diff] and dp[i][j]:
dp[i][i+diff] = dp[i][j] + 1
dp2[i][i+diff] = 1
dp2[i][i+diff] = min(dp2[i][i+diff], dp2[i][j]+dp2[j+1][i+diff])
if not dp2[i][i+diff]:
dp2[i][i+diff] = min(dp2[i+1][i+diff]+1, dp2[i][i+diff-1] + 1)
print(dp2[0][n-1]) | py |
1311 | D | D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48
| [
"brute force",
"math"
] | import bisect
import heapq
import sys
from types import GeneratorType
from functools import cmp_to_key
from collections import defaultdict, Counter, deque
import math
from functools import lru_cache
from heapq import nlargest
import random
inf = float("inf")
# sys.setrecursionlimit(1000000)
class FastIO:
def __init__(self):
return
@staticmethod
def _read():
return sys.stdin.readline().strip()
def read_int(self):
return int(self._read())
def read_float(self):
return float(self._read())
def read_ints(self):
return map(int, self._read().split())
def read_floats(self):
return map(float, self._read().split())
def read_ints_minus_one(self):
return map(lambda x: int(x) - 1, self._read().split())
def read_list_ints(self):
return list(map(int, self._read().split()))
def read_list_floats(self):
return list(map(float, self._read().split()))
def read_list_ints_minus_one(self):
return list(map(lambda x: int(x) - 1, self._read().split()))
def read_str(self):
return self._read()
def read_list_strs(self):
return self._read().split()
def read_list_str(self):
return list(self._read())
@staticmethod
def st(x):
return sys.stdout.write(str(x) + '\n')
@staticmethod
def lst(x):
return sys.stdout.write(" ".join(str(w) for w in x) + '\n')
@staticmethod
def round_5(f):
res = int(f)
if f - res >= 0.5:
res += 1
return res
@staticmethod
def max(a, b):
return a if a > b else b
@staticmethod
def min(a, b):
return a if a < b else b
@staticmethod
def bootstrap(f, queue=[]):
def wrappedfunc(*args, **kwargs):
if queue:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if isinstance(to, GeneratorType):
queue.append(to)
to = next(to)
else:
queue.pop()
if not queue:
break
to = queue[-1].send(to)
return to
return wrappedfunc
def main(ac=FastIO()):
for _ in range(ac.read_int()):
a, b, c = ac.read_list_ints()
ans = inf
res = []
for x in range(1, 2*a+1):
for y in range(x, 2*b+1, x):
if y%x == 0:
for z in [(c//y)*y, (c//y)*y+y]:
cost = abs(a-x)+abs(b-y)+abs(c-z)
if cost < ans:
ans = cost
res = [x, y, z]
ac.st(ans)
ac.lst(res)
return
main()
| 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"
] | import itertools as it
from collections import deque
n = int(input())
bd = [[] for _ in range(n)]
for i in range(n):
lt = list(map(int, input().split()))
for j in range(n):
bd[i].append((lt[j*2]-1, lt[j*2+1]-1))
def rpath(tr, tc, r, c):
q = deque([(r, c)])
while q:
i, j = q.popleft()
edge = [(i-1,j,'D'), (i+1,j,'U'), (i,j-1,'R'), (i,j+1,'L')]
for a, b, d in edge:
if a < 0 or a >= n or b < 0 or b >= n: continue
if bd[a][b] != (tr,tc) or res[a][b]: continue
res[a][b] = d
q.append((a, b))
ok = 1
res = [[None]*n for _ in range(n)]
for i, j in it.product(range(n), range(n)):
if bd[i][j] == (i,j):
res[i][j] = 'X'
rpath(i, j, i, j)
elif bd[i][j] == (-2,-2):
edge = [(i-1,j,'U','D'), (i+1,j,'D','U'), (i,j-1,'L','R'), (i,j+1,'R','L')]
for a, b, cur, next in edge:
if a < 0 or a >= n or b < 0 or b >= n: continue
if bd[a][b] != (-2,-2): continue
res[i][j], res[a][b] = cur, next
break
else:
ok = 0; break
if not all(res[i][j] for i, j in it.product(range(n), range(n))):
ok = 0
print("VALID" if ok else "INVALID")
if ok: print('\n'.join([''.join(u) for u in res]))
| py |
1292 | C | C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment: With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment: With this assignment, all non-zero mex value are listed below: mex(1,3)=1mex(1,3)=1 mex(1,5)=2mex(1,5)=2 mex(2,3)=1mex(2,3)=1 mex(2,5)=2mex(2,5)=2 mex(3,4)=1mex(3,4)=1 mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10. | [
"combinatorics",
"dfs and similar",
"dp",
"greedy",
"trees"
] | import sys
input = sys.stdin.readline
from collections import deque
N=int(input())
E=[[] for i in range(N+1)]
for i in range(N-1):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
Q=deque()
USE=[0]*(N+1)
Q.append(1)
H=[0]*(N+1)
H[1]=1
USE[1]=1
P=[-1]*(N+1)
QI=deque()
while Q:
x=Q.pop()
for to in E[x]:
if USE[to]==0:
USE[to]=1
H[to]=H[x]+1
P[to]=x
Q.append(to)
QI.append((x,to,to,x))
P[to]=x
EH=[(h,ind+1) for ind,h in enumerate(H[1:])]
EH.sort(reverse=True)
COME=[1]*(N+1)
USE=[0]*(N+1)
for h,ind in EH:
USE[ind]=1
for to in E[ind]:
if USE[to]==0:
COME[to]+=COME[ind]
GO=[N-COME[i] for i in range(N+1)]
DP=[[0]*(N+1) for i in range(N+1)]
USE=[[0]*(N+1) for i in range(N+1)]
while QI:
l,frl,r,frr=QI.popleft()
if P[l]==frl:
A1=COME[l]
else:
A1=GO[frl]
if P[r]==frr:
A2=COME[r]
else:
A2=GO[frr]
DP[l][r]=DP[r][l]=A1*A2+max(DP[frl][r],DP[l][frr])
for to in E[l]:
if to==frl or USE[to][r]==1:
continue
USE[to][r]=USE[r][to]=1
QI.append((to,l,r,frr))
#for to in E[r]:
# if to==frr or USE[l][to]==1:
# continue
# USE[to][l]=USE[l][to]=1
# QI.append((l,frl,to,r))
ANS=0
for d in DP:
ANS=max(ANS,max(d))
print(ANS)
| py |
1286 | C1 | C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4
a
aa
a
cb
b
c
cOutputCopy? 1 2
? 3 4
? 4 4
! aabc | [
"brute force",
"constructive algorithms",
"interactive",
"math"
] | import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int,minp().split())
def sub(s1,s2):
d = dict()
for i in s1:
d[i] = d.get(i,0)+1
for i in s2:
d[i] = d.get(i,0)-1
for j in d:
if d[j] > 0:
return j
return 'a'
ans = ''
def emit(l,r):
a = []
print('?', l, r)
sys.stdout.flush()
z = (r-l+1)*(r-l+2)//2
while len(a) < z:
q = minp()
if q == '-':
exit(0)
if len(q) != 0:
a.append(q)
return a
a = hm(ans[l-1:r])
if len(a) != z:
raise Exception("wrong %d %d"%(len(a),z))
return a
def solve():
#global ans
#ans = minp()
#n = len(ans)
n = mint()
a = emit(1,n)
if n == 1:
print('!',a[0])
return
b = emit(1,n-1)
d = dict()
for i in a:
z = ''.join(sorted(i))
d[z] = d.get(z,0)+1
for i in b:
z = ''.join(sorted(i))
d[z] = d.get(z,0)-1
z = []
for j in d:
if d[j] > 0:
z.append(j)
z.sort(key=lambda a: len(a))
#print(z)
s = ''
for i in z:
#print(i,s)
s = sub(i,s) + s
print("!", s)
sys.stdout.flush()
from random import randint
def shufled(s):
s = list(s)
r = ''
for i in range(len(s)):
r += s.pop(randint(0,len(s)-1))
return r
def hm(s):
a = []
n = len(s)
for i in range(0,n):
for j in range(i+1,n+1):
a.append((j-i,''.join(shufled(s[i:j]))))
a.sort()
print(*a,sep='\n')
return [i[1] for i in a]#
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"
] | #! /bin/env python3
def cmp(k1, k2):
p1, p2 = k1, k2
d1, d2 = 1 , 1
for i in range(n):
if s[p1] > s[p2]: return 1
if s[p1] < s[p2]: return -1
if p1 == n:
if (n-k1+1)&1 == 1:
p1, d1 = k1, -1
else: p1 = 0
if p2 == n:
if (n-k2+1)&1 == 1:
p2, d2 = k2, -1
else: p2 = 0
p1 += d1
p2 += d2
return 0
t = int(input())
for i in range(t):
n = int(input())
s = '0' + input()
# solve
mn = 1
for j in range(2, n+1):
if cmp(mn, j) > 0: mn = j
ATshayu, d = mn, 1
for j in range(n):
print(s[ATshayu], end='')
if ATshayu == n:
if (n-mn+1)&1 == 1:
ATshayu, d = mn, -1
else: ATshayu = 0
ATshayu += d
print('\n'+str(mn))
| py |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | t=int(input())
for i in range(t):
n=int(input())
even=odd=0
l=list(map(int,input().split()))
for i in l:
if i%2==0:
even+=1
else:
odd+=1
if sum(l)%2!=0:
print("YES")
else:
if even!=0 and odd!=0:
print("YES")
else:
print("NO")
| py |
1320 | C | C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1
| [
"brute force",
"data structures",
"sortings"
] | from collections import defaultdict
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def update(l, r, s):
q, ll, rr, i = [1], [0], [l1 - 1], 0
while len(q) ^ i:
j = q[i]
l0, r0 = ll[i], rr[i]
if l <= l0 and r0 <= r:
lazy[j] += s
i += 1
continue
m0 = (l0 + r0) >> 1
if j < l1 and lazy[j]:
lazy[j << 1] += lazy[j]
lazy[j << 1 ^ 1] += lazy[j]
lazy[j] = 0
if l <= m0 and l0 <= r:
q.append(j << 1)
ll.append(l0)
rr.append(m0)
if l <= r0 and m0 + 1 <= r:
q.append(j << 1 ^ 1)
ll.append(m0 + 1)
rr.append(r0)
i += 1
for i in reversed(q):
if i < l1:
j, k = i << 1, i << 1 ^ 1
tree[i] = max(tree[j] + lazy[j], tree[k] + lazy[k])
return
def get_max(s, t):
update(s, t, 0)
s += l1
t += l1
ans = -inf
while s <= t:
if s % 2:
ans = max(ans, tree[s] + lazy[s])
s += 1
s >>= 1
if not t % 2:
ans = max(ans, tree[t] + lazy[t])
t -= 1
t >>= 1
return ans
n, m, p = map(int, input().split())
a = [tuple(map(int, input().split())) for _ in range(n)]
b = [tuple(map(int, input().split())) for _ in range(m)]
xyz = [tuple(map(int, input().split())) for _ in range(p)]
l = pow(10, 6) + 5
s = [0] * l
for b0, _ in b:
s[b0] = 1
for i in range(1, l):
s[i] += s[i - 1]
c = s[-1]
l1 = pow(2, (c + 5).bit_length())
l2 = 2 * l1
inf = pow(10, 9) + 1
tree, lazy = [-inf] * l2, [0] * l2
ma1 = -inf
for b0, cb in b:
ma1 = max(ma1, -cb)
tree[s[b0] + l1] = max(tree[s[b0] + l1], -cb)
for i in range(l1 - 1, 0, -1):
tree[i] = max(tree[2 * i], tree[2 * i + 1])
da = defaultdict(lambda : -inf)
dx = defaultdict(lambda : [])
ma2 = -inf
for a0, ca in a:
ma2 = max(ma2, -ca)
da[a0] = max(da[a0], -ca)
for x, y, z in xyz:
dx[x].append((y, z))
ans = ma1 + ma2
for i in range(1, l):
if i in da:
ans = max(ans, get_max(1, c) + da[i])
if i in dx:
for y, z in dx[i]:
update(s[y] + 1, c + 1, z)
print(ans) | py |
1325 | C | C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample: | [
"constructive algorithms",
"dfs and similar",
"greedy",
"trees"
] | #https://codeforces.com/contest/1325/problem/C
import sys
from collections import *
sys.setrecursionlimit(10**5)
itr = (line for line in sys.stdin.read().strip().split('\n'))
INP = lambda: next(itr)
def ni(): return int(INP())
def nl(): return [int(_) for _ in INP().split()]
def solve(n, g, edge):
visited = [False for _ in range(n+1)]
triplets = {}
pos = False
for i in range(1,n+1):
if len(g[i]) >= 3:
pos = True
for j in range(3):
triplets[g[i][j][1]] = True
break
cnt = 0
cnt2 = 3
if pos:
for i in range(n-1):
if i in triplets:
print(cnt)
cnt += 1
else:
print(cnt2)
cnt2 += 1
else:
for i in range(n-1):
print(i)
n = ni()
g = [[] for _ in range(n+1)]
edge = []
for nr in range(n-1):
a, b = nl()
g[a].append((b,nr))
g[b].append((a, nr))
edge.append((a,b))
solve(n, g, edge) | 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"
] | import sys
# sys.stdin=open("input.txt","r")
# sys.stdout=open("output.txt","w")
n=int(input())
ans,num=0,n
for i in range(1,n+1):
ans+=(1/num)
num-=1
print(ans) | py |
1307 | C | C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l. | [
"brute force",
"dp",
"math",
"strings"
] | 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
s=str(input())
n=len(s)
b=set()
a={}
res=-float("inf")
for j in range(1,n):
for i in range(26):
a[chr(ord('a')+i)]=0
c=1
if s[j-1] in b:
continue
else:
b.add(s[j-1])
for i in range(j,n):
a[s[i]]+=c
if s[i]==s[j-1]:
c+=1
res=max(res,max(a.values()))
for i in range(26):
a[chr(ord('a')+i)]=0
for i in s:
a[i]+=1
res=max(res,max(a.values()))
print(res)
| py |
1294 | A | A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES
| [
"math"
] | t=int(input())
for i in range(t):
arr=list(map(int,input().split()))
total=sum(arr)
maximum=max(arr[0:3])
if(total%3==0 and total/3 >= maximum):
print("YES")
else:
print("NO")
| py |
1284 | B | B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences. | [
"binary search",
"combinatorics",
"data structures",
"dp",
"implementation",
"sortings"
] | n = int(input())
ans = 0
mx = [0] * (10 ** 6 + 5)
mn = []
koltrue = 0
for _ in range(n):
l = list(map(int, input().split()))
mnn = l[1]
mxx = l[1]
t = False
for i in range(2, l[0] + 1):
if l[i-1] < l[i]:
t = True
mnn = min(mnn, l[i])
mxx = max(mxx, l[i])
if t:
koltrue += 1
mn.append('t')
else:
mn.append(mnn)
mx[mxx] += 1
#print(koltrue)
sufs = [0] * (10 ** 6 + 5)
for i in range(len(sufs) - 2, -1, -1):
sufs[i] = mx[i] + sufs[i+1]
#print(sufs[:10])
#print(mn)
for i in range(len(mn)):
if mn[i] == 't':
ans += n
else:
ans += koltrue
#print('#', mn[i], i)
ans += sufs[mn[i] + 1]
#print(ans)
print(ans)
# Thu Nov 24 2022 20:38:24 GMT+0300 (Moscow Standard Time)
# Sat Nov 26 2022 14:10:03 GMT+0300 (Moscow Standard Time)
| py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | n = int(input())
teachs = list(map(int,input().split()))
studs = list(map(int,input().split()))
diffs = [teachs[i]-studs[i] for i in range(n)]
res = 0
diffs.sort()
# print(diffs)
l , r = 0 , n - 1
while l < r:
if diffs[l] > -diffs[r]:
res += r - l
r -= 1
else:
l += 1
print(res)
| 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"
] | # from collections import Counter
ints = lambda: list(map(int, input().split()))
tw = lambda n: (n&(n-1)==0) and n!=0
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
def solve():
# by Azimjonm2333
a=input()
b=input()
c=input()
for i in range(len(a)):
if c[i]!=b[i] and a[i]!=c[i]: print('NO'); return
print("YES")
t=1
t=int(input())
for i in range(t): solve()
| py |
1324 | D | D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0
| [
"binary search",
"data structures",
"sortings",
"two pointers"
] | size: int = int(input())
diff: list[int] = []
a = list(map(int,input().split()))
b = list(map(int,input().split()))
for i in range(size):
diff.append(a[i]-b[i])
diff.sort()
l: int = 0
r: int = diff.__len__()-1
ans:int = 0
while l < r :
if diff[r] + diff[l] > 0 :
ans += r - l
r -= 1
else:
l += 1
print(ans)
| py |
1303 | A | A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111). | [
"implementation",
"strings"
] | t = int(input())
for i in range(t):
s = input()
if len(s) <= 2:
print(0)
else:
first_index = 0
for i in range(len(s)):
if s[i] == '1':
first_index = i
break
last_index = 0
for i in range(len(s) - 1, -1, -1):
if s[i] == '1':
last_index = i
break
c = 0
for i in range(first_index + 1, last_index):
if s[i] == '0':
c = c + 1
print(c)
| py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | t = int(input())
for i in range(t):
n = int(input())
m = 2 * n
arr = list(map(int, input().split()))[:m]
arr.sort()
print(abs(arr[n-1] - arr[n])) | 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"
] | def main():
import sys
input = sys.stdin.buffer.readline
# max
def STfunc(a, b):
if a > b:
return a
else:
return b
# クエリは0-indexedで[(r1, c1), (r2, c2))
class SparseTable():
def __init__(self, grid):
# A: 処理したい2D配列
self.N = len(grid)
self.M = len(grid[0])
self.KN = self.N.bit_length() - 1
self.KM = self.M.bit_length() - 1
self.flatten = lambda n, m, kn, km: \
(n * self.M + m) * ((self.KN + 1) * (self.KM + 1)) + (kn * (self.KM + 1) + km)
self.table = [0] * (self.flatten(self.N - 1, self.M - 1, self.KN, self.KM) + 1)
for i, line in enumerate(grid):
for j, val in enumerate(line):
self.table[self.flatten(i, j, 0, 0)] = val
for km in range(1, self.KM + 1):
for i in range(self.N):
for j in range(self.M):
j2 = j + (1 << (km - 1))
if j2 <= self.M - 1:
self.table[self.flatten(i, j, 0, km)] = \
STfunc(self.table[self.flatten(i, j, 0, km - 1)],
self.table[self.flatten(i, j2, 0, km - 1)])
for kn in range(1, self.KN + 1):
for km in range(self.KM + 1):
for i in range(self.N):
i2 = i + (1 << (kn - 1))
for j in range(self.M):
if i2 <= self.N - 1:
self.table[self.flatten(i, j, kn, km)] = \
STfunc(self.table[self.flatten(i, j, kn - 1, km)],
self.table[self.flatten(i2, j, kn - 1, km)])
def query(self, r1, c1, r2, c2):
# [(r1, c1), (r2, c2))の最小値を求める
kr = (r2 - r1).bit_length() - 1
kc = (c2 - c1).bit_length() - 1
r2 -= (1 << kr)
c2 -= (1 << kc)
return STfunc(STfunc(self.table[self.flatten(r1, c1, kr, kc)], self.table[self.flatten(r2, c1, kr, kc)]),
STfunc(self.table[self.flatten(r1, c2, kr, kc)], self.table[self.flatten(r2, c2, kr, kc)]))
H, W, Q = map(int, input().split())
grid = []
for _ in range(H):
grid.append(input())
#print(grid)
R = [[0] * W for _ in range(H)]
G = [[0] * W for _ in range(H)]
Y = [[0] * W for _ in range(H)]
B = [[0] * W for _ in range(H)]
R_enc = ord('R')
G_enc = ord('G')
Y_enc = ord('Y')
B_enc = ord('B')
for h in range(H):
for w in range(W):
if grid[h][w] == R_enc:
R[h][w] = 1
elif grid[h][w] == G_enc:
G[h][w] = 1
elif grid[h][w] == Y_enc:
Y[h][w] = 1
else:
B[h][w] = 1
for h in range(1, H):
for w in range(1, W):
if R[h][w]:
tmp = min(R[h-1][w-1], R[h-1][w], R[h][w-1]) + 1
if tmp > 1:
R[h][w] = tmp
for h in range(1, H):
for w in range(W-2, -1, -1):
if G[h][w]:
tmp = min(G[h-1][w+1], G[h-1][w], G[h][w+1]) + 1
if tmp > 1:
G[h][w] = tmp
for h in range(H-2, -1, -1):
for w in range(1, W):
if Y[h][w]:
tmp = min(Y[h+1][w-1], Y[h+1][w], Y[h][w-1]) + 1
if tmp > 1:
Y[h][w] = tmp
for h in range(H-2, -1, -1):
for w in range(W-2, -1, -1):
if B[h][w]:
tmp = min(B[h+1][w+1], B[h+1][w], B[h][w+1]) + 1
if tmp > 1:
B[h][w] = tmp
M = [[0] * W for _ in range(H)]
for h in range(H):
for w in range(W):
if h < H-1 and w < W-1:
M[h][w] = min(R[h][w], G[h][w+1], Y[h+1][w], B[h+1][w+1])
ST = SparseTable(M)
ans = [None] * Q
for q in range(Q):
r1, c1, r2, c2 = map(int, input().split())
r1 -= 1
c1 -= 1
r2 -= 1
c2 -= 1
ok = 0
ng = 501
mid = 250
while ng - ok > 1:
R1 = r1 + mid - 1
C1 = c1 + mid - 1
R2 = r2 - mid + 1
C2 = c2 - mid + 1
if R1 >= R2 or C1 >= C2:
ng = mid
mid = (ok + ng)//2
continue
#print(ST.query(R1, C1, R2, C2), mid, [R1, C1, R2, C2])
if ST.query(R1, C1, R2, C2) >= mid:
ok = mid
else:
ng = mid
mid = (ok+ng)//2
#[print(M[h]) for h in range(H)]
ans[q] = (2*ok)**2
sys.stdout.write('\n'.join(map(str, ans)))
if __name__ == '__main__':
main()
| py |
1300 | B | B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference. | [
"greedy",
"implementation",
"sortings"
] | # LUOGU_RID: 100980329
for i in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a.sort()
print(a[n]-a[n-1]) | py |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | # 6 5
# 5 0 3 1 2
# 1 8 9 1 3
# 1 2 3 4 5
# 9 1 0 3 7
# 2 3 0 6 3
# 6 4 1 7 0
import sys
input = lambda: sys.stdin.buffer.readline().decode().strip()
max_a = 10**9
min_a = 0
def solve():
n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
# binary search where tail remains in the portion and head does not
tail, head = 0, 1 + 10**9
while tail + 1 != head:
mid = head + tail >> 1
# run the check for mid
t = mid
is_present = [[] for i in range(2**m)]
for i, ai in enumerate(a):
num = 0
for aik in ai:
# print(t, aik, head, tail)
num = num * 2 + int(t <= aik)
is_present[num].append(i)
check = 0
for pair1 in range(2**m):
for pair2 in range(2**m):
if check: break
if pair2 | pair1 == 2**m - 1:
if len(is_present[pair1]) > 0 and len(is_present[pair2]) > 0:
check = 1
ans = [is_present[pair1][0], is_present[pair2][0]]
break
# print(check, t, is_present)
#########################
if check:
tail = mid
else:
head = mid
try:
print(ans[0] + 1, ans[1] + 1)
except:
print(1, 1)
solve()
| 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={input()for _ in[0]*n}
a=[['SET'.find(x)for x in y]for y in s]
print(sum(''.join('SET '[(3-x-y,x)[x==y]]for x,y in
zip(a[i],a[j]))in s for i in range(n)for j in range(i))//3)
| py |
1316 | C | C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109), — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109) — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2) — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | [
"constructive algorithms",
"math",
"ternary search"
] | 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, m, p = I()
a, b = I(), I()
for i in range(n):
if a[i] % p != 0:
idx_i = i
break
for i in range(m):
if b[i] % p != 0:
idx_j = i
break
print(idx_i + idx_j)
if __name__ == '__main__':
# for _ in range(II()):
# main()
main()
# | py |
1295 | B | B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232. | [
"math",
"strings"
] | import sys, threading
import math
from os import path
from collections import deque, defaultdict, Counter
from bisect import *
from string import ascii_lowercase
from functools import cmp_to_key
from random import randint
from heapq import *
from array import array
from types import GeneratorType
def readInts():
x = list(map(int, (sys.stdin.readline().rstrip().split())))
return x[0] if len(x) == 1 else x
def readList(type=int):
x = sys.stdin.readline()
x = list(map(type, x.rstrip('\n\r').split()))
return x
def readStr():
x = sys.stdin.readline().rstrip('\r\n')
return x
write = sys.stdout.write
read = sys.stdin.readline
MAXN = 1123456
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
class mydict:
def __init__(self, func=lambda: 0):
self.random = randint(0, 1 << 32)
self.default = func
self.dict = {}
def __getitem__(self, key):
mykey = self.random ^ key
if mykey not in self.dict:
self.dict[mykey] = self.default()
return self.dict[mykey]
def get(self, key, default):
mykey = self.random ^ key
if mykey not in self.dict:
return default
return self.dict[mykey]
def __setitem__(self, key, item):
mykey = self.random ^ key
self.dict[mykey] = item
def getkeys(self):
return [self.random ^ i for i in self.dict]
def __str__(self):
return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'
def lcm(a, b):
return (a*b)//(math.gcd(a,b))
def mod(n):
return n%(1000000007)
def solve(t):
# print(f'Case #{t}: ', end = '')
n, x = readInts()
s = readStr()
mp = mydict(int)
cur = 0
for num in s:
if num == '0':
cur += 1
else:
cur -= 1
mp[cur] += 1
p = cur
ans = 0
if x == 0 and p == 0:
print(-1)
return
# print(mp, p)
if x == 0:
ans += 1
for num in mp.getkeys():
dif = (x-num)
# print('d', dif)
if p != 0:
if dif%p == 0 and dif//p >= 0:
ans += mp[num]
else:
if x == num:
print(-1)
return
print(ans)
def main():
t = 1
if path.exists("/Users/arijitbhaumik/Library/Application Support/Sublime Text/Packages/User/input.txt"):
sys.stdin = open("/Users/arijitbhaumik/Library/Application Support/Sublime Text/Packages/User/input.txt", 'r')
sys.stdout = open("/Users/arijitbhaumik/Library/Application Support/Sublime Text/Packages/User/output.txt", 'w')
# sys.setrecursionlimit(100000)
t = readInts()
for i in range(t):
solve(i+1)
if __name__ == '__main__':
main() | 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 sys
from sys import stdin
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
if ret[nex] > ret[now] + 1:
ret[nex] = ret[now] + 1
plis[nex] = now
q.append(nex)
return ret,plis
n = int(stdin.readline())
lis = [ [] for i in range(n)]
clis = [None] * n
for i in range(n):
p,c = map(int,stdin.readline().split())
p -= 1
clis[i] = c
if p != -1:
lis[p].append(i)
else:
root = i
dlis,_ = NC_Dij(lis,root)
dv = [ (dlis[i],i) for i in range(n) ]
dv.sort()
dv.reverse()
ans = [ [] for i in range(n) ]
for d,v in dv:
flag = False
if clis[v] == 0:
ans[v].append(v)
flag = True
for nex in lis[v]:
for tv in ans[nex]:
ans[v].append(tv)
if len(ans[v]) == clis[v]:
ans[v].append(v)
flag = True
if not flag:
print ("NO")
sys.exit()
#print (ans)
rans = [None] * n
for i in range(n):
rans[ ans[root][i] ] = i+1
print ("YES")
print (" ".join(map(str,rans)))
| 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"
] | # 13:01-
import sys
input = lambda: sys.stdin.readline().rstrip()
N,a,b,K = map(int, input().split())
A = list(map(int, input().split()))
total = a+b
ans = 0
B = []
for i in range(N):
t = A[i]%total
if t==0:
t = total
if t>a:
B.append((t-a-1)//a+1)
else:
ans += 1
B.sort(reverse=True)
while K>0 and B:
t = B.pop()
if K>=t:
ans+=1
K-=t
print(ans)
| py |
1305 | F | F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012) — the elements of the array.OutputPrint a single integer — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. | [
"math",
"number theory",
"probabilities"
] | import sys
input = sys.stdin.readline
from math import sqrt
import random
n=int(input())
A=list(map(int,input().split()))
random.shuffle(A)
MOD={2,3,5}
USED=set()
for t in A[:31]:
if t in USED:
continue
else:
USED.add(t)
for x in [t-1,t,t+1]:
if x<=5:
continue
L=int(sqrt(x))
for i in range(2,L+2):
while x%i==0:
MOD.add(i)
x=x//i
if x==1:
break
if x!=1:
MOD.add(x)
ANS=1<<29
for m in MOD:
SCORE=0
for a in A:
if a<=m:
SCORE+=m-a
else:
SCORE+=min(a%m,(-a)%m)
if SCORE>=ANS:
break
else:
ANS=SCORE
print(ANS)
| 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"
] | import os, sys, io
# switch to fastio
fast_mode = 0
# local file test -> 1, remote test --> 0
local_mode = 0
if local_mode:
fin = open("./data/input.txt", "r")
fout = open("./data/output.txt", "w")
sys.stdin = fin
sys.stdout = fout
if fast_mode:
input = io.BytesIO(os.read(sys.stdin.fileno(), os.fstat(0).st_size)).readline # fast input
if local_mode:
fin = open("./data/input.txt", "br") # binary mode
input = io.BytesIO(fin.read()).readline # for local file
else:
input = lambda: sys.stdin.readline().rstrip("\r\n") # normal mode
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
ssw = sys.stdout.write
def ini():
return int(input())
def inlt():
return list(map(int, input().split()))
def instr():
s = input().decode().rstrip("\r\n") if fast_mode else input()
return list(s)
# main code
def solve():
for ii in range(ini()):
n = ini()
a = inlt()
a.sort(reverse=True)
print(*a)
if __name__ == '__main__':
solve()
os.write(sys.stdout.fileno(), stdout.getvalue()) # final output
if local_mode:
fin.close()
fout.close() | py |
1288 | D | D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5
| [
"binary search",
"bitmasks",
"dp"
] | import sys
# 1288D
def solve(a):
m, n = len(a), len(a[0])
maxx = max(max(t) for t in a)
def check(t):
idx = [-1] * 256
for i in range(m):
mask = 0
for j in range(n):
if a[i][j] >= t:
mask |= 1 << j
# idx: [5,-1,6,8,-1……]
idx[mask] = i
for i in range(1 << n):
if idx[i] == -1:
continue
for j in range(i, 1 << n):
if idx[j] == -1:
continue
if (i | j) == (1 << n) - 1:
return [idx[i], idx[j]]
return [-1, -1]
l, r = -1, maxx + 1
while l < r - 1:
mid = (l + r) // 2
if check(mid) != [-1, -1]:
l = mid
else:
r = mid
# [ TTTTTT FFFFFF ]
# l r
return check(l)
m, n = map(int, input().split())
a = []
for i in range(m):
a.append([int(i) for i in input().split()])
res = solve(a)
print(res[0] + 1, res[1] + 1)
# 1103B
# def query(x, y):
# print("?", x, y)
# sys.stdout.flush()
# res = input()
# return res
# def solve():
# # write function here
# return -1
# while True:
# res = solve()
# if res == -1: break
# print("!", res)
# def cutThemAll(lengths, minLength):
# for i in range(len(lengths) - 1):
# if lengths[i] + lengths[i+1] >= minLength:
# return "Possible"
# return "Impossible"
# ls = [3,5,6]
# print(cutThemAll(ls, 12))
# def getUniqueCharacter(s):
# cnt = [0] * 26
# for c in s:
# cnt[ord(c) - ord('a')] += 1
# for i in range(len(s)):
# if cnt[ord(s[i]) - ord('a')] == 1:
# return i + 1
# return -1
# print(getUniqueCharacter("madam"))
# from cmath import log
# from collections import Counter
# from dis import findlabels
# base = 10**9 + 7
# def findRight(a):
# # find the index of the first less one in the left side, for every a[i]
# n = len(a)
# st, res = [], [0] * n
# for i in range(n - 1, -1, -1):
# while len(st) and a[st[-1]] >= a[i]:
# st.pop()
# res[i] = n if len(st) == 0 else st[-1]
# st.append(i)
# return res
# def findLeft(a):
# # find the index of the first less or equal one in the right side, for every a[i]
# n = len(a)
# st, res = [], [0] * n
# for i in range(n):
# while len(st) and a[st[-1]] > a[i]:
# st.pop()
# res[i] = -1 if len(st) == 0 else st[-1]
# st.append(i)
# return res
# def findTotalPower(a):
# # In order to avoid repeated calculations,
# # the left side finds the first element less than a[i],
# # and the right side finds the first element less than or equal to a[i]
# left = findLeft(a)
# right = findRight(a)
# n, res = len(a), 0
# s = [0] * (n + 1)
# ss = [0] * (n + 2)
# # s means the prefix sum of a
# for i in range(n): s[i+1] = s[i] + a[i]
# # ss meams the prefix sum of s
# for i in range(n + 1): ss[i+1] = ss[i] + s[i]
# for i in range(n):
# # every left one could be the leader of subarray, which can be combined with the ending on the right
# l = i - left[i]
# # every right one could be the ending of subarray, which can be combined with the leader on the left
# r = right[i] - i
# # find the sum(sum([i, r]))
# now = ((ss[right[i] + 1] - ss[i + 1]) - r * s[i]) % base
# # find the sum(sum([i, r])) * a[i] * (i-left)
# res += ((now * l) % base * a[i]) % base
# # find the sum(sum([l, i]))
# now = (s[i] * (l - 1) - (ss[i] - ss[left[i] + 1])) % base
# # find the sum(sum([l, i])) * a[i] * (right-i)
# res += ((now * r) % base * a[i]) % base
# res %= base
# return res % base
# ls = [2,3,2,1]
# res = findTotalPower(ls)
# print(res)
# def solve(a):
# m, n = len(a), len(a[0])
# maxx = max(max(t) for t in a)
# def ok(t):
# idx = [-1] * 256
# maxm = 1 << n
# for i in range(m):
# mask = 0
# for j in range(n):
# if a[i][j] >= t:
# mask |= 1 << j
# if idx[mask] == -1:
# idx[mask] = i
# for i in range(maxm):
# if idx[i] == -1:
# continue
# for j in range(i, maxm):
# if idx[j] == -1:
# continue
# if (i | j) == maxm - 1:
# return [idx[i], idx[j]]
# return [-1, -1]
# l, r = 0, maxx
# while l <= r:
# mid = (l + r) // 2
# if ok(mid) != [-1, -1]:
# l = mid + 1
# else:
# r = mid - 1
# return ok(r) | 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):
for _ in range(1): pass
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 |
1299 | C | C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence. | [
"data structures",
"geometry",
"greedy"
] | import sys
input = sys.stdin.buffer.readline
N = int(input())
a = list(map(int, input().split()))
s = [(0, N)]
for x in a:
c = 1
while s[-1][0] * c >= x * s[-1][1]:
y, d = s.pop()
x += y
c += d
s.append((x, c))
s.reverse()
s.pop()
i = 0
while len(s):
x, c = s.pop()
for j in range(i, i + c): print(x / c)
i += c | 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"
] | import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify, nlargest
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
# assert i > 0
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i, j=None):
if j is None:
return self.el[i]
return self.sum(j) - self.sum(i)
# 1_indexed
# n = 6
# a = [1,2,3,4,5,6]
# bit = BIT(n)
# for i,e in enumerate(a):
# bit.add(i+1,e)
# print(bit.get(2,5)) #12 (3+4+5)
n = inp()
X = inpl()
V = inpl()
d = {}; dd={}
for i,x in enumerate(sorted(X)):
d[x] = i; dd[i]=x
for i,x in enumerate(X):
X[i] = d[x]
xv = [(x,v) for x,v in zip(X,V)]
xv.sort(key=lambda x:x[0] ,reverse=True)
xv.sort(key=lambda x:x[1], reverse=True)
cnt_bit = BIT(n+10)
sum_bit = BIT(n+10)
res = 0
for x,_ in xv:
res += sum_bit.get(x,n+5) - cnt_bit.get(x,n+5)*dd[x]
sum_bit.add(x+1,dd[x])
cnt_bit.add(x+1,1)
print(res)
| 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 = [int(i) for i in input().split(" ")]
a = input().split(" ")
b = input().split(" ")
t = int(input())
for i in range(t):
year = int(input())
print(a[year%(n[0]) - 1]+b[year%(n[1]) - 1])
| py |
1312 | D | D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. | [
"combinatorics",
"math"
] |
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
n,m=map(int, input().split())
md=998244353
if n==2:
print(0)
else:
ans=ncr(m,n-1,md)
ans=(ans*(n-2))%md
ans=(ans*pow(2,n-3,md))%md
print(ans) | py |
1321 | C | C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. | [
"brute force",
"constructive algorithms",
"greedy",
"strings"
] | n = int(input())
x = input()
def remove(tmp, x):
removed = 0
if len(tmp) >= 2 and tmp[0] == x and tmp[1] == x - 1:
removed += 1
tmp.pop(0)
i = 0
n = len(tmp)
while i < n:
if i == 0:
if len(tmp) >= 2 and tmp[0] == x and tmp[1] == x - 1:
removed += 1
tmp.pop(0)
n -= 1
continue
elif i == n - 1:
if len(tmp) >= 2 and tmp[-1] == x and tmp[-2] == x - 1:
removed += 1
tmp.pop(len(tmp) -1 )
n -= 1
continue
elif tmp[i] == x and (tmp[i + 1] == x - 1 or tmp[i - 1] == x - 1 ):
removed += 1
tmp.pop(i)
i -= 1
n -= 1
continue
i += 1
return removed
def solve (x, n):
out = 0
tmp = [ord(e) for e in x]
chars = list(set(tmp[::]))
chars.sort(reverse=True)
for char in chars:
out += remove(tmp, char)
print(out)
solve(x,n) | 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"
] | n = int(input())
b = list(map(int, input().split()))
smth = dict()
for i in range(n):
if not (b[i] - i) in smth:
smth[b[i] - i] = 0
smth[b[i] - i] += b[i]
ans = 0
for el in smth:
ans = max(ans, smth[el])
print(ans) | py |
1288 | B | B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19). | [
"math"
] | for t in range(int(input())):
a, b = map(int, input().split())
print(a * (len(str(b + 1)) - 1)) | py |
1291 | A | A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000) — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit). | [
"greedy",
"math",
"strings"
] | for _ in range(int(input())):
n = input()
s = input()
a = 0
for i in s:
a += int(i)
m = int(s)
flag = True
while True:
if a % 2 == 0 and int(s) % 2 != 0:
print(s)
flag = False
break
a -= int(s[-1])
s = s[0:-1]
if len(s) == 0:
break
if flag:
print(-1) | py |
1304 | A | A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward. | [
"math"
] | t=int(input())
for i in range(t):
x,y,a,b=map(int,input().split())
k=(y-x)%(a+b)
if k:
print(-1)
else:
print((y-x)//(a+b)) | 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"
] | def main():
n = int(input())
board = []
told = []
blocked = []
for r in range(1, n + 1):
endings = list(map(int, input().split()))
board.append([])
told.append([])
for i in range(0, 2 * n, 2):
x, y = endings[i:i + 2]
told[-1].append((x, y))
if x == r and y == i // 2 + 1:
board[-1].append("X")
blocked.append((x - 1, y - 1))
else:
board[-1].append("")
unvisited = []
#print(blocked)
for bx, by in blocked:
one_idx = (bx + 1, by + 1)
if bx and told[bx - 1][by] == one_idx:
board[bx - 1][by] = "D"
unvisited.append((bx - 1, by))
if bx < n - 1 and told[bx + 1][by] == one_idx:
board[bx + 1][by] = "U"
unvisited.append((bx + 1, by))
if by and told[bx][by - 1] == one_idx:
board[bx][by - 1] = "R"
unvisited.append((bx, by - 1))
if by < n - 1 and told[bx][by + 1] == one_idx:
board[bx][by + 1] = "L"
unvisited.append((bx, by + 1))
#print(unvisited)
z = 0
while z < len(unvisited):
x, y = unvisited[z]
if x and board[x - 1][y] == "" and told[x - 1][y] == told[x][y]:
unvisited.append((x - 1, y))
board[x - 1][y] = "D"
if x < n - 1 and board[x + 1][y] == "" and told[x + 1][y] == told[x][y]:
unvisited.append((x + 1, y))
board[x + 1][y] = "U"
if y and board[x][y - 1] == "" and told[x][y - 1] == told[x][y]:
unvisited.append((x, y - 1))
board[x][y - 1] = "R"
if y < n - 1 and board[x][y + 1] == "" and told[x][y + 1] == told[x][y]:
unvisited.append((x, y + 1))
board[x][y + 1] = "L"
z += 1
for i in range(n):
for j in range(n):
if board[i][j] == "":
if told[i][j] != (-1, -1):
print("INVALID")
return
if i and told[i - 1][j] == (-1, -1):
board[i][j] = "U"
continue
if i < n - 1 and told[i + 1][j] == (-1, -1):
board[i][j] = "D"
continue
if j and told[i][j - 1] == (-1, -1):
board[i][j] = "L"
continue
if j < n - 1 and told[i][j + 1] == (-1, -1):
board[i][j] = "R"
continue
print("INVALID")
return
print("VALID")
for k in range(n):
print("".join(board[k]))
main() | 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 io
import os
from array import array
# Rewrote in C++
DEBUG = False
if DEBUG:
from functools import lru_cache
def solveTopDown(N, P, K, audienceScore, playerScore):
# Choose P players and K audience members from N people
assert len(audienceScore) == len(playerScore) == N
# Sort both scores by audience score from largest to smallest
scores = sorted(zip(audienceScore, playerScore), reverse=True)
audienceScore = [a for a, p in scores]
playerScore = [p for a, p in scores]
@lru_cache(maxsize=None)
def f(n, mask):
# Return best score using up to the nth person with mask of positions used
# Since we sorted by audience scores, we can take everyone not used in mask until exceed K
if n == 0:
# Single person
if mask == 0:
# Not a player so must be an audience member
return audienceScore[n]
else:
# Must be player at some position
for pos in range(P):
if mask == 1 << pos:
return playerScore[n][pos]
# Otherwise invalid
return float("-inf")
# nth is neither audience nor player
best = f(n - 1, mask)
# Check if nth could be an audience member
num = n + 1 # there are n + 1 people in 0 to n inclusive
numPlayers = _popcount[mask] # number of players in the mask
if num - numPlayers <= K:
# The audience members are always the first K not in mask and we are within that K
best += audienceScore[n]
# Try placing as a player, audience remains the same
for pos in range(P):
if (1 << pos) & mask:
best = max(best, playerScore[n][pos] + f(n - 1, mask - (1 << pos)))
return best
best = 0
for i in range(N):
for mask in range(1 << P):
# print(i, bin(mask)[2:])
val = f(i, mask)
# print("\t", val)
best = max(best, val)
return best
def popcount(i):
# Python doesn't have __builtin_popcount
# https://stackoverflow.com/a/407758
assert 0 <= i < 0x100000000
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xFFFFFFFF) >> 24
_popcount = []
for mask in range(1 << 7):
_popcount.append(popcount(mask))
maskToPos = []
for mask in range(1 << 7):
maskToPos.append([i for i in range(7) if mask & (1 << i)])
negInf = float("-inf")
def solve(N, P, K, audienceScore, playerScore):
scores = sorted(zip(audienceScore, playerScore), reverse=True)
scoresA = [0.0 for i in range(N)]
scoresP = [0.0 for i in range(7 * N)]
for i, (a, ps) in enumerate(scores):
scoresA[i] = float(a)
for j, p in enumerate(ps):
scoresP[7 * i + j] = float(p)
f = [negInf for mask in range(1 << P)]
nextF = [negInf for mask in range(1 << P)]
f[0] = scoresA[0]
for pos in range(P):
f[1 << pos] = scoresP[pos]
for n in range(1, N):
for mask in range(1 << P):
best = f[mask]
if n - _popcount[mask] < K:
best += scoresA[n]
for pos in maskToPos[mask]:
best = max(best, scoresP[7 * n + pos] + f[mask - (1 << pos)])
nextF[mask] = best
f, nextF = nextF, f
return int(max(f))
if DEBUG:
from random import randint
N = 100000
P = 7
K = 90000
audienceScore = [randint(1, 100) for i in range(N)]
playerScore = [[randint(1, 100) for j in range(7)] for i in range(N)]
ans = solve(N, P, K, audienceScore, playerScore)
if False:
assert ans == solveTopDown(N, P, K, audienceScore, playerScore)
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, P, K = list(map(int, input().split()))
audienceScore = [int(x) for x in input().split()]
playerScore = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, P, K, audienceScore, playerScore)
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"
] | 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 |
13 | B | B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES | [
"geometry",
"implementation"
] | """ A : Determine if three line segments form A """
def cross(vecA, vecB):
return vecA[0] * vecB[1] - vecA[1] * vecB[0]
def dot(vecA, vecB):
return vecA[0] * vecB[0] + vecA[1] * vecB[1]
def angle(lineA, lineB):
x1, y1 = (lineA[0][0] - lineA[1][0], lineA[0][1] - lineA[1][1])
x2, y2 = (lineB[0][0] - lineB[1][0], lineB[0][1] - lineB[1][1])
d1 = (x1 ** 2 + y1 ** 2) ** 0.5
d2 = (x2 ** 2 + y2 ** 2) ** 0.5
return (x1 * x2 + y1 * y2) / (d1*d2)
def div_ratio(line, point):
# Simple way to approximately check if the point lies on the line
mx, my = point
(a, b), (c, d) = line
if not (min(a, c) <= mx <= max(a, c) and min(b, d) <= my <= max(b, d)):
return -1
# Again make sure the point lies on the line
vecA = (a - mx, b - my)
vecB = (a - c, b - d)
if cross(vecA, vecB) != 0:
return -1
# Finally compute the ratio
if c == a and d == b: return -1
if d != b:
ratio = (my - b) / (d - b)
if a != c:
ratio = (mx - a) / (c - a)
if ratio < 0.2 or ratio > 0.8:
ratio = -1
return ratio
def isA(lines):
""" Given three line segments check if they form A of not"""
# Find the two slanted line segments
k, l = -1, -1
lines_found = False
for i in range(3):
if lines_found: break
temp = set(lines[i])
for j in range(i + 1, 3):
# Check which of the two points is the common point
if lines[j][0] in temp:
common = lines[j][0]
k, l = i, j
lines_found = True
break
if not lines_found and lines[j][1] in temp:
common = lines[j][1]
k, l = i, j
lines_found = True
break
if not lines_found: return False
# Process the lines
lineA = lines[k]
if lineA[0] != common:
lineA = [lineA[1], lineA[0]]
lineB = lines[l]
if lineB[0] != common:
lineB = [lineB[1], lineB[0]]
# Check the angle between two lines. Must be greater than 0 and less than 90
degree = angle(lineA, lineB)
# print("Degree ", degree)
if degree < 0 or degree >= 1: return False
# The third is the line connecting two slanted line segments
divider = lines[3 - k - l]
# If first point of divider does not divide (or lie on) either of the line segments, it does not form A
thresh = 0.2 # Converted 1/4 to 1/5 in another metric
r1 = div_ratio(lineA, divider[0])
if r1 == -1:
r2 = div_ratio(lineB, divider[0]) # div[0] lies on lineB
if r2 == -1: return False
r1 = div_ratio(lineA, divider[1]) # div[1] lies on lineA
if r1 == -1: return False
else:
r2 = div_ratio(lineB, divider[1])
if r2 == -1: return False
# For everything else
return True
def CF14C():
N = int(input())
result = []
for _ in range(N):
lines = []
for _ in range(3):
a, b, c, d = map(int, input().split())
lines.append(((a, b), (c, d)))
res = isA(lines)
result.append("YES" if res else "NO")
return result
res = CF14C()
print("\n".join(res))
| 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"
] | from sys import stdin,stdout
input = stdin.readline
from math import gcd,ceil,sqrt,inf,factorial
# from collections import Counter
# from heapq import heapify,heappop,heappush
# from time import time
# from bisect import bisect, bisect_left
for _ in range(int(input())):
n = int(input())
p = int(n)
fac = set()
for i in range(2,int(sqrt(n)) + 2):
count = 0
while p%i == 0 :
count += 1
p = p//i
if count >= 1:
fac.add(i)
if count>= 3:
fac.add(i**2)
t = []
for i in fac:
t.append(i)
if len(t) >= 2:
temp1 = t[0]
temp2 = t[1]
k = n//(temp1*temp2)
fac = {temp1,temp2,k}
if len(fac) == 3 and k != 1:
print("YES")
print(*fac)
else:
print("NO")
else:
print("NO") | 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"
] | n, a, b, k = map(int, input().split())
l = []
p = 0
for h in map(int, input().split()):
r = (h - a)%(a+b)
if r <= b:
l.append(r//a + (r % a != 0))
else:
p += 1
l.sort()
s = 0
for i in l:
s += i
if s > k:
break
p += 1
print(p)
| 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"
] | from collections import deque
N,M,K = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
def count(w):
l = deque(B[:w])
num = l.count(0)
ans = 0
for i in range(w,M):
if num==0:ans += 1
if l.popleft()==0:num-=1
if B[i]==0:num+=1
l.append(B[i])
if num==0:ans += 1
return ans
l = [0]*(N+1)
num = 0
for i in range(1,N+1):
if K%i==0 and K//i<=M:
h,w = i,K//i
l[h]+=count(w)
num = 0
k = [0]*(N+1)
for i in range(1,N+1):
num += l[i]
k[i] += num+k[i-1]
ans = 0
num = 0
for x in range(N):
if A[x]==1:
num+=1
elif num!=0:
ans += k[num]
num = 0
if num!=0:
ans += k[num]
print(ans)
| py |
1305 | D | D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3
3
4
4
OutputCopy
? 5 6
? 3 1
? 1 2
! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | [
"constructive algorithms",
"dfs and similar",
"interactive",
"trees"
] | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
############# Importing modules and stuffs we require ######################################################
try:
import sys
from functools import lru_cache, cmp_to_key, reduce
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as Cntr
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect, insort
from time import perf_counter
from fractions import Fraction
import copy
from copy import deepcopy
import time
from decimal import *
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
def data(): return sys.stdin.readline()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
def A2(n,m): return [[0]*m for i in range(n)]
def A(n):return [0]*n
# from sys import stdin
# input = stdin.buffer.readline
# I = lambda : list(map(int,input().split()))
# import sys
# input=sys.stdin.readline
import random
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
except:
pass
rr = range
############# Importing modules and stuffs we require ######################################################
n = L()[0]
A = [L() for i in range(n-1)]
g = [set() for i in range(n+1)]
for x,y in A:
g[x].add(y)
g[y].add(x)
rem = set([i for i in range(1,n+1)])
for i in range(n//2):
u = 0
for i in range(1,n+1):
if len(g[i])==1:
u = i
break
v = -1
for i in range(u+1,n+1):
if len(g[i])==1:
v = i
break
print("?",u,v,flush=True)
z = L()[0]
if z in [u,v]:
print("!",z,flush=True)
exit()
else:
for ele in g[u]:
g[ele].remove(u)
g[u]=set()
for ele in g[v]:
g[ele].remove(v)
g[v]=set()
rem.remove(u)
rem.remove(v)
else:
for ele in rem:
print("!",ele,flush=True)
exit() | 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 sys
input = sys.stdin.readline
from bisect import bisect_left
n = int(input())
g = [[] for _ in range(n)]
c = [0] * n
for i in range(n):
p, c[i] = map(int, input().split())
if p != 0:
g[p - 1].append(i)
else:
root = i
s = [root]
v = [0] * n
d = [[] for _ in range(n)]
idx = 0
while s:
p = s.pop()
if v[p] == 0:
s.append(p)
v[p] = 1
for node in g[p]:
s.append(node)
else:
for node in g[p]:
d[p] += d[node]
if len(d[p]) < c[p]:
print('NO')
exit(0)
d[p].insert(c[p], p)
res = [0] * n
x = d[root]
for i in range(n):
res[x[i]] = i + 1
print('YES')
print(*res) | 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"
] | # でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
def main(n, d):
P = [0] + list(range(n - 1))
C = [set() for _ in range(n)]
for v in range(n - 1):
C[v].add(v + 1)
D = list(range(n))
Vd = [set() for _ in range(n)]
for v in range(n):
Vd[v].add(v)
L = [n - 1]
B = [0] * n
s = (n - 1) * n // 2
if d > s: return None
while s > d:
if not L: return None
v = L.pop()
if D[v] < 2: continue
if B[v]: continue
for p in Vd[D[v] - 2]:
if len(C[p]) == 2: continue
s -= 1
bp = P[v]
C[bp].remove(v)
if len(C[bp]) == 0: L.append(bp)
P[v] = p
C[p].add(v)
Vd[D[v]].remove(v)
D[v] -= 1
Vd[D[v]].add(v)
L.append(v)
break
else:
B[v] = 1
return (P[i] + 1 for i in range(1, n))
if __name__ == '__main__':
input = sys.stdin.readline
T = int(input())
for _ in range(T):
n, d = map(int, input().split())
ans = main(n, d)
if ans is None:
print('NO')
else:
print('YES')
print(*ans)
| 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 bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
n = int(_input())
a = list(map(int, _input().split()))
f = [0] * n
for i in range(n):
f[i] = i - 1
while f[i] >= 0 and a[i] < a[f[i]]:
f[i] = f[f[i]]
b = [n] * n
for i in range(n - 1, -1, -1):
b[i] = i + 1
while b[i] < n and a[i] < a[b[i]]:
b[i] = b[b[i]]
c = [0] * (n + 1)
for i in range(n):
c[i + 1] = c[f[i] + 1] + a[i] * (i - f[i])
d = [0] * (n + 1)
for i in range(n - 1, -1, -1):
d[i] = d[b[i]] + a[i] * (b[i] - i)
# print(*a)
# print(*f)
# print(*b)
# print(*c)
# print(*d)
u, v = 0, -1
for i in range(n):
x = c[i] + d[i]
if x > v:
u, v = i, x
# print(u, v)
x = a[u]
for i in range(u - 1, -1, -1):
x = min(x, a[i])
a[i] = x
x = a[u]
for i in range(u + 1, n):
x = min(x, a[i])
a[i] = x
print(*a) | py |
1294 | D | D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. | [
"data structures",
"greedy",
"implementation",
"math"
] | import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, data, default=float('inf'), func=min):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def operation(S, x):
my_min = S.query(0, x)
if S[0]==my_min:
return my_min*x
else:
s = 0
e = x
while s+1 < e:
m = (s+e)//2
if S.query(0, m+1) > my_min:
s, e = m, e
else:
s, e = s, m
return my_min*x+e
def process(A, x):
n = len(A)
d = [0 for i in range(x)]
S = SegmentTree(data=d)
for i in range(n):
ai = A[i]
S[ai % x]+=1
entry = operation(S, x)
sys.stdout.write(f'{entry}\n')
return
n, x = [int(x) for x in input().split()]
A = []
for i in range(n):
ai = int(input())
A.append(ai)
process(A, x)
| py |
1141 | F2 | F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3
| [
"data structures",
"greedy"
] | g = dict()
n = int(input())
a = list(map(int,input().split()))
for i in range(n):
total = 0
for j in range(i,n):
total += a[j]
if total in g:
g[total].append((i + 1,j + 1))
else:
g[total] = [(i+1,j+1)]
ans = 0
res = []
for k in g:
t = -1
temp = 0
li = []
for l,r in g[k]:
if l > t:
temp += 1
li.append((l,r))
t = r
elif t > r:
li[-1] = (l,r)
t = r
if temp > ans:
ans = temp
res = li
print(ans)
for i in res:
print(*i) | py |
1307 | E | E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000) — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n) — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n) — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2
1 1 1 1 1
1 2
1 3
OutputCopy2 2
InputCopy5 2
1 1 1 1 1
1 2
1 4
OutputCopy1 4
InputCopy3 2
2 3 2
3 1
2 1
OutputCopy2 4
InputCopy5 1
1 1 1 1 1
2 5
OutputCopy0 1
NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side. | [
"binary search",
"combinatorics",
"dp",
"greedy",
"implementation",
"math"
] | import bisect
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
s = list(map(int, input().split()))
mod = pow(10, 9) + 7
x = [[] for _ in range(n + 1)]
for i in range(n):
x[s[i]].append(i + 1)
y = [[] for _ in range(n + 1)]
for _ in range(m):
f, h = map(int, input().split())
if len(x[f]) < h:
continue
y[f].append(h)
for i in range(1, n + 1):
y[i].sort()
cntl, cntr = [0] * (n + 1), [0] * (n + 1)
for i in s:
cntr[i] += 1
l0, r0 = [0] * (n + 1), [0] * (n + 1)
cnt = [0]
for i in range(1, n + 1):
l = bisect.bisect_right(y[i], cntl[i])
r = bisect.bisect_right(y[i], cntr[i])
if r:
cnt[0] += 1
r0[i] = r
l1, r1 = list(l0), list(r0)
x = []
for i in s:
cnt.append(cnt[-1])
l, r = l0[i], r0[i]
if l > r:
l, r = r, l
if 0 < l and 2 <= r:
cnt[-1] -= 2
elif max(l, r):
cnt[-1] -= 1
cntl[i] += 1
cntr[i] -= 1
l = bisect.bisect_right(y[i], cntl[i])
r = bisect.bisect_right(y[i], cntr[i])
l0[i], r0[i] = l, r
x.append((l, r))
if l > r:
l, r = r, l
if 0 < l and 2 <= r:
cnt[-1] += 2
elif max(l, r):
cnt[-1] += 1
ans = [max(cnt), 0]
ans0 = 1
now = []
for i in r1:
now.append(max(1, i))
ans0 *= now[-1]
ans0 %= mod
if ans[0] == cnt[0]:
ans[1] = ans0
for i in range(n):
j = s[i]
l, r = x[i]
l0, r0 = l1[j], r1[j]
l1[j], r1[j] = l, r
ans0 *= pow(now[j], mod - 2, mod)
ans0 %= mod
if ans[0] ^ cnt[i + 1] or cnt[i] ^ cnt[i + 1]:
if l > r:
l, r = r, l
if 0 < l and 2 <= r:
now[j] = l * (r - 1) % mod
else:
now[j] = l + r
now[j] = max(now[j], 1)
ans0 *= now[j]
ans0 %= mod
if ans[0] == cnt[i + 1]:
ans[1] += ans0
ans[1] %= mod
else:
if 0 < min(l, r) and 2 <= max(l, r):
c = 0
for k in range(l0 + 1, l + 1):
if k <= r:
c += r - 1
else:
c += r
else:
c = l - l0
ans[1] += ans0 * c % mod
ans[1] %= mod
if l > r:
l, r = r, l
if 0 < l and 2 <= r:
now[j] = l * (r - 1) % mod
else:
now[j] = l + r
now[j] = max(now[j], 1)
ans0 *= now[j]
ans0 %= mod
sys.stdout.write(" ".join(map(str, ans))) | py |
1294 | B | B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: | [
"implementation",
"sortings"
] | for _ in range(int(input())):
n = int(input())
cords = []
for i in range(n):
a, b = map(int, input().split())
cords.append([a, b])
cords = sorted(cords, key = lambda t: t[0])
cords = sorted(cords, key = lambda t: t[1])
prevx = 0
prevy = 0
ans = ''
flag = False
for a, b in cords:
if a < prevx:
flag = True
break
xcord = a - prevx
ycord = b - prevy
ans += xcord*"R" + ycord*"U"
prevx = a
prevy = b
if flag:
print('NO')
else:
print('YES')
print(ans) | py |
1296 | A | A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO
| [
"math"
] | import sys
input = sys.stdin.readline
output = sys.stdout.write
def main():
tests = int(input().rstrip())
for i in range(tests):
length_ = int(input().rstrip())
list_ = list(map(int, input().rstrip().split()))
if length_ % 2 == 0:
i = 0
for num in list_:
if num % 2 == 1:
i += 1
if not (0 < i < length_) is True:
output('NO')
else:
output('YES')
else:
state = False
for num in list_:
if num % 2 == 1:
state = True
break
if state:
output('YES')
else:
output('NO')
output('\n')
if __name__ == '__main__':
main()
| py |
13 | A | A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively. | [
"implementation",
"math"
] | import sys
input = sys.stdin.readline
A = int(input())
res = 0
def calc(x, base):
v = 0
while x > 0:
v += x % base
x //= base
return v
def gcd(a, b):
return a if b == 0 else gcd(b, a%b)
for i in range(2, A):
res += calc(A, i)
d = gcd(res, A-2)
print(f'{res//d}/{(A-2)//d}')
| 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"
] |
def naive(n, a):
xor = 0
for i in range(n):
for j in range(i + 1, n):
xor ^= (a[i] + a[j])
return xor
def main():
n = int(input())
a = readIntArr()
m = 25
# m = 4
xorparity = [0] * m
for twopow in range(m):
base = 2 ** twopow
a2 = [v % (base * 2) for v in a]
a2.sort()
# print('base:{} a2:{}'.format(base * 2, a2))
for l, r in ((base, (base * 2) - 1),
(base + base * 2, base * 4 - 1)):
LEFTPOINTER = RIGHTPOINTER = n
for i in range(n):
LEFTPOINTER = max(LEFTPOINTER, i + 1)
RIGHTPOINTER = max(RIGHTPOINTER, i + 1)
# search for l boundary
while LEFTPOINTER - 1 >= i + 1 and a2[LEFTPOINTER - 1] >= l - a2[i]:
LEFTPOINTER -= 1
LEFT = LEFTPOINTER
# lo, hi = i, n - 1
# while lo < hi:
# mid = (lo + hi + 1) // 2
# if a2[mid] < l - a2[i]:
# lo = mid
# else:
# hi = mid - 1
# LEFT = lo + 1
# search for r boundary
while RIGHTPOINTER - 1 >= i + 1 and a2[RIGHTPOINTER - 1] > r - a2[i]:
RIGHTPOINTER -= 1
RIGHT = RIGHTPOINTER - 1
# lo, hi = i, n - 1
# while lo < hi:
# mid = (lo + hi + 1) // 2
# if a2[mid] <= r - a2[i]:
# lo = mid
# else:
# hi = mid - 1
# RIGHT = lo
# print('twopow:{} l:{} r:{} base:{} i:{} LEFT:{} RIGHT:{}'.format(
# twopow, l, r, base, i, LEFT, RIGHT))
xorparity[twopow] ^= ((RIGHT - LEFT + 1) % 2)
ans = 0
for twopow in range(m):
ans += xorparity[twopow] * (2 ** twopow)
print(ans)
# assert ans == naive(n, a)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b):
print('? {} {}'.format(a, b))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | py |
1312 | A | A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO". | [
"geometry",
"greedy",
"math",
"number theory"
] | t=int(input(""))
def test(l):
a,b=int(l[0]),int(l[1])
if a%b==0:
return "YES"
else:
return "NO"
l=[]
for i in range(t):
s=input("").split(" ")
c=test(s)
l.append(c)
for j in range(len(l)):
print(l[j])
| py |
1285 | C | C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1
| [
"brute force",
"math",
"number theory"
] | from math import gcd
n = int(input())
x, y = 1e19, 1e19
i = 1
while i*i <= n:
if n % i == 0 and gcd(i, n//i) == 1:
if n//i < max(x, y):
x, y = i, n//i
i += 1
print(x, y) | 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"
] |
import math
def u(x,a):
for m in divisors[x]:
sum[m]+=a
def coprime(x):
count = 0
for i in divisors[x]:
count+=sum[i]*mobius[i]
return count
n = int(input())
a = input().split(" ")
maxlcm = 0
b = [False]*100010
for x in range(n):
a[x] = int(a[x])
maxlcm = max(a[x],maxlcm)
b[a[x]] = True
a.sort(reverse=True)
m = 100005
sum = [0]*(m+5)
mobius = [0]*(m+5)
divisors = {}
for i in range(1,m):
for j in range(i,m,i):
try:
divisors[j].append(i)
except:
divisors[j] = [1]
if(i==1):
mobius[i] = 1
elif ((i/divisors[i][1]%divisors[i][1])==0):
mobius[i]=0
else:
mobius[i] = -mobius[int(i/divisors[i][1])]
for g in range(1,m):
s = []
for x in range(int(m/g)):
x = int(m/g)-x
if(not b[x*g]):
continue
c = coprime(x)
while c:
if(math.gcd(x,s[-1])==1):
maxlcm = max(maxlcm,x*g*s[-1])
c-=1
u(s[-1],-1)
s.pop(-1)
u(x,1)
s.append(x)
while(len(s)!=0):
u(s[-1],-1)
s.pop(-1)
print(maxlcm)
| 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"
] | def f():
t=int(input())
for i in range(t):
n=int(input())
ans=0
while True:
d=(n//10)*10
ans=ans+d
n=(n-d)+(d//10)
if n<10:
ans=ans+n
break
print(ans)
f()
| 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 i in range(t):
n=int(input())
l=list(map(int,input().split()))
l.sort(reverse=True)
l=list(map(str,l))
print(" ".join(l))
| 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"
] | import sys,math,heapq,queue
fast_input=sys.stdin.readline
h,n=map(int,fast_input().split())
d=list(map(int,fast_input().split()))
for i in range(1,n):
d[i]+=d[i-1]
m=min(d)
if h+m<=0:
for i in range(n):
if d[i]+h<=0:
print(i+1)
break
elif h+d[-1]>=h:
print(-1)
else:
x=math.ceil((h+m)/abs(d[-1]))
h=h-x*abs(d[-1])
for i in range(n):
if h+d[i]<=0:
print(x*n+i+1)
break
| 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"
] | from sys import stdin
input = stdin.readline
inp = lambda : list(map(int,input().split()))
def answer():
left , s = [-1 for i in range(n)] , []
for i in range(n - 1 , -1 , -1):
while(len(s) and a[s[-1]] >= a[i]):
left[s.pop()] = i
s.append(i)
right , s = [n for i in range(n)] , []
for i in range(n):
while(len(s) and a[s[-1]] >= a[i]):
right[s.pop()] = i
s.append(i)
sumval = [0 for i in range(n + 1)]
for i in range(n):
sumval[i + 1] = sumval[i] + a[i]
prefix = [0 for i in range(n + 1)]
for i in range(n):
sval = sumval[i] - sumval[left[i] + 1]
prefix[i + 1] = prefix[left[i] + 1] + sval - (i - left[i] - 1) * a[i]
suffix = [0 for i in range(n + 1)]
for i in range(n - 1 , -1 , -1):
sval = sumval[right[i]] - sumval[i + 1]
suffix[i] = suffix[right[i]] + sval - (right[i] - i - 1) * a[i]
best = float('inf')
for i in range(n):
value = prefix[i + 1] + suffix[i]
if(best > value):
best = value
peak = i
for i in range(peak - 1 , -1 , -1):
if(a[i] > a[i + 1]):
a[i] = a[i + 1]
for i in range(peak + 1 , n):
if(a[i] > a[i - 1]):
a[i] = a[i - 1]
return a
for T in range(1):
n = int(input())
a = inp()
print(*answer())
| py |
1325 | D | D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | [
"bitmasks",
"constructive algorithms",
"greedy",
"number theory"
] | u,v=map(int,input().split())
if u>v or (u%2!=v%2):
print(-1)
elif u==0 and v==0:
print(0)
elif u==v:
print(1)
print(u)
else:
x=(v-u)//2
if u&x==0:
print(2)
print(u+x,x)
else:
print(3)
print(u,x,x) | 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 sys,heapq
from collections import defaultdict,deque
import math
input = sys.stdin.readline
############ ---- Input Functions ---- ############
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 traverse_password(neighbor, visited, path, key):
path.append(key)
visited.add(key)
for neigh in neighbor[key]:
if neigh not in visited:
traverse_password(neighbor, visited, path, neigh)
return path
def main():
test = inp()
for _ in range(test):
password = insr()
if len(password) == 1:
res = []
for i in range(97,123):
res.append(chr(i))
print("YES")
print(''.join(res))
else:
neighbor = defaultdict(set)
for i in range(1,len(password)):
neighbor[password[i]].add(password[i-1])
neighbor[password[i-1]].add(password[i])
startKey = None
isPossible = True
for key in neighbor.keys():
if len(neighbor[key]) > 2:
isPossible = False
break
if len(neighbor[key]) == 1:
startKey = key
if not startKey or not isPossible:
print("NO")
else:
visited = set()
answer = traverse_password(neighbor, visited, [], startKey)
for character in range(97,123):
letter = chr(character)
if letter not in neighbor:
answer.append(letter)
print("YES")
print(''.join(answer))
main()
| py |
1296 | E2 | E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1
| [
"data structures",
"dp"
] | from sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
s=[ord(i)-97 for i in input()]
c=[-1]*27
ans=[]
for i in s:
mx=max(c[i+1:])
c[i]=mx+1
ans.append(mx+2)
print(max(ans))
print(*ans) | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.