A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here:  After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5).  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3).  After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

from sys import stdin

input = stdin.readline

#// - remember to add .strip() when input is a string

t = 1

for _ in range(t):

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

  hashm = {}

  counter = 0

  for i in range(q):

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

    if (r,c) in hashm:

      if (2 - ((r+1)%2), c-1) in hashm:

        counter -= 1

      if (2 - ((r+1)%2), c) in hashm:

        counter -= 1

      if (2 - ((r+1)%2), c+1) in hashm:

        counter -= 1

      hashm.pop((r,c))

    else:

      if (2 - ((r+1)%2), c-1) in hashm:

        counter += 1

      if (2 - ((r+1)%2), c) in hashm:

        counter += 1

      if (2 - ((r+1)%2), c+1) in hashm:

        counter += 1

      hashm[(r,c)] = None

    if counter == 0:

      print("YES")

    else:

      print("NO")


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

from bisect import insort

def min_steps_N(arr):

    pri_q = []

    ans = 0

    for n in arr:

        if pri_q:

            if pri_q[-1] > n:

                ans += pri_q[-1] - n

                pri_q.pop()

                insort(pri_q, n)

        insort(pri_q, n)

    return ans

if __name__ == '__main__':

    N = input()

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

    print(min_steps_N(arr))


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    odd = 0
    even = 0
    for i in a:
        if i%2 == 0:
            even += 1
        else:
            odd += 1
    if odd == 0 or even == 0:
        print("YES")
    else:
        print("NO")


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.

from collections import deque, defaultdict, Counter

from heapq import heappush, heappop, heapify

from math import inf, sqrt, ceil, log2

from functools import lru_cache

from itertools import accumulate, combinations, permutations, product

from typing import List

from bisect import bisect_left, bisect_right

import sys

import string

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

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

ii=lambda:int(input())

#sys.setrecursionlimit(5*(10 ** 3))

N, M, P = mis()

A = list(mis())

B = list(mis())

pi = None

pj = None

for i in range(N):

    if A[i] % P != 0:

        pi = i

        break

for j in range(M):

    if B[j] % P != 0:

        pj = j

        break

print(pi + pj)


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

import io, os, sys, atexit

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

inputs =lambda: input().decode().strip()

stdout = io.BytesIO()

sys.stdout.write = lambda s: stdout.write(s.encode())

atexit.register(lambda: os.write(1, stdout.getvalue()))

## code start

from collections import defaultdict

from itertools import accumulate

n=int(input())

a=[*map(int,input().split())]

presum=list(accumulate(a,initial=0))  # 前缀和

data=defaultdict(list)

for h in range(n):

    for t in range(h+1,n+1):

        data[presum[t]-presum[h]].append((h+1,t))   # 以区间和为键值, 建立字典, 记录所有区间和为该键值的起终点

maxcnt,res=0,[]

for key in data:                   # 枚举区间和

    data[key].sort(key=lambda x:x[1])    # 所有区间按终点排序

    cnt,prev=0,-1

    for a,b in data[key]:

        if a>prev:              # 如果起点大于上一段终点, 贪心加入

            cnt+=1            # 计数加1

            prev=b            # 终点变成本区间终点

    if cnt>maxcnt:

        maxcnt=cnt

        res=key

print(maxcnt)

prev=-1

for a,b in data[res]:

    if a>prev:

        print(a,b)

        prev=b


B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows:  The coordinates of the 00-th node is (x0,y0)(x0,y0)  For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions:  From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second.  If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows:   Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds.  Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows:   Collect the 33-rd node. This requires no seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.

import sys

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

def dist(a,b):

    return sum([abs(a[i]-b[i]) for i in range(2)])

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

points=[temp[0:2]]

a=temp[2:4]

b=temp[4:6]

start=[0,0]

*start,t=map(int,input().split())

while points[-1][0]-start[0]<=t:

	points.append([points[-1][i]*a[i]+b[i] for i in range(2)])

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

	for j in range(len(points)-i):

		if dist(points[j],points[j+i])+min(dist(start,points[j]),dist(start,points[j+i]))<=t:

			print(i+1)

			sys.exit()

print(0)


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

t = int(input())

for _ in range(t):

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

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

    ans = 0

    for i in range(k+1):

        if (s-i >= 1 and not s-i in a) or (s+i <= n and not s+i in a):

            ans = i

            break

    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

# Thank God that I'm not you.

import bisect

from collections import Counter, deque

