contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().split())) print(*sorted(arr, reverse = True))
py
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
def palindrome(a): n = len(a) for i in range(n - 2): for j in range(i + 2, n): if a[i] == a[j]: return True return False t = int(input()) for _ in range(t): input() a = list(map(int, input().split())) if palindrome(a): print("YES") else: print("NO")
py
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
[ "implementation", "math" ]
def get_sumDigit(n,base): sum_digits =0 #digits = [] while n>0: digit = n%base #digits.append(digit) sum_digits += digit n//=base #print(*digits[::-1],sep='') return sum_digits def gcd(a,b): if b==0: return a return gcd(b,a%b) n = int(input()) s=0 for i in range(2,n): s += get_sumDigit(n,i) great = gcd(s,n-2) print(s//great,'/',(n-2)//great,sep='')
py
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
def main(): n = int(input()) board = [] told = [] blocked = [] for r in range(1, n + 1): endings = list(map(int, input().split())) board.append([]) told.append([]) for i in range(0, 2 * n, 2): x, y = endings[i:i + 2] told[-1].append((x, y)) if x == r and y == i // 2 + 1: board[-1].append("X") blocked.append((x - 1, y - 1)) else: board[-1].append("") unvisited = [] #print(blocked) for bx, by in blocked: one_idx = (bx + 1, by + 1) if bx and told[bx - 1][by] == one_idx: board[bx - 1][by] = "D" unvisited.append((bx - 1, by)) if bx < n - 1 and told[bx + 1][by] == one_idx: board[bx + 1][by] = "U" unvisited.append((bx + 1, by)) if by and told[bx][by - 1] == one_idx: board[bx][by - 1] = "R" unvisited.append((bx, by - 1)) if by < n - 1 and told[bx][by + 1] == one_idx: board[bx][by + 1] = "L" unvisited.append((bx, by + 1)) #print(unvisited) z = 0 while z < len(unvisited): x, y = unvisited[z] if x and board[x - 1][y] == "" and told[x - 1][y] == told[x][y]: unvisited.append((x - 1, y)) board[x - 1][y] = "D" if x < n - 1 and board[x + 1][y] == "" and told[x + 1][y] == told[x][y]: unvisited.append((x + 1, y)) board[x + 1][y] = "U" if y and board[x][y - 1] == "" and told[x][y - 1] == told[x][y]: unvisited.append((x, y - 1)) board[x][y - 1] = "R" if y < n - 1 and board[x][y + 1] == "" and told[x][y + 1] == told[x][y]: unvisited.append((x, y + 1)) board[x][y + 1] = "L" z += 1 for i in range(n): for j in range(n): if board[i][j] == "": if told[i][j] != (-1, -1): print("INVALID") return if i and told[i - 1][j] == (-1, -1): board[i][j] = "U" continue if i < n - 1 and told[i + 1][j] == (-1, -1): board[i][j] = "D" continue if j and told[i][j - 1] == (-1, -1): board[i][j] = "L" continue if j < n - 1 and told[i][j + 1] == (-1, -1): board[i][j] = "R" continue print("INVALID") return print("VALID") for k in range(n): print("".join(board[k])) main()
py
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3
[ "data structures", "dsu" ]
import sys input = sys.stdin.readline n, m = map(int, input().split()) p = list(map(int, input().split())) LENGTH = 320 block = [i // LENGTH for i in range(n)] lompat = [0] * n akhir = [0] * n for i in range(n - 1, -1, -1): next = i + p[i] if next >= n: akhir[i] = i + n lompat[i] = 1 elif block[i] != block[next]: lompat[i] = 1 akhir[i] = next else: lompat[i] = lompat[next] + 1 akhir[i] = akhir[next] ans = [] for _ in range(m): s = input().strip() if s[0] == '0': a, b, c = s.split() b = int(b) - 1 c = int(c) p[b] = c i = b while i >= 0 and block[i] == block[b]: next = i + p[i] if next >= n: akhir[i] = i + n lompat[i] = 1 elif block[i] != block[next]: lompat[i] = 1 akhir[i] = next else: lompat[i] = lompat[next] + 1 akhir[i] = akhir[next] i -= 1 else: a, b = s.split() sekarang = int(b) - 1 total = 0 while sekarang < n: total += lompat[sekarang] sekarang = akhir[sekarang] ans.append(str(sekarang - n + 1) + ' ' + str(total)) print('\n'.join(ans))
py
1285
E
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
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
import io import os from collections import defaultdict # From: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size : _size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) class Node: def __init__(self, numClose, count, numOpen): self.close = numClose self.count = count self.open = numOpen neutral = Node(0, 0, 0) def combine(x, y): # Track numClose, numCount, numOpen: # e.g., )))) (...)(...)(...) (((((( if x.open == y.close == 0: ret = x.close, x.count + y.count, y.open elif x.open == y.close: ret = x.close, x.count + 1 + y.count, y.open elif x.open > y.close: ret = x.close, x.count, x.open - y.close + y.open elif x.open < y.close: ret = x.close + y.close - x.open, y.count, y.open return Node(*ret) def solve(N, intervals): OPEN = 0 CLOSE = 1 endpoints = [] for i, (l, r) in enumerate(intervals): endpoints.append((l, OPEN, i)) endpoints.append((r, CLOSE, i)) endpoints.sort(key=lambda t: t[1]) endpoints.sort(key=lambda t: t[0]) # Build the segment tree and track the endpoints of each interval in the segment tree data = [] idToIndices = defaultdict(list) for x, kind, intervalId in endpoints: if kind == OPEN: data.append(Node(0, 0, 1)) else: assert kind == CLOSE data.append(Node(1, 0, 0)) idToIndices[intervalId].append(len(data) - 1) assert len(data) == 2 * N segTree = SegmentTree(data, Node(0, 0, 0), combine) best = 0 for intervalId, indices in idToIndices.items(): # Remove the two endpoints i, j = indices removed1, removed2 = segTree[i], segTree[j] segTree[i], segTree[j] = neutral, neutral # Query res = segTree.query(0, 2 * N) assert res.open == 0 assert res.close == 0 best = max(best, res.count) # Add back the two endpoints segTree[i], segTree[j] = removed1, removed2 return best if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] intervals = [[int(x) for x in input().split()] for i in range(N)] ans = solve(N, intervals) print(ans)
py
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
from itertools import accumulate from math import ceil H, n = map(int, input().split()) nums = list(map(int, input().split())) prefixsum = list(accumulate(nums)) # find the min elmnt the_min = -min(prefixsum) last_change = -prefixsum[-1] # calculate the iteration turns = 0 if H > the_min and prefixsum[-1] < 0: turns = ceil((H - the_min)/last_change) # print(turns) H -= last_change * turns ans = turns * n # print(H) for num in nums: ans += 1 H += num if H <= 0: break if H <= 0: print(ans) else: print(-1)
py
1292
F
F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,…,ana1,a2,…,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai∣ajai∣aj and ai∣akai∣ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3≤n≤603≤n≤60), denoting the number of boxes.The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤601≤ai≤60), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3 2 6 8 OutputCopy2 InputCopy5 2 3 4 9 12 OutputCopy4 InputCopy4 5 7 2 9 OutputCopy1 NoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]−→−−(1,3,2)[2,8][2,6,8]→(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]−→−−(1,2,3)[2,6][2,6,8]→(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,3,4)[2,3,4][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,3,4)[2,3,9][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]−→−−(1,5,3)[2,3,9,12]−→−−(2,4,3)[2,3,12][2,3,4,9,12]→(1,5,3)[2,3,9,12]→(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]−→−−(2,5,4)[2,3,4,12]−→−−(1,4,3)[2,3,12][2,3,4,9,12]→(2,5,4)[2,3,4,12]→(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.
[ "bitmasks", "combinatorics", "dp" ]
MOD = 1000000007 def isSubset(a, b): return (a & b) == a def isIntersect(a, b): return (a & b) != 0 # Solve for each weakly connected component (WCC) def cntOrder(s, t): p = len(s) m = len(t) inMask = [0 for i in range(m)] for x in range(p): for i in range(m): if t[i] % s[x] == 0: inMask[i] |= 1 << x cnt = [0 for mask in range(1<<p)] for mask in range(1<<p): for i in range(m): if isSubset(inMask[i], mask): cnt[mask] += 1 dp = [[0 for mask in range(1<<p)] for k in range(m+1)] for i in range(m): dp[1][inMask[i]] += 1 for k in range(m): for mask in range(1<<p): for i in range(m): if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask): dp[k+1][mask | inMask[i]] = (dp[k+1][mask | inMask[i]] + dp[k][mask]) % MOD dp[k+1][mask] = (dp[k+1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD return dp[m][(1<<p)-1] def dfs(u): global a, graph, degIn, visited, s, t visited[u] = True if degIn[u] == 0: s.append(a[u]) else: t.append(a[u]) for v in graph[u]: if not visited[v]: dfs(v) def main(): global a, graph, degIn, visited, s, t # Reading input n = int(input()) a = list(map(int, input().split())) # Pre-calculate C(n, k) c = [[0 for j in range(n)] for i in range(n)] for i in range(n): c[i][0] = 1 for j in range(1, i+1): c[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD # Building divisibility graph degIn = [0 for u in range(n)] graph = [[] for u in range(n)] for u in range(n): for v in range(n): if u != v and a[v] % a[u] == 0: graph[u].append(v) graph[v].append(u) degIn[v] += 1 # Solve for each WCC of divisibility graph and combine result ans = 1 curLen = 0 visited = [False for u in range(n)] for u in range(n): if not visited[u]: s = [] t = [] dfs(u) if len(t) > 0: sz = len(t) - 1 cnt = cntOrder(s, t) # Number of orders for current WCC ans = (ans * cnt) % MOD # Number of ways to insert <sz> number to array of <curLen> elements ans = (ans * c[curLen + sz][sz]) % MOD curLen += sz print(ans) if __name__ == "__main__": main()
py
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
import sys input = sys.stdin.buffer.readline from collections import deque def radix_sort(a): l = len(a) mx = max(a) m = 0 while mx > 0: mx = mx // 10 m += 1 bucket = [deque([]) for _ in range (10)] for j in range (m): div = pow(10, j) for i in range (l): bucket[(a[i]//div)%10].append(a[i]) a *= 0 for i in range (10): while len(bucket[i]) > 0: a.append(bucket[i].popleft()) N = int(input()) a = list(map(int, input().split())) res = 0 radix_sort(a) for k in range(max(a).bit_length(), -1, -1): z = 1 << k c = 0 j = jj = jjj = N - 1 for i in range(N): while j >= 0 and a[i] + a[j] >= z: j -= 1 while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1 while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1 c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj) res += z * (c & 1) for i in range(N): a[i] = min(a[i] ^ z, a[i]) a.sort() #print(res, a, c) print(res)
py
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
t = int(input()) for _ in range(t): m,n = map(int,input().split()) l = list(map(int,input().split())) p = list(map(int,input().split())) p.sort() d,c = 0,0 for i in range(n-1): if p[i]+1 == p[i+1]: if c == 0: x = p[i] y = p[i+1] c = 1 else: y = p[i+1] d = 1 else: if d == 0: x,y = p[i],p[i] l[x-1:y+1] = sorted(l[x-1:y+1]) d,c = 0,0 if d == 1: l[x-1:y+1] = sorted(l[x-1:y+1]) l[p[n-1]-1 : p[n-1]+1] = sorted(l[p[n-1]-1 : p[n-1]+1]) c = 0 for i in range(m-1): if l[i]>l[i+1]: c=1 break if c==1: print("NO") else: print("YES")
py
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
def main(): t = int(input()) anss = [0] * t for it in range(t): x, y, a, b = map(int, input().split()) d, m = divmod(y - x, a + b) anss[it] = d if m == 0 else -1 for ans in anss: print(ans) main()
py
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
[ "greedy", "implementation", "math" ]
n = int(input()) for i in range(n): p,q = [int(i) for i in input().split()] if p==q: print(0) elif p<q: diff = q-p if diff%2==0: print(2) else: print(1) elif p>q: diff = p-q if diff%2==0: print(1) else: print(2)
py
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3 4 9 5 10 42 9999999967 OutputCopy6 1 9999999966 NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
[ "math", "number theory" ]
def gcd(a, b): if a > b: a, b = b, a if b % a==0: return a return gcd(b % a, a) primes = [] for p in range(2, 10**5+1): is_prime = True for p2 in primes: if p2*p2 > p: break if p % p2==0: is_prime = False break if is_prime: primes.append(p) def factor(x): d = {} for p in primes: if p*p > x: break if x % p==0: c = 0 while x % p==0: c+=1 x = x//p d[p] = c if x > 1: d[x] = 1 return d def process(a, m): g = gcd(a, m) A = a//g M = m//g d = factor(M) answer = 1 for p in d: c = d[p] answer = answer*(p-1)*p**(c-1) return answer T = int(input()) for i in range(T): a, m = [int(x) for x in input().split()] print(process(a, m))
py
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
def solve(): n,q = (int(i) for i in input().split(" ")) arr = [[0,0] for i in range(n)] count = 1 for t in range(q): a,b = (int(i)-1 for i in input().split(" ")) d = 1 if arr[b][a]==1 else -1 arr[b][a] = 1 - arr[b][a] for dy in range(-1, 2): if b+dy>=0 and b+dy<n: if arr[b+dy][1-a]==1: count+=d if count==1: print("YES") else: print("NO") t = 1#int(input()) for _ in range(t): solve()
py
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,m,k=map(int,input().split()) if k>2*(m*(n-1)+n*(m-1)): print("NO") sys.exit(0) ans=[] cur=0 t=0 while(t<m-1): ans.append((1,'R')) t+=1 ans.append((n-1,'D')) ans.append((n-1,'U')) t=0 ans.append((m-1,'L')) while(t<n-1): ans.append((1, 'D')) t += 1 ans.append((m - 1, 'R')) ans.append((m - 1, 'L')) ans.append((n-1,'U')) fi=[] y=0 while(cur<k): a,b=ans[y] if a==0: y+=1 continue if a+cur<=k: fi.append(ans[y]) cur=cur+a else: fi.append((k-cur,b)) cur=k y+=1 print("YES") print(len(fi)) for i in range(len(fi)): print(*fi[i])
py
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
from sys import stdin input = stdin.readline #google = lambda : print("Case #%d: "%(T + 1) , end = '') inp = lambda : list(map(int,input().split())) def answer(): cost = 0 ans , cur = n , "?" for i in range(n - 2 , -1 , -1): if(s[i] != cur): cur = s[i] if(cur == 'A'):cost += a else:cost += b if(cost <= p): ans = i + 1 else:break return ans for T in range(int(input())): a , b , p = inp() s = input().strip() n = len(s) print(answer())
py
1325
F
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
from collections import Counter from collections import defaultdict import math import random import heapq as hq from math import sqrt import sys from functools import reduce # sys.setrecursionlimit(10000000) def input(): return sys.stdin.readline().strip() def iinput(): return int(input()) def tinput(): return input().split() def rinput(): return map(int, tinput()) def rlinput(): return list(rinput()) mod = int(1e9)+7 def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) # ---------------------------------------------------- def dfs(): parent = [0]*(n+1) # for cycles stk = [4] depth = [0]*(n+1) while len(stk) > 0: node = stk.pop() if depth[node] != 0: continue depth[node] = depth[parent[node]] + 1 for nd in gdup[node]: if depth[nd] == 0: stk.append(nd) parent[nd] = node elif depth[node] - depth[nd] + 1 >= want: cycle = [nd] curr = node while curr != nd: cycle.append(curr) curr = parent[curr] return cycle if __name__ == "__main__": n, m = rinput() gdup = defaultdict(list) want = int(math.ceil(math.sqrt(n))) for _ in range(m): u, v = rinput() gdup[u].append(v) gdup[v].append(u) # part 1 flag = False independent = set() setlen = 0 temp = sorted(gdup, key=lambda x: len(gdup[x])) visited = [False]*(n+1) for i in temp: if not visited[i]: independent.add(i) setlen += 1 if setlen == want: flag = True break visited[i] = True for nd in gdup[i]: visited[nd] = True if flag: print(1) print(*independent) # part 2 if not flag: cycle = dfs() print(2) print(len(cycle)) print(*cycle)
py
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
for _ in range(int(input())): n = int(input()) s = input() odd = [] for i in range(n): if (int(s[i]) % 2 != 0): odd.append(s[i]) if (len(odd) >= 2): print(''.join(odd[-2:])) else: print(-1)
py
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
t=int(input()) for k in range(t): nit,x,y=map(int,input().split()) print(max(1,min(nit,x+y-nit+1)),min(x+y-1,nit))
py
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
n=int(input()) s=input() for _ in range(len(s)): mx=0 ind=-1 for i in range(len(s)): a=-1 b=-1 if i>0: if ord(s[i-1])==ord(s[i])-1: a=i if i+1<len(s): if ord(s[i+1])==ord(s[i])-1: b=i if a==i or b==i: if ord(s[i])>mx: mx=ord(s[i]) ind=i if ind==-1: break else: s=s[:ind]+s[ind+1:] print(n-len(s))
py
1294
B
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 OutputCopyYES RUUURRRRUU NO YES RRRRUUU NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
[ "implementation", "sortings" ]
for _ in range(int(input())): n = int(input()) arr = [] for i in range(n): arr.append(tuple(map(int, input().split()))) arr.sort() valid = True path = ("R" * arr[0][0]) + ("U" * arr[0][1]) for i in range(1, n): if arr[i][1] - arr[i - 1][1] < 0: valid = False break path += ("R" * (arr[i][0] - arr[i - 1][0])) + ("U" * (arr[i][1] - arr[i - 1][1])) if valid: print("YES") print(path) else: print("NO")
py
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
import sys from array import array from collections import deque input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: [dtype(x) for x in input().split()] debug = lambda *x: print(*x, file=sys.stderr) ceil1 = lambda a, b: (a + b - 1) // b Mint, Mlong = 2 ** 31 - 1, 2 ** 63 - 1 out, tests = [], 1 class graph: def __init__(self, n): self.n = n self.gdict = [array('i') for _ in range(n + 1)] def add_edge(self, node1, node2): self.gdict[node1].append(node2) self.gdict[node2].append(node1) def subtree(self, root): queue, visit = deque([root]), array('b', [0] * (self.n + 1)) self.level, child = array('i', [0] * (self.n + 1)), array('i') self.par, visit[root] = array('i', [-1] * (self.n + 1)), True while queue: s = queue.popleft() for i1 in self.gdict[s]: if not visit[i1]: queue.append(i1) visit[i1], self.level[i1] = True, self.level[s] + 1 child.append(i1) self.par[i1] = s def lca_preprocess(self, root): self.subtree(root) self.lev = 21 self.table = [array('i', [-1] * (self.n + 1)) for _ in range(self.lev)] self.table[0] = self.par for i in range(1, self.lev): for node in range(1, self.n + 1): if self.table[i - 1][node] != -1: self.table[i][node] = self.table[i - 1][self.table[i - 1][node]] def lca(self, u, v): if self.level[v] < self.level[u]: u, v = v, u diff = self.level[v] - self.level[u] for i in range(self.lev): if (diff >> i) & 1: v = self.table[i][v] if u == v: return u for i in range(self.lev - 1, -1, -1): if self.table[i][u] != self.table[i][v]: u, v = self.table[i][u], self.table[i][v] return self.table[0][u] def get_dist(u, v): return g.level[u] + g.level[v] - g.level[g.lca(u, v)] * 2 for _ in range(tests): n = int(input()) g = graph(n) for i in range(n - 1): u, v = inp(int) g.add_edge(u, v) g.lca_preprocess(1) for i in range(int(input())): x, y, a, b, k = inp(int) dists = [get_dist(a, b), get_dist(a, x) + 1 + get_dist(y, b), get_dist(a, y) + 1 + get_dist(x, b)] for d in dists: if d <= k and (k - d) & 1 == 0: out.append('yes') break else: out.append('no') print('\n'.join(map(str, out)))
py
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
import sys zz=1 sys.setrecursionlimit(10**5) if zz: input=sys.stdin.readline else: sys.stdin=open('input.txt', 'r') sys.stdout=open('all.txt','w') di=[[-1,0],[1,0],[0,1],[0,-1]] def fori(n): return [fi() for i in range(n)] def inc(d,c,x=1): d[c]=d[c]+x if c in d else x def ii(): return input().rstrip() def li(): return [int(xx) for xx in input().split()] def fli(): return [float(x) for x in input().split()] def comp(a,b): if(a>b): return 2 return 2 if a==b else 0 def gi(): return [xx for xx in input().split()] def gtc(tc,ans): print("Case #"+str(tc)+":",ans) def cil(n,m): return n//m+int(n%m>0) def fi(): return int(input()) def pro(a): return reduce(lambda a,b:a*b,a) def swap(a,i,j): a[i],a[j]=a[j],a[i] def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) def gh(): sys.stdout.flush() def isvalid(i,j,n,m): return 0<=i<n and 0<=j<m def bo(i): return ord(i)-ord('a') def graph(n,m): for i in range(m): x,y=mi() a[x].append(y) a[y].append(x) t=1 uu=t def dfs(i,p=-1,c=-1): st=[(i,p,c)] vis={} while st: i,p,c=st[-1] if i in vis: st.pop() continue vis[i]=1 r=(c+1)%ans for j in a[i]: if j!=p: col[edge[i,j]]=r+1 st.append((j,i,r)) r=(r+1)%ans while t>0: t-=1 d={} n,k=mi() col=[0]*(n-1) d=[0]*(n+1) a=[[] for i in range(n+1)] edge={} for i in range(n-1): x,y=mi() d[x]+=1 d[y]+=1 edge[x,y]=i edge[y,x]=i a[x].append(y) a[y].append(x) p={} for i in range(1,n+1): inc(p,d[i]) r=[] for i in p: r.append([i,p[i]]) r.sort(reverse=True) ans=1 for i in range(len(r)): if k<r[i][1]: ans=r[i][0] break k-=r[i][1] print(ans) dfs(1) print(*col)
py
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
from sys import stdin input = stdin.readline from math import ceil inp = lambda : list(map(int,input().split())) """ we need n / 2 good days """ def answer(): x = n // 2 + (n % 2) y = x // g good = y * g bad = (y - 1) * b if(x % g): good += x % g bad += b req = max(0 , n - (good + bad)) return good + bad + req for T in range(int(input())): n , g , b = inp() print(answer())
py
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
# Time complexity: O(n) # Space complexity: O(n) # The solution iterates through each vertex and edge once O(n + m) # Then it iterates through each node it travels and its edge O(k + m) import math n, m = map(int, input().strip().split()) outadj = [set() for _ in range(n + 1)] inadj = [set() for _ in range(n + 1)] cost = [math.inf] * (n + 1) discovered = [False] * (n + 1) for _ in range(m): u, v = map(int, input().strip().split()) outadj[u].add(v) inadj[v].add(u) k = int(input()) path = list(map(int, input().strip().split())) src = path[0] dest = path[-1] q = [dest] cost[dest] = 0 discovered[dest] = True while len(q) != 0: u = q.pop(0) for v in inadj[u]: if discovered[v]: continue discovered[v] = True cost[v] = cost[u] + 1 q.append(v) minim = 0 maxim = 0 for i in range(k - 1): # if not the shortest path if cost[path[i]] - 1 != cost[path[i+1]]: minim += 1 maxim += 1 else: # find alternative shortest paths for v in outadj[path[i]]: if cost[path[i]] - 1 == cost[v] and v != path[i+1]: maxim += 1 break print(minim, maxim)
py
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
from 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 main(): n = int(input()) adj = [[] for _ in range(n)] for i in range(n - 1): u, v = readIntArr() u -= 1; v -= 1 adj[u].append((v, i)) adj[v].append((u, i)) m = int(input()) clues = [] for _ in range(m): u, v, g = readIntArr() u -= 1; v -= 1 clues.append((u, v, g)) clues.sort(key=lambda arr: arr[2], reverse=True) ans = [1] * (n - 1) # @bootstrap # def dfs(u, target): # if u == target: # yield 1 # for v, e in adj[u]: # if vi[v] == 0: # vi[v] = 1 # edges.append(e) # temp = (yield dfs(v, target)) # vi[v] = 0 # if temp == 1: # yield 1 # else: # edges.pop() # yield 0 # Avoid recursion nodedepth = [-1] * n parnode = [-1] * n paredge = [-1] * n st = [0] nodedepth[0] = 0 while st: u = st.pop() for v, e in adj[u]: if nodedepth[v] == -1: # not visited nodedepth[v] = nodedepth[u] + 1 parnode[v] = u paredge[v] = e st.append(v) # vi = [0] * n for u, v, g in clues: edges = [] # vi[u] = 1 # dfs(u, v) # vi[u] = 0 ok = False u2, v2 = u, v if nodedepth[u] > nodedepth[v]: u, v = v, u while nodedepth[u] < nodedepth[v]: edges.append(paredge[v]) v = parnode[v] while u != v: edges.append(paredge[u]) edges.append(paredge[v]) u = parnode[u]; v = parnode[v] for e in edges: if g >= ans[e]: ok = True ans[e] = g if not ok: print(-1) return oneLineArrayPrint(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(a, b): print('? {} {}'.format(a, b)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil import math # from math import floor,ceil # for Python2 for _abc in range(1): main()
py
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
# 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 # 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) ############ Main! ############# # mod = 998244353 def ncr(n, r): ans = 1 while(r): ans *= n ans %= mod n -= 1 r -= 1 return ans def sangee(): n = ri() tree = dd(list) ans = [-1]*(n-1) for i in range(n-1): x, y = rl() tree[x].append(i) tree[y].append(i) tree = sorted(tree.items(), key=lambda x: len(x[1]), reverse=True) val = 0 # print(tree) for node in tree: curr = node[1] # print(curr) for i in curr: if ans[i] == -1: ans[i] = val val += 1 # print(ans) print(*ans, sep="\n") for _ in range(1): # for _ in range(ri()): sangee()
py
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
def predictFeature(a,b): if a==b: return a else: if 'S' in (a,b): pass else: return 'S' if 'T' in (a,b): pass else: return 'T' return 'E' def hyperSet(n,k,l): d = {} for x in l: if x not in d: d[x]=1 else: d[x]+=1 ans = 0 for i in range(n): for j in range(n): if i!=j: w = '' for x in range(k): w += predictFeature(l[i][x],l[j][x]) # print(w) if w in d: c=0 if w==l[i]: c+=1 if w==l[j]: c+=1 ans += d[w]-c return ans//6 n,k = map(int,input().split()) l = [] for _ in range(n): l.append(input()) print(hyperSet(n,k,l))
py
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
import os,sys from random import randint, shuffle from io import BytesIO, IOBase from collections import defaultdict,deque,Counter from bisect import bisect_left,bisect_right from heapq import heappush,heappop from functools import lru_cache from itertools import accumulate, permutations import math # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # for _ in range(int(input())): # n = int(input()) # a = list(map(int, input().split())) # for _ in range(int(input())): # n = int(input()) # s = input() # ans = '' # for i in range(n): # if int(s[i]) % 2: # ans += s[i] # if len(ans) == 2: # break # if len(ans) == 2: # print(ans) # else: # print(-1) for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) l, r = 0, n - 1 while l < n and a[l] >= l: l += 1 while r >= 0 and a[r] >= n - 1 - r: r -= 1 if l > r + 1: print('YES') else: print('NO')
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
T = int(input()) for _ in range(T): n, x = map(int, input().split(' ')) ls = sorted(list(map(int, input().split(' ')))) if x in ls: print(1) elif ls[-1] > x: print(2) else: print((x + ls[-1] - 1) // ls[-1])
py
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4 7 5 5 7 OutputCopy5.666666667 5.666666667 5.666666667 7.000000000 InputCopy5 7 8 8 10 12 OutputCopy7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 InputCopy10 3 9 5 5 1 7 5 3 8 7 OutputCopy3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
[ "data structures", "geometry", "greedy" ]
import sys input = sys.stdin.buffer.readline n = int(input()) a = list(map(int, input().split())) stk = [] for x in a: s = x c = 1 while stk and stk[-1][0] * c >= s * stk[-1][1]: s += stk[-1][0] c += stk[-1][1] stk.pop() stk.append((s, c)) print(''.join('{}\n'.format(s / c) * c for s, c in stk))
py
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
for t in range(int(input())): a,b,p=map(int,input().split()) s=input() n=len(s) j,rj=0,0 pr='' for i in range(n-2,-1,-1): if s[i]!=pr: if s[i]=='A' and p>=a: p-=a elif s[i]=='B' and p>=b: p-=b else: rj=i+2 break pr=s[i] if rj==0: print(1) else: print(rj)
py
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
import sys input = sys.stdin.readline for _ in range(int(input())): n = int(input()) w = list(map(int, input().split())) s = set() c = 0 for i in range(n): if w[i] == -1: if i > 0 and w[i-1] != -1: s.add(w[i-1]) if i < n-1 and w[i+1] != -1: s.add(w[i+1]) else: if i > 0 and w[i-1] != -1: if abs(w[i]-w[i-1]) > c: c = abs(w[i] - w[i-1]) if i < n-1 and w[i+1] != -1: if abs(w[i]-w[i+1]) > c: c = abs(w[i]-w[i+1]) if len(s) == 0: print(c, 0) continue a = max(s) b = min(s) x = (a+b)//2 c = max(a-x, c) print(c, x)
py
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
# https://codeforces.com/problemset/problem/1288/C def f0(n, m): mod = int(1e9 + 7) c = 2 * m + 1 dp = [[0] * c for _ in range(n + 1)] dp[0][0] = 1 for i in range(n): # TODO 空间压缩 for j in range(c): for k in range(j, c): d = k - j s = (d + 1) * (d + 2) // 2 e = d + 1 e = 1 dp[i + 1][k] = (dp[i + 1][k] + e * dp[i][j]) % mod # for v in dp: print(v) return dp[-1][-1] def f1(n, m): # mod = int(1e9 + 7) def power(base, exp): val = 1 while exp: if exp & 1: val = val * base % mod base = base * base % mod exp >>= 1 return val a = b = c = 1 x = 2 * n * m y = 2 * m z = x - y for i in range(1, x + 1): a = a * i % mod if i == y: b = a if i == z: c = a ans = a ans = ans * power(b, mod - 2) % mod ans = ans * power(c, mod - 2) % mod return ans n, m = map(int, input().split()) print(f0(n, m))
py
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
from collections import deque,Counter,OrderedDict from math import * import sys import random from bisect import * from functools import reduce from sys import stdin from heapq import * import copy import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion def gcd(x,y): while y:x,y=y,x%y return x n = int(input()) s = input() left,right = s.count('('),s.count(')') if n%2==1 or (left!=right): print(-1) sys.exit() left,right=0,0 ans = 0 pre = [0 for i in range(len(s))] for i in range(len(s)): if s[i] == ')': pre[i]-=1 else: pre[i]+=1 pos=0 neg = False ans=0 for i in range(len(pre)): pos+=pre[i] if pos<0: ans+=1 neg = True if pos == 0 and neg==True: ans+=1 neg=False print(ans)
py
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
# 22:32- import sys input = lambda: sys.stdin.readline().strip() from collections import Counter,defaultdict def get_sums(A): sum1 = [] for i in range(len(A)): a,c = A[i] t = [0]*26 if not sum1 else sum1[-1][::] t[ord(a)-ord('a')]+=c sum1.append(t) return sum1 S = input() C = Counter(S) ans = 0 for k,v in C.items(): ans = max(ans,v,v*(v-1)//2) A=[] for c in S: if not A or c!=A[-1][0]: A.append([c,1]) else: A[-1][1]+=1 M = len(A) sum1 = get_sums(A) sum2 = get_sums(A[::-1])[::-1] chars = [chr(c) for c in range(ord('a'),ord('z')+1)] lib = defaultdict(int) for i,[a,c] in enumerate(A): for c1 in chars: if c1==a:continue lib[a+c1]+=c*sum2[i][ord(c1)-ord('a')] for k,v in lib.items(): ans = max(ans, v) print(ans)
py
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
[ "greedy", "implementation", "math" ]
import sys input = sys.stdin.readline output = sys.stdout.write def main(): tests = int(input().rstrip()) for i in range(tests): a, b = map(int, input().rstrip().split()) cond1 = a % 2 == 1 and b % 2 == 1 cond2 = a % 2 == 0 and b % 2 == 0 res = 1 if a == b: output('0') output('\n') continue elif a < b: if cond1 is True or cond2 is True: res += 1 else: if (cond1 is True or cond2 is True) is False: res += 1 output(str(res)) output('\n') if __name__ == '__main__': main()
py
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
import sys input = sys.stdin.buffer.readline from collections import deque def countingSort(arr, exp1): n = len(arr) output = [0] * (n) count = [0] * (10) for i in range(0, n): index = arr[i] // exp1 count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] i = n - 1 while i >= 0: index = arr[i] // exp1 output[count[index % 10] - 1] = arr[i] count[index % 10] -= 1 i -= 1 i = 0 for i in range(0, len(arr)): arr[i] = output[i] def radixSort(arr): max1 = max(arr) exp = 1 while max1 / exp >= 1: countingSort(arr, exp) exp *= 10 N = int(input()) a = list(map(int, input().split())) res = 0 a.sort() for k in range(max(a).bit_length(), -1, -1): z = 1 << k c = 0 j = jj = jjj = N - 1 for i in range(N): while j >= 0 and a[i] + a[j] >= z: j -= 1 while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1 while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1 c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj) res += z * (c & 1) for i in range(N): a[i] = min(a[i] ^ z, a[i]) radixSort(a) #print(res, a, c) print(res)
py
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
row1 = int(input()) for r1 in range(row1): l1 = input().split(' ') row2 = int(l1[0]) tem = int(l1[1]) a = tem b = tem t1 = 0 state = 0 for r2 in range(row2): l2 = input().split(' ') t2 = int(l2[0]) c = int(l2[1]) d = int(l2[2]) a = a+t1-t2 b = b+t2-t1 if a <= d and b >= c: a = max(a,c) b = min(b,d) t1 = t2 else: state = 1 if state == 1: print("NO") else: print("YES")
py
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
from collections import deque import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def bfs(s): q = deque() q.append(s) dist = [inf] * (n + 1) dist[s] = 0 ans0 = n while q: i = q.popleft() di = dist[i] if di > p: return ans0 ans0 = min(ans0, i) for j, c in G[i]: dist[j] = di + c q.append(j) return ans0 t = int(input()) ans = [] inf = pow(10, 9) + 1 for _ in range(t): a, b, p = map(int, input().split()) s = list(input().rstrip()) n = len(s) x = 0 y = [] for i in range(n): if x ^ s[i]: x = s[i] y.append(i + 1) if y[-1] ^ n: y.append(n) G = [[] for _ in range(n + 1)] for i in range(len(y) - 1): k = y[i] c = a if s[k - 1] & 1 else b for j in range(y[i] + 1, y[i + 1] + 1): G[j].append((k, c)) ans0 = bfs(n) ans.append(ans0) sys.stdout.write("\n".join(map(str, ans)))
py
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
n = int(input()) a = list(map(int, input().split())) groups = [a[0]] counts = [1] for i in range(1, len(a)): ai = a[i] if groups[-1] == ai: counts[-1] += 1 else: groups.append(ai) counts.append(1) best_count = 0 if groups[-1] == 1 and groups[0] == 1: best_count = counts[-1] + counts[0] for i in range(len(counts)): if groups[i] == 1: best_count = max(best_count, counts[i]) print(best_count)
py
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1 4 2 1 2 1 2 0 1OutputCopy ? C ? CH ? CCHO ! CCHH InputCopy2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1OutputCopy ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
[ "constructive algorithms", "greedy", "interactive", "math" ]
import sys n, L, minID = None, None, None s = [] def fill(id, c): global n, L, s, minID L -= (s[id] == 'L') s = s[0:id] + c + s[ id +1:] minID = min(minID, id) def query(cmd, str): global n, L, s, minID print(cmd, ''.join(str)) print(cmd, ''.join(str), file=sys.stderr) sys.stdout.flush() if (cmd == '?'): result = list(map(int, input().split())) assert(result[0] != -1) for z in result[1:]: z -= 1 for i in range(len(str)): assert(s[z+i] == 'L' or s[z+i] == str[ i ]) fill(z+i, str[i]) elif (cmd == '!'): correct = int(input()) assert(correct == 1) for _ in range(int(input())): n = int(input()) if n >= 13: ans = [''] * (n + 1) print('? CO') co = list(map(int, input().split()))[1:] print('? CH') ch = list(map(int, input().split()))[1:] print('? CC') cc = list(map(int, input().split()))[1:] for d in co: ans[d] = 'C' ans[d + 1] = 'O' for d in ch: ans[d] = 'C' ans[d + 1] = 'H' for d in cc: ans[d] = 'C' ans[d + 1] = 'C' print('? OO') oo = list(map(int, input().split()))[1:] print('? OH') oh = list(map(int, input().split()))[1:] for d in oo: ans[d] = 'O' ans[d + 1] = 'O' for d in oh: ans[d] = 'O' ans[d + 1] = 'H' for i in range(1, n): if ans[i] == 'O' and ans[i + 1] == '': ans[i + 1] = 'C' for i in range(1, n): if ans[i] == '' and ans[i + 1] == 'O': ans[i] = 'H' for i in range(1, n): if ans[i] == '' and ans[i + 1] == 'H': ans[i] = 'H' for i in range(1, n): if ans[i] == '' and ans[i + 1] == '': ans[i] = 'H' print('? HOC') hoc = list(map(int, input().split()))[1:] for d in hoc: ans[d] = 'H' ans[d + 1] = 'O' ans[d + 2] = 'C' for d in range(2, n): if ans[d] == '': ans[d] = 'H' if ans[1] == '': print('?', 'H' + ''.join(ans[2:-1])) if input()[0] != '0': ans[1] = 'H' else: ans[1] = 'O' if ans[-1] == '': print('?', ''.join(ans[1:-1]) + 'H') if input()[0] != '0': ans[-1] = 'H' else: print('?', ''.join(ans[1:-1]) + 'O') if input()[0] != '0': ans[-1] = 'O' else: ans[-1] = 'C' print('!', ''.join(ans[1:])) kek = input() else: L, minID = n, n s = 'L' * n query('?', "CH") query('?', "CO") query('?', "HC") query('?', "HO") if (L == n): # the string exists in form O...OX...X, with X=C or X=H # or it's completely mono-character query('?', "CCC") if (minID < n): for x in range(minID - 1, -1, -1): fill(x, 'O') else: query('?', "HHH") if (minID < n): for x in range(minID - 1, -1, -1): fill(x, 'O') else: query('?', "OOO") if (minID == n): # obviously n=4 query('?', "OOCC") if (minID == n): fill(0, 'O') fill(1, 'O') fill(2, 'H') fill(3, 'H') if (s[n - 1] == 'L'): t = s[0:n - 1] + 'C' if (t[n - 2] == 'L'): t = t[0:n - 2] + 'C' + t[n - 1:] query('?', t) if (s[n - 1] == 'L'): fill(n - 1, 'H') if (s[n - 2] == 'L'): fill(n - 2, 'H') else: maxID = minID while (maxID < n - 1 and s[maxID + 1] != 'L'): maxID += 1 for i in range(minID - 1, -1, -1): query('?', s[i + 1:i + 2] + s[minID:maxID + 1]) if (minID != i): for x in range(i + 1): fill(x, 'O') break nextFilled = None i = maxID + 1 while i < n: if (s[i] != 'L'): i += 1 continue nextFilled = i while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1 query('?', s[0:i] + s[i - 1]) if (s[i] == 'L'): if (s[i - 1] != 'O'): fill(i, 'O') else: if (nextFilled == n): query('?', s[0:i] + 'C') if (s[i] == 'L'): fill(i, 'H') for x in range(i + 1, nextFilled): fill(x, s[i]) else: for x in range(i, nextFilled): fill(x, s[nextFilled]) i = nextFilled - 1 i += 1 query('!', s)
py
1296
E1
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
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
import random, sys, os, math, gc from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations, product from heapq import nsmallest, nlargest, heapify, heappop, heappush from io import BytesIO, IOBase from copy import deepcopy from bisect import bisect_left, bisect_right from math import factorial, gcd from operator import mul, xor from types import GeneratorType # if "PyPy" in sys.version: # import pypyjit; pypyjit.set_param('max_unroll_recursion=-1') # sys.setrecursionlimit(2*10**5) BUFSIZE = 8192 MOD = 10**9 + 7 MODD = 998244353 INF = float('inf') D4 = [(1, 0), (0, 1), (-1, 0), (0, -1)] D8 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)] def solve(): n = II() s = I() no = [0] * 26 c = [0] * 26 ans = [] for i in s[::-1]: i = ord(i) - 97 for j in range(i): if c[j]: if no[j] + 1 > no[i]: no[i] = no[j] + 1 ans.append(no[i]) c[i] += 1 if max(no) <= 1: print("YES") print("".join(map(str, ans[::-1]))) else: print("NO") def main(): t = 1 # t = II() for _ in range(t): solve() def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def bitcnt(n): c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555) c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333) c = (c & 0x0F0F0F0F0F0F0F0F) + ((c >> 4) & 0x0F0F0F0F0F0F0F0F) c = (c & 0x00FF00FF00FF00FF) + ((c >> 8) & 0x00FF00FF00FF00FF) c = (c & 0x0000FFFF0000FFFF) + ((c >> 16) & 0x0000FFFF0000FFFF) c = (c & 0x00000000FFFFFFFF) + ((c >> 32) & 0x00000000FFFFFFFF) return c def lcm(x, y): return x * y // gcd(x, y) def lowbit(x): return x & -x def perm(n, r): return factorial(n) // factorial(n - r) if n >= r else 0 def comb(n, r): return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0 def probabilityMod(x, y, mod): return x * pow(y, mod-2, mod) % mod class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) # sys.stdout = IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MI(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): return list(map(lambda x: int(x) - 1, input().split())) def getGraph(n, m, directed=False): d = [[] for _ in range(n)] for _ in range(m): u, v = LGMI() d[u].append(v) if not directed: d[v].append(u) return d def getWeightedGraph(n, m, directed=False): d = [[] for _ in range(n)] for _ in range(m): u, v, w = LII() u -= 1; v -= 1 d[u].append((v, w)) if not directed: d[v].append((u, w)) return d if __name__ == "__main__": main()
py
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
import sys, os input = sys.stdin.buffer.readline def f(u, v): os.write(1, b"%s %d %d\n" % (a, u, v)) w = int(input()) return w def bfs(s): q, k = [s], 0 visit[s] = 1 while len(q) ^ k: i = q[k] for j in G[i]: if not visit[j]: q.append(j) visit[j] = 1 k += 1 return n = int(input()) G = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v = map(int, input().split()) G[u].append(v) G[v].append(u) a, b = "?".encode(), "!".encode() visit = [0] * (n + 1) while True: x = [] for i in range(1, n + 1): if visit[i]: continue c = 0 for j in G[i]: if not visit[j]: c += 1 if c <= 1: x.append(i) if len(x) == 2: break if len(x) == 2: u, v = x w = f(u, v) visit[w] = 1 if not visit[u]: bfs(u) if not visit[v]: bfs(v) visit[w] = 0 elif len(x) == 1: r = x[0] os.write(1, b"%s %d\n" % (b, r)) exit()
py
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6 10 7 1 9 10 15 OutputCopy26 InputCopy1 400000 OutputCopy400000 InputCopy7 8 9 26 11 12 29 14 OutputCopy55 NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
[ "data structures", "dp", "greedy", "math", "sortings" ]
from collections import defaultdict import sys input=sys.stdin.readline n=int(input()) a=list(map(int,input().strip().split())) d=defaultdict(int) mx=max(a) for i in range(n): d[a[i]-i-1]+=a[i] mx=max(mx,d[a[i]-i-1]) print(mx)
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
import sys input = sys.stdin.readline import bisect n = int(input()) a, b = [], [] for i in range(n): w = list(map(int, input().split()))[1:] if sorted(w) == w[::-1]: a.append(w[0]) b.append(w[-1]) a.sort() print(n**2 - sum(bisect.bisect_right(a, i) for i in b))
py
1141
F1
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
[ "greedy" ]
from collections import defaultdict, deque, Counter from heapq import heapify, heappop, heappush import math from copy import deepcopy from itertools import combinations, permutations, product, combinations_with_replacement from bisect import bisect_left, bisect_right import sys def input(): return sys.stdin.readline().rstrip() def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getListGraph(): return list(map(lambda x:int(x) - 1, input().split())) def getArray(intn): return [int(input()) for i in range(intn)] mod = 10 ** 9 + 7 MOD = 998244353 # import pypyjit # pypyjit.set_param('max_unroll_recursion=-1') inf = float('inf') eps = 10 ** (-15) dy = [0, 1, 0, -1] dx = [1, 0, -1, 0] ############# # Main Code # ############# """ 交差しない2つの区間 これの最大値 適当に区切ってみる いくつを作るか Nは小さい 区間スケジュール """ N = getN() A = [0] + getList() for i in range(1, N + 1): A[i] += A[i - 1] d = defaultdict(list) for i in range(N): for j in range(i, N): l = A[j + 1] - A[i] d[l].append((i, j)) ans1 = 0 ans2 = [] for _, l in d.items(): l.sort(key = lambda i:i[1]) c = 0 last = l[0][1] opt = [l[0]] for i in range(1, len(l)): if l[i][0] <= last: c += 1 else: last = l[i][1] opt.append(l[i]) if len(l) - c > ans1: ans1 = len(l) - c ans2 = opt print(ans1) for l, r in ans2: print(l + 1, r + 1)
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
count_of_ex = int(input()) rob1 = [int(x) for x in input().split()] rob2 = [int(x) for x in input().split()] rob1_dom = 0 rob2_dom = 0 i = 0 while i < count_of_ex: if rob2[i] > rob1[i]: rob2_dom += 1 elif rob1[i] > rob2[i]: rob1_dom += 1 i += 1 if rob1_dom == 0: print(-1) else: if rob1_dom > rob2_dom: print(1) else: print(rob2_dom//rob1_dom + 1)
py
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
from sys import stdin input=lambda :stdin.readline()[:-1] h,w=map(int,input().split()) mat=[] for i in range(h): mat.append(list(map(lambda x:int(x)-1,input().split()))) def calc(col): ok=[0]*h for i in range(h): if col[i]!=-1: ok[(i-col[i])%h]+=1 res=h for i in range(h): res=min(res,i+h-ok[i]) return res ans=0 for i in range(w): col=[] for j in range(h): if mat[j][i]%w==i and mat[j][i]<h*w: col.append(mat[j][i]//w) else: col.append(-1) ans+=calc(col) print(ans)
py
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
t = int(input()) for i in range(t): n = int(input()) x = input() ans = [] for i in x: i = int(i) if i % 2 == 1: ans.append(i) if len(ans) > 1: print(ans[0], ans[1], sep = "") else: print(-1)
py
1323
B
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2 1 0 1 1 1 1 OutputCopy4 InputCopy3 5 4 1 1 1 1 1 1 1 1 OutputCopy14 NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
[ "binary search", "greedy", "implementation" ]
import sys import math import collections from heapq import heappush, heappop from functools import reduce input = sys.stdin.readline ints = lambda: list(map(int, input().split())) def factors(n): return list(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) n, m, k = ints() a = ints() b = ints() cols = [] cnt = 0 for i in range(m): if b[i] == 1: cnt += 1 else: cols.append(cnt) cnt = 0 cols.append(cnt) cols.sort(reverse=True) cols_p = [cols[0]] for i in range(1, len(cols)): cols_p.append(cols_p[-1] + cols[i]) rows = [] cnt = 0 for i in range(n): if a[i] == 1: cnt += 1 else: rows.append(cnt) cnt = 0 rows.append(cnt) rows.sort(reverse=True) rows_p = [rows[0]] for i in range(1, len(rows)): rows_p.append(rows_p[-1] + rows[i]) def bsearch(x, arr): l, r = 0, len(arr) - 1 while l <= r: m = (l + r) // 2 if arr[m] >= x: l = m + 1 else: r = m - 1 return l facs = factors(k) facs.sort() ans = 0 for i in range(len(facs)): fac1, fac2 = facs[i], k // facs[i] j = bsearch(fac1, cols) p = 0 amt = 0 if j != 0: p = cols_p[j - 1] amt = p - j * fac1 + j j = bsearch(fac2, rows) p = 0 if j != 0: p = rows_p[j - 1] amt *= (p - j * fac2 + j) else: amt = 0 ans += amt print(ans)
py
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
# 2022-07-03T13:11:49Z def proc(n, s): s = list(map(ord, s)) while True and len(s) > 1: to_remove = [] for i in range(len(s)): if i == 0: if s[i] == s[i + 1] + 1: to_remove.append(i) elif i == len(s) - 1: if s[i] == s[i - 1] + 1: if not to_remove or s[i] > s[to_remove[0]]: to_remove = [i] elif s[i] == s[to_remove[0]]: to_remove.append(s[i]) else: if s[i] == s[i + 1] + 1 or s[i] == s[i - 1] + 1: if not to_remove or s[i] > s[to_remove[0]]: to_remove = [i] elif s[i] == s[to_remove[0]]: to_remove.append(s[i]) if not to_remove: break ns = [] to_remove = set(to_remove) for i in range(len(s)): if i in to_remove: continue ns.append(s[i]) s = ns # print(list(map(chr, s))) return n - len(s) n = int(input()) s = input().strip() ans = proc(n, s) print(ans) """ bacab[c]ab bacabab """
py
1286
A
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.
[ "dp", "greedy", "sortings" ]
n=int(input()) f=[[[1000,1000]for _ in range(n+1)]for _ in range(n+1)] f[0][0]=[0,0] for i,v in enumerate(map(int,input().split())): for j in range(i+2): if v==0 or v%2:f[i+1][j][1]=min(f[i][j][0]+1,f[i][j][1]) if v%2==0:f[i+1][j][0]=min(f[i][j-1][0],f[i][j-1][1]+1) print(min(f[n][n//2]))
py
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
t = int(input()) for _ in range(t): n, m = map(int, input().split()) s = input() p = list(map(int, input().split())) mp = [0] * n for value in p: mp[value - 1] += 1 for i in range(n - 1, 0, -1): mp[i - 1] += mp[i] occ = [0] * 26 for i in range(len(s)): occ[ord(s[i]) - ord('a')] += mp[i] occ[ord(s[i]) - ord('a')] += 1 print(' '.join(list(map(str, occ))))
py
1286
C1
C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "interactive", "math" ]
import sys, 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])] # 標準出力による質問 interactive TEST = 0 import sys def _q(l,r): if l>=r: return [] print("?", l+1, r) sys.stdout.flush() res = [] for i in range((r-l)*(r-l+1)//2): v = SI() res.append(v) return res def answer(v): print(f"! {v}") sys.stdout.flush() n = int(input()) if TEST: import random # random.seed(0) _a = [random.randint(0,25) for _ in range(n)] def _q(l,r): if l>=r: return [] res = [] for i in range(l,r): for j in range(i+1,r+1): res.append(_a[i:j]) # print(l,r,res) return res def sub(n): res = _q(0,n) count = [[0]*26 for _ in range(n+2)] for s in res: for v in s: count[len(s)][v] += 1 vs = [[] for _ in range((n+1)//2)] for i in range((n+1)//2): cur = [0]*26 for v in range(26): cur[v] += count[1][v]*(i+2) - count[i+2][v] for j in range(i): for v in vs[j]: cur[v] -= (i-j+1) for v in range(26): if cur[v]: vs[i].extend([v]*cur[v]) assert len(vs[i])<=2, (i, vs[i], cur) return vs vs = sub(n) vs2 = sub(n-1) res = _q(n-1,n) val = res[0][0] ans = [0]*n ans[n-1] = val u = n-1 for i in range(n-1): if i%2==0: vs[n-1-u].remove(ans[u]) val = vs[n-1-u][0] u = n-1-u ans[u] = val else: vs2[u].remove(val) val = vs2[u][0] u = n-2-u ans[u] = val if TEST: assert ans==_a answer("".join([chr(v+ord("a")) for v in ans]))
py
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
for i in range(int(input())): n = int(input()) b = list(map(int , input().split())) dic = {} l = [] for j in range(1 , 2*n+1): dic[j] = 1 for j in range(n): dic[b[j]] = 0 for j in range(n): l.append(b[j]) # print(b[j] ,end= " ") dic[b[j]]=0 for k in dic: if k > b[j] and dic[k]!=0: # print(k , end=" ") l.append(k) dic[k]=0 break if len(l)==2*n: print(*l) else: print(-1) # print(dic)
py
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2 6 3 7 3 OutputCopyYES NO Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
[ "geometry", "greedy", "math", "number theory" ]
t = int(input()) for _ in range(0, t): n, m = map(int, input().split()) n, m = max(n, m), min(n, m) if n%m == 0: print("YES") else: print("NO")
py
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
t = int(input()) for _ in range(t): s = input().strip('0') print(s.count('0'))
py
1141
F1
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
[ "greedy" ]
import os, sys from io import BytesIO, IOBase from math import log2, ceil, sqrt, gcd from _collections import deque import heapq as hp from bisect import bisect_left, bisect_right from math import cos, sin from itertools import permutations from operator import itemgetter # sys.setrecursionlimit(2*10**5+10000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") mod = 10 ** 9 + 7 n=int(input()) a=list(map(int,input().split())) d=dict() for i in range(n): tot=0 for j in range(i,n): tot+=a[j] d[tot]=d.get(tot,[]) d[tot].append([i+1,j+1]) ans=0 ar=[] xx=0 for i in d: ck=d[i] ck.sort(key=itemgetter(1)) nr=[] last=0 for x,y in ck: if x>last: nr.append([x,y]) last=y if len(nr)>ans: ans=len(nr) ar=nr xx=i print(ans) for i in ar: print(*i)
py
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
from math import inf, sqrt def main(): t = int(input()) while t: a, b, c = list(map(int, input().split(' '))) res = inf res_list = list() for i in range(1, 10001): for j in range(i, 20001 ,i): now = abs(j - b) + abs(i - a) if c <= j : now += j - c k = j else: now += min(abs(c - j * (c // j)), abs(c - j * (c // j + 1))) if abs(c - j * (c // j)) < abs(c - j * (c // j + 1)): k = j * (c // j) else: k = j * (c // j + 1) if now < res: res = now res_list = (i, j, k) ''' # wrong in 137 10000 10000, answer is 137 10001 10001 for j in range(1, 10001): now = abs(j - b) if a >= j: now += a - j i = j else: minv = inf best_i = 0 for i in range(1, int(sqrt(j)) + 1): if j % i == 0: if abs(i - a) < minv: minv = abs(i - a) best_i = i if abs(j // i - a) < minv: minv = abs(j // i - a) best_i = j // i i = best_i now += minv if c <= j : now += j - c k = j else: now += min(abs(c - j * (c // j)), abs(c - j * (c // j + 1))) if abs(c - j * (c // j)) < abs(c - j * (c // j + 1)): k = j * (c // j) else: k = j * (c // j + 1) if now < res: res = now res_list = (i, j, k) ''' print(res) print(*res_list) t -= 1 return main()
py
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
for _ in range(int(input())): a, b = map(int, input().split()) print(a*(len(str(b+1)) - 1))
py
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 OutputCopy56 6 442 1 45 80 NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
[ "implementation" ]
t=int(input()) for i in range(t): a,b,x,y=[int(j) for j in input().split()] z1=(a-1-x)*b z2=x*b z3=a*(b-1-y) z4=a*y print(max(z1,z2,z3,z4))
py
1324
D
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5 4 8 2 6 2 4 5 4 1 3 OutputCopy7 InputCopy4 1 3 2 4 1 3 2 4 OutputCopy0
[ "binary search", "data structures", "sortings", "two pointers" ]
n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) arr = [a[i] - b[i] for i in range(n)] arr.sort(reverse=True) r = n - 1 res = 0 for i in range(n): while r > i and arr[i] + arr[r] <= 0: r -= 1 #print(f'i: {i}, r: {r}') if r - i > 0: res += r - i print(res)
py
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
for i in range(int(input())): a='R'+input()+'R' b=0 c=0 for j in range(len(a)): if a[j]=='R': c=max(c,j-b) b=j print(c)
py
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
n = [int(_) for _ in input().split()] a = [_ for _ in input().split()] b = [_ for _ in input().split()] for i in range(int(input())): s = int(input()) v1 = s % n[0] v2 = s % n[1] print(''.join(a[v1-1])+ ''.join(b[v2-1]))
py
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
def main_function(): n = int(input()) s = list(input()) counter_1 = 0 counter_2 = 0 for i in s: if i == ")": counter_2 += 1 else: counter_1 += 1 if counter_1 != counter_2: print(-1) else: is_started = False one_counter = 0 another_counter = 0 final_counter = 0 if n % 2 == 1: print(-1) else: for i in range(n): if s[i] == "(": one_counter += 1 else: one_counter -= 1 if not is_started: if one_counter < 0: another_counter = 1 is_started = True else: another_counter += 1 if one_counter < 0: pass else: final_counter += another_counter another_counter = 0 is_started = False # print(i) # print(final_counter) print(final_counter) if __name__ == '__main__': main_function()
py
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
import sys input = lambda: sys.stdin.readline().rstrip() N = int(input()) W = [(i+12345)**2 % 998244353 for i in range(N)] AL, AR, BL, BR = [], [], [], [] for i in range(N): a, b, c, d = map(int, input().split()) AL.append(a) AR.append(b) BL.append(c) BR.append(d) def chk(L, R): D = {s:i for i, s in enumerate(sorted(list(set(L + R))))} X = [0] * 200200 for i, l in enumerate(L): X[D[l]] += W[i] for i in range(1, 200200): X[i] += X[i-1] return sum([X[D[r]] * W[i] for i, r in enumerate(R)]) print("YES" if chk(AL, AR) == chk(BL, BR) else "NO")
py
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
input() a = b = 0 for x, y in zip(input(), input()): a += x > y b += x < y print(-1 if a==0 else b//a+1)
py
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") print = lambda s: sys.stdout.write(s + "\n") n = int(input()) G = [[] for _ in range(n)] for _ in range(n-1): u,v = map(int,input().split()) G[u-1].append(v-1) G[v-1].append(u-1) depth = [] euler = [] ref = [-1]*n log = [] root = 0 stk = [(root,-1,-1)] while stk: node,par,idx = stk.pop() if idx == -1: # unseen node if par != -1: depth.append(depth[ref[par]] + 1) else: depth.append(0) ref[node] = len(euler) euler.append(len(euler)) log.append(node) idx += 1 else: euler.append(euler[ref[node]]) depth.append(depth[ref[node]]) log.append(node) if idx < len(G[node]) and G[node][idx] == par: idx += 1 if idx == len(G[node]): continue stk.append((node, par, idx+1)) stk.append((G[node][idx], node, -1)) def sparse_table(x): sz = len(x) LOG = 0 while 1<<(LOG+1) < sz+1: LOG += 1 dp = [[None]*(LOG+1) for _ in range(sz)] for i in range(sz): dp[i][0] = x[i] for j in range(1,LOG+1): for i in range(sz): if i-1 + (1<<j) >= sz: break dp[i][j] = min(dp[i][j-1], dp[i + (1<<(j-1))][j-1]) return dp dp = sparse_table(euler) def lca(i,j): i,j = min(i,j),max(i,j) L = 0 while 1<<(1+L) <= j-i+1: L += 1 t = min(dp[i][L], dp[j+1 - (1<<L)][L]) return log[t] def dist(u,v): du = depth[ref[u]] dv = depth[ref[v]] dlca = depth[ref[lca(ref[u],ref[v])]] return du + dv - 2*dlca for nq in range(int(input())): x,y,a,b,k = map(int,input().split()) x -= 1 y -= 1 a -= 1 b -= 1 path1 = dist(a,b) if path1 <= k and (path1-k)%2 == 0: print("YES") continue path2 = dist(a,x) + dist(b,y) + 1 if path2 <= k and (path2-k)%2 == 0: print("YES") continue path3 = dist(a,y) + dist(b,x) + 1 if path3 <= k and (path3-k)%2 == 0: print("YES") continue print("NO")
py
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
a=int(input()) for i in range(a): n=int(input()) a1=list(map(int, input().split())) a2=list(map(int, input().split())) a1.sort() a2.sort() for j in range(n): print(a1[j],end=" ") print() for j in range(n): print(a2[j],end=" ") print()
py
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
import sys for i in range(int(sys.stdin.readline())): s = sys.stdin.readline().strip() s += 'R' m = 0 lc = 1 for j in s: if j == 'L': lc += 1 continue m = max(lc, m) lc = 1 print(m)
py
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
import math import copy import itertools import bisect import sys from heapq import heapify, heappop, heappush input = lambda: sys.stdin.readline().rstrip("\r\n") def ilst(): return list(map(int,input().split())) def islst(): return list(map(str,input().split())) def inum(): return map(int,input().split()) def freq(l): d = {} for i in l: d[i] = d.get(i,0)+1 return d def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issub(s1,s2): #s2 is a sub of s1 j = 0 for i in range(len(s1)): if s1[i] == s2[j]: j += 1 if j == len(s2): return True return False t = int(input()) for _ in range(t): n,m = inum() l = [] for i in range(n): l.append(ilst()) l.sort() low,high = m,m prev = 0 f = False for i in range(n): high = min(high+l[i][0]-prev,l[i][2]) low = max(low-(l[i][0]-prev),l[i][1]) if high < l[i][1] or low > l[i][2]: f = True break prev = l[i][0] if not f: print("YES") else: print("NO")
py
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
q = int(input()) for i in range(q): w, e, r, t = map(int, input().split()) y = max(w, e, r) u = min(w, e, r) o = w + e + r - y - u p = (y - u) + (y - o) if p <= t: if (t - p) % 3 == 0: print("YES") else: print("NO") else: print("NO")
py
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
for i in range(int(input())): n1, n2 = map(int, input().split()) a_dados = list(map(int, input().split())) p_posicoes = list(map(int, input().split())) for i in range(n2): for j in p_posicoes: if a_dados[j-1]> a_dados[j]: a_dados[j-1],a_dados[j] = a_dados[j],a_dados[j-1] if a_dados != sorted(a_dados): print("NO") else: print("YES")
py
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
T = int(input()) for _ in range(T): n = int(input()) A = sorted(list(map(int, input().split()))) B = sorted(list(map(int, input().split()))) print(*A) print(*B)
py
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
import sys readline = sys.stdin.buffer.readline T = int(readline()) Ans = [None]*T for qu in range(T): N, x, y, z = map(int, readline().split()) A = list(map(int, readline().split())) ts = 200 dp = [[0]*3 for _ in range(ts)] table = [[[0]*4 for _ in range(3)] for _ in range(ts+8)] for hp in range(ts): if 0 < hp <= x: table[hp][0][0] = 1 table[hp][1][0] = 1 table[hp][2][0] = 1 if 0 < hp <= y: table[hp][0][0] = 1 table[hp][2][0] = 1 if 0 < hp <= z: table[hp][0][0] = 1 table[hp][1][0] = 1 for ty in range(3): dp[hp][ty] = table[hp][ty].index(0) val0 = dp[hp][0] val1 = dp[hp][1] val2 = dp[hp][2] table[hp+x][0][val0] = 1 table[hp+x][1][val0] = 1 table[hp+x][2][val0] = 1 table[hp+y][0][val1] = 1 table[hp+y][2][val1] = 1 table[hp+z][0][val2] = 1 table[hp+z][1][val2] = 1 cl = None for loop in range(10, 61): for i in range(loop): if dp[ts-1-i] != dp[ts-1-i-loop]: break else: cl = loop break continue A1 = [None]*N for i in range(N): a = A[i] if a < ts: A1[i] = a else: k = 1 + (a-ts)//cl A1[i] = a - k*cl xx = 0 for a in A1: xx ^= dp[a][0] res = 0 for a in A1: da = dp[a][0] if dp[max(0, a-x)][0]^da == xx: res += 1 if dp[max(0, a-y)][1]^da == xx: res += 1 if dp[max(0, a-z)][2]^da == xx: res += 1 Ans[qu] = res print('\n'.join(map(str, Ans)))
py
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
import sys import math from collections import defaultdict,Counter,deque input = sys.stdin.readline def I(): return input() def II(): return int(input()) def MII(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): return list(map(lambda x: int(x) - 1, input().split())) def WRITE(out): return print('\n'.join(map(str, out))) def WS(out): return print(' '.join(map(str, out))) def WNS(out): return print(''.join(map(str, out))) ''' E or Two O ''' def solve(): t = II() for _ in range(t): n = II() a = LII() odds = [] evens = [] for i,num in enumerate(a): if num & 1: odds.append(i+1) else: evens.append(i+1) if evens or len(odds) > 1: break if evens: print(1) print(evens[0]) elif len(odds) > 1: print(2) print(odds[0], odds[1]) else: print(-1) solve()
py
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1 4 2 1 2 1 2 0 1OutputCopy ? C ? CH ? CCHO ! CCHH InputCopy2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1OutputCopy ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
[ "constructive algorithms", "greedy", "interactive", "math" ]
import sys t = int(input()) def get(): ans = "" for i in range(n): ans = ans + S[i] return ans def query(pat): print("Querying ", pat, file = sys.stderr) print("? " + pat, flush = True) A = list(map(int, input().split())) for k in A[1:]: for i in range(len(pat)): S[k-1+i] = pat[i] return A[0] def answer(): ans = "! " for i in range(n): ans = ans + S[i] print("Answering ", ans, file = sys.stderr) print(ans, flush = True) input() for q in range(t): n = int(input()) S = ['?'] * n Ptrns = [ "CO", "CH", "HO", "HC" ] for pat in Ptrns: query(pat) print("After initial queries ", get(), file = sys.stderr) known = None for i in range(n): if S[i]!='?': known = i break if known is None: if query("OOO")>0: if query("OOOC")>0: for i in range(n): if S[i]=='?': S[i] = 'C' else: for i in range(n): if S[i]=='?': S[i] = 'H' else: if query("CCC")>0: for i in range(n): if S[i]=='?': S[i] = 'O' elif query("HHH")>0: for i in range(n): if S[i]=='?': S[i] = 'O' else: S[0] = S[1] = 'O' if query("OOHH")>0: S[2] = S[3] = 'H' else: S[2] = S[3] = 'C' answer() continue suf = S[known] + S[known+1] while known > 0: query(S[known] + suf) if S[known-1]=='?': for i in range(known): S[i] = 'O' break known-=1 suf = S[known] + suf r = known while r < n and S[r]!='?': r+=1 pref = "" for i in range(r): pref = pref + S[i] while r < n: print("I have now ", pref, file = sys.stderr) if S[r-1]=='O': query(pref + "O") if S[r]=='?': if r==n-1: # ostatni znak if query(pref + "C")==0: S[r] = 'H' else: # jeszcze nie query(pref+ "CC") if S[r]=='?': S[r] = S[r+1] = 'H' else: S[r]=S[r-1] while r < n and S[r]!='?': pref = pref + S[r] r+=1 answer()
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
import sys input = sys.stdin.readline n,m,p=map(int,input().split()) W=[tuple(map(int,input().split())) for i in range(n)] A=[tuple(map(int,input().split())) for i in range(m)] M=[tuple(map(int,input().split())) for i in range(p)] INF=2*(10**9) Q=[[] for i in range(10**6+1)] for x,y,c in M: Q[x].append((c,y)) for x,c in W: Q[x-1].append((c,0)) seg_el=1<<((10**6+1).bit_length()) SEGMAX=[-INF]*seg_el for x,y in A: SEGMAX[x-1]=max(SEGMAX[x-1],-y) for i in range(seg_el-2,-1,-1): SEGMAX[i]=max(SEGMAX[i+1],SEGMAX[i]) SEGMAX=[-INF]*(seg_el)+SEGMAX for i in range(seg_el-1,0,-1): SEGMAX[i]=max(SEGMAX[i*2],SEGMAX[(i*2)+1]) SEGADD=[0]*(2*seg_el) def adds(l,r,x): L=l+seg_el R=r+seg_el while L<R: if L & 1: SEGADD[L]+=x L+=1 if R & 1: R-=1 SEGADD[R]+=x L>>=1 R>>=1 L=(l+seg_el)>>1 R=(r+seg_el-1)>>1 while L!=R: if L>R: SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)]) L>>=1 else: SEGMAX[R]=max(SEGMAX[R*2]+SEGADD[R*2],SEGMAX[1+(R*2)]+SEGADD[1+(R*2)]) R>>=1 while L!=0: SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)]) L>>=1 ANS=-INF for i in range(10**6+1): for c,y in Q[i]: if y==0: ANS=max(ANS,SEGMAX[1]-c) else: adds(y,seg_el,c) print(ANS)
py
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
n = int(input());jaya= [0]*(n+1);l = [] for i in range(n-1): a,b = map(int,input().split());a -= 1;b -= 1;jaya[a] += 1;jaya[b] += 1;l.append([a,b]) m = 0;mex = n-2 for a,b in l: if jaya[a] == 1 or jaya[b] == 1:print(m);m+= 1 else:print(mex);mex -= 1
py
1292
E
E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1 4 2 1 2 1 2 0 1OutputCopy ? C ? CH ? CCHO ! CCHH InputCopy2 5 0 2 2 3 1 8 1 5 1 5 1 3 2 1 2 1OutputCopy ? O ? HHH ! CHHHH ? COO ? COOH ? HCCOO ? HH ! HHHCCOOH NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.
[ "constructive algorithms", "greedy", "interactive", "math" ]
import sys t = int(input()) def get(): ans = "" for i in range(n): ans = ans + S[i] return ans def query(pat): print("Querying ", pat, file = sys.stderr) print("? " + pat, flush = True) A = list(map(int, input().split())) for k in A[1:]: for i in range(len(pat)): S[k-1+i] = pat[i] return A[0] def answer(): ans = "! " for i in range(n): ans = ans + S[i] print("Answering ", ans, file = sys.stderr) print(ans, flush = True) input() for q in range(t): n = int(input()) S = ['?'] * n Ptrns = [ "CO", "CH", "HO", "HC" ] for pat in Ptrns: query(pat) print("After initial queries ", get(), file = sys.stderr) known = None for i in range(n): if S[i]!='?': known = i break if known is None: if query("OOO")>0: if query("OOOC")>0: for i in range(n): if S[i]=='?': S[i] = 'C' else: for i in range(n): if S[i]=='?': S[i] = 'H' else: if query("CCC")>0: for i in range(n): if S[i]=='?': S[i] = 'O' elif query("HHH")>0: for i in range(n): if S[i]=='?': S[i] = 'O' else: S[0] = S[1] = 'O' if query("OOHH")>0: S[2] = S[3] = 'H' else: S[2] = S[3] = 'C' answer() continue suf = S[known] + S[known+1] while known > 0: query(S[known] + suf) if S[known-1]=='?': for i in range(known): S[i] = 'O' break known-=1 suf = S[known] + suf r = known while r < n and S[r]!='?': r+=1 pref = "" for i in range(r): pref = pref + S[i] while r < n: print("I have now ", pref, file = sys.stderr) if S[r-1]=='O': query(pref + "O") if S[r]=='?': if r==n-1: # ostatni znak if query(pref + "C")==0: S[r] = 'H' else: # jeszcze nie query(pref+ "CC") if S[r]=='?': S[r] = S[r+1] = 'H' else: S[r]=S[r-1] while r < n and S[r]!='?': pref = pref + S[r] r+=1 answer()
py
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
def f0(n, m): mod = int(1e9 + 7) c = 2 * m + 1 dp = [[0] * c for _ in range(n + 1)] dp[0][0] = 1 for i in range(n): # TODO 空间压缩 / 斜率优化 for j in range(c): for k in range(j, c): dp[i + 1][k] = (dp[i + 1][k] + dp[i][j]) % mod return dp[-1][-1] def f1(n, m): def power(base, exp): val = 1 while exp: if exp & 1: val = val * base % mod base = base * base % mod exp >>= 1 return val mod = int(1e9 + 7) a = b = c = 1 x = n + m * 2 - 1 y = 2 * m z = x - y for i in range(1, x + 1): a = a * i % mod if i == y: b = a if i == z: c = a ans = a ans = ans * power(b, mod - 2) % mod ans = ans * power(c, mod - 2) % mod return ans # import numpy.random as r # # for _ in range(1000): # n, m = r.randint(1, 1000, 2) # r0 = f0(n, m) # r1 = f1(n, m) # # print(n, m) # if r0 != r1: # print("!!!!!", r0, r1) # exit(1) # exit() n, m = map(int, input().split()) print(f0(n, m))
py
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
[ "dp", "greedy", "implementation" ]
# import sys # sys.stdin = open('ip.txt','r') # sys.stdout = open('op.txt','w') import math from bisect import * R=lambda:map(int,input().split()) t,=R() while t: t-=1; n, = R() arr = list(R()) presum = 0; k1 =float('-inf') k2 =float('-inf') all_sum = sum(arr) s = 0; e = len(arr) # K(0,n-1) for i in range(len(arr)-1): if presum == 0: s = i presum+=arr[i] if presum > k1: e = i k1 = presum if presum < 0: presum = 0 # K(1,n) presum = 0 for i in range(1,len(arr)): if presum == 0: s = i presum+=arr[i] if presum > k2: e = i k2 = presum if presum < 0: presum = 0 # max(k1,k2) k = max(k1,k2) if all_sum > k: print('YES') else : print('NO')
py
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
from sys import stdin input=lambda :stdin.readline()[:-1] m=10**5 div=[[] for i in range(m)] for i in range(1,m): for j in range(i,m,i): div[j].append(i) def solve(): a,b,c=map(int,input().split()) ans=10**9 for i in range(10**4): C=c+i for B in div[C]: for A in div[B]: res=i+abs(A-a)+abs(B-b) if res<ans: ans=res ANS=(A,B,C) C=c-i if C<1: continue for B in div[C]: for A in div[B]: res=i+abs(A-a)+abs(B-b) if res<ans: ans=res ANS=(A,B,C) print(ans) print(*ANS) for _ in range(int(input())): solve()
py
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
from math import factorial as fact mod = 10**9 + 7 def C(n, k): return fact(n) // (fact(k) * fact(n - k)) n, m = map(int, input().split()) print(C(n + 2*m - 1, 2*m) % mod)
py
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
[ "greedy", "implementation", "math" ]
T = int(input()) for _ in range(T): a,b = map(int,input().split()) ans=0 diff=0 if(a==b): ans = 0 elif(a>b): diff=a-b ans+= 1 if(diff%2!=0): ans+= 1 elif(a<b): diff=b-a ans+=1 if(diff%2!=1): ans+=1 print(ans)
py
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
import sys from math import sqrt, gcd, factorial, ceil, floor, pi, inf from collections import deque, Counter, OrderedDict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**6) #======================================================# 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 primelist(): L = [False for i in range(10**9)] primes = [False for i in range(10**9)] for i in range(2,10**9): if not L[i]: primes[i]=True for j in range(i,10**9,i): L[j]=True return primes def isPrime(n): p = primelist() return p[n] #======================================================# def bst(arr,x): low,high = 0,len(arr)-1 ans = -1 while low<=high: mid = (low+high)//2 if arr[mid]==x: return mid elif arr[mid]<x: ans = mid low = mid+1 else: high = mid-1 return ans #======================================================# for _ in range(I()): n = I() a = L() x = -1 for i in range(n): if a[i]<i: break else: x=i y = n for i in range(n-1,-1,-1): if a[i]<n-1-i: break else: y=i if n-1-y==x and y>x: print("NO") continue if y-x<=1: print("YES") else: print("NO")
py
1294
B
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 OutputCopyYES RUUURRRRUU NO YES RRRRUUU NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
[ "implementation", "sortings" ]
for _ in range(int(input())): a= [(0, 0)] n= int(input()) for i in range(n): x, y= map(int, input().split()) a.append((x, y)) a.sort() s= str() for k in range(1, n+1): if a[k][0] < a[k-1][0] or a[k][1] < a[k-1][1]: print('NO') break else: p= a[k][0]- a[k-1][0] q= a[k][1]- a[k-1][1] s += (p*'R')+ (q*'U') else: print('YES') print(s)
py
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
import sys input = sys.stdin.readline n, m = map(int, input().split()) d = [1] c = 0 for i in range(1, n+1): d.append(d[-1]*i%m) for i in range(1, n+1): c += (n-i+1)*d[n-i+1]*d[i]%m c %=m print(c)
py
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
t = int(input()) for _ in range(t): n = int(input()) num = list(map(int, input().split())) num.sort() num = num[::-1] num = list(map(str, num)) print(" ".join(num))
py
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
n = int(input()) lst = [int(x) for x in input().split()][:n] cnt, m_cnt = 0, 0 cnt2, m_cnt2 = 0, 0 if lst[0] == lst[-1] and lst[0] == 1: cnt = 1 for j in range(n - 1): if lst[j] == 1: cnt += 1 else: pos = j break if cnt > m_cnt: m_cnt = cnt for j in range(n - 2, pos, -1): if lst[j] == 1: cnt += 1 else: break if cnt > m_cnt: m_cnt = cnt for j in range(n): if lst[j] == 1: cnt2 += 1 else: cnt2 = 0 if cnt2 > m_cnt2: m_cnt2 = cnt2 print(max(m_cnt, m_cnt2))
py
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me, import sys #then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize, import os #just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails from io import BytesIO, IOBase BUFSIZE = 8192 #every now and then. Just keep coding, just keep working and you'll keep progressing at speed- # -forcing. 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") #code by _Frust(CF)/Frust(AtCoder) sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from os import path if(path.exists('input.txt')): sys.stdin = open("input.txt","r") sys.stdout = open("output.txt","w") input = lambda: sys.stdin.readline().rstrip("\r\n") import math import heapq as hq for _ in range(int(input())): n, x, y=map(int, input().split()) if x==1 and y==1: print(1, 1) elif x==n and y==n: print(n, n) else: best=max(x+y+1-n, 1) worst=min(x+y-1, n) print(best, worst) # for i in range(1, 10): # for j in range(1, 10): # print(9, i, j)
py
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
from __future__ import division, print_function import os import sys from io import BytesIO, IOBase def powmin2(x, r): return pow(x, r - 2, r) def comb(m, n, k): res = 1 for i in range(n): res = (res * (m - i)) % k pro_mod = 1 for i in range(2, n + 1): pro_mod = (pro_mod * i) % k return (res * powmin2(pro_mod, k)) % k def main(): n, m = map(int, input().split()) if n == 2: print(0) else: print( (comb(m, n - 1, 998244353) * (n - 2) * pow(2, n - 3, 998244353)) % 998244353 ) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
py
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
from collections import defaultdict, deque, Counter from heapq import heapify, heappop, heappush import math from copy import deepcopy from itertools import combinations, permutations, product, combinations_with_replacement from bisect import bisect_left, bisect_right import sys def input(): return sys.stdin.readline().rstrip() def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getListGraph(): return list(map(lambda x:int(x) - 1, input().split())) def getArray(intn): return [int(input()) for i in range(intn)] mod = 10 ** 9 + 7 MOD = 998244353 # sys.setrecursionlimit(1000000) inf = float('inf') eps = 10 ** (-10) dy = [0, 1, 0, -1] dx = [1, 0, -1, 0] ############# # Main Code # ############# N, M = getNM() mat = [getList() for i in range(N)] ans = 0 # 各列ごと for j in range(M): opt = inf cnt = [0] * N # t回回転 for i in range(N): if (mat[i][j] - (j + 1)) % M == 0 and (mat[i][j] - (j + 1)) // M < N: time = (i - (mat[i][j] - (j + 1)) // M) % N cnt[time] += 1 for i in range(N): opt = min(opt, i + (N - cnt[i])) ans += opt print(ans)
py
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
import bisect import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_min(s, t): s += l1 t += l1 ans = inf while s <= t: if s % 2 == 0: s //= 2 else: ans = min(ans, mi[s]) s = (s + 1) // 2 if t % 2 == 1: t //= 2 else: ans = min(ans, mi[t]) t = (t - 1) // 2 return ans def get_max(s, t): s += l1 t += l1 ans = -inf while s <= t: if s % 2 == 0: s //= 2 else: ans = max(ans, ma[s]) s = (s + 1) // 2 if t % 2 == 1: t //= 2 else: ans = max(ans, ma[t]) t = (t - 1) // 2 return ans def fenwick_tree(n): tree = [0] * (n + 1) return tree def get_sum(i, tree): s = 0 while i > 0: s += tree[i] i -= i & -i return s def add(i, x, tree): while i < len(tree): tree[i] += x i += i & -i n = int(input()) a, x = [], [] for i in range(n): sa, ea, sb, eb = map(int, input().split()) a.append(ea * n + i) x.append((sa, ea, sb, eb)) a.sort() u = [] inf = pow(10, 9) + 1 l1 = pow(2, n.bit_length()) l2 = 2 * l1 mi, ma = [inf] * l2, [-inf] * l2 ok = 1 z = [[] for _ in range(n + 1)] s = set([inf, -inf]) for k in range(n): i = a[k] % n sa, ea, sb, eb = x[i] s.add(sb) s.add(eb) u.append(ea) c = bisect.bisect_left(u, sa) j = k + l1 mi[j], ma[j] = eb, sb j //= 2 while j: mi[j] = min(mi[2 * j], mi[2 * j + 1]) ma[j] = max(ma[2 * j], ma[2 * j + 1]) j //= 2 z[c].append(i) if c < k and (get_min(c, k - 1) < sb or eb < get_max(c, k - 1)): ok = 0 break if ok: l, r = ma[l1:], mi[l1:] s = list(s) s.sort() d = dict() m = len(s) for i in range(m): d[s[i]] = i + 1 cl, cr = fenwick_tree(m + 5), fenwick_tree(m + 5) for i in range(1, n + 1): add(d[l[i - 1]], 1, cl) add(d[r[i - 1]], 1, cr) for j in z[i]: _, _, sb, eb = x[j] if get_sum(d[sb] - 1, cr) ^ get_sum(d[eb], cl): ok = 0 break if not ok: break ans = "YES" if ok else "NO" print(ans)
py
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
def process(M): n = len(M) m = len(M[0]) answer = 0 for j in range(1, m+1): d = {} for i in range(n): entry = M[i][j-1] if entry % m == j % m and entry <= n*m: if j < m: entry1 = entry//m else: entry1 = entry//m-1 entry1 = (i-entry1) % n if entry1 not in d: d[entry1] = 0 d[entry1]+=1 moves = n for x in d: moves = min(moves, n-d[x]+x) answer+=moves return answer n, m = [int(x) for x in input().split()] M = [] for i in range(n): row = [int(x) for x in input().split()] M.append(row) print(process(M))
py
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10 codeforces dodivthree OutputCopy5 7 8 4 9 2 2 9 10 3 1 InputCopy7 abaca?b zabbbcc OutputCopy5 6 5 2 3 4 6 7 4 1 2 InputCopy9 bambarbia hellocode OutputCopy0 InputCopy10 code?????? ??????test OutputCopy10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
[ "greedy", "implementation" ]
n=int(input()) left=input() right=input() leftlist=[[] for _ in range(27)] for i in range(n): if left[i]!='?': leftlist[ord(left[i])-ord('a')].append(i) else: leftlist[26].append(i) res=[] temp=[] for i in range(n): if right[i]=='?': temp.append(i) else: x=ord(right[i])-ord('a') if len(leftlist[x])!=0: res.append([leftlist[x].pop()+1,i+1]) elif len(leftlist[26])!=0: res.append([leftlist[26].pop()+1,i+1]) for l in leftlist: while temp and l: res.append([l.pop()+1,temp.pop()+1]) print(len(res)) for r in res: print(*r)
py
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) arr.sort(reverse=True) print(*arr)
py
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2 3 3 2 1 6 3 1 4 1 5 9 OutputCopy3 5 NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
[ "greedy", "implementation" ]
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=set(l) print(len(s))
py
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
def find_nextmax(arr,x): for i in range(len(arr)): if arr[i]>x: y=arr[i] arr[i]=0 return y return -1 for _ in range(int(input())): n=int(input()) b=list(map(int,input().split())) a=[] for i in range(2*n): if i%2==0: a.append(b[i//2]) else: a.append(0) c=[i for i in range(1,2*n+1)] for i in range(0,2*n,2): c[a[i]-1]=0 possible=True # print(a,c) # print(find_nextmax(c,5)) # print(c) # print(a,c) for i in range(1,2*n,2): x=find_nextmax(c,a[i-1]) if x==-1: possible=False break a[i]=x # print(a,c) if not possible: print(-1) continue for i in a: print(i,end=' ') print()
py