C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.

def solve():

    n, m = read_ints()

    seq = input()

    pseq = read_ints()

    a = ord('a')

    accs = [[0] * 26 for _ in range(n+1)]

    for i, c in enumerate(seq):

        for j in range(26):

            accs[i+1][j] = accs[i][j]

            if j == ord(c) - a:

                accs[i+1][ord(c)-a] += 1

    res = [0] * 26

    for i, pi in enumerate(pseq):

        for j in range(26):

            res[j] += accs[pi][j]

    for c in seq:

        res[ord(c)-a] += 1

    print(*res)

def main():

    t = int(input())

    for _ in range(t):

        solve()

def read_ints(): return [int(c) for c in input().split()]

def print_lines(lst): print('\n'.join(map(str, lst)))

if __name__ == "__main__":

    from os import environ as env

    if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:

        import sys

        sys.stdout = open('out.txt', 'w')

        sys.stdin = open('in.txt', 'r')

    main()


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).

a=int(input())

for x in range(a):

    b=input()

    if b.count('1')==0 or b.count('0')==0 or b.count('1')==1:

        print(0)

    else:

        m=b.index('1')

        s=len(b)-1

        while b[s]!='1':

            s-=1

        print(b[m:s+1].count('0'))


D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0

from math import log2

for _ in range(int(input())):

    n,m=map(int,input().split())

    arr=list(map(int,input().split()))

    c=[0]*(65)

    s=0

    for  el in  arr:

        c[int(log2(el))]+=1

        s+=el

    if s<n:

        print(-1)

        continue

    i=0

    res=0

    while i<60:

        if (n&(1<<i))!=0:

            if c[i]>0:

                c[i]-=1

            else :

                while i<60 and c[i]==0:

                    i+=1

                    res+=1

                c[i]-=1

                continue

        c[i+1]+=c[i]//2

        i+=1

    print(res)


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).

for _ in range(int(input())):

    n, x = [int(x) for x in input().split()]

    a = [int(x) for x in input().split()]

    f = max(a)

    if f < x:

        print((x + f - 1) // f)

    elif x in a:

        print(1)

    else:

        print(2)


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).

import sys

from math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm

from collections import deque, Counter, OrderedDict, defaultdict

from heapq import heapify, heappush, heappop

#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 = len(arr)

    while low<=high:

        mid = (low+high)//2

        #if arr[mid]==x:

        #    return x

        if arr[mid]<x:

            low = mid+1

        else:

            high = mid-1

            ans = mid

    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 x

        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

#======================================================#

def f():

    return a*(len(str(b+1))-1)

for _ in range(I()):

    a,b = M()

    print(f())


B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs:  buy one bus ticket to get from 11 to 33,  buy one tram ticket to get from 33 to 66,  buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6

def check(sr, w, a, b, p):

    count = 0

    while w != len(sr) - 1:

        if sr[w] == "A" and w != len(sr) - 1:

            count += a

            while w != len(sr) - 1 and sr[w] == "A":

                w += 1

        if s[w] == "B" and w != len(sr) - 1:

            count += b

            while  w != len(sr) - 1 and s[w] == "B":

                w += 1

#    print(count)

    return count > p

for _ in range(int(input())):

    a, b, p = map(int, input().split())

    s = input()

    l = -1

    r = len(s)

#    print(a, "LOL")

    while r - l > 1:

        m  = (r + l) // 2

#        print(l, r, m)

        if check(s, m, a, b, p):

            l = m

        else:

            r = m

    print(r + 1)


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.

import sys

import random

input = sys.stdin.readline

n, m, p = [int(xx) for xx in input().split()]

a = [int(xx) for xx in input().split()]

b = [int(Xx) for Xx in input().split()]

for i in range(n):

    a[i] %= p

for i in range(m):

    b[i] %= p

pr1 = [0]

pr2 = [0]

for i in range(n):

    pr1.append(pr1[-1] + a[i])

for i in range(m):

    pr2.append(pr2[-1] + b[i])

for i in range(n):

    if pr1[i]:

        break

for j in range(m):

    if pr2[j]:

        break

for x in range(max(0, i + j - 2), 101010101101010101):

    ans = 0

    for i in range(min(x + 1, n)):

        if x - i < m:

            ans += a[i] * b[x - i]

    if ans % p:

        print(x)

        quit()


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

import math

import sys

n,m=[int(s) for s in input().split()]

ans=[]

curr_balance=0