import heapq

import itertools

import math

import random

import sys

from types import GeneratorType;

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

                    to = stack[-1].send(to)

            return to

    return wrappedfunc

def primeFactors(n):

    counter = Counter();

    while n % 2 == 0:

        counter[2] += 1;

        n = n / 2

    for i in range(3,int(math.sqrt(n))+1,2):

        while n % i== 0:

            counter[i] += 1;

            n = n / i

    if (n > 2):

        counter[n] += 1;

    return counter;

n = int(input())

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

hashMap = {}

for i in range(n):

    currentSum = 0

    for x in range(i, n):

        currentSum += array[x]

        left, right = i, x;

        if currentSum not in hashMap:

            hashMap[currentSum] = [[[left, right], 1]]

        else:

            currentMax = 0

            for (leftOne, rightOne), cnt in hashMap[currentSum]:

                if (rightOne) < left:

                    currentMax = max(currentMax, cnt)

            hashMap[currentSum].append([[left, right], currentMax + 1])

currentMax, sumAss = 1, None;

for sumElems in hashMap:

    for _, cnt in hashMap[sumElems]:

        if cnt >= currentMax:

            currentMax = cnt;

            sumAss = sumElems;

lastSegment = None;

result = []

for segment, cnt in hashMap[sumAss][::-1]:

    if not currentMax:

        break;

    if cnt == currentMax:

        if lastSegment is None:

            lastSegment = segment;

            result.append(segment);

            currentMax -= 1

            continue

        leftOne, rightOne = lastSegment

        leftTwo, rightTwo = segment

        if leftOne > rightTwo:

            lastSegment = segment

            result.append(segment)

            currentMax -= 1

print(len(result))

for left, right in result:

    print(left + 1, right + 1)


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.

n=int(input())

for i in range(n):

    print(1,int(input())-1)


import sys

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

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

cur = [[0] * n for _ in range(2)]

blocked_c = 0

for _ in range(q):

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

    x -= 1

    y -= 1

    nx = x ^ 1

    if cur[x][y] == 0:

        delta = 1

    else:

        delta = -1

    cur[x][y] ^= 1

    for ny in range(y - 1, y + 2):

        if 0 <= ny < n:

            if cur[nx][ny] == 1:

                blocked_c += delta

    if blocked_c:

        print('No')

    else:

        print('Yes')


T = 1

for test_no in range(T):

    x0, y0, ax, ay, bx, by = map(int, input().split())

    xs, ys, t = map(int, input().split())

    LIMIT = 2 ** 62 - 1

    x, y = [x0], [y0]

    while ((LIMIT - bx) / ax >= x[-1] and (LIMIT - by) / ay >= y[-1]):

        x.append(ax * x[-1] + bx)

        y.append(ay * y[-1] + by)

    n = len(x)

    ans = 0

    for i in range(n):

        for j in range(i, n):

            length = x[j] - x[i] + y[j] - y[i]

            dist2Left = abs(xs - x[i]) + abs(ys - y[i])

            dist2Right = abs(xs - x[j]) + abs(ys - y[j])

            if (length <= t - dist2Left or length <= t - dist2Right): ans = max(ans, j - i + 1)

    print(ans)


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

import heapq

import math

import os

from collections import Counter, deque, defaultdict

from sys import stdout

import time

from math import factorial, log, gcd

import sys

from decimal import Decimal

import threading

from heapq import *

import random

def S():

    return sys.stdin.readline().split()

def I():

    return [int(i) for i in sys.stdin.readline().split()]

def II():

    return int(sys.stdin.readline())

def IS():

    return sys.stdin.readline().replace('\n', '')

def main():

    n = II()

    s = IS()

    d = dict([(chr(i + 1), chr(i)) for i in range(ord('a'), ord('z'))])

    c = Counter(s)

    ans = 0

    while True:

        flag = False

        for i in range(ord('z'), ord('a'), -1):

            mx = chr(i)

            if flag:

                break

            if c[mx] > 0:

                for j in range(n):

                    if s[j] == mx:

                        if (j > 0 and s[j - 1] == d[mx]) or (j < n - 1 and s[j + 1] == d[mx]):

                            if 0 < j < n - 1:

                                s = s[:j] + s[j + 1:]

                            elif j == 0:

                                s = s[1:]

                            else:

                                s = s[:-1]

                            flag = True

                            ans += 1

                            n -= 1

                            break

        if not flag:

            break

    print(ans)

