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

n = int(input())
s = input()

symbols = [(s[i], i) for i in range(n)]
unsorted = [-1]*n

result = None

odd_unsorted = True
even_unsorted = True

pairs = dict()
for i in range(n):
    pairs[i] = set()

while odd_unsorted or even_unsorted:
    even_unsorted = False
    for i in range(0, 2 * (n//2), 2):
        if symbols[i][0] > symbols[i+1][0]:
            even_unsorted = True
            # check constraints
            if len(pairs[symbols[i][1]].intersection(pairs[symbols[i+1][1]])) != 0:
                result = 'NO'
                break
            pairs[symbols[i][1]].add(symbols[i+1][1])
            pairs[symbols[i+1][1]].add(symbols[i][1])
            symbols[i], symbols[i+1] = symbols[i+1], symbols[i]

    if result:
        break

    odd_unsorted = False
    for i in range(1, 2 * ((n-1)//2) + 1, 2):
        if symbols[i][0] > symbols[i+1][0]:
            odd_unsorted = True
            # check constraints
            if len(pairs[symbols[i][1]].intersection(pairs[symbols[i+1][1]])) != 0:
                result = 'NO'
                break
            pairs[symbols[i][1]].add(symbols[i+1][1])
            pairs[symbols[i+1][1]].add(symbols[i][1])
            symbols[i], symbols[i+1] = symbols[i+1], symbols[i]

    if result:
        break

if not result:
    result = 'YES'

    for i in range(n):
        if unsorted[i] == -1:
            unsorted[i] = 0
        for j in pairs[i]:
            if unsorted[j] == -1:
                unsorted[j] = (unsorted[i]+1) % 2
            # else:
            #     if unsorted[i] == unsorted[j]:
            #         print('ERROR')

print(result)
if result == 'YES':
    print(*unsorted, sep='')


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 sys

input = sys.stdin.readline

N, M = map(int, input().split())

ans = [1, 2]

tmp = 0

ind = 3

while tmp < M:

    t = (ind-1)//2

    if tmp + t <= M:

        ans.append(ind)

        tmp += t

        ind += 1

    else:

        delta = M-tmp

        ans.append(ind-1+(ind-2*delta))

        break

if M == 0:

    if N == 1:

        ans = [1]

if len(ans) > N:

    print(-1)

else:

    rem = []

    last = ans[-1]

    tmp = 10**9

    for _ in range(N-len(ans)):

        rem.append(tmp)

        tmp -= last+1

    ans = ans + rem[::-1]

    print(*ans)


C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1

from sys import stdin

from itertools import accumulate

input = stdin.readline

n = int(input())

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

psum = list(accumulate(q)); min_ind = 0; min_val = 0

for i in range(len(psum)):

    if psum[i] <= min_val:

        min_ind = i + 1; min_val = psum[i]

psum = [0] + psum

#1 <=> psum[min_ind]

off = 0; offs = [0]

for elem in q:

    off = (off + elem) % n

    offs.append(off)

if len(set(offs)) != len(offs) or max(psum) > n - 1:

    print(-1)

else:

    ans = [0 for i in range(n)]

    for i in range(n): ans[i] = (psum[i] - min_val) + 1

    if not 1 <= max(ans) <= n:

        print(-1)

    else:

        print(' '.join(str(num) for num in ans))


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

t = int(input())

while t != 0:

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

    #a* vi theo quy tac nhan, con b luon co dang 9999999...

    #vd 1 -> 1+9+1*9 = 19, 2 = 2+9+2*9 = 29

    #str(b+1) xong lay len -1

    #vi 99 se co len(100)-1 = 2

    #98 len(99)-1 = 1 (van la 1 cach)

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

    t -= 1


t=int(input())

for _ in range(t):

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

    n=len(str(b))-1

    if str(b)=='9'*(n+1):

        n+=1

    print(a*n)


D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows:  The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii.  If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:  the defeated participant is hospitalized and leaves the show.  aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level.  The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1≤n,m≤20001≤n,m≤2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1≤li≤m1≤li≤m) — initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0≤si≤50000≤si≤5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|≤5000|ci|≤5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInputCopy5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
OutputCopy6
InputCopy2 2
1 2
0 0
2 1 -100 -100
OutputCopy2
InputCopy5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
OutputCopy62
NoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows:  a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles;  a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles;  a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble;  a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11−5=611−5=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.

import sys

input = sys.stdin.readline

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

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

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

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

DP=[[-1<<30]*(n+1) for i in range(5001)]

# DP[k][cnt] = Aのmaxがkで, そういう人間がcnt人いるときのprofitの最大値

for i in range(5001):

    DP[i][0]=0

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

    a,c = A[i]-1,C[i]

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

        if DP[a][j]==-1<<30:

            continue

        if DP[a][j] - c + P[a] > DP[a][j+1]:

            DP[a][j+1] = DP[a][j] - c + P[a]

            x, w=a, j+1

            while x+1<n+m:

                if DP[x+1][w//2] < DP[x][w] + w//2 * P[x+1]:

                    DP[x+1][w//2] = DP[x][w] + w//2 * P[x+1]

                    x,w=x+1,w//2

                else:

                    break

ANS=0

for i in range(5001):

    ANS=max(ANS,DP[i][0],DP[i][1])

print(ANS)


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

import sys,random,bisect

from collections import deque,defaultdict

from heapq import heapify,heappop,heappush

from itertools import permutations

from math import gcd,log,comb,perm,factorial

mod = int(1e9 + 7)

inf = int(1e20)

input = lambda :sys.stdin.readline().rstrip()

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

li = lambda :list(mi())

ii = lambda :int(input())

t=ii()

for _ in range(t):

    n=ii()

    print("{} {}".format(1,n-1))


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

out = 0.0

inp = int(input());

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

    out = out + 1/i

print(out)


C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

import sys

input = sys.stdin.readline

from bisect import bisect_left

n = int(input())

print('?', 1, n)

sys.stdout.flush()

m = (n + 1) // 2

l1 = [[0] * 26 for _ in range(m + 1)]

for i in range(n * (n + 1) // 2):

    s = input()[:-1]

    if len(s) <= m:

        for j in range(len(s)):

            l1[len(s)][ord(s[j]) - 97] += 1

for i in range(m, 0, -1):

    for j in range(26):

        l1[i][j] -= l1[i - 1][j]

for i in range(m):

    for j in range(26):

        l1[i][j] -= l1[i + 1][j]

if n > 1:

    n = n - 1

    print('?', 1, n)

    sys.stdout.flush()

    m = (n + 1) // 2

    l2 = [[0] * 26 for _ in range(m + 1)]

    for i in range(n * (n + 1) // 2):

        s = input()[:-1]

        if len(s) <= m:

            for j in range(len(s)):

                l2[len(s)][ord(s[j]) - 97] += 1

    for i in range(m, 0, -1):

        for j in range(26):

            l2[i][j] -= l2[i - 1][j]

    for i in range(m):

        for j in range(26):

            l2[i][j] -= l2[i + 1][j]

    n += 1

x = [-1] * n

y = [-1] * n

for i in range(n):

    if i % 2 == 0:

        for j in range(26):

            if l1[i//2+1][j] >= 1:

                l1[i//2+1][j] -= 1

                x[i] = j

                break

        for j in range(26):

            if l1[i//2+1][j] >= 1:

                l1[i//2+1][j] -= 1

                y[i] = j

                break

    else:

        for j in range(26):

            if l2[i//2+1][j] >= 1:

                l2[i//2+1][j] -= 1

                x[i] = j

                break

        for j in range(26):

            if l2[i//2+1][j] >= 1:

                l2[i//2+1][j] -= 1

                y[i] = j

                break

ans = [0] * n

m = (n + 1) // 2

ll = []

if n % 2 == 1:

    ll.append(n // 2)

    for i in range(n // 2):

        ll.append(n // 2 - i - 1)

        ll.append(n // 2 + i + 1)

else:

    for i in range(n // 2):

        ll.append(n // 2 - i - 1)

        ll.append(n // 2 + i)

ans[ll[0]] = x[-1]

t = 0

for i in range(n - 1):

    if t == 0:

        if x[n - i - 2] == x[n - i - 1]:

            ans[ll[i + 1]] = y[n - i - 2]

            t = 1

        else:

            ans[ll[i + 1]] = x[n - i - 2]

    else:

        if x[n - i - 2] == y[n - i - 1]:

            ans[ll[i + 1]] = y[n - i - 2]

        else:

            ans[ll[i + 1]] = x[n - i - 2]

            t = 0

print('! ', *map(lambda x:chr(x+97), ans), sep='')


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

import os

import sys

from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

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

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

fact=[1]

for i in range(1,250009):

    curr=((fact[-1]%mod)*(i%mod))%mod

    fact.append(curr)

ans=0

x=n-1

y=2

for i in range(n-1):

    ans=((ans%mod)+((((x%mod)*(fact[x])*(fact[y])))%mod))%mod

    x-=1

    y+=1

ans=((ans%mod)+(n*(fact[n])))%mod

print(ans)


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]

class BIT:

    def __init__(self, n):

        self.n = n

        self.bit = [0]*(self.n+1) # 1-indexed

    def init(self, init_val):

        for i, v in enumerate(init_val):

            self.add(i, v)

    def add(self, i, x):

        # i: 0-indexed

        i += 1 # to 1-indexed

        while i <= self.n:

            self.bit[i] += x

            i += (i & -i)

    def sum(self, i, j):

        # return sum of [i, j)

        # i, j: 0-indexed

        return self._sum(j) - self._sum(i)

    def _sum(self, i):

        # return sum of [0, i)

        # i: 0-indexed

        res = 0

        while i > 0:

            res += self.bit[i]

            i -= i & (-i)

        return res

class RangeAddBIT:

    def __init__(self, n):

        self.n = n

        self.bit1 = BIT(n)

        self.bit2 = BIT(n)

    def init(self, init_val):

        self.bit2.init(init_val)

    def add(self, l, r, x):

        # add x to [l, r)

        # l, r: 0-indexed

        self.bit1.add(l, x)

        self.bit1.add(r, -x)

        self.bit2.add(l, -x*l)

        self.bit2.add(r, x*r)

    def sum(self, l, r):

        # return sum of [l, r)

        # l, r: 0-indexed

        return self._sum(r) - self._sum(l)

    def _sum(self, i):

        # return sum of [0, i)

        # i: 0-indexed

        return self.bit1._sum(i)*i + self.bit2._sum(i)

    def __str__(self): # for debug

        arr = [self.sum(i,i+1) for i in range(self.n)]

        return str(arr)

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

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

A = [a-1 for a in A]

mn = [i for i in range(n)]

for a in A:

    mn[a] = 0

A = list(range(n-1, -1, -1))+A

bit = RangeAddBIT(len(A)+1)

mx = [i for i in range(n)]

prev = [-1]*n

for r, a in enumerate(A):

    l = prev[a]

    mx[a] = max(mx[a], bit.sum(l, l+1))

    bit.add(l+1, r, 1)

    prev[a] = r

for a in range(n):

    l = prev[a]

    mx[a] = max(mx[a], bit.sum(l, l+1))

for i in range(n):

    print(mn[i]+1, mx[i]+1)


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

t=int(input())

for i in range(t):

    n=int(input())

    if n%2!=0:

        s='7'

        for j in range((n-3)//2):

            s+="1"

        print(s)

    else:

        s=""

        for j in range(n//2):

            s+='1'

        print(s)


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

from functools import lru_cache

n = int(input())

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

c = [i % 2 for i in p].count(1)

if n % 2 == 0:

    t = n // 2 - c

else:

    t = n // 2 - c + 1

@lru_cache(None)

def dfs(i, t, q):

    if t < 0 or t > n - i:

        return float("inf")

    elif i == n:

        return 0 if t == 0 else float("inf")

    if p[i] == 0:

        if q == 0:

            return min(dfs(i + 1, t, 0), dfs(i + 1, t - 1, 1) + 1)

        else:

            return min(dfs(i + 1, t - 1, 1), dfs(i + 1, t, 0) + 1)

    else:

        return abs(q - p[i] % 2) + dfs(i + 1, t, p[i] % 2)

if p[0] == 0:

    print(min(dfs(1, t - 1, 1), dfs(1, t, 0)))

else:

    print(dfs(1, t, p[0] % 2))


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:

def helper(arr):

    res=[0]*(len(arr)+1)

    i=0

    while i<len(arr):

        if arr[i]==0:

            i+=1

        else :

            j=i

            while (j<len(arr) and arr[j]==1):

                j+=1

            for l in range(1,j-i+1):

                res[l]+=j-i-l+1

            i=j

    return res[:]

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

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

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

ga=helper(arr)

gb=helper(brr)

ans=0

# print(ga,gb)

for i in range(1,len(ga)):

    if k%i==0 and k//i<=m:

        # print(i,k//i)

        ans+=ga[i]*gb[k//i]

print(ans)


n=int(input())

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

res=[]

a=0

b=0

temp=0

for el in arr:

    temp+=el

    a=min(a,temp)

    b=max(b,temp)

el=-a+1

level=b

if el+level==n:

    res.append(el)

    for el in arr:

        res.append(res[-1]+el)

    if len(set(res))!=n:

        print(-1)

    else :

        print(*res)

else:

    print(-1)


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

for i in[0]*int(input()):input();a=[*map(int,input().split())];b=[y for x,y,z in zip([0]+a,a,a[1:]+[0])if 0>x|z<y]or[0];l=min(b);m=max([(max(b)-l+1)//2]+[abs(x-y)for x,y in zip(a,a[1:])if~x&~y]);print(m,l+m)


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1

import os, sys

from io import BytesIO, IOBase

from math import log2, ceil, sqrt, gcd

from _collections import deque

import heapq as hp

from bisect import bisect_left, bisect_right

from math import cos, sin

from itertools import permutations

from operator import itemgetter

# sys.setrecursionlimit(2*10**5+10000)

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

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

mod = 10 ** 9 + 7

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

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

edge = dict()

cc = [0] * (n + 1)

for i in range(n - 1):

    x, y = map(int, input().split())

    a[x].add(y)

    a[y].add(x)

    if x > y:

        x, y = y, x

    edge[(x, y)] = i

    cc[x] += 1

    cc[y] += 1

ck1 = [0] * (n + 1)

no = 0

for i in cc:

    ck1[i] += 1

    no = max(no, ck1[i])

tot = 0

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

    if tot <= k:

        no = min(no, i)

    tot += ck1[i]

print(no)

ans = [0] * (n - 1)

d = deque()

d.append(1)

while d:

    i = d.popleft()

    color = set()

    pair = []

    for j in a[i]:

        x = i

        y = j

        if x > y:

            x, y = y, x

        z = ans[edge[(x, y)]]

        if z:

            color.add(z)

        else:

            pair.append([x, y])

            d.append(j)

    j = 1

    while pair and j <= no:

        if j in color:

            j += 1

        else:

            x, y = pair.pop()

            ans[edge[(x, y)]] = j

            j += 1

    j = no

    while pair:

        x, y = pair.pop()

        ans[edge[(x, y)]] = j

        j -= 1

        if j == 0:

            j = no

print(*ans)


A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.

import os,sys

from random import randint, shuffle

from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter

from bisect import bisect_left,bisect_right

from heapq import heappush,heappop

from functools import lru_cache

from itertools import accumulate, permutations

import math

# Fast IO Region

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

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

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

#     n = int(input())

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

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

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

    ans = 0

    for i in range(1 << 7):

        x = y = z = 0

        cnt = 0

        for j in range(7):

            if i >> j & 1:

                cnt += 1

                if j == 0:

                    x += 1

                elif j == 1:

                    y += 1

                elif j == 2:

                    z += 1

                elif j == 3:

                    x += 1

                    y += 1

                elif j == 4:

                    x += 1

                    z += 1

                elif j == 5:

                    y += 1

                    z += 1

                else:

                    x += 1

                    y += 1

                    z += 1

        if x <= a and y <= b and z <= c:

            ans = max(ans, cnt)

    print(ans)


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

from collections import defaultdict, Counter, deque

import threading

import sys

# input = sys.stdin.readline

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

def rs(): return input()

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

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

threading.stack_size(10**8)

sys.setrecursionlimit(10**6)

def main():

    n = ri()

    a = [0]+rl()

    for i in range(n+1):

        if i != 0 and a[i] == 0:

            a[i] = -1

    g = defaultdict(list)

    for _ in range(n-1):

        u, v = rl()

        g[u].append(v)

        g[v].append(u)

    par = [-1]*(n+1)

    dp = [0]*(n+1)

    def d1(cn, p):

        par[cn] = p

        dp[cn] = a[cn]

        for nn in g[cn]:

            if nn != p:

                dp[cn] += max(0, d1(nn, cn))

        return dp[cn]

    d1(1, 0)

    def d2(cn, p):

        if cn != 1:

            if dp[cn] > 0:

                res[cn] = max(res[par[cn]], dp[cn])

            else:

                res[cn] = max(res[par[cn]]+dp[cn], dp[cn])

        for nn in g[cn]:

            if nn != p:

                d2(nn, cn)

    res = [0]*(n+1)

    res[1] = dp[1]

    d2(1, 0)

    print(*res[1:])

    pass

# main()

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


E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific:  The artifact only contains 7575 units of energy.  For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy.  If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4

2 1 2

1 2

0

1OutputCopy

? C

? CH

? CCHO

! CCHH

InputCopy2
5

0

2 2 3

1
8

1 5

1 5

1 3

2 1 2

1OutputCopy

? O

? HHH

! CHHHH

? COO

? COOH

? HCCOO

? HH

! HHHCCOOH

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.

import sys

n, L, minID = None, None, None

s = []

def fill(id, c):

    global n, L, s, minID

    L -= (s[id] == 'L')

    s = s[0:id] + c + s[ id +1:]

    minID = min(minID, id)

def query(cmd, str):

    global n, L, s, minID

    print(cmd, ''.join(str))

    print(cmd, ''.join(str), file=sys.stderr)

    sys.stdout.flush()

    if (cmd == '?'):

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

        assert(result[0] != -1)

        for z in result[1:]:

            z -= 1

            for i in range(len(str)):

                assert(s[z+i] == 'L' or s[z+i] == str[ i ])

                fill(z+i, str[i])

    elif (cmd == '!'):

        correct = int(input())

        assert(correct == 1)

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

    n = int(input())

    if n >= 13:

        ans = [''] * (n + 1)

        print('? CO')

        co = list(map(int, input().split()))[1:]

        print('? CH')

        ch = list(map(int, input().split()))[1:]

        print('? CC')

        cc = list(map(int, input().split()))[1:]

        for d in co:

            ans[d] = 'C'

            ans[d + 1] = 'O'

        for d in ch:

            ans[d] = 'C'

            ans[d + 1] = 'H'

        for d in cc:

            ans[d] = 'C'

            ans[d + 1] = 'C'

        print('? OO')

        oo = list(map(int, input().split()))[1:]

        print('? OH')

        oh = list(map(int, input().split()))[1:]

        for d in oo:

            ans[d] = 'O'

            ans[d + 1] = 'O'

        for d in oh:

            ans[d] = 'O'

            ans[d + 1] = 'H'

        for i in range(1, n):

            if ans[i] == 'O' and ans[i + 1] == '':

                ans[i + 1] = 'C'

        for i in range(1, n):

            if ans[i] == '' and ans[i + 1] == 'O':

                ans[i] = 'H'

        for i in range(1, n):

            if ans[i] == '' and ans[i + 1] == 'H':

                ans[i] = 'H'

        for i in range(1, n):

            if ans[i] == '' and ans[i + 1] == '':

                ans[i] = 'H'

        print('? HOC')

        hoc = list(map(int, input().split()))[1:]

        for d in hoc:

            ans[d] = 'H'

            ans[d + 1] = 'O'

            ans[d + 2] = 'C'

        for d in range(2, n):

            if ans[d] == '':

                ans[d] = 'H'

        if ans[1] == '':

            print('?', 'H' + ''.join(ans[2:-1]))

            if input()[0] != '0':

                ans[1] = 'H'

            else:

                ans[1] = 'O'

        if ans[-1] == '':

            print('?', ''.join(ans[1:-1]) + 'H')

            if input()[0] != '0':

                ans[-1] = 'H'

            else:

                print('?', ''.join(ans[1:-1]) + 'O')

                if input()[0] != '0':

                    ans[-1] = 'O'

                else:

                    ans[-1] = 'C'

        print('!', ''.join(ans[1:]))

        kek = input()

    else:

        L, minID = n, n

        s = 'L' * n

        query('?', "CH")

        query('?', "CO")

        query('?', "HC")

        query('?', "HO")

        if (L == n):

            # the string exists in form O...OX...X, with X=C or X=H

            # or it's completely mono-character

            query('?', "CCC")

            if (minID < n):

                for x in range(minID - 1, -1, -1): fill(x, 'O')

            else:

                query('?', "HHH")

                if (minID < n):

                    for x in range(minID - 1, -1, -1): fill(x, 'O')

                else:

                    query('?', "OOO")

                    if (minID == n):

                        # obviously n=4

                        query('?', "OOCC")

                        if (minID == n):

                            fill(0, 'O')

                            fill(1, 'O')

                            fill(2, 'H')

                            fill(3, 'H')

                    if (s[n - 1] == 'L'):

                        t = s[0:n - 1] + 'C'

                        if (t[n - 2] == 'L'): t = t[0:n - 2] + 'C' + t[n - 1:]

                        query('?', t)

                        if (s[n - 1] == 'L'):

                            fill(n - 1, 'H')

                            if (s[n - 2] == 'L'): fill(n - 2, 'H')

        else:

            maxID = minID

            while (maxID < n - 1 and s[maxID + 1] != 'L'): maxID += 1

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

                query('?', s[i + 1:i + 2] + s[minID:maxID + 1])

                if (minID != i):

                    for x in range(i + 1): fill(x, 'O')

                    break

            nextFilled = None

            i = maxID + 1

            while i < n:

                if (s[i] != 'L'):

                    i += 1

                    continue

                nextFilled = i

                while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1

                query('?', s[0:i] + s[i - 1])

                if (s[i] == 'L'):

                    if (s[i - 1] != 'O'):

                        fill(i, 'O')

                    else:

                        if (nextFilled == n):

                            query('?', s[0:i] + 'C')

                            if (s[i] == 'L'): fill(i, 'H')

                            for x in range(i + 1, nextFilled): fill(x, s[i])

                        else:

                            for x in range(i, nextFilled): fill(x, s[nextFilled])

                        i = nextFilled - 1

                i += 1

        query('!', s)


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

def solve(n, d, arr):

    i = 1

    while d > 0 and i < n:

        if arr[i] <= 0 or d < i:

            i += 1

        elif d >= i:

            d -= i

            arr[0] += 1

            arr[i] -= 1

    return arr[0]

if __name__ == "__main__":

    t = int(input())

    results = list()

    for _ in range(0, t):

        n, d = list(map(int, input().split(" ")))

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

        results.append(solve(n, d, arr))

    for result in results:

        print(result)


tst = int(input())

for i in range(tst) :

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

    arr.sort()

    a, b, c = arr[2], arr[1], arr[0]

    cnt = 0

    if a >= 4 and b >= 4 and c >= 4 :

        print(7)

        continue

    if a > 0 :

        a -= 1

        cnt += 1

    if b > 0 :

        b -= 1

        cnt += 1

    if c > 0 :

        c -= 1

        cnt += 1

    if a > 0 and b > 0:

        a -= 1

        b -= 1

        cnt += 1

    if a > 0 and c > 0:

        a -= 1

        c -= 1

        cnt += 1

    if b > 0 and c > 0 :

        b -= 1

        c -= 1

        cnt += 1

    if a > 0 and b > 0 and c > 0 :

        a -= 1

        b -= 1

        c -= 1

        cnt += 1

    print(cnt)


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.

import sys

input=sys.stdin.readline

def validparenthesis(s,i,j):

    stack=[]

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

        if s[idx]=='(':stack.append(s[idx])

        else:

            if len(stack)==0:return False

            else:

                stack.pop()

    if len(stack)!=0:return False

    return True

from collections import Counter

n=int(input())

s=input().rstrip()

d=Counter(s)

if d[')']!=d['('] or n==1:print(-1)

else:

    i=c1=c2=0

    j=0

    ans=0

    while j<n:

        if s[j]=='(':c1+=1

        else:c2+=1

        if c1==c2:

            if not validparenthesis(s,i,j):

                ans+=(c1+c2)

            i=j+1

            j+=1

            c1=c2=0

        else:

            j+=1

    print(ans)


F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212.

from bisect import bisect_left

M = 998244353

def pw(x, y):

    if y == 0:

        return 1

    res = pw(x, y//2)

    res = res * res % M

    if y % 2 == 1:

        res = res * x % M

    return res

def cal(x, y):

    y += x - 1

    res = 1

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

        res = res * (y - i + 1)

        res = res * pw(i, M - 2) % M

    return res % M

n = int(input())

a = []

b = []

res = 1

for i in range(n):

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

    res = res * (a[-1][1] + 1 - a[-1][0]) % M

    b.append(a[-1][0])

    b.append(a[-1][1] + 1)

    b = set(b)

    b = sorted(list(b))

g = [b[i + 1] - b[i] for i in range(len(b) - 1)]

for i in range(n):

    a[i][0] = bisect_left(b, a[i][0])

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

a = a[::-1]

f = [[0 for _ in range(len(b))] for __ in range(n)]

for i in range(a[0][0], len(b)):

    if i == 0:

        f[0][i] = g[i]

    else:

        if i < a[0][1]:

            f[0][i] = (f[0][i - 1] + g[i]) % M

        else:

            f[0][i] = f[0][i - 1]

for i in range(1, n):

    for j in range(a[i][0], len(b)):

        if j > 0:

            f[i][j] = f[i][j - 1]

        if j < a[i][1]:

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

                if a[k][1] <= j or j < a[k][0]:

                    break

                if k == 0 or j != 0:

                    tmp = cal(i - k + 1, g[j])

                    if k > 0:

                        f[i][j] += f[k - 1][j - 1] * tmp % M

                    else:

                        f[i][j] += tmp

                    f[i][j] %= M

#print(f)

#print(f[n - 1][len(b) - 1], res)

print(f[n - 1][len(b) - 1] * pw(res, M - 2) % M)


C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

# 15:02-

import sys

input = lambda: sys.stdin.readline().strip()

N = int(input())

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

def deal(top,A):

	arr = []

	ans = 0

	for a in A:

		if a>top:

			a=top

		else:

			top=a

		ans+=a

		arr.append(a)

	return ans,arr

cnt=0

ans=[]

for i in range(N):

	A = M[:i][::-1]

	B = M[i+1:]

	t1,a1=deal(M[i],A)

	t2,a2=deal(M[i],B)

	t = t1+t2+M[i]

	if t>cnt:

		cnt=t

		ans = a1[::-1]+[M[i]]+a2

#print(cnt)

print(*ans)


F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

from itertools import*

from collections import*

n=int(input())

arr=[0] +[*accumulate(map(int,input().split()))]

g=defaultdict(list)

for i in range(n):

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

        g[arr[j] -arr[i]].append([i+1,j])

ans=[]

maxi=[]

for i in g:

    f=sorted(g[i],key=lambda x:x[1])

    ans=[f[0]]

    for l,r in f:

        if l >ans[-1][1]:

            ans.append([l,r])

    maxi=max(maxi,ans,key=len)

print(len(maxi))

for i in maxi:

    print(*i)


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

t = int(input())

for i in range(t):

  s = input()

  if ('1' in s) == True:

    l = s.index('1')

    r = s.rindex('1')

    s = s[l:r].count('0')

    print(s)

  else:

    print(0)


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

test = int(input())
for _ in range(test):
        x, y , a, b = map(int, input().split())
        if (y - x) % (a+b) == 0 :
            print((y-x)//(a+b))
        else:
            print(-1)


C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker "X" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n−1n−1 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n−2n−2 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=∑1≤u<v≤nmex(u,v)S=∑1≤u<v≤nmex(u,v)Here, mex(u,v)mex(u,v) denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang uu to gang vv.Xenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of SS, so that the AIs can be deployed efficiently.Now, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible SS before he returns?InputThe first line contains an integer nn (2≤n≤30002≤n≤3000), the number of gangs in the network.Each of the next n−1n−1 lines contains integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n; ui≠viui≠vi), indicating there's a direct link between gangs uiui and vivi.It's guaranteed that links are placed in such a way that each pair of gangs will be connected by exactly one simple path.OutputPrint the maximum possible value of SS — the number of password layers in the gangs' network.ExamplesInputCopy3
1 2
2 3
OutputCopy3
InputCopy5
1 2
1 3
1 4
3 5
OutputCopy10
NoteIn the first example; one can achieve the maximum SS with the following assignment:  With this assignment, mex(1,2)=0mex(1,2)=0, mex(1,3)=2mex(1,3)=2 and mex(2,3)=1mex(2,3)=1. Therefore, S=0+2+1=3S=0+2+1=3.In the second example, one can achieve the maximum SS with the following assignment:  With this assignment, all non-zero mex value are listed below:   mex(1,3)=1mex(1,3)=1  mex(1,5)=2mex(1,5)=2  mex(2,3)=1mex(2,3)=1  mex(2,5)=2mex(2,5)=2  mex(3,4)=1mex(3,4)=1  mex(4,5)=3mex(4,5)=3 Therefore, S=1+2+1+2+1+3=10S=1+2+1+2+1+3=10.

import sys

# Read input and build the graph

inp = [int(x) for x in sys.stdin.buffer.read().split()]; ii = 0

n = inp[ii]; ii += 1

coupl = [[] for _ in range(n)]

for _ in range(n - 1):

    u = inp[ii] - 1; ii += 1

    v = inp[ii] - 1; ii += 1

    coupl[u].append(v)

    coupl[v].append(u)

# Relabel to speed up n^2 operations later on

bfs = [0]

found = [0]*n

found[0] = 1

for node in bfs:

    for nei in coupl[node]:

        if not found[nei]:

            found[nei] = 1

            bfs.append(nei)

new_label = [0]*n

for i in range(n):

    new_label[bfs[i]] = i

coupl = [coupl[i] for i in bfs]

for c in coupl:

    c[:] = [new_label[x] for x in c]

##### DP using multisource bfs

DP = [0] * (n * n)

size = [1] * (n * n)

P = [-1] * (n * n)

# Create the bfs ordering

bfs = [root * n + root for root in range(n)]

for ind in bfs:

    P[ind] = ind

for ind in bfs:

    node, root = divmod(ind, n)

    for nei in coupl[node]:

        ind2 = nei * n + root

        if P[ind2] == -1:

            bfs.append(ind2)

            P[ind2] = ind

del bfs[:n]

# Do the DP

for ind in reversed(bfs):

    node, root = divmod(ind, n)

    ind2 = root * n + node

    pind = P[ind]

    parent = pind//n

    # Update size of (root, parent)

    size[pind] += size[ind]

    # Update DP value of (root, parent)

    DP[pind] = max(DP[pind], max(DP[ind], DP[ind2]) + size[ind] * size[ind2])

print(max(DP[root * n + root] for root in range(n)))


D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array;  for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array;  for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example:  After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11.  After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22.  After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33.  After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations).  After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44.  After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44.  After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations:   a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5,  a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3,  a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3,  a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6,  a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7,  a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4.  The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.

# MEX maximizing

import sys

q, x = map(int, sys.stdin.readline().split())

map = {}

mex = 0

for _ in range(q):

    y = int(sys.stdin.readline())

    if y % x in map:

        if y % x + x*map[y % x] in map:

            map[y % x + x*map[y % x]] += 1

        else:

            map[y % x + x*map[y % x]] = 1

        map[y % x] += 1

    else:

        map[y % x] = 1

    while mex in map:

        mex += 1

    print(mex)


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,os,io,math,cmath,timeit,functools,operator,bisect

from collections import defaultdict

from collections import Counter

from math import factorial

from math import inf as INF

ONLINE_JUDGE = 1

input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

if not ONLINE_JUDGE :

    sys.stdin = open("C:/Users/mande/Downloads/Practice/Python 3.9.8/inp.in" , "r")

    sys.stdout = open("C:/Users/mande/Downloads/Practice/Python 3.9.8/outp.out" , "w")

#input = sys.stdin.readline

start = timeit.default_timer()

primes = []

mod=10**9+7

def power(x,b):

    p=1

    while b>0 :

        if b&1 :

            p=p*x

            p = p%mod

        b = b>>1

        x = x**x

        x = x%mod

    return p%mod

def seive(n):

    a = []

    prime = [True for i in range(n+1)]

    p = 2

    while (p * p <= n):

        if (prime[p] == True):

            for i in range(p ** 2,n + 1, p):

                prime[i] = False

        p = p + 1

    for p in range(2,n + 1):

        if prime[p]:

            primes.append(p)

def is_sorted(arr):

    return all(arr[i]<=arr[i+1] for i in range(len(arr)-1))

def invmod(n):

    return power(n,mod-2)

def binary_search(a,x,lo=0,hi=None):

    if hi is None:

        hi = len(a)

    while lo < hi:

        mid = (lo+hi)//2

        midval = a[mid]

        if midval < x:

            lo = mid+1

        elif midval > x:

            hi = mid

        else:

            return mid

    return -1

def yn(x):

    if x :

        sys.stdout.write("YES"+"\n")

    else :

        sys.stdout.write("NO"+"\n")

def nCr(n,r)->int :

    return factorial(n)//(factorial(r)*factorial(n-r))

def solve()->None :

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

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

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

    i,j=0,0

    while i<n :

        if an[i]%p :

            break

        i+=1

    while j<m :

        if am[j]%p :

            break

        j+=1

    print(i+j)

def main():

    tc=1

    #tc=int(input())

    for _ in range(tc):

        solve()

    stop = timeit.default_timer()

    if not ONLINE_JUDGE :

        sys.stdout.write("Time Elapsed : " + str(stop-start) + " seconds")

    sys.stdout.close()

main()