for i in range(1,n+1):

    new_balance=math.floor((i-1)/2);

    if curr_balance+new_balance > m:

        break

    curr_balance+=new_balance;

    ans.append(i);

if curr_balance<m:

    if len(ans)==n:

        print(-1)

        sys.exit()

    remaining_balance = m-curr_balance

    number_index = remaining_balance*2 - 1

    if ans[-1-number_index]+ans[-1] <= 1000000000:

        ans.append(ans[-1-number_index]+ans[-1])

num_to_add=ans[-1]+1

for i in range(len(ans)+1,n+1):

    if ans[-1]+num_to_add <= 1000000000:

        ans.append(ans[-1]+num_to_add)

    else:

        break;

if len(ans)<n:

    print(-1)

    sys.exit()

for i in ans:

    print(i," ")


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

n = int(input())

r = list(map(int,input().split()))

b = list(map(int,input().split()))

rt = 0

bt = 0

for i in range(n):

    if r[i]!=b[i]:

        if r[i]>b[i]:

            rt+=1

        else:

            bt+=1

if rt>bt:

    print('1')

else:

    if rt==0:

        print('-1')

    else:

        if bt%rt==0:

            print(bt//rt + 1)

        else:

            print((bt+(rt-bt%rt))//rt)


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

import sys

input = lambda: sys.stdin.readline().rstrip("\n\r")

import math

def solve():

    a, b, c = list(map(int, input().split()))

    ans = math.inf

    lst = [0, 0, 0]

    for i in range(1, 10001):

        for j in factors[i]:

            p = j * (c // j)

            q = j * (c // j + 1)

            k = None

            z = None

            if abs(c - p) < abs(c - q):

                k = p

                z = abs(c - p)

            else:

                k = q

                z = abs(c - q)

            y = abs(b - j)

            x = abs(a - i)

            if x + y + z < ans:

                ans = x + y + z

                lst = [i, j, k]

    print(ans)

    print(*lst)

factors = [[] for i in range(10001)]

for i in range(1, 10001):

    x = i

    ind = 1

    while True:

        val = x * ind

        if val > 20001:

            break

        factors[i].append(val)

        ind += 1

for _ in range(int(input())):

    solve()


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

import math

[n,a,b,k]=list(map(int,input().split(" ")))

new=list(map(int,input().split(" ")))

new=[(i-a)%(a+b) for i in new]

arr=[]

ans=0

for i in new:

  # print(i)

  if i>b:

    ans+=1

  else:

    arr.append(i)

arr.sort()

i=0

# print(arr)

while(i<len(arr) and k>0):

  k-=math.ceil(arr[i]/a)

  # print(k)

  if k>=0:

    ans+=1

    i+=1

    # print(ans)

print(ans)


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

import sys

import math

import collections

import heapq

import decimal

input=sys.stdin.readline

t=int(input())

for w in range(t):

    n,s=(i for i in input().split())

    n=int(n)

    s=list(s)

    ans1=[0]*n

    ans2=[0]*n

    k=n

    prev=-1

    for i in range(n):

        if(i==n-1 or s[i]=='>'):

            for j in range(i,prev,-1):

                ans1[j]=k

                k-=1

            prev=i

    k=1

    prev=-1

    for i in range(n):

        if(i==n-1 or s[i]=='<'):

            for j in range(i,prev,-1):

                ans2[j]=k

                k+=1

            prev=i

    print(*ans1)

    print(*ans2)


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.

def solve():

    n = int(input())

    seq = input()

    ans = [(seq, 1)]

    def check(k):

        if k == 1:

            ans[0] = (seq, 1)

            return

        seq_copy = list(seq)

        seq_copy = seq[k-1:]

        if (n-k) % 2 == 0:

            seq_copy += seq[:k-1][::-1]

        else:

            seq_copy += seq[:k-1]

        ans[0] = min(ans[0], (''.join(seq_copy), k))

    indices = []

    cmin = min(seq)

    for i, e in enumerate(seq):

        if e == cmin:

            indices.append(i+1)

    for idx in indices:

        check(idx)

    return ans[0]

def main():

    t = int(input())

    output = []

    for _ in range(t):

        ans0, ans1 = solve()

        output.append(ans0)

        output.append(ans1)

    print_lines(output)

def input(): return next(test).strip()

def read_ints(): return [int(c) for c in input().split()]

def print_lines(lst): print('\n'.join(map(str, lst)))

if __name__ == "__main__":

    import sys

    from os import environ as env

    if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:

        sys.stdout = open('out.txt', 'w')

        sys.stdin = open('in.txt', 'r')

    test = iter(sys.stdin.readlines())

    main()


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

import bisect

for _ in range(int(input())):

  n,m=map(int,input().split())

  a=[int(i) for i in input().split()]

  p=[int(i)for i in input().split()]

  res="Yes"

  for i in range(n):

    a[i]=(a[i],i+1)

  a=sorted(a);p=sorted(p)

  for i in range(n):

    x=min(a[i][1],i+1);y=max(a[i][1],i+1)

    if x==y:continue

    pos=bisect.bisect(p,x)

    if  pos==0   :res=    "No"       ;break

    pos+=y-x-1

    if pos>=m +1    :res =   "No"       ;break

    if p[pos-1] != y-1:res =   "No"       ;break

  print(res)


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"

import os,sys

from io import BytesIO, IOBase

def main():

    n,k = map(int,input().split())

    arr = [input().strip() for _ in range(n)]

    se = {arr[i]:i for i in range(n)}

    ans = 0

    for i in range(n):

        for j in range(i+1,n):

            req = []

            for z in range(k):

                if arr[i][z] == arr[j][z]:

                    req.append(arr[i][z])

                else:

                    xx = ["S","E","T"]

                    xx.remove(arr[i][z])

                    xx.remove(arr[j][z])

                    req.append(xx[0])

            if se.get(''.join(req),-1) > j:

                ans += 1

    print(ans)

# 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()


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy 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 one of the two 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 say if it is possible to color the given string 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≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

from collections import deque, defaultdict, Counter

from heapq import heappush, heappop, heapify

from math import inf, sqrt, ceil

from functools import lru_cache

from itertools import accumulate, combinations, permutations, product

from typing import List

from bisect import bisect_left, bisect_right

import sys

input=lambda:sys.stdin.readline().strip('\n')

mis=lambda:map(int,input().split())

ii=lambda:int(input())

#sys.setrecursionlimit(10 ** 7)

N = ii()

S = input()

edges = defaultdict(list)

color = [-1] * N

def dfs(i, node_color):

    if color[i] == node_color:

        return

    elif color[i] != -1 and color[i] ^ node_color:

        print("NO")

        exit(0)

    color[i] = node_color

    for nei in edges[i]:

        dfs(nei, 1-node_color)

for i, c in enumerate(S):

    for j in range(i):

        if S[j] > c:

            edges[i].append(j)

            edges[j].append(i)

for i in range(N):

    if color[i] == -1:

        dfs(i, 0)

print("YES")

print("".join(map(str,color)))


B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4
1 0
4 1
3 4
0 3
OutputCopyYESInputCopy3
100 86
50 0
150 0
OutputCopynOInputCopy8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.

import sys; import math;
CASE=0; rla=''

def solve() :
    n=int(rla)
    if n&1 :
        for i in range(n) : a, b=map(int, input().split())
        print("NO"); return
    else :
        x=[]; y=[]
        for i in range(n>>1) :
            a, b=map(int, input().split())
            x.append(a); y.append(b)
        flag=0
        a, b=map(int, input().split())
        for i in range(1, (n>>1)) :
            c, d=map(int, input().split())
            if c-a!=x[i-1]-x[i] or d-b!=y[i-1]-y[i] : flag=1
            a=c; b=d
        print("NO" if flag==1 else "YES")

while True :
    rla=sys.stdin.readline()
    cases=1
    if not rla: break
    if (rla=='\n')|(rla=='') : continue
    if CASE==1 : cases=int(rla)
    for cas in range(cases) :

        solve()


A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

n=int(input())

s=input()

c=0

for i in s:

  c+=1 if i=="(" else 0

if c!=n/2:

  print(-1)

  exit()

ans=0

dir=0

c=0

l=0

for i in s:

  if c==0:

    if dir==-1:

      ans+=l

    l=0

    dir =1 if i=="(" else -1

  if i=="(":

    c+=1

    l+=1

  else:

    c-=1

    l+=1

if c==0:

    if dir==-1:

      ans+=l

print(ans)


import sys

input=sys.stdin.buffer.readline

n,m,p=map(int,input().split())

a=list(map(int,input().split()))

b=list(map(int,input().split()))

idx1=-1

idx2=-1

for i in range(n):

  if a[i]%p!=0:

    idx1=i

    break

for i in range(m):

  if b[i]%p!=0:

    idx2=i

    break

print(idx1+idx2)


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.

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

import heapq

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

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, y = readInts()

    sm = x+y

    print(min(n, max(1, sm+1-n)), min(n, sm-1))

def main():

    t = 1

    if path.exists("F:/Comp Programming/input.txt"):

        sys.stdin = open("F:/Comp Programming/input.txt", 'r')

        sys.stdout = open("F:/Comp Programming/output1.txt", 'w')

    # sys.setrecursionlimit(100000)

    t = readInts()

    for i in range(t):

        solve(i+1)

if __name__ == '__main__':

    main()


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

import sys

import collections

input = sys.stdin.readline

ints = lambda: list(map(int, input().split()))

n, m, k = ints()

special = ints()

graph = [[] for _ in range(n + 1)]

for _ in range(m):

    x, y = ints()

    graph[x].append(y)

    graph[y].append(x)

d1 = [-1 for _ in range(n + 1)]

q = collections.deque([1])

depth = 1

d1[1] = 0

while q:

    for _ in range(len(q)):

        node = q.popleft()

        for nb in graph[node]:

            if d1[nb] == -1:

                q.append(nb)

                d1[nb] = depth

    depth += 1

d2 = [-1 for _ in range(n + 1)]

q = collections.deque([n])

depth = 1

d2[n] = 0

while q:

    for _ in range(len(q)):

        node = q.popleft()

        for nb in graph[node]:

            if d2[nb] == -1:

                q.append(nb)

                d2[nb] = depth

    depth += 1

ans = d2[1]

s_distances = [(d1[i], d2[i]) for i in special]

s_distances.sort(key=lambda x: x[1], reverse=True)

mx = 0

for i in range(len(s_distances) - 1):

    l = s_distances[i + 1][1] + 1 + s_distances[i][0]

    mx = max(mx, l)

print(min(ans, mx))


for _ in range(int(input())):

    a, b, p = map(int, input().split())

    s = input()

    if s[0] == 'A':

        j = 0

        c = 1*a

    else:

        j = 1

        c = 1*b

    for i in range(1, len(s)-1):

        if s[i] == 'A' and j == 1:

            c = c + a

            j = 0

        elif s[i] == 'B' and j == 0:

            c = c + b

            j = 1

    i = 1

    if s[0] == 'A':

        j = 0

    else:

        j = 1

    while c > p and i < len(s):

        if s[i] == 'A' and j == 1:

            c = c - b

            j = 0

        elif s[i] == 'B' and j == 0:

            c = c - a

            j = 1

        i = i + 1

    print(i)


E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2

from sys import stdin

input=lambda :stdin.readline()[:-1]

n=int(input())

p=list(map(lambda x:int(x)-1,input().split()))

a=list(map(int,input().split()))

def calc(mid):

  left=[0]*n

  c=0

  for i in range(n):

    if p[i]>mid:

      c+=a[i]

    left[i]=c

  right=[0]*n

  c=0

  for i in range(n-1,-1,-1):

    if p[i]<=mid:

      c+=a[i]

    right[i]=c

  res=10**18

  for i in range(n-1):

    res=min(res,left[i]+right[i+1])

  return res

def ternary_search(L,R):

  # 準下凸関数の最小値

  while L+2<R:

    c1=L+(R-L)//3

    c2=R-(R-L)//3

    if calc(c1)<calc(c2):

      R=c2

    else:

      L=c1

  ans=10**18

  for i in range(L,R+1):

    ans=min(ans,calc(i))

  return ans

ans=ternary_search(-1,n)

print(min(ans,a[0],a[-1]))


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.

from collections import deque,defaultdict

import sys

input=sys.stdin.readline

def make_mf():

    res=[-1]*(mxa+5)

    ptoi=[0]*(mxa+5)

    pn=1

    for i in range(2,mxa+5):

        if res[i]==-1:

            res[i]=i

            ptoi[i]=pn

            pn+=1

            for j in range(i**2,mxa+5,i):

                if res[j]==-1:res[j]=i

    return res,ptoi,pn

def make_to():

    to=[[] for _ in range(pn)]

    ss=set()

    for a in aa:

        pp=[]

        while a>1:

            p=mf[a]

            e=0

            while p==mf[a]:

                a//=p

                e^=1

            if e:pp.append(p)

        if len(pp)==0:ext(1)

        elif len(pp)==1:pp.append(1)

        u,v=ptoi[pp[0]],ptoi[pp[1]]

        to[u].append(v)

        to[v].append(u)

        if pp[0]**2<=mxa:ss.add(u)

        if pp[1]**2<=mxa:ss.add(v)

    return to,ss

def ext(ans):

    print(ans)

    exit()

def solve():

    ans=inf

    for u in ss:

        ans=bfs(u,ans)

    if ans==inf:ans=-1

    return ans

def bfs(u,ans):

    dist=[-1]*pn

    q=deque()

    q.append((u,0,-1))

    dist[u]=0

    while q:

        u,d,pu=q.popleft()

        if d*2>=ans:break

        for v in to[u]:

            if v==pu:continue

            if dist[v]!=-1:ans=min(ans,d+dist[v]+1)

            dist[v]=d+1

            q.append((v,d+1,u))

    return ans

inf=10**9

n=int(input())

aa=list(map(int,input().split()))

mxa=max(aa)

mf,ptoi,pn=make_mf()

to,ss=make_to()

print(solve())


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

n,m = [int(i) for i in input().strip().split()]

a = [[int(i) for i in input().strip().split()] for j in range(n)]

lo = float('inf')

hi = -float('inf')

val = (2**m)-1

ans = [None,None]

for i in range(n):

    lo = min(lo,min(a[i]))

    hi = max(hi,max(a[i]))

while lo<=hi:

    x = (lo+hi)//2

    already = set()

    masks = []

    for i in range(n):

        mask = int(''.join(['1' if a[i][k]>=x else '0' for k in range(m)]),2)

        if mask in already:

            continue

        else:

            already.add(mask)

            masks.append([mask,i])

    N = len(masks)

    check = False

    for i in range(N):

        for j in range(i,N):

            if masks[i][0]|masks[j][0]==val:

                check = True

                ans = [masks[i][1],masks[j][1]]

                break

        if check:

            break

    if check:

        lo = x+1

    else:

        hi = x-1

print(ans[0]+1,ans[1]+1)


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:

[a,a,area]=list(map(int,input().split(" ")))

a=[len(i)for i in input().replace(' ','').split('0')if len(i)>0]

b=[len(i)for i in input().replace(' ','').split('0')if len(i)>0]

ans=0

fac=[]

k=1

while(k*k<=area):

  if area%k==0:

    fac.append((k,area//k))

  k+=1

fac+=[(j,i)for i,j in fac if i!=j]

for x,y in fac:

  ans+=sum(i-x+1 for i in a if x<=i)*sum(j-y+1 for j in b if y<=j)

print(ans)


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.

import random

# Sieve

sieve_primes = []

PRIME_LIMIT = int(1e6)

sieve = [False for i in range(0,PRIME_LIMIT)]

for i in range(2,PRIME_LIMIT):

    if not sieve[i]:

        sieve_primes.append(i)

        for j in range(i*i, PRIME_LIMIT, i):

            sieve[j]=True

# Input

n = int(input())

arr=list(map(int, input().split()))

# Construct search space Primes

primes = set()

def addPrime(num):

    for sieve_prime in sieve_primes:

        if num%sieve_prime == 0:

            primes.add(sieve_prime)

            while num%sieve_prime == 0:

                num//=sieve_prime

    if num>1:

        primes.add(num)

# (Could use probability calculations here to reduce search space)

random.shuffle(arr)

for num in arr[:8]:

    if num > 1:

        addPrime(num)

    addPrime(num+1)

    if num > 2:

        addPrime(num-1)

# Find answer

ans = n

# Function to find answer based on input prime

def findAns(prime):

    global ans

    curr_ans = 0

    for num in arr:

        if num<prime:

            curr_ans += prime-num

        else:

            curr_ans += min(num%prime, prime - num%prime)

        if curr_ans >= ans:

            return

    ans = min(curr_ans, ans)

for prime in primes:

    findAns(prime)

    if ans == 0: break

print(ans)


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.

for i in range(int(input())):

	n,m = map(int,input().split())

	arr = map(int,input().split())

	print(min(m,sum(arr)))


def reverse(arr,i,j):

    while i<j:

        temp=arr[i]

        arr[i]=arr[j]

        arr[j]=temp

        i+=1

        j-=1

    return None

def main():

    t=int(input())

    allans=[]

    for _ in range(t):

        n,s=input().split()

        n=int(n)

        minLIS=list(range(n,0,-1))

        i=0

        while i<n-1:

            j=i

            while j<n-1 and s[j]=='<':

                j+=1

            reverse(minLIS,i,j)

            # print(i,j)

            i=j+1

        allans.append(minLIS)

        maxLIS=list(range(1,n+1))

        i=0

        while i<n-1:

            j=i

            while j<n-1 and s[j]=='>':

                j+=1

            reverse(maxLIS,i,j)

            # print(i,j)

            i=j+1

        allans.append(maxLIS)

    multiLineArrayOfArraysPrint(allans)

    return

# import sys

# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)

import sys

input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):

    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):

    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):

    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():

    return [int(x) for x in input().split()]

# def readFloatArr():

#     return [float(x) for x in input().split()]

def makeArr(*args):

    """

    *args : (default value, dimension 1, dimension 2,...)

    Returns : arr[dim1][dim2]... filled with default value

    """

    assert len(args) >= 2, "makeArr args should be (default value, dimension 1, dimension 2,..."

    if len(args) == 2:

        return [args[0] for _ in range(args[1])]

    else:

        return [makeArr(args[0],*args[2:]) for _ in range(args[1])]

def queryInteractive(x,y):

    print('? {} {}'.format(x,y))

    sys.stdout.flush()

    return int(input())

def answerInteractive(ans):

    print('! {}'.format(ans))

    sys.stdout.flush()

inf=float('inf')

MOD=10**9+7

for _abc in range(1):

    main()


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.

import math

# -------- info --------

# https://codeforces.com/profile/Wolxy

# -------- solve --------

def solve() -> None:

    n = int(input())

    print(sum(1 / i for i in range(1, n + 1)))

# -------- main --------

T = 1

# T = int(input())

for _ in range(T):

    solve()


C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1

N=int(input())

A=list(map(int,input().split()))

S=sorted(set(A))

DP=[0]*len(S)

for a in A:

    NDP=[0]*len(S)

    MIN=1<<60

    for i in range(len(S)):

        MIN=min(MIN,DP[i])

        x=S[i]

        NDP[i]=abs(a-x)+MIN

    DP=NDP

print(min(DP))


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

import sys

input=sys.stdin.readline

def binary_index(ar,n):

    for idx in range(1,n):

        idx2=idx+(idx&(-idx))

        if (idx2<n):

            ar[idx2]+=ar[idx]

def update(inp,add,ar,n):

    while(inp<n):

        ar[inp]+=add

        inp+=(inp&(-inp))

def summation(inp,ar):

    ans=0

    while(inp):

        ans+=ar[inp]

        inp-=(inp&(-inp))

    return ans

n,m=map(int,input().split())

ar=list(map(int,input().split()))

dic={}

mi=[0]

ma=[0]

for i in range(1,n+1):

    mi.append(i)

    dic[i]=n-i+1

    ma.append(dic[i])

li=[0]*(n+m+1)

for i in range(1,n+1):

    li[i]=1

le=n+m+1

binary_index(li,le)

pointer=n+1

for i in range(m):

    nu=ar[i]

    mi[nu]=1

    ind=dic[nu]

    dic[nu]=pointer

    ma[nu]=min(ma[nu],summation(ind,li))

    update(ind,-1,li,le)

    update(pointer,1,li,le)

    pointer+=1

for i in range(1,n+1):

    ma[i]=min(ma[i],summation(dic[i],li))

for i in range(1,n+1):

    print(mi[i],n-ma[i]+1)


B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png   When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4];  Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]);  Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4];  Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3