if __name__ == '__main__':

    # for _ in range(II()):

    #     main()

    main()


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.

n=int(input())
l=list(map(int,input().split()));su=0;ans=[]
for i in range(n):
    t=l[::]
    for j in range(i-1,-1,-1):t[j]=min(t[j],t[j+1])
    for j in range(i+1,n):t[j]=min(t[j],t[j-1])
    if sum(t)>su:
        su=sum(t);ans=t
print(*ans)


D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

import sys, threading

import math

from os import path

from collections import defaultdict, Counter, deque

from bisect import *

from string import ascii_lowercase

from functools import cmp_to_key

import heapq

def readInts():

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

    return x[0] if len(x) == 1 else x

def readList(type=int):

    x = sys.stdin.readline()

    x = list(map(type, x.rstrip('\n\r').split()))

    return x

def readStr():

    x = sys.stdin.readline().rstrip('\r\n')

    return x

write = sys.stdout.write

read = sys.stdin.readline

MAXN = 1123456

class mydict:

    def __init__(self, func):

        self.random = randint(0, 1 << 32)

        self.default = func

        self.dict = {}

    def __getitem__(self, key):

        mykey = self.random ^ key

        if mykey not in self.dict:

            self.dict[mykey] = self.default()

        return self.dict[mykey]

    def get(self, key, default):

        mykey = self.random ^ key

        if mykey not in self.dict:

            return default

        return self.dict[mykey]

    def __setitem__(self, key, item):

        mykey = self.random ^ key

        self.dict[mykey] = item

    def getkeys(self):

        return [self.random ^ i for i in self.dict]

    def __str__(self):

        return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'

def lcm(a, b):

    return (a*b)//(math.gcd(a,b))

def mod(n):

    return n%(10**9 + 7)

def upper_bound(a, num):

    l = 0

    r = len(a)-1

    ans = -1

    while l <= r:

        mid = (l+r)//2

        if a[mid] >= num:

            ans = mid

            r = mid-1

        else:

            l = mid+1

    return ans

def solve(t):

    # print(f'Case #{t}: ', end = '')

    u, v = readInts()

    res = []

    uc = u

    vc = v

    if u&1 != v&1 or u > v:

        print(-1)

        return

    # print(*xr, sep='')

    # print(*sr, sep='')

    res = [0 for _ in range(64)]

    if uc&1 and vc&1:

        res[0] += 1

    for i in range(1, 64):

        if not vc&(1 << (i-1)) and vc&(1<<(i-1)) != uc&(1<<(i-1)):

            # res[i-1] = 1

            vc -= (1<<i)

            if vc < 0:

                break

        if uc&(1 << i) != vc&(1 << i):

            if res[i-1] < 2:

                res[i-1] += 2

        if uc&(1<<i):

            res[i] = 1

        else:

            res[i] = 0

    # print(res)

    # print(*sr, sep='')

    ans = [0, 0, 0]

    for i in range(64):

        j = 0

        while res[i] > 0:

            ans[j] += 1<<i

            res[i] -= 1

            j += 1

    # print(ans)

    ans2 = []

    for num in ans:

        if num > 0:

            ans2.append(num)

            # print(bin(num)[2:][::-1])

    print(len(ans2))

    if len(ans2) > 0:

        print(*ans2)

def main():

    t = 1

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

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

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

    # sys.setrecursionlimit(10**5)

    # t = readInts()

    # print('here')

    for i in range(t):

        solve(i+1)

if __name__ == '__main__':

    main()


# watchu lookin at?

import sys

from math import *

# from itertools import *

# from heapq import heapify, heappop, heappush

# from bisect import bisect, bisect_left, bisect_right

from collections import deque, Counter, defaultdict as dd

mod = 10**9+7

abc = "abcdefghijklmnopqrstuvwxyz"

# Sangeeta Singh

def input(): return sys.stdin.readline().rstrip("\r\n")

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

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

def rls(): return list(map(str, input().split()))

def isPowerOfTwo(x): return (x and (not(x & (x - 1))))

def lcm(x, y): return (x*y)//gcd(x, y)

def alpha(x): return ord(x)-ord('A')

def gcd(x, y):

    while y:

        x, y = y, x % y

    return x

def d2b(n):

    s = bin(n).replace("0b", "")

    return (34-len(s))*'0'+s

def highestPowerof2(x):

    x |= x >> 1

    x |= x >> 2

    x |= x >> 4

    x |= x >> 8

    x |= x >> 16

    return x ^ (x >> 1)