import sys

import threading

input=sys.stdin.readline

from collections import Counter,defaultdict,deque

from heapq import heappush,heappop,heapify

#threading.stack_size(10**8)

#sys.setrecursionlimit(10**6)

def ri():return int(input())

def rs():return input()

def rl():return list(map(int,input().split()))

def rls():return list(input().split())

def main():

	b=defaultdict(list)

	f=defaultdict(list)

	n,m=rl()

	for _ in range(m):

		u,v=rl()

		f[u].append(v)

		b[v].append(u)

	k=ri()

	p=rl()

	dis=[1<<33]*(n+1)

	q=deque([(p[-1],0)])

	dis[p[-1]]=0

	vis=set()

	while q:

		cn,cd=q.popleft()

		vis.add(cn)

		dis[cn]=min(dis[cn],cd)

		for nn in b[cn]:

			if nn not in vis:

				q.append((nn,cd+1))

				vis.add(nn)

	#print(dis)

	mn,mx=0,0

	for i in range(k-1):

		if dis[p[i+1]]>dis[p[i]]-1:

			mx+=1;mn+=1

		else:

			c=0

			for j in f[p[i]]:

				if dis[j]==dis[p[i]]-1:

					c+=1

			if 	c>1:

				mx+=1

	print(mn,mx)

	pass

main()

#threading.Thread(target=main).start()