def nextPowerOf2(N):

    if not (N & (N - 1)):

        return N

    return int("1" + (len(bin(N)) - 2) * "0", 2)

def isPrime(x):

    if x == 1:

        return False

    if x == 2:

        return True

    for i in range(2, int(x ** 0.5) + 1):

        if x % i == 0:

            return False

    return True

def factors(n):

    i = 1

    ans = []

    while i <= sqrt(n):

        if (n % i == 0):

            if (n / i != i):

                ans.append(int(n/i))

            if i != 1:

                ans.append(i)

        i += 1

    return ans

Primes = [1] * 100001

primeNos = []

def SieveOfEratosthenes(n):

    p = 2

    while (p * p <= n):

        if (Primes[p]):

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

                Primes[i] = 0

        p += 1

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

        if Primes[p]:

            primeNos.append(p)

# SieveOfEratosthenes(100000)

# P = len(primeNos)

# print("P", P)

def ncr(n, r):

    ans = 1

    while(r):

        ans *= n

        ans %= mod

        n -= 1

        r -= 1

    return ans

############ Main! #############

# mod = 998244353

def skyScrapper(ind, a, n):

    ans = [0]*n

    ans[ind] = a[ind]

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

        ans[i] = min(ans[i-1], a[i])

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

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

    return [sum(ans), ans]

def sangee():

    n = ri()

    a = rl()

    k = 0

    ans = []

    for i in range(n):

        ans.append(skyScrapper(i, a, n))

    m = max(ans)

    print(*m[1])

    # print(ans)

t = 1

for _ in range(t):

    sangee()


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

#from sys import stdin

#input = stdin.readline

#// - remember to add .strip() when input is a string

n = int(input())

lets = list(input().strip())

a = []

b = []

binary_ans = []

flag = True

for i in lets:

  if len(a) == 0:

    a.append(i)

    binary_ans.append("0")

  elif i >= a[-1]:

    a.append(i)

    binary_ans.append("0")

  elif len(b) == 0:

    b.append(i)

    binary_ans.append("1")

  elif i >= b[-1]:

    b.append(i)

    binary_ans.append("1")

  else:

    flag = False

    break

if flag:

  print("YES")

  print("".join(binary_ans))

else:

  print("NO")


B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.

t = int(input())

for _ in range(t):

    n, g, b = map(int, input().split())

    half = (n+1) // 2 # nice way to get ceiling

    # ans = multipler * block of g+b days + remainder g days

    remainder = half % g

    ans = (half//g) * (g+b) + remainder

    if remainder == 0: # remove bad days excess

        ans -= b

    print(max(ans, n))


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

    n,g,b=map(int,input().split())

    l=0

    h=10**19

    def check(x):

        tg=(x//(g+b))*g

        tb=(x//(g+b))*b

        x=(x%(g+b))

        if x<=g:

            tg+=x

        else:

            tg+=g

            tb+=x-g

        if tg>=(n+1)//2:

            left=n-tg

            if left<=tb and left<=(n+1)//2:

                return True

            return False

        return False

    while l<=h:

        mid=(l+h)//2

        if check(mid):

            ans=mid

            h=mid-1

        else:

            l=mid+1

    print(ans)


A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands:  'L' (Left) sets the position x:=x−1x:=x−1;  'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully):   "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00;  "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well;  "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.

n = int(input())
args = input()
print(args.count('L') + args.count('R') + 1)


A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

n = int(input())

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

temp = []

store = {}

res = 0

for i in range(n):

    group = i - arr[i]

    temp.append(group)

    if group not in store:

        store[group] = arr[i]

    else:

        store[group] += arr[i]

    res = max(res, store[group])

print(res)


C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.

t=int(input())

for test in range(t):

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

    r=(n-m)%(m+1)

    d=(n-m)//(m+1)

    ans=(n-m+r)*(d+1)

    print((n*(n+1) - ans)//2)


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

import sys

input=sys.stdin.readline

t=int(input())

for _ in range(t):

    arr=list(input().split())

    n=int(arr[0])

    s=arr[1]

    r=[1]

    l=[1]

    c=0

    for i in range(n-1):

        if s[i]=='<':

            r[-1]+=1

            l.append(1)

        else:

            l[-1]+=1

            r.append(1)

    ans1=[0 for _ in range(n)]

    ans2=[0 for _ in range(n)]

    p=n

    p2=0

    for i in range(len(r)):

        for j in range(r[i]):

            ans1[p2]=p-r[i]+1+j

            p2+=1

        p-=r[i]

    p=1

    p2=0

    for i in range(len(l)):

        for j in range(l[i]):

            ans2[p2]=p+l[i]-1-j

            p2+=1

        p+=l[i]

    print(' '.join(map(str,ans1)))

    print(' '.join(map(str,ans2)))


D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that:  each array contains nn elements;  each element is an integer from 11 to mm;  for each array, there is exactly one pair of equal elements;  for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are:  [1,2,1][1,2,1];  [1,3,1][1,3,1];  [1,4,1][1,4,1];  [2,3,2][2,3,2];  [2,4,2][2,4,2];  [3,4,3][3,4,3].

import sys

from math import *

from collections import defaultdict

inp = lambda: sys.stdin.buffer.readline().decode().strip()

out=sys.stdout.write

# n=int(inp())

# arr=list(map(int,inp().split()))

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

mod= 998244353

fact=[1]*(m+1)

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

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

def modi(x,pri1):

    return fast_exp(x,pri1-2,pri1)

def ncr(n,r,pri1):

    return ((fact[n]*modi(fact[r],pri1))%pri1)*((modi(fact[n-r],pri1))%pri1)%pri1

def fast_exp(x,n,mod):

    ans=1

    while n>0:

        if n%2==1:

            ans=(ans*x)%mod

            n-=1

        x=(x*x)%mod

        n //= 2

    return ans

ans=ncr(m,n-1,mod)*(n-2)*fast_exp(2,n-3,mod)

ans%=mod

print(ans)


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

import copy

import random

import heapq

import math

import sys

import bisect

import datetime

from functools import lru_cache

from collections import deque

from collections import Counter

from collections import defaultdict

from itertools import combinations

from itertools import permutations

from types import GeneratorType

from functools import cmp_to_key

from functools import reduce

from operator import xor

from operator import mul

from operator import add

from decimal import Decimal

from heapq import nlargest

inf = float("inf")

class FastIO:

    def __init__(self):

        return

    @staticmethod

    def _read():

        return sys.stdin.readline().strip()

    def read_int(self):

        return int(self._read())

    def read_float(self):

        return float(self._read())

    def read_ints(self):

        return map(int, self._read().split())

    def read_floats(self):

        return map(float, self._read().split())

    def read_ints_minus_one(self):

        return map(lambda x: int(x) - 1, self._read().split())

    def read_list_ints(self):

        return list(map(int, self._read().split()))

    def read_list_floats(self):

        return list(map(float, self._read().split()))

    def read_list_ints_minus_one(self):

        return list(map(lambda x: int(x) - 1, self._read().split()))

    def read_str(self):

        return self._read()

    def read_list_strs(self):

        return self._read().split()

    def read_list_str(self):

        return list(self._read())

    @staticmethod

    def st(x):

        return sys.stdout.write(str(x) + '\n')

    @staticmethod

    def lst(x):

        return sys.stdout.write(" ".join(str(w) for w in x) + '\n')

    @staticmethod

    def round_5(f):

        res = int(f)

        if f - res >= 0.5:

            res += 1

        return res

    @staticmethod

    def max(a, b):

        return a if a > b else b

    @staticmethod

    def min(a, b):

        return a if a < b else b

    @staticmethod

    def bootstrap(f, stack=[]):

        def wrappedfunc(*args, **kwargs):

            if stack:

                return f(*args, **kwargs)

            else:

                to = f(*args, **kwargs)

                while True:

                    if isinstance(to, GeneratorType):

                        stack.append(to)

                        to = next(to)

                    else:

                        stack.pop()

                        if not stack:

                            break

                        to = stack[-1].send(to)

                return to

        return wrappedfunc

def main(ac=FastIO()):

    n = ac.read_int()

    a = ac.read_list_ints()

    t = ac.read_list_ints()

    lst = [[a[i], t[i]] for i in range(n)]

    del a

    del t

    lst.sort(key=lambda it: [it[0], -it[1]])

    stack = []

    total = ans = 0

    cur = -1

    i = 0

    while i < n or stack:

        if not stack:

            cur = lst[i][0]

        while i < n and lst[i][0] == cur:

            heapq.heappush(stack, -lst[i][1])

            total += lst[i][1]

            i += 1

        total += heapq.heappop(stack)

        ans += total

        cur += 1

    ac.st(ans)

    return

main()


E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:  if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100];  if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then:  erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union;  erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5

import sys

input = sys.stdin.readline

from itertools import accumulate

import random

t=int(input())

for testcases in range(t):

    n=int(input())

    S=[list(map(int,input().split())) for i in range(n)]

    compression_list=[]

    for l,r in S:

        compression_list.append(l)

        compression_list.append(r)

    compression_dict={a: ind for ind, a in enumerate(sorted(set(compression_list)))}

    for i in range(n):

        S[i][0]=compression_dict[S[i][0]]*2

        S[i][1]=compression_dict[S[i][1]]*2

    LEN=len(compression_dict)*2

    R=[0]*(LEN+1)

    for l,r in S:

        R[l]+=1

        R[r+1]-=1

    SR=list(accumulate(R))

    NOW=0

    for i in range(LEN):

        if SR[i]!=0 and SR[i+1]==0:

            NOW+=1

    ONECOUNT=[0]*(LEN+1)

    for i in range(1,LEN):

        if SR[i-1]!=1 and SR[i]==1:

            ONECOUNT[i]+=1

    SO=list(accumulate(ONECOUNT))

    SO.append(0)

    ANS=1

    for l,r in S:

        lr=0

        if SR[r]==1:

            lr-=1

        ANS=max(ANS,NOW+SO[r-1]-SO[l]+lr)

    print(ANS)


E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:

from sys import stdin, stdout

import __pypy__

def main():

    T = int(stdin.readline())

    for _ in range(T):

        a,b = list(map(int, stdin.readline().split()))

        a -= 1

        mx = int(a*(a+1)/2)

        mn = 0

        tmp = a

        pw = 1

        while (tmp > 0):

            c = int(pw * pow(2, pw))

            cc = int(pow(2,pw))

            if tmp >= cc:

                tmp -= cc

                mn += c

            else:

                mn += pw*tmp

                tmp = 0

            pw +=1

        if b < mn or b > mx:

            stdout.write("NO\n")

            continue

        else:

            stdout.write("YES\n")

            slot = [1] * a

            mn = 0

            cur = mx

            while len(slot) - (mn+1) > 0 and cur > b:

                #print(slot)

                if pow(2,(mn+1)) == slot[mn]:

                    mn+=1

                if len(slot) - (mn+1) <= 0:

                    break

                cur -= len(slot) - (mn+1)

                slot.pop()

                if cur < b:

                    mn += b - cur

                slot[mn] += 1

            ans = __pypy__.builders.StringBuilder()

            cur_num = 2

            last_row = [1]

            for x in slot:

                row = []

                count = 0

                pos = 0

                for z in range(x):

                    row.append(cur_num)

                    cur_num += 1

                    ans.append("%d "%last_row[pos])

                    count += 1

                    if count == 2:

                        count = 0

                        pos +=1

                last_row = row

            print(ans.build())

main()


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

from sys import stdout

def req(l, r, k=0):

    print('?', l, r)

    v = [''.join(sorted(input())) for i in range((r - l + 1) * (r - l + 2) // 2)]

    stdout.flush()

    return v

def compute(v):

    bukvi = [[0] * (n + 2) for _ in range(26)]

    for el in v:

        cur = len(el)

        for e in el:

            bukvi[ord(e) - ord('a')][cur] += 1

    return bukvi

def compute2(bukvi):

    bukvis = [[] for _ in range(26)]

    for i in range(26):

        prev = bukvi[i][1]

        for j in range(1, n // 2 + n % 2 + 1):

            while bukvi[i][j] != prev:

                bukvis[i].append(j)

                prev -= 1

    return bukvis

def main():

    va = req(1, n)

    # va2 = req(1, n // 2)

    # va3 = req(n - n // 2 + 1, n)

    # bukvi = compute(va)

    # bukvi2 = compute(va2)

    # bukvi3 = compute(va3)

    if n == 1:

        print('!', va[0][0])

        return

    va2 = req(2, n)

    for i in va2:

        va.remove(i)

    va.sort(key=len)

    print('!', va[0], end='')

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

        for j in range(26):

            if va[i].count(chr(ord('a') + j)) != va[i - 1].count(chr(ord('a') + j)):

                print(chr(ord('a') + j), end='')

    print()

n = int(input())

main()


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.

import sys, random
input = lambda : sys.stdin.readline().rstrip()

write = lambda x: sys.stdout.write(x+"\n"); writef = lambda x: print("{:.12f}".format(x))
debug = lambda x: sys.stderr.write(x+"\n")
YES="Yes"; NO="No"; pans = lambda v: print(YES if v else NO); INF=10**18
LI = lambda : list(map(int, input().split())); II=lambda : int(input()); SI=lambda : [ord(c)-ord("a") for c in input()]
def debug(_l_):
    for s in _l_.split():
        print(f"{s}={eval(s)}", end=" ")
    print()
def dlist(*l, fill=0):
    if len(l)==1:
        return [fill]*l[0]
    ll = l[1:]
    return [dlist(*ll, fill=fill) for _ in range(l[0])]

n = int(input())
a = list(map(int, input().split()))
odd = (n+1)//2
even = n//2
num = 0
for v in a:
    if v==0:
        num += 1
    else:
        if v%2:
            odd -= 1
        else:
            even -= 1
dp = [[INF]*(odd+1) for _ in range(2)]
dp[0][0] = dp[1][0] = 0
for v in a:
    ndp = [[INF]*(odd+1) for _ in range(2)]
    for i in range(odd+1):
        if v==0:
            ndp[0][i] = min(dp[0][i], dp[1][i]+1)
            if i>0:
                ndp[1][i] = min(dp[0][i-1]+1, dp[1][i-1])
        elif v%2==1:
            ndp[0][i] = INF
            ndp[1][i] = min(dp[0][i]+1, dp[1][i])
        else:
            ndp[0][i] = min(dp[0][i], dp[1][i]+1)
            ndp[1][i] = INF
    dp = ndp
#     print(dp)
ans = min(dp[0][odd], dp[1][odd])
print(ans)


A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.

import sys

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

from collections import deque, Counter, OrderedDict, defaultdict

from heapq import heapify, heappush, heappop

#from sortedcontainers import SortedList

#sys.setrecursionlimit(10**5)

from functools import lru_cache

#@lru_cache(None)

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

input = lambda: sys.stdin.readline()

I = lambda: int(input().strip())

S = lambda: input().strip()

M = lambda: map(int,input().strip().split())

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

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

def bs(arr,x):

    low,high = 0,len(arr)-1

    ans = len(arr)

    while low<=high:

        mid = (low+high)//2

        #if arr[mid]==x:

        #    return x

        if arr[mid]<x:

            low = mid+1

        else:

            high = mid-1

            ans = mid

    return ans

def addd(arr,x):

    t = bs(arr,x)

    ans = []

    if t!=0:

        ans = arr[:t]

    ans.append(x)

    if t!=len(arr):

        ans.extend(arr[t:])

    return ans

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

def factorial_inverse():

    mod=10**9+7

    upto=(10**3)*2+1

    nfactorial=[1 for i in range(upto)]

    ninverse=[1 for i in range(upto)]

    finverse=[1 for i in range(upto)]

    for i in range(2,upto):

        nfactorial[i]=(nfactorial[i-1]*i)%mod

        ninverse[i]=(-(mod//i)*ninverse[mod%i])%mod

        finverse[i]=(finverse[i-1]*ninverse[i])%mod

    return nfactorial,finverse

def nCk(n,k):

    if n<0 or k<0:

        return 0

    if k>n:

        return 0

    return ((nfactorial[n]*finverse[k]%mod)*finverse[n-k])%mod

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

def primelist():

    L = [False for i in range((10**10)+1)]

    primes = [False for i in range((10**10)+1)]

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

        if not L[i]:

            primes[i]=True

            for j in range(i,(10**10)+1,i):

                L[j]=True

    return primes

def isPrime(n):

    p = primelist()

    return p[n]

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

def bst(arr,x):

    low,high = 0,len(arr)-1

    ans = -1

    while low<=high:

        mid = (low+high)//2

        if arr[mid]==x:

            return x

        if arr[mid]<x:

            low = mid+1

            ans = mid

        else:

            high = mid-1

    return ans

def factors(x):

    l1 = []

    l2 = []

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

        if x%i==0:

            if (i*i)==x:

                l1.append(i)

            else:

                l1.append(i)

                l2.append(x//i)

    for i in range(len(l2)//2):

        l2[i],l2[len(l2)-1-i]=l2[len(l2)-1-i],l2[i]

    return l1+l2

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

def power(n,x):

    if x==0:

        return 1

    k = (10**9)+7

    if n==1:

        return 1

    if x==1:

        return n

    ans = power(n,x//2)

    if x%2==0:

        return (ans*ans)%k

    return (ans*ans*n)%k

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

def f(b):

    a = p[:]

    b = format(b,'b')

    for i in range(len(b)):

        if b[len(b)-1-i]=='1':

            a[31-i]-=1

    ans = []

    for i in a:

        if i>0:

            ans.append("1")

        else:

            ans.append("0")

    b = int(b,2)

    return b-(int("".join(ans),2)&b)

n = I()

a = L()

p = [0 for i in range(32)]

for i in a:

    b = format(i,'b')

    for j in range(len(b)):

        if b[len(b)-1-j]=='1':

            p[31-j]+=1

t = 0

q = f(a[0])

for i in range(1,n):

    if f(a[i])>q:

        t = i

        q = f(a[i])

a[0],a[t] = a[t],a[0]

print(*a)


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

import bisect

length = int(input())

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

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

for i in range(length):

    num1[i] -= num2[i]

num1.sort()

count = 0

for i in range(length):

    if num1[i] <= 0:

        count += length - bisect.bisect(num1, abs(num1[i]))

    else:

        count += length - i-1

print(count)


C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets:   a occurs at (1)(1), (2)(2), (3)(3)  b occurs at (4)(4), (5)(5)  ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5)  aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3)  bb occurs at (4,5)(4,5)  aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4)  aaa occurs at (1,2,3)(1,2,3)  abb occurs at (3,4,5)(3,4,5)  aaab occurs at (1,2,3,4)(1,2,3,4)  aabb occurs at (2,3,4,5)(2,3,4,5)  aaabb occurs at (1,2,3,4,5)(1,2,3,4,5)  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

def update(s,aa,ans):

    for r in range(26):

        if r!=s:

            ans[s][r]+=aa[r]

        else:

            ans[s][r]+=(aa[r]-1)

    return

a=input()

aa=[0]*26

fans=0

ans=[[0]*26 for i in range(26)]

for i in a:

    aa[ord(i)-ord('a')]+=1

    update((ord(i)-ord('a')),aa,ans)

for i in range(26):

    for j in range(26):

        fans=max(fans,ans[i][j])

    fans=max(fans,aa[i])

print(fans)


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

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

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

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

        solve()


from bisect import bisect
from operator import sub
def get(f): return f(input().strip())
def gets(f): return [*map(f, input().split())]

n = get(int)
a = gets(int)
b = gets(int)
d = sorted(map(sub, a, b))
s = 0
for i, v in enumerate(d):
    s += n - bisect(d, -v, i + 1)
print(s)


B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened;  The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.

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

    n = int(input())

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

    i = n

    j = -1

    for k in range(n):

        if a[k] < k:

            break

        j = k

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

        if a[k] < (n-k-1):

            break

        i = k

    if j >= i:

        print('YES')

    else:

        print('NO')


A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.

a = int(input())

for i in range(a):

    q = int(input())

    *s, = map(int, input().split(' '))

    d = 0

    for j in range(q):

        if s[j] == 0:

            d += 1

            s[j] = 1

    if sum(s) == 0:

        d += 1

    print(d)


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.

# ------------------- fast io --------------------

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

# ------------------- fast io --------------------

from collections import defaultdict

from types import GeneratorType

import sys

sys.setrecursionlimit(200001)

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

                    to = stack[-1].send(to)

            return to

    return wrappedfunc

def main():

    @bootstrap

    def dfs(u, fa):

        par[u] = fa

        dp[u] = 1 if a[u-1] == 1 else -1

        for v in adj[u]:

            if v != fa:

                yield dfs(v, u)

                if dp[v] > 0:

                    dp[u] += dp[v]

        yield

    @bootstrap

    def dfs2(u, fa):

        par[u] = fa

        for v in adj[u]:

            if v != fa:

                if res[u] > dp[v]:

                    if dp[v] < 0:

                        res[v] = res[u] + dp[v]

                    else:

                        res[v] = res[u]

                else:

                    res[v] = dp[v]

                yield dfs2(v, u)

        yield

    n = int(input())

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

    adj = defaultdict(list)

    for i in range(n - 1):

        u, v = map(int, input().split(' '))

        adj[u].append(v)

        adj[v].append(u)

    dp = [0] * (n + 1)

    par = [0] * (n + 1)

    res = [0] * (n + 1)

    dfs(1, 0)

    res[1] = dp[1]

    dfs2(1, 0)

    print(*res[1:])

main()