index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
900
8
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date. The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1. Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month. A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1. Input The first line contains the single number d — the maximum number of the day that Vasya's clock can show (1 ≤ d ≤ 106). The second line contains a single integer n — the number of months in the year (1 ≤ n ≤ 2000). The third line contains n space-separated integers: ai (1 ≤ ai ≤ d) — the number of days in each month in the order in which they follow, starting from the first one. Output Print a single number — the number of times Vasya manually increased the day number by one throughout the last year. Examples Input 4 2 2 2 Output 2 Input 5 3 3 4 3 Output 3 Input 31 12 31 28 31 30 31 30 31 31 30 31 30 31 Output 7 Note In the first sample the situation is like this: * Day 1. Month 1. The clock shows 1. Vasya changes nothing. * Day 2. Month 1. The clock shows 2. Vasya changes nothing. * Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. * Day 2. Month 2. The clock shows 2. Vasya changes nothing. In total, Vasya manually changed the day number by 1 exactly 2 times.
def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(mi()) d = ii() n = ii() a = li() su= 0 for i in range(n-1): su+=(abs(a[i]-d)) print(su)
{ "input": [ "31\n12\n31 28 31 30 31 30 31 31 30 31 30 31\n", "5\n3\n3 4 3\n", "4\n2\n2 2\n" ], "output": [ "7", "3", "2" ] }
901
10
The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered). Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny. Input The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces. Output On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1. Examples Input 3 4 7 4 7 7 4 Output 0 Input 5 4 7 7 4 2 11 9 7 1 1 Output 2 Note In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0. In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.
def main(): n = int(input()) d = {} for i in range(n): a, b = [int(i) for i in input().split()] if a == b: if a not in d: d[a] = [0, 0] d[a][0] += 1 else: if a not in d: d[a] = [0, 0] d[a][0] += 1 if b not in d: d[b] = [0, 0] d[b][1] += 1 result = float("inf") half = (n + 1) // 2 for a, b in d.values(): if a + b >= half: result = min(max(0, half - a), result) if result == float("inf"): print(-1) else: print(result) main()
{ "input": [ "3\n4 7\n4 7\n7 4\n", "5\n4 7\n7 4\n2 11\n9 7\n1 1\n" ], "output": [ "0\n", "2\n" ] }
902
9
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers. Input The first input line contains 3 space-separated integer numbers n, m, v (3 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ v ≤ n), n — amount of servers, m — amount of direct connections, v — index of the server that fails and leads to the failure of the whole system. Output If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any. Examples Input 5 6 3 Output 1 2 2 3 3 4 4 5 1 3 3 5 Input 6 100 1 Output -1
def _print(v, n): for i in range(1, n + 1): if v != i: print(i," ",v) n, m, v = map(int,input().split()) l = (n - 1) * (n - 2) div = 2 + 1 if m < n - 1 or m > l//2+1: print(-1) exit() k = n - 1 if n == v: n -= 1 _print(v, n) x, y = 1, 1 while k != m: if x == n - 1: x = y + 2 y += 1 else: x += 1 if x != v and y != v: print(x," ",y) k+=1
{ "input": [ "5 6 3\n", "6 100 1\n" ], "output": [ "3 1\n3 2\n3 4\n3 5\n2 4\n2 5\n", "-1\n" ] }
903
8
Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime: 1. Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. 2. Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows: 1. If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. 2. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s. Input The first line contains a non-empty string s. It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string. Output In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s. Examples Input x Output x Input yxyxy Output y Input xxxxxy Output xxxx Note In the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change. In the second test the transformation will be like this: 1. string "yxyxy" transforms into string "xyyxy"; 2. string "xyyxy" transforms into string "xyxyy"; 3. string "xyxyy" transforms into string "xxyyy"; 4. string "xxyyy" transforms into string "xyy"; 5. string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".
def main(): stack = [] for c in input(): if stack and stack[-1] != c: del stack[-1] else: stack.append(c) print(''.join(reversed(stack))) if __name__ == '__main__': main()
{ "input": [ "x\n", "yxyxy\n", "xxxxxy\n" ], "output": [ "x", "y", "xxxx" ] }
904
8
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book. Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read. Input The first line contains two integers n and t (1 ≤ n ≤ 105; 1 ≤ t ≤ 109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 104), where number ai shows the number of minutes that the boy needs to read the i-th book. Output Print a single integer — the maximum number of books Valera can read. Examples Input 4 5 3 1 2 1 Output 3 Input 3 3 2 2 3 Output 1
def bs(a,t): d=0 c=0 for i in range(len(a)): d+=a[i] if d>t: d-=a[c] c+=1 return len(a)-c n,t=map(int,input().split()) a=[int(i) for i in input().split()] print(bs(a,t))
{ "input": [ "4 5\n3 1 2 1\n", "3 3\n2 2 3\n" ], "output": [ "3\n", "1\n" ] }
905
7
Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. Input The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value. Output In a single line print the answer to the problem — the maximum sum that Yaroslav can get. Examples Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 Note In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
def main(): n = int(input()) l = list(map(int, input().split())) res = sum(map(abs, l)) if not n & 1 and sum(x < 0 for x in l) & 1: res -= abs(min(l, key=abs)) * 2 print(res) if __name__ == '__main__': main()
{ "input": [ "2\n-1 -100 -1\n", "2\n50 50 50\n" ], "output": [ "100\n", "150\n" ] }
906
10
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types: 1. Blue towers. Each has population limit equal to 100. 2. Red towers. Each has population limit equal to 200. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side. Iahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case). Iahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible. He says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks. Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 500). Each of the next n lines contains m characters, describing the grid. The j-th character in the i-th line is '.' if you're allowed to build at the cell with coordinates (i, j) a tower (empty cell) or '#' if there is a big hole there. Output Print an integer k in the first line (0 ≤ k ≤ 106) — the number of operations Iahub should perform to obtain optimal result. Each of the following k lines must contain a single operation in the following format: 1. «B x y» (1 ≤ x ≤ n, 1 ≤ y ≤ m) — building a blue tower at the cell (x, y); 2. «R x y» (1 ≤ x ≤ n, 1 ≤ y ≤ m) — building a red tower at the cell (x, y); 3. «D x y» (1 ≤ x ≤ n, 1 ≤ y ≤ m) — destroying a tower at the cell (x, y). If there are multiple solutions you can output any of them. Note, that you shouldn't minimize the number of operations. Examples Input 2 3 ..# .#. Output 4 B 1 1 R 1 2 R 2 1 B 2 3 Input 1 3 ... Output 5 B 1 1 B 1 2 R 1 3 D 1 2 R 1 2
#Connected component import sys from collections import deque sys.setrecursionlimit(501 * 501) n,m = [int(i) for i in input().split()] a=[[0 for i in range(m)] for i in range(n)] d=[(0,1),(0,-1),(1,0),(-1,0)] q=deque() def main(): global a ans=[] first=[] q=deque() for i in range(n): line = input() for j in range(m): if line[j]=='#': a[i][j]=-1 else: first.append('B %s %s' %(i+1, j+1)) for i in range(n): for j in range(m): if a[i][j]!=-1: q.append((i,j)) while q: x,y = q.pop() if a[x][y]==-1: continue a[x][y] = -1 if (x,y)!=(i,j): ans.append('R %s %s' %(x+1,y+1)) ans.append('D %s %s' %(x+1,y+1)) for dx,dy in d: x1 = x+dx y1 = y+dy if (0<=x1<n) and (0<=y1<m) and a[x1][y1]!=-1: q.appendleft((x1,y1)) ans.reverse() print(len(ans)+len(first), end='\n') print('\n'.join(first)) print('\n'.join(ans)) main()
{ "input": [ "1 3\n...\n", "2 3\n..#\n.#.\n" ], "output": [ "7\nB 1 1\nB 1 2\nB 1 3\nD 1 3\nR 1 3\nD 1 2\nR 1 2\n", "8\nB 1 1\nB 2 1\nD 2 1\nR 2 1\nB 1 2\nD 1 2\nR 1 2\nB 2 3\n" ] }
907
7
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel. Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail. You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing. Input The first line contains a single integer k (1 ≤ k ≤ 5) — the number of panels Cucumber boy can press with his one hand. Next 4 lines contain 4 characters each (digits from 1 to 9, or period) — table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel. Output Output "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes). Examples Input 1 .135 1247 3468 5789 Output YES Input 5 ..1. 1111 ..1. ..1. Output YES Input 1 .... 12.1 .2.. .2.. Output NO Note In the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands.
k=int(input()) b={} for i in range(4): s=input() for i in s: if i in b:b[i]+=1 else:b[i]=1 def fn(b): for i in b: if i!='.' and b[i]>2*k:return 'NO' return 'YES' print(fn(b))
{ "input": [ "5\n..1.\n1111\n..1.\n..1.\n", "1\n.135\n1247\n3468\n5789\n", "1\n....\n12.1\n.2..\n.2..\n" ], "output": [ "YES\n", "YES\n", "NO\n" ] }
908
9
During the break, we decided to relax and play dominoes. Our box with Domino was empty, so we decided to borrow the teacher's dominoes. The teacher responded instantly at our request. He put nm dominoes on the table as an n × 2m rectangle so that each of the n rows contained m dominoes arranged horizontally. Each half of each domino contained number (0 or 1). We were taken aback, and the teacher smiled and said: "Consider some arrangement of dominoes in an n × 2m matrix. Let's count for each column of the matrix the sum of numbers in this column. Then among all such sums find the maximum one. Can you rearrange the dominoes in the matrix in such a way that the maximum sum will be minimum possible? Note that it is prohibited to change the orientation of the dominoes, they all need to stay horizontal, nevertheless dominoes are allowed to rotate by 180 degrees. As a reward I will give you all my dominoes". We got even more taken aback. And while we are wondering what was going on, help us make an optimal matrix of dominoes. Input The first line contains integers n, m (1 ≤ n, m ≤ 103). In the next lines there is a description of the teachers' matrix. Each of next n lines contains m dominoes. The description of one domino is two integers (0 or 1), written without a space — the digits on the left and right half of the domino. Output Print the resulting matrix of dominoes in the format: n lines, each of them contains m space-separated dominoes. If there are multiple optimal solutions, print any of them. Examples Input 2 3 01 11 00 00 01 11 Output 11 11 10 00 00 01 Input 4 1 11 10 01 00 Output 11 10 01 00 Note Consider the answer for the first sample. There, the maximum sum among all columns equals 1 (the number of columns is 6, and not 3). Obviously, this maximum can't be less than 1, then such matrix is optimal. Note that the dominoes can be rotated by 180 degrees.
def find_matrix_col_sum(mat): max_sum = -1 for cols in range(len(mat[0])): s = 0 for i in range(2): for rows in range(len(mat)): s+=int(mat[rows][cols][i]) if s > max_sum: max_sum = s return max_sum n,m=input().split() n,m=int(n), int(m) dominos_count = [0, 0, 0] for i in range(n): dominos = input().split() for dominohaya in dominos: if dominohaya == "11": dominos_count[0] += 1 elif dominohaya == "01" or dominohaya == "10": dominos_count[1] += 1 else: dominos_count[2] += 1 dominios_list = [0]*n total_sum = [0]*n prev_sum_row = [0]*(2*m) new_sum_row=[0]*(2*m) for i in range(n): new_row = [""]*(m) for j in range(m): if dominos_count[0] > 0: new_sum_row[2*j]=prev_sum_row[2 * j] + 1 new_sum_row[2*j+1]=prev_sum_row[2 * j + 1] + 1 new_row[j]="11" dominos_count[0] -= 1 elif dominos_count[1] > 0: min_val = min(prev_sum_row) if prev_sum_row[2 * j] == min_val: new_row[j]="10" dominos_count[1] -= 1 new_sum_row[2*j]=prev_sum_row[2 * j] + 1 new_sum_row[2*j+1]=prev_sum_row[2 * j + 1] elif prev_sum_row[2 * j + 1] == min_val: new_row[j]="01" dominos_count[1] -= 1 new_sum_row[2*j]=prev_sum_row[2 * j] new_sum_row[2*j+1]=prev_sum_row[2 * j + 1] + 1 else: if dominos_count[2]>0: new_row[j]="00" dominos_count[2] -= 1 new_sum_row[2*j]=prev_sum_row[2 * j] new_sum_row[2*j+1]=prev_sum_row[2 * j + 1] else: new_row[j]="01" dominos_count[1] -= 1 new_sum_row[2*j]=prev_sum_row[2 * j] + 1 new_sum_row[2*j+1]=prev_sum_row[2 * j + 1] + 1 else: new_row[j]="00" dominos_count[2] -= 1 new_sum_row[2*j]=prev_sum_row[2 * j] new_sum_row[2*j+1]=prev_sum_row[2 * j + 1] total_sum[i] = new_sum_row # dominios_list[i] = new_row prev_sum_row = new_sum_row s = " ".join(new_row) print(s) # for i in range(n): # for j in range(m): # print(dominios_list[i][j], end="") # if j < m-1: # print(" ", end="") # print("") #
{ "input": [ "4 1\n11\n10\n01\n00\n", "2 3\n01 11 00\n00 01 11\n" ], "output": [ "11 \n10 \n01 \n00 \n", "11 11 10 \n00 00 01 \n" ] }
909
9
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>. Input The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤ 109) — the elements of array a. Output Print a single integer — the number of ways to split the array into three parts with the same sum. Examples Input 5 1 2 3 0 3 Output 2 Input 4 0 1 -1 0 Output 1 Input 2 4 1 Output 0
def main(): n = int(input()) l = list(map(int,input().split())) s=0 for x in l: s+=x if s%3!=0: print(0) else: s//=3 su=0 k=0 ans=0 l.pop() for x in l: su+=x if su==2*s: ans+=k if su==s: k+=1 print(ans) if __name__ == '__main__': main()
{ "input": [ "2\n4 1\n", "4\n0 1 -1 0\n", "5\n1 2 3 0 3\n" ], "output": [ "0\n", "1\n", "2\n" ] }
910
7
Uncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown. Input The first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture. Output Print "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?". Examples Input rock rock rock Output ? Input paper rock rock Output F Input scissors rock rock Output ? Input scissors paper rock Output ?
f = input() m = input() s = input() def win(x, y): return (x == 'rock' and y == 'scissors') or (x == 'scissors' and y == 'paper') or (x == 'paper' and y == 'rock') if win(f, m) and win(f, s): print("F") elif win(m, f) and win(m, s): print("M") elif win(s, f) and win(s, m): print("S") else: print("?")
{ "input": [ "scissors\nrock\nrock\n", "scissors\npaper\nrock\n", "rock\nrock\nrock\n", "paper\nrock\nrock\n" ], "output": [ "?\n", "?\n", "?\n", "F\n" ] }
911
7
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point. Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in). Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city. For each city calculate two values ​​mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city Input The first line of the input contains integer n (2 ≤ n ≤ 105) — the number of cities in Lineland. The second line contains the sequence of n distinct integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order. Output Print n lines, the i-th line must contain two integers mini, maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city. Examples Input 4 -5 -2 2 7 Output 3 12 3 9 4 7 5 12 Input 2 -1 1 Output 2 2 2 2
def call(i,a): print(min(abs(a[i]-a[i-1]),abs(a[i]-a[i+1])),max(abs(a[i]-a[0]),abs(a[i]-a[n-1]))) n=int(input()) a=list(map(int,input().split())) print(abs(a[0]-a[1]),abs(a[0]-a[n-1])) for i in range(1,n-1): call(i,a) print(abs(a[n-2]-a[n-1]),abs(a[n-1]-a[0]))
{ "input": [ "2\n-1 1\n", "4\n-5 -2 2 7\n" ], "output": [ "2 2\n2 2\n", "3 12\n3 9\n4 7\n5 12\n" ] }
912
9
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. <image> Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two. Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. Input The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values. Output Print the minimum number of steps in a single line. Examples Input 5 1 1 2 3 3 Output 2 Input 4 0 1 2 3 Output 4 Note In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two. In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.
def inc(a,w): n=len(a) i=w while(i<n and a[i]==1): a[i]=0 i+=1 if(i<n): a[i]=1 else: a.append(1) n=int(input()) x=input().split(' ') w=[int(y) for y in x] a=[0]*1000024 for t in w: inc(a,t) print(sum(a))
{ "input": [ "5\n1 1 2 3 3\n", "4\n0 1 2 3\n" ], "output": [ "2\n", "4\n" ] }
913
11
Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones. The mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After x minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo p will the mushrooms have in another y minutes? Input The first line contains four integers n, x, y, p (1 ≤ n ≤ 106, 0 ≤ x, y ≤ 1018, x + y > 0, 2 ≤ p ≤ 109) which represent the number of mushrooms, the number of minutes after the first replanting, the number of minutes after the second replanting and the module. The next line contains n integers ai which represent the mushrooms' weight in the non-decreasing order (0 ≤ ai ≤ 109). Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d). Output The answer should contain a single number which is the total weights of the mushrooms modulo p in the end after x + y minutes. Examples Input 2 1 0 657276545 1 2 Output 6 Input 2 1 1 888450282 1 2 Output 14 Input 4 5 0 10000 1 2 3 4 Output 1825
#!/usr/bin/pypy3 from sys import stdin, stdout input, print = stdin.readline, stdout.write p = 0 def readints(): return list(map(int, input().split())) def writeln(x): print(str(x) + '\n') def mod(x): return (x % p + p) % p def matmul(a, b): n = len(a) c = [[0 for x in range(n)] for y in range(n)] for i in range(n): for j in range(n): for k in range(n): c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % p return c def matpow(b, p): n = len(b) res = [[0 if x != y else 1 for x in range(n)] for y in range(n)] while p: if p & 1: res = matmul(res, b) b = matmul(b, b) p >>= 1 return res n, x, y, p = readints() a = [each % p for each in sorted(readints())] if n == 1: writeln(a[0]) exit(0) """ [a sum] * [[1 -1], = [a sum] [0 3]] [sc mv] * [[0 1], [1, 1]] = [mv mv+sc] """ b = matpow([ [1, -1], [0, 3]], x) sum0 = matmul([ [a[0] + a[-1], sum(a)], [0, 0]], b)[0][1] b = matpow([ [0, 1], [1, 1]], x) maxa = matmul( [[a[-2], a[-1]], [0, 0]], b)[0][1] b = matpow([ [1, -1], [0, 3]], y) sum1 = matmul([ [a[0] + maxa, sum0], [0, 0]], b)[0][1] writeln(mod(sum1))
{ "input": [ "2 1 0 657276545\n1 2\n", "4 5 0 10000\n1 2 3 4\n", "2 1 1 888450282\n1 2\n" ], "output": [ "6", "1825", "14" ] }
914
8
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive. The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest. Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct. Output Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region. Examples Input 5 2 Ivanov 1 763 Andreev 2 800 Petrov 1 595 Sidorov 1 790 Semenov 2 503 Output Sidorov Ivanov Andreev Semenov Input 5 2 Ivanov 1 800 Andreev 2 763 Petrov 1 800 Sidorov 1 800 Semenov 2 503 Output ? Andreev Semenov Note In the first sample region teams are uniquely determined. In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.
def cmp(x): return x[1] n,m=map(int,input().split()) q=[[] for i in range(m)] for i in range(n): name,r,b=input().split() q[int(r)-1].append([name,int(b)]) for i in q: i=sorted(i,key=cmp) if len(i)==2: print(i[-1][0],i[-2][0]) elif i[-1][1]==i[-2][1]==i[-3][1] or i[-2][1]==i[-3][1]: print('?') else: print(i[-1][0],i[-2][0])
{ "input": [ "5 2\nIvanov 1 763\nAndreev 2 800\nPetrov 1 595\nSidorov 1 790\nSemenov 2 503\n", "5 2\nIvanov 1 800\nAndreev 2 763\nPetrov 1 800\nSidorov 1 800\nSemenov 2 503\n" ], "output": [ "Sidorov Ivanov\nAndreev Semenov\n", "?\nAndreev Semenov\n" ] }
915
10
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n. Each man has at most one father but may have arbitrary number of sons. Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied: * A = B; * the man number A is the father of the man number B; * there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B. Of course, if the man number A is an ancestor of the man number B and A ≠ B, then the man number B is not an ancestor of the man number A. The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens. 1. A list of candidates is prepared, containing some (possibly all) of the n men in some order. 2. Each of the n men decides to give a gift. 3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself. 4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone. This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above? Input In the first line of the input two integers n and m (0 ≤ m < n ≤ 100 000) are given — the number of the men in the Sasha's family and the number of family relations in it respectively. The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 ≤ pi, qi ≤ n, pi ≠ qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 ≤ i ≤ n the man numbered ai is an ancestor of the man numbered i. Output Print an integer k (1 ≤ k ≤ n) — the number of the men in the list of candidates, in the first line. Print then k pairwise different positive integers not exceeding n — the numbers of the men in the list in an order satisfying every of the men's wishes, one per line. If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line. Examples Input 3 2 1 2 2 3 1 2 1 Output -1 Input 4 2 1 2 3 4 1 2 3 3 Output 3 2 1 3 Note The first sample explanation: * if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1); * if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2); * if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2). * if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1).
n, m = map(int, input().split()) adj = [[] for _ in range(n)] cp = [-1] * n for i in range(m): p, c = map(int, input().split()) adj[p - 1].append(c - 1) cp[c - 1] = p - 1 pres = [i - 1 for i in map(int, input().split())] level = [0] * n from collections import deque def bfs(v): q = deque([v]) while q: v = q.pop() if cp[v] >= 0: level[v] = level[cp[v]] + 1 for nv in adj[v]: q.append(nv) for i in range(n): if cp[i] == -1: bfs(i) for i in range(n): if level[i] > 0: par = cp[i] if pres[i] != pres[par] and level[pres[i]] <= level[par]: print(-1) exit() pres = list(set(pres)) pres = sorted(pres, key = lambda i : level[i], reverse = True) print(len(pres)) pres = [i + 1 for i in pres] print("\n".join(map(str, pres)))
{ "input": [ "3 2\n1 2\n2 3\n1 2 1\n", "4 2\n1 2\n3 4\n1 2 3 3\n" ], "output": [ "-1\n", "3\n2\n1\n3\n" ] }
916
7
Vasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: * multiply the current number by 2 (that is, replace the number x by 2·x); * append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasily to transform the number a into the number b using only the operations described above, or find that it is impossible. Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform a into b. Input The first line contains two positive integers a and b (1 ≤ a < b ≤ 109) — the number which Vasily has and the number he wants to have. Output If there is no way to get b from a, print "NO" (without quotes). Otherwise print three lines. On the first line print "YES" (without quotes). The second line should contain single integer k — the length of the transformation sequence. On the third line print the sequence of transformations x1, x2, ..., xk, where: * x1 should be equal to a, * xk should be equal to b, * xi should be obtained from xi - 1 using any of two described operations (1 < i ≤ k). If there are multiple answers, print any of them. Examples Input 2 162 Output YES 5 2 4 8 81 162 Input 4 42 Output NO Input 100 40021 Output YES 5 100 200 2001 4002 40021
def reach(a, b, path=[]): if a > b: return if a == b: path.append(a) print("YES") print(len(path)) print(*path) exit(0) reach(a*2,b,path+[a]) reach(a*10+1,b,path+[a]) a,b=map(int,input().split()) reach(a,b,[]) print("NO")
{ "input": [ "4 42\n", "2 162\n", "100 40021\n" ], "output": [ "NO\n", "YES\n5\n2 4 8 81 162 \n", "YES\n5\n100 200 2001 4002 40021 \n" ] }
917
8
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard. You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once. Input The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters. Output If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes). Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct. If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair. Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes. Examples Input helloworld ehoolwlroz Output 3 h e l o d z Input hastalavistababy hastalavistababy Output 0 Input merrychristmas christmasmerry Output -1
def solve(s, t): n=len(s) M={} for i in range(n): if M.get(s[i], t[i])!=t[i] or M.get(t[i], s[i])!=s[i]: return -1 M[ s[i] ]=t[i] M[ t[i] ]=s[i] return M M=solve(input(), input()) if M==-1: print(-1) else: M=list((c, M[c]) for c in M if c<M[c]) print(len(M)) for x in M: print(*x)
{ "input": [ "helloworld\nehoolwlroz\n", "hastalavistababy\nhastalavistababy\n", "merrychristmas\nchristmasmerry\n" ], "output": [ "3\nh e\nl o\nd z\n", "0\n", "-1\n" ] }
918
7
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures). There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves. Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z. For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well. Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes. Input The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input. Output If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes). Examples Input 4 3 1 3 3 4 1 4 Output YES Input 4 4 3 1 2 3 3 4 1 2 Output NO Input 10 4 4 3 5 10 8 9 1 2 Output YES Input 3 2 1 2 2 3 Output NO Note The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not. <image>
from collections import Counter as cntr from math import inf def cin(): return map(int, input().split(' ')) def dfs(graph, src, n): q = [src] h = 0 global visited edges = 0 while q: idx = q.pop() h += 1 for v in graph[idx]: edges += 1 if visited[v] == False: visited[v] = True q.append(v) return h,edges n,m = cin() g = {i:[] for i in range(n)} for i in range(m): a, b = cin() a -= 1 b -= 1 g[a].append(b) g[b].append(a) visited = [False for i in range(n)] for i in range(n): if visited[i] == False: visited[i] = True v,e = dfs(g, i, n) e = e//2 if e != (v*(v-1))//2: print('NO') exit(0) print('YES')
{ "input": [ "10 4\n4 3\n5 10\n8 9\n1 2\n", "4 4\n3 1\n2 3\n3 4\n1 2\n", "3 2\n1 2\n2 3\n", "4 3\n1 3\n3 4\n1 4\n" ], "output": [ "YES\n", "NO\n", "NO\n", "YES\n" ] }
919
7
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. <image> The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: house i and house i + 1 (1 ≤ i < n) are exactly 10 meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased. You will be given n integers a1, a2, ..., an that denote the availability and the prices of the houses. If house i is occupied, and therefore cannot be bought, then ai equals 0. Otherwise, house i can be bought, and ai represents the money required to buy it, in dollars. As Zane has only k dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love. Input The first line contains three integers n, m, and k (2 ≤ n ≤ 100, 1 ≤ m ≤ n, 1 ≤ k ≤ 100) — the number of houses in the village, the house where the girl lives, and the amount of money Zane has (in dollars), respectively. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100) — denoting the availability and the prices of the houses. It is guaranteed that am = 0 and that it is possible to purchase some house with no more than k dollars. Output Print one integer — the minimum distance, in meters, from the house where the girl Zane likes lives to the house Zane can buy. Examples Input 5 1 20 0 27 32 21 19 Output 40 Input 7 3 50 62 0 0 0 99 33 22 Output 30 Input 10 5 100 1 0 1 0 0 0 0 0 1 1 Output 20 Note In the first sample, with k = 20 dollars, Zane can buy only house 5. The distance from house m = 1 to house 5 is 10 + 10 + 10 + 10 = 40 meters. In the second sample, Zane can buy houses 6 and 7. It is better to buy house 6 than house 7, since house m = 3 and house 6 are only 30 meters away, while house m = 3 and house 7 are 40 meters away.
n, m, k = [int(x) for x in input().split()] ls = [int(x) for x in input().split()] dp = [] def dist(f, t): return abs((t-f)*10) for i in range(0,n): if ls[i] != 0 and ls[i] <= k: dp.append(dist(m-1,i)) else: dp.append(1000) print(min(dp))
{ "input": [ "10 5 100\n1 0 1 0 0 0 0 0 1 1\n", "5 1 20\n0 27 32 21 19\n", "7 3 50\n62 0 0 0 99 33 22\n" ], "output": [ "20", "40", "30" ] }
920
8
To stay woke and attentive during classes, Karen needs some coffee! <image> Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe". She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste. Karen thinks that a temperature is admissible if at least k recipes recommend it. Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range? Input The first line of input contains three integers, n, k (1 ≤ k ≤ n ≤ 200000), and q (1 ≤ q ≤ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively. The next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1 ≤ li ≤ ri ≤ 200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive. The next q lines describe the questions. Each of these lines contains a and b, (1 ≤ a ≤ b ≤ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive. Output For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive. Examples Input 3 2 4 91 94 92 97 97 99 92 94 93 97 95 96 90 100 Output 3 3 0 4 Input 2 1 1 1 1 200000 200000 90 100 Output 0 Note In the first test case, Karen knows 3 recipes. 1. The first one recommends brewing the coffee between 91 and 94 degrees, inclusive. 2. The second one recommends brewing the coffee between 92 and 97 degrees, inclusive. 3. The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. A temperature is admissible if at least 2 recipes recommend it. She asks 4 questions. In her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible. In her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible. In her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none. In her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible. In the second test case, Karen knows 2 recipes. 1. The first one, "wikiHow to make Cold Brew Coffee", recommends brewing the coffee at exactly 1 degree. 2. The second one, "What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?", recommends brewing the coffee at exactly 200000 degrees. A temperature is admissible if at least 1 recipe recommends it. In her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none.
import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def pref_sum(s): t = 0 for i in range(200002): t += s[i] s[i] = t n, k, q = map(int, input().split()) s = [0]*(200002) for _ in range(n): l, r = map(int, input().split()) s[l] += 1 s[r+1] -= 1 pref_sum(s) for i in range(200002): s[i] = (1 if s[i] >= k else 0) pref_sum(s) for _ in range(q): l, r = map(int, input().split()) print(s[r] - s[l-1])
{ "input": [ "3 2 4\n91 94\n92 97\n97 99\n92 94\n93 97\n95 96\n90 100\n", "2 1 1\n1 1\n200000 200000\n90 100\n" ], "output": [ "3\n3\n0\n4\n", "0\n" ] }
921
8
Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally? Input First line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109). Output Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes). Examples Input 4 1 3 2 3 Output First Input 2 2 2 Output Second Note In first sample first player remove whole array in one move and win. In second sample first player can't make a move and lose.
def f(l): return 'First' if sum([i%2>0 for i in l])>0 else 'Second' _ = input() l = list(map(int,input().split())) print(f(l))
{ "input": [ "4\n1 3 2 3\n", "2\n2 2\n" ], "output": [ "First\n", "Second\n" ] }
922
9
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets. Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106. Input The only line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the set and the desired bitwise-xor, respectively. Output If there is no such set, print "NO" (without quotes). Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them. Examples Input 5 5 Output YES 1 2 4 5 7 Input 3 6 Output YES 1 2 5 Note You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR> For the first sample <image>. For the second sample <image>.
def list_input(): return list(map(int,input().split())) def map_input(): return map(int,input().split()) def map_string(): return input().split() from random import randint n,x = map_input() if n == 2 and x == 0: print("NO") else: while True: s = set([]) a = [] cnt = 0 for i in range(n-1): while True: cur = randint(0,500001) if cur not in s: s.add(cur) a.append(cur) cnt ^= cur break cnt ^= x if cnt in s: continue else: print("YES") for i in a: print(i,end=' ') print(cnt) break
{ "input": [ "3 6\n", "5 5\n" ], "output": [ "YES\n0 131072 131078\n", "YES\n1 2 0 131072 131078\n" ] }
923
7
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima. An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array. Input The first line contains one integer n (1 ≤ n ≤ 1000) — the number of elements in array a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of array a. Output Print the number of local extrema in the given array. Examples Input 3 1 2 3 Output 0 Input 4 1 5 2 5 Output 2
def le(v,n): t=0 for c in range(1,n-1): if v[c-1]<v[c]>v[c+1] or v[c-1]>v[c]<v[c+1]: t+=1 return t n=int(input()) v=[int(c) for c in input().split()] print(le(v,n))
{ "input": [ "3\n1 2 3\n", "4\n1 5 2 5\n" ], "output": [ "0\n", "2\n" ] }
924
8
Petya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side. Determine a minimal number of wooden bars which are needed to make the frames for two doors. Petya can cut the wooden bars into any parts, but each side of each door should be a solid piece of a wooden bar (or a whole wooden bar). Input The first line contains a single integer n (1 ≤ n ≤ 1 000) — the length of each wooden bar. The second line contains a single integer a (1 ≤ a ≤ n) — the length of the vertical (left and right) sides of a door frame. The third line contains a single integer b (1 ≤ b ≤ n) — the length of the upper side of a door frame. Output Print the minimal number of wooden bars with length n which are needed to make the frames for two doors. Examples Input 8 1 2 Output 1 Input 5 3 4 Output 6 Input 6 4 2 Output 4 Input 20 5 6 Output 2 Note In the first example one wooden bar is enough, since the total length of all six sides of the frames for two doors is 8. In the second example 6 wooden bars is enough, because for each side of the frames the new wooden bar is needed.
def check(n,a,b,vertical,upper,bar,bars): if vertical==0 and upper==0: bars[bar-1]=True return for i in range(vertical+1): for j in range(upper+1): if i+j>0 and i*a+j*b<=n: check(n,a,b,vertical-i,upper-j,bar+1,bars) n=int(input()) a=int(input()) b=int(input()) bars=[False]*6 check(n,a,b,4,2,0,bars) for i in range(6): if bars[i]: print(i+1) break
{ "input": [ "6\n4\n2\n", "5\n3\n4\n", "8\n1\n2\n", "20\n5\n6\n" ], "output": [ "4", "6", "1", "2" ] }
925
11
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight <image> (where <image> is the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)). Can you find the weight of the minimum spanning tree of that graph? You can read about complete graphs in <https://en.wikipedia.org/wiki/Complete_graph> You can read about the minimum spanning tree in <https://en.wikipedia.org/wiki/Minimum_spanning_tree> The weight of the minimum spanning tree is the sum of the weights on the edges included in it. Input The only line contains an integer n (2 ≤ n ≤ 1012), the number of vertices in the graph. Output The only line contains an integer x, the weight of the graph's minimum spanning tree. Example Input 4 Output 4 Note In the first sample: <image> The weight of the minimum spanning tree is 1+2+1=4.
a = int(input()) def ans(n, p=1): return ans( (n+1) // 2, p*2 ) + (n//2)*p if n > 1 else 0 print (ans(a))
{ "input": [ "4\n" ], "output": [ "4\n" ] }
926
9
You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Count the number of connected components in that graph. Input In the first line of input there are two integers n and m (0 ≤ n ≤ 22, 1 ≤ m ≤ 2^{n}). In the second line there are m integers a_1, a_2, …, a_m (0 ≤ a_{i} < 2^{n}) — the elements of the set. All a_{i} are distinct. Output Print the number of connected components. Examples Input 2 3 1 2 3 Output 2 Input 5 5 5 19 10 20 12 Output 2 Note Graph from first sample: <image> Graph from second sample: <image>
n, m = map(int, input().split()) a = set(map(int, input().split())) y = 2 ** n mk = [0] * (2 * y) cur = 0 for x in a: if mk[x]: continue mk[x] = 1 st = [x] def push(v): if not mk[v]: mk[v] = 1; st.append(v) while st: u = st.pop() if u < y: push(y + u) else: for b in range(n): v = u | 1 << b push(v) v = y - 1 - (u - y) if v in a: push(v) cur += 1 print(cur)
{ "input": [ "2 3\n1 2 3\n", "5 5\n5 19 10 20 12\n" ], "output": [ "2\n", "2\n" ] }
927
12
There is a rectangular grid of size n × m. Each cell has a number written on it; the number on the cell (i, j) is a_{i, j}. Your task is to calculate the number of paths from the upper-left cell (1, 1) to the bottom-right cell (n, m) meeting the following constraints: * You can move to the right or to the bottom only. Formally, from the cell (i, j) you may move to the cell (i, j + 1) or to the cell (i + 1, j). The target cell can't be outside of the grid. * The xor of all the numbers on the path from the cell (1, 1) to the cell (n, m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid. Input The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 20, 0 ≤ k ≤ 10^{18}) — the height and the width of the grid, and the number k. The next n lines contain m integers each, the j-th element in the i-th line is a_{i, j} (0 ≤ a_{i, j} ≤ 10^{18}). Output Print one integer — the number of paths from (1, 1) to (n, m) with xor sum equal to k. Examples Input 3 3 11 2 1 5 7 10 0 12 6 4 Output 3 Input 3 4 2 1 3 3 3 0 3 3 2 3 0 1 1 Output 5 Input 3 4 1000000000000000000 1 3 3 3 0 3 3 2 3 0 1 1 Output 0 Note All the paths from the first example: * (1, 1) → (2, 1) → (3, 1) → (3, 2) → (3, 3); * (1, 1) → (2, 1) → (2, 2) → (2, 3) → (3, 3); * (1, 1) → (1, 2) → (2, 2) → (3, 2) → (3, 3). All the paths from the second example: * (1, 1) → (2, 1) → (3, 1) → (3, 2) → (3, 3) → (3, 4); * (1, 1) → (2, 1) → (2, 2) → (3, 2) → (3, 3) → (3, 4); * (1, 1) → (2, 1) → (2, 2) → (2, 3) → (2, 4) → (3, 4); * (1, 1) → (1, 2) → (2, 2) → (2, 3) → (3, 3) → (3, 4); * (1, 1) → (1, 2) → (1, 3) → (2, 3) → (3, 3) → (3, 4).
n, m, k = map(int, input().split()) l = [list(map(int, input().split())) for _ in range(n)] re = 0 half = (m + n - 2) // 2 d = [dict() for _ in range(22)] def forward(i, j, value): if i >= n or j >= m: return value ^= l[i][j] if i + j == half: if value in d[i]: d[i][value] += 1 else: d[i][value] = 1 return None forward(i+1, j, value) forward(i, j+1, value) def backward(i, j, value): if i < 0 or j < 0: return if i + j == half: tmp = k^value #print(tmp) if tmp in d[i]: global re re += d[i][tmp] return None value ^= l[i][j] backward(i-1, j, value) backward(i, j-1, value) forward(0, 0, 0) backward(n-1, m-1, 0) #print(d) print(re)
{ "input": [ "3 4 1000000000000000000\n1 3 3 3\n0 3 3 2\n3 0 1 1\n", "3 3 11\n2 1 5\n7 10 0\n12 6 4\n", "3 4 2\n1 3 3 3\n0 3 3 2\n3 0 1 1\n" ], "output": [ "0\n", "3\n", "5\n" ] }
928
11
Vasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, ..., s_k that s_1 + s_2 + ... + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others. Let's call some partition of a beautiful if each of its elements contains no leading zeros. Vasya want to know the number of beautiful partitions of number a, which has each of s_i satisfy the condition l ≤ s_i ≤ r. Note that the comparison is the integer comparison, not the string one. Help Vasya to count the amount of partitions of number a such that they match all the given requirements. The result can be rather big, so print it modulo 998244353. Input The first line contains a single integer a~(1 ≤ a ≤ 10^{1000000}). The second line contains a single integer l~(0 ≤ l ≤ 10^{1000000}). The third line contains a single integer r~(0 ≤ r ≤ 10^{1000000}). It is guaranteed that l ≤ r. It is also guaranteed that numbers a, l, r contain no leading zeros. Output Print a single integer — the amount of partitions of number a such that they match all the given requirements modulo 998244353. Examples Input 135 1 15 Output 2 Input 10000 0 9 Output 1 Note In the first test case, there are two good partitions 13+5 and 1+3+5. In the second test case, there is one good partition 1+0+0+0+0.
def kmp(pat,text,t): s=pat+"?"+text; #z[i] es el tamaño del prefijo mas largo de, formado por una subcadena s[i:...] z=[0 for i in range(len(s))] L=0;R=0;n=len(s); for i in range(1,len(s)): if i>R: L=R=i while R<n and s[R-L]==s[R]: R+=1 z[i]=R-L R-=1 elif z[i-L]+i<=R: z[i]=z[i-L] else: L=i while R<n and s[R-L]==s[R]: R+=1 z[i]=R-L R-=1 for i in range(len(pat)+1,len(z)): dp[t][i-(len(pat)+1)]=z[i]%len(pat) from sys import stdin mod=998244353 a=stdin.readline().strip() l=stdin.readline().strip() r=stdin.readline().strip() x=len(l) y=len(r) n=len(a) dp=[[0 for i in range(len(a))]for j in range(2)] ans=[0 for i in range(len(a)+1)] ans[-1]=1 kmp(l,a,0) kmp(r,a,1) auxl=x-1 auxr=y-1 acum=[0 for i in range(n+2)] acum[n]=1 for i in range(n-1,-1,-1): if a[i]=="0": if l[0]=="0": ans[i]=ans[i+1] acum[i]=(acum[i+1]+ans[i])%mod continue if auxl>=n: acum[i]=(acum[i+1]+ans[i])%mod continue if auxl!=auxr: if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]]: ans[i]=(ans[i]+ans[i+auxl+1])%mod if (auxr+i)<n and a[dp[1][i]+i]<=r[dp[1][i]]: ans[i]=(ans[i]+ans[i+auxr+1])%mod else: if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]] and a[dp[1][i]+i]<=r[dp[1][i]]: ans[i]=(ans[i]+ans[i+auxl+1])%mod lim1=auxl+i+2 lim2=min(auxr+i+1,n+1) if lim1<lim2: ans[i]=(ans[i]+acum[lim1]-acum[lim2])%mod acum[i]=(acum[i+1]+ans[i])%mod print(ans[0]%mod)
{ "input": [ "135\n1\n15\n", "10000\n0\n9\n" ], "output": [ "2", "1" ] }
929
12
You are given an undirected unweighted tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges. Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1). It is guaranteed that it is possible to choose such pairs for the given tree. Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths. It is guaranteed that the answer with at least two common vertices exists for the given tree. The length of the path is the number of edges in it. The simple path is the path that visits each vertex at most once. Input The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5). Each of the next n - 1 lines describes the edges of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). It is guaranteed that the given edges form a tree. It is guaranteed that the answer with at least two common vertices exists for the given tree. Output Print any two pairs of vertices satisfying the conditions described in the problem statement. It is guaranteed that it is possible to choose such pairs for the given tree. Examples Input 7 1 4 1 5 1 6 2 3 2 4 4 7 Output 3 6 7 5 Input 9 9 3 3 5 1 2 4 3 4 7 1 7 4 6 3 8 Output 2 9 6 8 Input 10 6 8 10 3 3 7 5 8 1 7 7 2 2 9 2 8 1 4 Output 10 6 4 5 Input 11 1 2 2 3 3 4 1 5 1 6 6 7 5 8 5 9 4 10 4 11 Output 9 11 8 10 Note The picture corresponding to the first example: <image> The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7. The picture corresponding to the second example: <image> The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8. The picture corresponding to the third example: <image> The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10. The picture corresponding to the fourth example: <image> The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12.
import sys n = int(sys.stdin.readline()) edges = [[] for _ in range(n)] for _ in range(n - 1): i, j = tuple(int(k) for k in sys.stdin.readline().split()) i -= 1 j -= 1 edges[i].append(j) edges[j].append(i) # Prunes the graph starting from the vertices with # only 1 edge until we reach a vertex with 3+ edges. # Stores the distance from each non-pruned vertex # to each of the leaves it reaches. def prune(): pruned = [False for _ in range(n)] leaves = [[] for _ in range(n)] todo = [] for i in range(n): if len(edges[i]) == 1: todo.append((0, i, i)) while len(todo) > 0: d, i, j = todo.pop() pruned[j] = True for k in edges[j]: if not pruned[k]: if len(edges[k]) < 3: todo.append((d + 1, i, k)) else: leaves[k].append((d + 1, i)) return pruned, leaves pruned, leaves = prune() # Returns the furthest non-pruned vertices # from another non-pruned vertex. def furthest(i): assert not pruned[i] visited = list(pruned) top_distance = 0 top_vertices = [] todo = [(0, i)] while len(todo) > 0: d, i = todo.pop() visited[i] = True if d > top_distance: top_distance = d top_vertices = [] if d == top_distance: top_vertices.append(i) for j in edges[i]: if not visited[j]: todo.append((d + 1, j)) return top_vertices # Single center topology. # Only 1 vertex with 3+ edges. def solve_single_center(i): l = list(reversed(sorted(leaves[i])))[:4] return list(l[j][1] for j in range(4)) # Scores non-pruned vertices according to the sum # of the distances to their two furthest leaves. def vertices_score(v): scores = [] for i in v: assert not pruned[i] l = list(reversed(sorted(leaves[i])))[:2] score = (l[0][0] + l[1][0]), l[0][1], l[1][1] scores.append(score) return list(reversed(sorted(scores))) # Single cluster topology. # 1 cluster of vertices, all equally far away from each other. def solve_single_cluster(v): s = vertices_score(v)[:2] return s[0][1], s[1][1], s[0][2], s[1][2] # Double cluster topology. # 2 clusters of vertices, pairwise equally far away from each other. def solve_double_cluster(v1, v2): s1 = vertices_score(v1)[:1] s2 = vertices_score(v2)[:1] return s1[0][1], s2[0][1], s1[0][2], s2[0][2] def solve(): def start_vertex(): for i in range(n): if not pruned[i]: return furthest(i)[0] i = start_vertex() v1 = furthest(i) if len(v1) == 1 and v1[0] == i: return solve_single_center(v1[0]) else: v2 = furthest(v1[0]) v = list(set(v1) | set(v2)) if len(v) < len(v1) + len(v2): return solve_single_cluster(v) else: return solve_double_cluster(v1, v2) a, b, c, d = solve() print(a + 1, b + 1) print(c + 1, d + 1)
{ "input": [ "9\n9 3\n3 5\n1 2\n4 3\n4 7\n1 7\n4 6\n3 8\n", "10\n6 8\n10 3\n3 7\n5 8\n1 7\n7 2\n2 9\n2 8\n1 4\n", "11\n1 2\n2 3\n3 4\n1 5\n1 6\n6 7\n5 8\n5 9\n4 10\n4 11\n", "7\n1 4\n1 5\n1 6\n2 3\n2 4\n4 7\n" ], "output": [ "8 2\n5 6\n", "10 6\n4 5\n", "11 9\n10 8\n", "3 6\n7 5\n" ] }
930
12
You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph. You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it. What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph. Input The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices. Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins. Output Print one integer — the minimum number of coins you have to pay to make the graph connected. Examples Input 3 2 1 3 3 2 3 5 2 1 1 Output 5 Input 4 0 1 3 3 7 Output 16 Input 5 4 1 2 3 4 5 1 2 8 1 3 10 1 4 7 1 5 15 Output 18 Note In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers. In next two examples the optimal answer may be achieved without using special offers.
import sys input = sys.stdin.readline n,m=map(int,input().split()) A=list(map(int,input().split())) SP=[list(map(int,input().split())) for i in range(m)] MIN=min(A) x=A.index(MIN) EDGE_x=[[x+1,i+1,A[x]+A[i]] for i in range(n) if x!=i] EDGE=EDGE_x+SP EDGE.sort(key=lambda x:x[2]) #UnionFind Group=[i for i in range(n+1)] def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): Group[find(y)]=Group[find(x)]=min(find(y),find(x)) ANS=0 for i,j,x in EDGE: if find(i)!=find(j): ANS+=x Union(i,j) print(ANS)
{ "input": [ "5 4\n1 2 3 4 5\n1 2 8\n1 3 10\n1 4 7\n1 5 15\n", "3 2\n1 3 3\n2 3 5\n2 1 1\n", "4 0\n1 3 3 7\n" ], "output": [ "18\n", "5\n", "16\n" ] }
931
7
You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding). If there are many such subsegments find the longest one. Input The first line contains single integer n (1 ≤ n ≤ 10^5) — length of the array a. The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the array a. Output Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean. Example Input 5 6 1 6 6 0 Output 2 Note The subsegment [3, 4] is the longest among all subsegments with maximum arithmetic mean.
def inpl(): return list(map(int, input().split())) N = int(input()) A = inpl() + [-1] x = max(A) ctr = 0 ans = 0 for a in A: if a == x: ctr += 1 else: ans = max(ans, ctr) ctr = 0 print(ans)
{ "input": [ "5\n6 1 6 6 0\n" ], "output": [ "2\n" ] }
932
9
You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root. Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1. <image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5 You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them. You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v. <image> An example of deletion of the vertex 7. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices. Output In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1. Examples Input 5 3 1 1 1 -1 0 2 1 3 0 Output 1 2 4 Input 5 -1 0 1 1 1 1 2 0 3 0 Output -1 Input 8 2 1 -1 0 1 0 1 1 1 1 4 0 5 1 7 0 Output 5 Note The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow): * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices; * the vertex 2 will be connected with the vertex 3 after deletion; * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it; * the vertex 4 will be connected with the vertex 3; * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth)); * you will just delete the vertex 4; * there are no more vertices to delete. <image> In the second example you don't need to delete any vertex: * vertices 2 and 3 have children that respect them; * vertices 4 and 5 respect ancestors. <image> In the third example the tree will change this way: <image>
import sys def input(): return sys.stdin.buffer.readline().strip() n=int(input()) notremove = [0]*(n+1) for i in range(1,n+1): p,c = map(int,input().split()) if(c==0): notremove[i] = 1 if(p>0): notremove[p] = 1 check=0 for i in range(1,n+1): if(notremove[i]==0): check=1 print(i,end=" ") if(check==0): print(-1)
{ "input": [ "5\n3 1\n1 1\n-1 0\n2 1\n3 0\n", "8\n2 1\n-1 0\n1 0\n1 1\n1 1\n4 0\n5 1\n7 0\n", "5\n-1 0\n1 1\n1 1\n2 0\n3 0\n" ], "output": [ "1 2 4\n", "5\n", "-1\n" ] }
933
9
This problem is same as the next one, but has smaller constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic. At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire. Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem? Input The first line contains a single integer n (2 ≤ n ≤ 50) — the number of electric poles. Each of the following n lines contains two integers x_i, y_i (-10^4 ≤ x_i, y_i ≤ 10^4) — the coordinates of the poles. It is guaranteed that all of these n points are distinct. Output Print a single integer — the number of pairs of wires that are intersecting. Examples Input 4 0 0 1 1 0 3 1 2 Output 14 Input 4 0 0 0 2 0 4 2 0 Output 6 Input 3 -1 -1 1 0 3 1 Output 0 Note In the first example: <image> In the second example: <image> Note that the three poles (0, 0), (0, 2) and (0, 4) are connected by a single wire. In the third example: <image>
def gcd(x,y): while y: x,y=y,x%y return x def frac(a,b): x=gcd(a,b) return (a//x,b//x) n=int(input()) coords=[] for i in range(n): coords.append(tuple(map(int,input().split()))) slopes={} for i in range(n): for j in range(i+1,n): x1,y1=coords[i][0],coords[i][1] x2,y2=coords[j][0],coords[j][1] if x1==x2: slope="inf" mark=x1 else: slope=frac(y2-y1,x2-x1) mark=frac(y1*x2-y2*x1,x2-x1) if slope in slopes: slopes[slope].add(mark) else: slopes[slope]={mark} tot=sum(len(slopes[guy]) for guy in slopes) sumi=0 for guy in slopes: a=len(slopes[guy]) sumi+=a*(tot-a) print(sumi//2)
{ "input": [ "4\n0 0\n1 1\n0 3\n1 2\n", "4\n0 0\n0 2\n0 4\n2 0\n", "3\n-1 -1\n1 0\n3 1\n" ], "output": [ "14\n", "6\n", "0\n" ] }
934
7
Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor. Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques. The first hashing function she designed is as follows. Given two positive integers (x, y) she defines H(x,y):=x^2+2xy+x+1. Now, Heidi wonders if the function is reversible. That is, given a positive integer r, can you find a pair (x, y) (of positive integers) such that H(x, y) = r? If multiple such pairs exist, output the one with smallest possible x. If there is no such pair, output "NO". Input The first and only line contains an integer r (1 ≤ r ≤ 10^{12}). Output Output integers x, y such that H(x,y) = r and x is smallest possible, or "NO" if no such pair exists. Examples Input 19 Output 1 8 Input 16 Output NO
def f(n): return ['NO'] if (n%2==0 or n<5) else [1,((n-3)//2)] n = int(input()) print(*f(n))
{ "input": [ "19\n", "16\n" ], "output": [ "1 8\n", "NO\n" ] }
935
10
You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i). Initially you stand at the lower left corner of the island, at the position (1, 1). If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from (r, c) to (r+1, c)), left (from (r, c) to (r, c-1)), or right (from position (r, c) to (r, c+1)). Because of the traps, you can't move down. However, moving up is also risky. You can move up only if you are in a safe column. There are q safe columns: b_1, b_2, …, b_q. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures. Input The first line contains integers n, m, k and q (2 ≤ n, m, k, q ≤ 2 ⋅ 10^5, q ≤ m) — the number of rows, the number of columns, the number of treasures in the island and the number of safe columns. Each of the next k lines contains two integers r_i, c_i, (1 ≤ r_i ≤ n, 1 ≤ c_i ≤ m) — the coordinates of the cell with a treasure. All treasures are located in distinct cells. The last line contains q distinct integers b_1, b_2, …, b_q (1 ≤ b_i ≤ m) — the indices of safe columns. Output Print the minimum number of moves required to collect all the treasures. Examples Input 3 3 3 2 1 1 2 1 3 1 2 3 Output 6 Input 3 5 3 2 1 2 2 3 3 1 1 5 Output 8 Input 3 6 3 2 1 6 2 2 3 4 1 6 Output 15 Note In the first example you should use the second column to go up, collecting in each row treasures from the first column. <image> In the second example, it is optimal to use the first column to go up. <image> In the third example, it is optimal to collect the treasure at cell (1;6), go up to row 2 at column 6, then collect the treasure at cell (2;2), go up to the top row at column 1 and collect the last treasure at cell (3;4). That's a total of 15 moves. <image>
from bisect import bisect_left n, m, k, q = map(int, input().split()) x = sorted(list(map(int, input().split())) for _ in range(k)) y = sorted(map(int, input().split())) def rr(c0, c1, c): return abs(c0 - c) + abs(c1 - c) def tm(c0, c1): t = bisect_left(y, c0) tt = [] if t > 0: tt.append(rr(c0, c1, y[t-1])) if t < q: tt.append(rr(c0, c1, y[t])) return min(tt) z = [] for r, c in x: if z and z[-1][0] == r: z[-1][2] = c else: z.append([r, c, c]) v1, v2, r0, c01, c02 = 0, 0, 1, 1, 1 for r1, c11, c12 in z: d = c12 - c11 + r1 - r0 if r1 > r0: d11 = tm(c01, c11) d12 = tm(c01, c12) d21 = tm(c02, c11) d22 = tm(c02, c12) v2, v1 = d + min(v1 + d11, v2 + d21), d + min(v1 + d12, v2 + d22) else: v1, v2 = d + c12 - c02, d + c11 - c01 r0, c01, c02 = r1, c11, c12 print(min(v1, v2))
{ "input": [ "3 6 3 2\n1 6\n2 2\n3 4\n1 6\n", "3 3 3 2\n1 1\n2 1\n3 1\n2 3\n", "3 5 3 2\n1 2\n2 3\n3 1\n1 5\n" ], "output": [ "15\n", "6\n", "8\n" ] }
936
9
Alice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example: X = 123123123 is periodic number with length L = 3 and L = 9 X = 42424242 is periodic number with length L = 2,L = 4 and L = 8 X = 12345 is periodic number with length L = 5 For given positive period length L and positive integer number A, Alice wants to find smallest integer number X strictly greater than A that is periodic with length L. Input First line contains one positive integer number L \ (1 ≤ L ≤ 10^5) representing length of the period. Second line contains one positive integer number A \ (1 ≤ A ≤ 10^{100 000}). Output One positive integer number representing smallest positive number that is periodic with length L and is greater than A. Examples Input 3 123456 Output 124124 Input 3 12345 Output 100100 Note In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124). In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
l = int(input()) xs = input() def run(): if len(xs)%l != 0: d = len(xs)//l+1 ans = ('1'+'0'*(l-1))*d return ans d = len(xs) // l prf = xs[:l] tl = prf*d if tl > xs: return tl if prf == '9'*l: return ('1'+'0'*(l-1))*(d+1) return str(int(prf)+1)*d print(run())
{ "input": [ "3\n12345\n", "3\n123456\n" ], "output": [ "100100", "124124" ] }
937
9
Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate. The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers i and j, such that |j - i| is a divisor of n greater than 1, they have the same color. Formally, the colors of two tiles with numbers i and j should be the same if |i-j| > 1 and n mod |i-j| = 0 (where x mod y is the remainder when dividing x by y). Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic? Input The first line of input contains a single integer n (1 ≤ n ≤ 10^{12}), the length of the path. Output Output a single integer, the maximum possible number of colors that the path can be painted in. Examples Input 4 Output 2 Input 5 Output 5 Note In the first sample, two colors is the maximum number. Tiles 1 and 3 should have the same color since 4 mod |3-1| = 0. Also, tiles 2 and 4 should have the same color since 4 mod |4-2| = 0. In the second sample, all five colors can be used. <image>
def mdc( a, b ): if ( b == 0 ): return a return mdc(b, a % b) n = int(input()) a = n for i in range(2, int(n ** .5) + 1): if ( n % i == 0 ): a = mdc(a, i) a = mdc(a, n // i) print(a)
{ "input": [ "5\n", "4\n" ], "output": [ "5\n", "2\n" ] }
938
8
A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0. Polycarp has n (2 ≤ n ≤ 10) bank cards, the PIN code of the i-th card is p_i. Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all n codes would become different. Formally, in one step, Polycarp picks i-th card (1 ≤ i ≤ n), then in its PIN code p_i selects one position (from 1 to 4), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different. Polycarp quickly solved this problem. Can you solve it? Input The first line contains integer t (1 ≤ t ≤ 100) — the number of test cases in the input. Then test cases follow. The first line of each of t test sets contains a single integer n (2 ≤ n ≤ 10) — the number of Polycarp's bank cards. The next n lines contain the PIN codes p_1, p_2, ..., p_n — one per line. The length of each of them is 4. All PIN codes consist of digits only. Output Print the answers to t test sets. The answer to each set should consist of a n + 1 lines In the first line print k — the least number of changes to make all PIN codes different. In the next n lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them. Example Input 3 2 1234 0600 2 1337 1337 4 3139 3139 3139 3139 Output 0 1234 0600 1 1337 1237 3 3139 3138 3939 6139
def solve(): n = int(input()) num = [] for i in range(n): ss = input() num.append(ss) cnt = 0 for i in range(n): if (num[i] in num[i+1:]): cnt += 1 j = 0 while (num[i] in num[:i] + num[i+1:]): num[i] = num[i][:3] + str(j) j += 1 print(cnt) print(*num, sep = '\n') t = int(input()) for i in range(t): solve()
{ "input": [ "3\n2\n1234\n0600\n2\n1337\n1337\n4\n3139\n3139\n3139\n3139\n" ], "output": [ "0\n1234\n0600\n1\n1337\n0337\n3\n3139\n0139\n1139\n2139\n" ] }
939
7
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The only line of the test case contains two integers a and b (1 ≤ a, b ≤ 10^9). Output For each test case print the answer — the minimum number of moves you need to do in order to make a divisible by b. Example Input 5 10 4 13 9 100 13 123 456 92 46 Output 2 5 4 333 0
def turn(a,b): if a%b==0: return 0 else: c=a%b return b-c for _ in range(int(input())): a,b=map(int,input().split()) print(turn(a,b))
{ "input": [ "5\n10 4\n13 9\n100 13\n123 456\n92 46\n" ], "output": [ "2\n5\n4\n333\n0\n" ] }
940
7
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weights in the second pile. Help Phoenix minimize |a-b|, the absolute value of a-b. Input The input consists of multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100) — the number of test cases. The first line of each test case contains an integer n (2 ≤ n ≤ 30; n is even) — the number of coins that Phoenix has. Output For each test case, output one integer — the minimum possible difference of weights between the two piles. Example Input 2 2 4 Output 2 6 Note In the first test case, Phoenix has two coins with weights 2 and 4. No matter how he divides the coins, the difference will be 4-2=2. In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16. It is optimal for Phoenix to place coins with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another pile. The difference is (2+16)-(4+8)=6.
def do(n): print(int(2*(2**(n/2)-1))) t = int(input()) for _ in range(t): do(int(input()))
{ "input": [ "2\n2\n4\n" ], "output": [ "2\n6\n" ] }
941
7
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is even. In order to open a door, Naruto must find such n seals with integer energies b_1, b_2, ..., b_n that the following equality holds: a_{1} ⋅ b_{1} + a_{2} ⋅ b_{2} + ... + a_{n} ⋅ b_{n} = 0. All b_i must be nonzero as well as a_i are, and also must not exceed 100 by absolute value. Please find required seals for every room there. Input The first line contains the only integer T (1 ≤ T ≤ 1000) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors. Each description starts with the line containing the only even integer n (2 ≤ n ≤ 100) denoting the number of seals. The following line contains the space separated sequence of nonzero integers a_1, a_2, ..., a_n (|a_{i}| ≤ 100, a_{i} ≠ 0) denoting the energies of seals. Output For each door print a space separated sequence of nonzero integers b_1, b_2, ..., b_n (|b_{i}| ≤ 100, b_{i} ≠ 0) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists. Example Input 2 2 1 100 4 1 2 3 6 Output -100 1 1 1 1 -1 Note For the first door Naruto can use energies [-100, 1]. The required equality does indeed hold: 1 ⋅ (-100) + 100 ⋅ 1 = 0. For the second door Naruto can use, for example, energies [1, 1, 1, -1]. The required equality also holds: 1 ⋅ 1 + 2 ⋅ 1 + 3 ⋅ 1 + 6 ⋅ (-1) = 0.
def inplst(): return list(map(int,input().split())) for _ in range(int(input())): n=int(input()) l=inplst() for i in range(1,n,2): print(-l[i],l[i-1],end=' ') print()
{ "input": [ "2\n2\n1 100\n4\n1 2 3 6\n" ], "output": [ "-100 1\n-2 1 -6 3\n" ] }
942
7
Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111. Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well). Your task is the following: for the given positive integer n, calculate the number of different values of g(x) among all numbers x such that 1 ≤ x ≤ n. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Each test case consists of one line containing one integer n (1 ≤ n < 10^{100}). This integer is given without leading zeroes. Output For each test case, print one integer — the number of different values of the function g(x), if x can be any integer from [1, n]. Example Input 5 4 37 998244353 1000000007 12345678901337426966631415 Output 1 2 9 10 26 Note Explanations for the two first test cases of the example: 1. if n = 4, then for every integer x such that 1 ≤ x ≤ n, (x)/(f(f(x))) = 1; 2. if n = 37, then for some integers x such that 1 ≤ x ≤ n, (x)/(f(f(x))) = 1 (for example, if x = 23, f(f(x)) = 23,(x)/(f(f(x))) = 1); and for other values of x, (x)/(f(f(x))) = 10 (for example, if x = 30, f(f(x)) = 3, (x)/(f(f(x))) = 10). So, there are two different values of g(x).
def read(): return [int(x) for x in input().split()] if __name__ == '__main__': ca, = read() for _ in range(ca): print(len(input()))
{ "input": [ "5\n4\n37\n998244353\n1000000007\n12345678901337426966631415\n" ], "output": [ "\n1\n2\n9\n10\n26\n" ] }
943
8
The only difference between the two versions is that this version asks the minimal possible answer. Homer likes arrays a lot. Today he is painting an array a_1, a_2, ..., a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, ..., a_n is described by an array b_1, b_2, ..., b_n that b_i indicates the color of a_i (0 for white and 1 for black). According to a painting assignment b_1, b_2, ..., b_n, the array a is split into two new arrays a^{(0)} and a^{(1)}, where a^{(0)} is the sub-sequence of all white elements in a and a^{(1)} is the sub-sequence of all black elements in a. For example, if a = [1,2,3,4,5,6] and b = [0,1,0,1,0,0], then a^{(0)} = [1,3,5,6] and a^{(1)} = [2,4]. The number of segments in an array c_1, c_2, ..., c_k, denoted seg(c), is the number of elements if we merge all adjacent elements with the same value in c. For example, the number of segments in [1,1,2,2,3,3,3,2] is 4, because the array will become [1,2,3,2] after merging adjacent elements with the same value. Especially, the number of segments in an empty array is 0. Homer wants to find a painting assignment b, according to which the number of segments in both a^{(0)} and a^{(1)}, i.e. seg(a^{(0)})+seg(a^{(1)}), is as small as possible. Find this number. Input The first line contains an integer n (1 ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n). Output Output a single integer, indicating the minimal possible total number of segments. Examples Input 6 1 2 3 1 2 2 Output 4 Input 7 1 2 1 2 1 2 1 Output 2 Note In the first example, we can choose a^{(0)} = [1,1,2,2], a^{(1)} = [2,3] and seg(a^{(0)}) = seg(a^{(1)}) = 2. So the answer is 2+2 = 4. In the second example, we can choose a^{(0)} = [1,1,1,1], a^{(1)} = [2,2,2] and seg(a^{(0)}) = seg(a^{(1)}) = 1. So the answer is 1+1 = 2.
#!/usr/bin/env python3 import collections def solveTestCase(): n = int(input()) A = [int(i) for i in input().split()] s1 = [0] s2 = [0] d = dict() v = n B = [] for i in A[::-1]: nxt = n+1 if i in d: nxt = d[i] B.append((i, nxt)) d[i] = v v -= 1 B = B[::-1] next1 = n+2 next2 = n+2 for (v, nxt) in B: if v == s1[-1]: next1 = nxt elif v == s2[-1]: next2 = nxt elif s1[-1] == s2[-1]: s1.append(v) next1 = nxt elif next1 < next2: s2.append(v) next2 = nxt else: s1.append(v) next1 = nxt print(len(s1)+len(s2)-2) if __name__ == "__main__": solveTestCase()
{ "input": [ "7\n1 2 1 2 1 2 1\n", "6\n1 2 3 1 2 2\n" ], "output": [ "\n2\n", "\n4\n" ] }
944
7
Polycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns": * cells are numbered starting from one; * cells are numbered from left to right by columns, and inside each column from top to bottom; * number of each cell is an integer one greater than in the previous cell. For example, if n = 3 and m = 5, the table will be numbered as follows: $$$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\\ 2 & 5 & 8 & 11 & 14 \\\ 3 & 6 & 9 & 12 & 15 \\\ \end{matrix} $$$ However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows": * cells are numbered starting from one; * cells are numbered from top to bottom by rows, and inside each row from left to right; * number of each cell is an integer one greater than the number of the previous cell. For example, if n = 3 and m = 5, then Polycarp likes the following table numbering: $$$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\\ 6 & 7 & 8 & 9 & 10 \\\ 11 & 12 & 13 & 14 & 15 \\\ \end{matrix} $$$ Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number x? Input The first line contains a single integer t (1 ≤ t ≤ 10^4). Then t test cases follow. Each test case consists of a single line containing three integers n, m, x (1 ≤ n, m ≤ 10^6, 1 ≤ x ≤ n ⋅ m), where n and m are the number of rows and columns in the table, and x is the cell number. Note that the numbers in some test cases do not fit into the 32-bit integer type, so you must use at least the 64-bit integer type of your programming language. Output For each test case, output the cell number in the numbering "by rows". Example Input 5 1 1 1 2 2 3 3 5 11 100 100 7312 1000000 1000000 1000000000000 Output 1 2 9 1174 1000000000000
def solve(): n,m,x = map(int,input().split()) x-=1 col = int(x/n) row = int(x%n) print(row*m+col+1) n = int(input()) for i in range(n): solve()
{ "input": [ "5\n1 1 1\n2 2 3\n3 5 11\n100 100 7312\n1000000 1000000 1000000000000\n" ], "output": [ "\n1\n2\n9\n1174\n1000000000000\n" ] }
945
8
A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequence. In particular, any sequence of length at most 1 is strange. For example, the sequences (-2021, -1, -1, -1) and (-1, 0, 1) are strange, but (3, 0, 1) is not, because |0 - 1| < 3. Sifid has an array a of n integers. Sifid likes everything big, so among all the strange subsequences of a, he wants to find the length of the longest one. Can you help him? A sequence c is a subsequence of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements. Input The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (1≤ n≤ 10^5) — the length of the array a. The second line of each test case contains n integers a_1, a_2, …, a_n (-10^9≤ a_i ≤ 10^9) — the elements of the array a. It is guaranteed that the sum of n over all test cases doesn't exceed 10^5. Output For each test case output a single integer — the length of the longest strange subsequence of a. Example Input 6 4 -1 -2 0 0 7 -3 4 -2 0 -4 6 1 5 0 5 -3 2 -5 3 2 3 1 4 -3 0 2 0 6 -3 -2 -1 1 1 1 Output 4 5 4 1 3 4 Note In the first test case, one of the longest strange subsequences is (a_1, a_2, a_3, a_4) In the second test case, one of the longest strange subsequences is (a_1, a_3, a_4, a_5, a_7). In the third test case, one of the longest strange subsequences is (a_1, a_3, a_4, a_5). In the fourth test case, one of the longest strange subsequences is (a_2). In the fifth test case, one of the longest strange subsequences is (a_1, a_2, a_4).
def solve(values): values.sort() x = 1 while x < len(values) and values[x] <= 0: x += 1 if x == len(values): return x else: for y in range(1, x + 1): if abs(values[y] - values[y - 1]) < values[x]: return x return x + 1 if __name__ == '__main__': for _ in range(int(input())): input() print(solve(list(map(int, input().split()))))
{ "input": [ "6\n4\n-1 -2 0 0\n7\n-3 4 -2 0 -4 6 1\n5\n0 5 -3 2 -5\n3\n2 3 1\n4\n-3 0 2 0\n6\n-3 -2 -1 1 1 1\n" ], "output": [ "\n4\n5\n4\n1\n3\n4\n" ] }
946
8
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half. But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half. For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2 > 1 and 4 > 2), ticket 0135 also meets the criterion (the sought correspondence is 0 < 3 and 1 < 5), and ticket 3754 does not meet the criterion. You have a ticket in your hands, it contains 2n digits. Your task is to check whether it meets the unluckiness criterion. Input The first line contains an integer n (1 ≤ n ≤ 100). The second line contains a string that consists of 2n digits and defines your ticket. Output In the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes). Examples Input 2 2421 Output YES Input 2 0135 Output YES Input 2 3754 Output NO
n=int(input()) s=input() def solve(): s1=sorted(s[:n]) s2=sorted(s[n:]) if s2[0]<s1[0]: s1,s2=s2,s1 for x in range(n): if s1[x]>=s2[x]: return "NO" return "YES" print(solve())
{ "input": [ "2\n3754\n", "2\n0135\n", "2\n2421\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
947
8
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n. A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct. There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules: * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below. * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2. 1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p. 2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p. We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times. Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding. Input The first line contains two integers n and k (1 ≤ n, k ≤ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≤ qi ≤ n) — the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format. It is guaranteed that the given sequences q and s are correct permutations. Output If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes). Examples Input 4 1 2 3 4 1 1 2 3 4 Output NO Input 4 1 4 3 1 2 3 4 2 1 Output YES Input 4 3 4 3 1 2 3 4 2 1 Output YES Input 4 2 4 3 1 2 2 1 4 3 Output YES Input 4 1 4 3 1 2 2 1 4 3 Output NO Note In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed. In the second sample the described situation is possible, in case if after we toss a coin, we get tails. In the third sample the possible coin tossing sequence is: heads-tails-tails. In the fourth sample the possible coin tossing sequence is: heads-heads.
def Solve(x,L): if(x==k[0]): return L==S if((x,tuple(L)) in Mem): return False if(L==S): return False E=[] for i in range(len(L)): E.append(L[Q[i]-1]) if(Solve(x+1,E)): return True E=[0]*len(L) for i in range(len(L)): E[Q[i]-1]=L[i] if(Solve(x+1,E)): return True Mem[(x,tuple(L))]=1 return False Mem={} k=[0] n,k[0]=map(int,input().split()) P=list(range(1,n+1)) Q=list(map(int,input().split())) S=list(map(int,input().split())) if(Solve(0,P)): print("YES") else: print("NO")
{ "input": [ "4 1\n4 3 1 2\n3 4 2 1\n", "4 1\n4 3 1 2\n2 1 4 3\n", "4 3\n4 3 1 2\n3 4 2 1\n", "4 1\n2 3 4 1\n1 2 3 4\n", "4 2\n4 3 1 2\n2 1 4 3\n" ], "output": [ "YES\n", "NO\n", "YES\n", "NO\n", "YES\n" ] }
948
9
The little girl loves the problems on array queries very much. One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive. The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum. Input The first line contains two space-separated integers n (1 ≤ n ≤ 2⋅10^5) and q (1 ≤ q ≤ 2⋅10^5) — the number of elements in the array and the number of queries, correspondingly. The next line contains n space-separated integers a_i (1 ≤ a_i ≤ 2⋅10^5) — the array elements. Each of the following q lines contains two space-separated integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the i-th query. Output In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 3 5 3 2 1 2 2 3 1 3 Output 25 Input 5 3 5 2 4 1 3 1 5 2 3 2 3 Output 33
from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) n,q=mp() d=[0]*n l=sorted(mp(),reverse=True) for _ in range(q): v=mp() d[v[0]-1]+=1 if v[1]!=n: d[v[1]]-=1 for i in range(1,n): d[i]+=d[i-1] d.sort(reverse=True) ans=0 for i in range(n): ans+=d[i]*l[i] print(ans)
{ "input": [ "5 3\n5 2 4 1 3\n1 5\n2 3\n2 3\n", "3 3\n5 3 2\n1 2\n2 3\n1 3\n" ], "output": [ "33\n", "25\n" ] }
949
9
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: * 'U': go up, (x, y) → (x, y+1); * 'D': go down, (x, y) → (x, y-1); * 'L': go left, (x, y) → (x-1, y); * 'R': go right, (x, y) → (x+1, y). The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b). Input The first line contains two integers a and b, ( - 109 ≤ a, b ≤ 109). The second line contains a string s (1 ≤ |s| ≤ 100, s only contains characters 'U', 'D', 'L', 'R') — the command. Output Print "Yes" if the robot will be located at (a, b), and "No" otherwise. Examples Input 2 2 RU Output Yes Input 1 2 RU Output No Input -1 1000000000 LRRLU Output Yes Input 0 0 D Output Yes Note In the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on. The locations of its moves are (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → ... So it can reach (2, 2) but not (1, 2).
def inc(c, x, y): if c == 'R': x += 1 if c == 'L': x -= 1 if c == 'U': y += 1 if c == 'D': y -= 1 return x, y a, b = map(int, input().split()) s = input() x, y = 0, 0 for i in range(len(s)): x, y = inc(s[i], x, y) nx, ny = 0, 0 for i in range(len(s) + 1): if x == 0 and y == 0 and nx == a and ny == b: print('Yes') exit() if x == 0 and y != 0 and nx == a and (b - ny) % y == 0 and (b - ny) // y >= 0: print('Yes') exit() if x != 0 and y == 0 and ny == b and (a - nx) % x == 0 and (a - nx) // x >= 0: print('Yes') exit() if x != 0 and y != 0 and (a - nx) % x == 0 and (b - ny) % y == 0 and (a - nx) // x >= 0 and (b - ny) // y >= 0 and (a - nx) // x == (b - ny) // y >= 0: print('Yes') exit() if i < len(s): nx, ny = inc(s[i], nx, ny) print('No')
{ "input": [ "0 0\nD\n", "-1 1000000000\nLRRLU\n", "2 2\nRU\n", "1 2\nRU\n" ], "output": [ "Yes\n", "Yes\n", "Yes\n", "No\n" ] }
950
7
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn). Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value. Input The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a1, a2, ..., an (|ai| ≤ 1000). Output Print the required sequence x1, x2, ..., xn. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value. Examples Input 5 100 -100 50 0 -50 Output 100 -50 0 50 -100 Note In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one. Sequence x1, x2, ... , xp is lexicographically smaller than sequence y1, y2, ... , yp if there exists an integer r (0 ≤ r < p) such that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.
def main(): input() a = sorted(input().split(), key=int) print(a[-1], ' '.join(a[1:-1]), a[0]) if __name__ == '__main__': main()
{ "input": [ "5\n100 -100 50 0 -50\n" ], "output": [ "100 -50 0 50 -100\n" ] }
951
8
Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers. During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct. You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not. Input The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer mi (1 ≤ mi ≤ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers ai, 1, ai, 2, ..., ai, mi (1 ≤ ai, k ≤ 100) — the numbers on the i-th player's card. The numbers in the lines are separated by single spaces. It is guaranteed that all the numbers on each card are distinct. Output Print n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise. Examples Input 3 1 1 3 2 4 1 2 10 11 Output YES NO YES Input 2 1 1 1 1 Output NO NO
def s(): n = int(input()) a = [set(list(map(int,input().split()))[1:])for _ in range(n)] res = 0 print(*['YES'if sum(i.issubset(j)for i in a) == 1 else 'NO' for j in a],sep = '\n') s()
{ "input": [ "2\n1 1\n1 1\n", "3\n1 1\n3 2 4 1\n2 10 11\n" ], "output": [ "NO\nNO\n", "YES\nNO\nYES\n" ] }
952
9
Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y). Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that: * r ≥ 2; * for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds; * each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: * no pair of tubes has common cells; * each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner. Input The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly. Output Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists. Examples Input 3 3 3 Output 3 1 1 1 2 1 3 3 2 1 2 2 2 3 3 3 1 3 2 3 3 Input 2 3 1 Output 6 1 1 1 2 1 3 2 3 2 2 2 1 Note Picture for the first sample: <image> Picture for the second sample: <image>
def print_tube(a): print(len(a),end = " ") print(" ".join(map(lambda x: " ".join(str(i) for i in x), a))) n, m, k = map(int, input().split()) res = [(x+1,y+1) for x in range(n) for y in range(m)[::(1 if (x%2 == 0) else -1)]] for i in range(k-1): print_tube(res[2*i:2*i+2]) print_tube(res[2*k-2:])
{ "input": [ "3 3 3\n", "2 3 1\n" ], "output": [ "2 1 1 1 2\n2 1 3 2 3\n5 2 2 2 1 3 1 3 2 3 3\n", "6 1 1 1 2 1 3 2 3 2 2 2 1\n" ] }
953
10
Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari? You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem Input The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation. Output Print the length of the longest common subsequence. Examples Input 4 3 1 4 2 3 4 1 2 3 1 2 4 3 Output 3 Note The answer for the first test sample is subsequence [1, 2, 3].
def main(): n, k = tuple(map(int, input().split())) a = [set(range(n)) for _ in range(n)] for i in range(k): p = set() for j in map(int, input().split()): a[j-1] -= p p.add(j-1) sa = sorted(range(n), key=lambda i: len(a[i])) maxx = [0] * n res = 0 for i in sa: m = 1 + maxx[max(a[i], key=lambda e: maxx[e])] if a[i] else 0 maxx[i] = m res = max(res, m) print(res) if __name__ == '__main__': main()
{ "input": [ "4 3\n1 4 2 3\n4 1 2 3\n1 2 4 3\n" ], "output": [ "3" ] }
954
9
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>. Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1]. Input The only input line contains an integer n (1 ≤ n ≤ 105). Output In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists. If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n. If there are multiple solutions, you are allowed to print any of them. Examples Input 7 Output YES 1 4 3 6 5 2 7 Input 6 Output NO Note For the second sample, there are no valid sequences.
def comp(x): for i in range(2, x): if x % i == 0: return True return False N = int(input()) if N == 4: print('YES', '1', '3', '2', '4', sep = '\n') elif comp(N): print('NO') else: print('YES', '1', sep = '\n') if N > 1: for i in range(2, N): print((i - 1) * pow(i, N - 2, N) % N) print(N)
{ "input": [ "6\n", "7\n" ], "output": [ "NO\n", "YES\n1\n2\n5\n6\n3\n4\n7\n" ] }
955
8
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this: <image> Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors. The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: 1. These k dots are different: if i ≠ j then di is different from dj. 2. k is at least 4. 3. All dots belong to the same color. 4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field. Input The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter. Output Output "Yes" if there exists a cycle, and "No" otherwise. Examples Input 3 4 AAAA ABCA AAAA Output Yes Input 3 4 AAAA ABCA AADA Output No Input 4 4 YYYR BYBY BBBY BBBY Output Yes Input 7 6 AAAAAB ABBBAB ABAAAB ABABBB ABAAAB ABBBAB AAAAAB Output Yes Input 2 13 ABCDEFGHIJKLM NOPQRSTUVWXYZ Output No Note In first sample test all 'A' form a cycle. In second sample there is no such cycle. The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
def dfs(x,y,x1,y1): v.add((x,y)) for dx,dy in [(-1,0),(0,1),(1,0),(0,-1)]: if x+dx>=0 and x+dx<n and y+dy>=0 and y+dy<m and (x+dx,y+dy)!=(x1,y1) and a[x+dx][y+dy]==a[x][y]: if (x+dx,y+dy) in v or dfs(x+dx,y+dy,x,y): return True return False import sys sys.setrecursionlimit(10000) n,m=map(int,input().split()) a=[input() for i in range(n)] v=set() for i in range(n): for j in range(m): if not (i,j) in v and dfs(i,j,-1,-1): print('Yes') quit() print('No') # Made By Mostafa_Khaled
{ "input": [ "2 13\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ\n", "7 6\nAAAAAB\nABBBAB\nABAAAB\nABABBB\nABAAAB\nABBBAB\nAAAAAB\n", "3 4\nAAAA\nABCA\nAAAA\n", "3 4\nAAAA\nABCA\nAADA\n", "4 4\nYYYR\nBYBY\nBBBY\nBBBY\n" ], "output": [ "No\n", "Yes\n", "Yes\n", "No\n", "Yes\n" ] }
956
9
Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. <image> Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B. For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero. Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r. Input The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105). Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query. Output For each query, print its answer in a single line. Examples Input 2 1 4 1 5 3 3 3 10 7 10 2 6 4 8 Output 4 -1 8 -1 Input 1 5 2 1 5 10 2 7 4 Output 1 2
import sys input = sys.stdin.readline a, b, n, l, t, m = -1, -1, -1, -1, -1, -1 def is_valid(mid): biggest = a + (mid - 1) * b; if t < biggest: return False sum = ((mid - l + 1) * (a + (l - 1) * b + biggest)) // 2 return t >= biggest and m * t >= sum def binary_search(b, e): while b <= e: mid = b + e >> 1 if is_valid(mid): b = mid + 1 else: e = mid - 1 return b - 1 a, b, n = map(int, input().split()) for _ in range(n): l, t, m = map(int, input().split()) res = binary_search(l, l + int(1e6)) print(-1 if res == l - 1 else res)
{ "input": [ "1 5 2\n1 5 10\n2 7 4\n", "2 1 4\n1 5 3\n3 3 10\n7 10 2\n6 4 8\n" ], "output": [ "1\n2\n", "4\n-1\n8\n-1\n" ] }
957
7
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying. One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes). The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks). The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not. Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university. Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home. Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair. Input The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university. The second line contains n numbers ai (0 ≤ ai ≤ 1). Number ai equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a1, a2, ..., an are separated by spaces. Output Print a single number — the number of pairs during which Alena stays at the university. Examples Input 5 0 1 0 1 1 Output 4 Input 7 1 0 1 0 0 1 0 Output 4 Input 1 0 Output 0 Note In the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair. In the last sample Alena doesn't have a single pair, so she spends all the time at home.
def main(): input() s = input() s = s[s.find("1"): s.rfind("1") + 1:2] s1 = s.replace("10", "1") print(len(s) - s1.count("0") - s1.count("10")) if __name__ == '__main__': main()
{ "input": [ "5\n0 1 0 1 1\n", "7\n1 0 1 0 0 1 0\n", "1\n0\n" ], "output": [ "4\n", "4\n", "0\n" ] }
958
8
Genos needs your help. He was asked to solve the following programming problem by Saitama: The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2. Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|. Input The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000). The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only. Output Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|. Examples Input 01 00111 Output 3 Input 0011 0110 Output 2 Note For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3. The second sample case is described in the statement.
def solve(a, b): m = len(a) n = len(b) p_b = [0] for x in b[:]: p_b.append(p_b[-1] + int(x)) s = 0 for i in range(m): if a[i] == '0': s += p_b[n - m + 1 + i] - p_b[i] else: s += (n - m + 1) - (p_b[n - m + 1 + i] - p_b[i]) return s a = input() b = input() print(solve(a, b))
{ "input": [ "01\n00111\n", "0011\n0110\n" ], "output": [ "3\n", "2\n" ] }
959
7
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them. A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych. The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams. So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has al fingers on her left hand and ar fingers on the right one. The boy correspondingly has bl and br fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable." The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa. Input The first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly. Output Print YES or NO, that is, the answer to Petr Palych's question. Examples Input 5 1 10 5 Output YES Input 4 5 3 3 Output YES Input 1 2 11 6 Output NO Note The boy and the girl don't really care who goes to the left.
f=lambda:map(int,input().split()) dl,dr=f() ml,mr=f() def chk(d,m): return d-2<m and m<2*d+3 if chk(dl,mr) or chk(dr,ml): print("YES") else: print("NO")
{ "input": [ "4 5\n3 3\n", "5 1\n10 5\n", "1 2\n11 6\n" ], "output": [ "YES\n", "YES\n", "NO\n" ] }
960
7
You are given names of two days of the week. Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year. In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday". Input The input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday". Output Print "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes). Examples Input monday tuesday Output NO Input sunday sunday Output YES Input saturday tuesday Output YES Note In the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays. In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday.
def main(): d = {"monday": 6, "tuesday": 5, "wednesday": 4, "thursday": 3, "friday": 2, "saturday": 1, "sunday": 0} dif = (d[input()] - d[input()]) % 7 print(("NO", "YES")[any(a % 7 == dif for a in (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31))]) if __name__ == '__main__': main()
{ "input": [ "monday\ntuesday\n", "saturday\ntuesday\n", "sunday\nsunday\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
961
7
Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits. Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0. Input The first line contains the positive integer a (1 ≤ a ≤ 1000) — the number of lemons Nikolay has. The second line contains the positive integer b (1 ≤ b ≤ 1000) — the number of apples Nikolay has. The third line contains the positive integer c (1 ≤ c ≤ 1000) — the number of pears Nikolay has. Output Print the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. Examples Input 2 5 7 Output 7 Input 4 7 13 Output 21 Input 2 3 2 Output 0 Note In the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7. In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21. In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0.
def r(): return int(input()) a = r() b = r() c = r() print(min(a, b // 2, c // 4) * 7)
{ "input": [ "2\n5\n7\n", "4\n7\n13\n", "2\n3\n2\n" ], "output": [ "7", "21", "0" ] }
962
7
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than x from the year of university entrance of this student, where x — some non-negative integer. A value x is not given, but it can be uniquely determined from the available data. Note that students don't join other groups. You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance. Input The first line contains the positive odd integer n (1 ≤ n ≤ 5) — the number of groups which Igor joined. The next line contains n distinct integers a1, a2, ..., an (2010 ≤ ai ≤ 2100) — years of student's university entrance for each group in which Igor is the member. It is guaranteed that the input data is correct and the answer always exists. Groups are given randomly. Output Print the year of Igor's university entrance. Examples Input 3 2014 2016 2015 Output 2015 Input 1 2050 Output 2050 Note In the first test the value x = 1. Igor entered the university in 2015. So he joined groups members of which are students who entered the university in 2014, 2015 and 2016. In the second test the value x = 0. Igor entered only the group which corresponds to the year of his university entrance.
import sys def main(): _, *l = map(int, sys.stdin.read().strip().split()) return sum(l)//len(l) print(main())
{ "input": [ "1\n2050\n", "3\n2014 2016 2015\n" ], "output": [ "2050\n", "2015\n" ] }
963
7
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question? Input The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices. Output Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible. Examples Input 3 3 12 9 15 Output 3 Input 2 2 10 9 Output -1 Input 4 1 1 1000000000 1000000000 1000000000 Output 2999999997 Note Consider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds. There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3. In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal. In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
def f(l,m,n): c=0 k=min(l) for i in l: d=i-k if d%m!=0: return -1 c+=d//m return c n,m=map(int,input().split()) l=list(map(int,input().split())) print(f(l,m,n))
{ "input": [ "2 2\n10 9\n", "3 3\n12 9 15\n", "4 1\n1 1000000000 1000000000 1000000000\n" ], "output": [ "-1\n", "3\n", "2999999997\n" ] }
964
10
Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody. Input The first line contains one integer number n (2 ≤ n ≤ 5000). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — notes written on a sheet. Output Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody. Examples Input 4 1 2 4 5 Output 4 Input 6 62 22 60 61 48 49 Output 5 Note In the first example subsequences [1, 2] and [4, 5] give length 4 in total. In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal.
import sys def solve(): n = int(sys.stdin.readline()) a = [0] + [int(i) for i in sys.stdin.readline().split()] dp = [[0]*(n + 1) for i in range(n + 1)] ans = 0 maxnum = [0] * (10**5 + 2) maxmod = [0] * 7 for y in range(n + 1): maxmod = [0] * 7 for ai in a: maxnum[ai] = 0 for i in range(y): maxmod[a[i] % 7] = max(maxmod[a[i] % 7], dp[i][y]) maxnum[a[i]] = max(maxnum[a[i]], dp[i][y]) for x in range(y + 1, n + 1): dp[x][y] = max(maxmod[a[x] % 7], maxnum[a[x] + 1], maxnum[a[x] - 1], dp[0][y]) + 1 dp[y][x] = dp[x][y] maxmod[a[x] % 7] = max(maxmod[a[x] % 7], dp[x][y]) maxnum[a[x]] = max(maxnum[a[x]], dp[x][y]) ans = max(ans, dp[x][y]) print(ans) if __name__ == '__main__': solve()
{ "input": [ "6\n62 22 60 61 48 49\n", "4\n1 2 4 5\n" ], "output": [ "5\n", "4\n" ] }
965
9
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>. Input The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads. Output Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Examples Input 4 1 2 1 3 2 4 Output 1.500000000000000 Input 5 1 2 1 3 3 4 2 5 Output 2.000000000000000 Note In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5. In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
from sys import stdin def main(): n = int(input()) g, r = [[] for _ in range(n + 1)], 0. for s in stdin.read().splitlines(): u, v = map(int, s.split()) g[u].append(v) g[v].append(u) stack = [(1, 1, -1)] while stack: u, denom, depth = stack.pop() depth += 1 vv = g[u] if vv: denom *= len(vv) for v in vv: g[v].remove(u) stack.append((v, denom, depth)) else: r += depth / denom print(r) if __name__ == '__main__': main()
{ "input": [ "5\n1 2\n1 3\n3 4\n2 5\n", "4\n1 2\n1 3\n2 4\n" ], "output": [ "2.000000\n", "1.500000\n" ] }
966
7
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i. Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time. Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest. Input First line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences. Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down. Output Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest. Examples Input 3 1 1 Output 1 Input 5 1 2 2 2 Output 3 Input 18 1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4 Output 4 Note In first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them. In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.
# python3 def main(): n = int(input()) parent = tuple(int(x) - 1 for x in input().split()) depth = [0] for v in range(n - 1): depth.append(depth[parent[v]] + 1) parity = [0] * n for d in depth: parity[d] ^= 1 print(sum(parity)) main()
{ "input": [ "18\n1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4\n", "3\n1 1\n", "5\n1 2 2 2\n" ], "output": [ "4\n", "1\n", "3\n" ] }
967
7
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate turns. The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it. You want to know what number will be left on the board after n - 1 turns if both players make optimal moves. Input The first line contains one integer n (1 ≤ n ≤ 1000) — the number of numbers on the board. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^6). Output Print one number that will be left on the board. Examples Input 3 2 1 3 Output 2 Input 3 2 2 2 Output 2 Note In the first sample, the first player erases 3 and the second erases 1. 2 is left on the board. In the second sample, 2 is left on the board regardless of the actions of the players.
def do(): N=int(input()) ch=sorted(map(int,input().split())) print(ch[(N-1)//2]) do()
{ "input": [ "3\n2 2 2\n", "3\n2 1 3\n" ], "output": [ "2\n", "2\n" ] }
968
8
Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo M. What are the residues modulo M that Ajs cannot obtain with this action? Input The first line contains two positive integer N (1 ≤ N ≤ 200 000) and M (N+1 ≤ M ≤ 10^{9}), denoting the number of the elements in the first bag and the modulus, respectively. The second line contains N nonnegative integers a_1,a_2,…,a_N (0 ≤ a_1<a_2< …< a_N<M), the contents of the first bag. Output In the first line, output the cardinality K of the set of residues modulo M which Ajs cannot obtain. In the second line of the output, print K space-separated integers greater or equal than zero and less than M, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If K=0, do not output the second line. Examples Input 2 5 3 4 Output 1 2 Input 4 1000000000 5 25 125 625 Output 0 Input 2 4 1 3 Output 2 0 2 Note In the first sample, the first bag and the second bag contain \{3,4\} and \{0,1,2\}, respectively. Ajs can obtain every residue modulo 5 except the residue 2: 4+1 ≡ 0, 4+2 ≡ 1, 3+0 ≡ 3, 3+1 ≡ 4 modulo 5. One can check that there is no choice of elements from the first and the second bag which sum to 2 modulo 5. In the second sample, the contents of the first bag are \{5,25,125,625\}, while the second bag contains all other nonnegative integers with at most 9 decimal digits. Every residue modulo 1 000 000 000 can be obtained as a sum of an element in the first bag and an element in the second bag.
import sys input = sys.stdin.readline def main(): n, m = map(int, input().split()) a = list(map(int, input().split())) + [0]*500000 ans_S = 0 a[n] = a[0] + m s = [0]*600600 for i in range(n): s[i] = a[i + 1] - a[i] s[n] = -1 for i in range(n): s[2*n - i] = s[i] for i in range(2*n + 1, 3*n + 1): s[i] = s[i - n] l, r = 0, 0 z = [0]*600600 for i in range(1, 3*n + 1): if i < r: z[i] = z[i - l] while i + z[i] <= 3*n and (s[i + z[i]] == s[z[i]]): z[i] += 1 if i + z[i] > r: l = i r = i + z[i] ans = [] for i in range(n + 1, 2*n + 1): if z[i] < n: continue ans_S += 1 ans.append((a[0] + a[2*n - i + 1]) % m) ans.sort() print(ans_S) print(*ans) return if __name__=="__main__": main()
{ "input": [ "4 1000000000\n5 25 125 625\n", "2 4\n1 3\n", "2 5\n3 4\n" ], "output": [ "0\n", "2\n0 2 \n", "1\n2 \n" ] }
969
8
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board. Input The only line contains one integer — b (1 ≤ b ≤ 10^{10}). Output Print one number — answer for the problem. Examples Input 1 Output 1 Input 2 Output 2 Note In the first example [a, 1] = a, therefore ([a, b])/(a) is always equal to 1. In the second example [a, 2] can be equal to a or 2 ⋅ a depending on parity of a. ([a, b])/(a) can be equal to 1 and 2.
def fun(): n=int(input()) s=set() limit= int(n**0.5)+1 for i in range(1,limit): if(n%i==0): s.add(i) s.add(n//i) print(len(s)) fun()
{ "input": [ "1\n", "2\n" ], "output": [ "1\n", "2\n" ] }
970
7
You are given a string s=s_1s_2... s_n of length n, which only contains digits 1, 2, ..., 9. A substring s[l ... r] of s is a string s_l s_{l + 1} s_{l + 2} … s_r. A substring s[l ... r] of s is called even if the number represented by it is even. Find the number of even substrings of s. Note, that even if some substrings are equal as strings, but have different l and r, they are counted as different substrings. Input The first line contains an integer n (1 ≤ n ≤ 65000) — the length of the string s. The second line contains a string s of length n. The string s consists only of digits 1, 2, ..., 9. Output Print the number of even substrings of s. Examples Input 4 1234 Output 6 Input 4 2244 Output 10 Note In the first example, the [l, r] pairs corresponding to even substrings are: * s[1 ... 2] * s[2 ... 2] * s[1 ... 4] * s[2 ... 4] * s[3 ... 4] * s[4 ... 4] In the second example, all 10 substrings of s are even substrings. Note, that while substrings s[1 ... 1] and s[2 ... 2] both define the substring "2", they are still counted as different substrings.
def f(): n=int(input()) s=input() rez=0 for i in range(n): if int(s[i])%2==0: rez+=i+1 print(rez) f()
{ "input": [ "4\n1234\n", "4\n2244\n" ], "output": [ "6\n", "10\n" ] }
971
8
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digit x from this segment with f(x). For example, if a = 1337, f(1) = 1, f(3) = 5, f(7) = 3, and you choose the segment consisting of three rightmost digits, you get 1553 as the result. What is the maximum possible number you can obtain applying this operation no more than once? Input The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of digits in a. The second line contains a string of n characters, denoting the number a. Each character is a decimal digit from 1 to 9. The third line contains exactly 9 integers f(1), f(2), ..., f(9) (1 ≤ f(i) ≤ 9). Output Print the maximum number you can get after applying the operation described in the statement no more than once. Examples Input 4 1337 1 2 5 4 6 6 3 1 9 Output 1557 Input 5 11111 9 8 7 6 5 4 3 2 1 Output 99999 Input 2 33 1 1 1 1 1 1 1 1 1 Output 33
import sys input=sys.stdin.readline def main(): n=int(input()) l=list(map(int,list(input().strip()))) f=[0]+list(map(int,input().split())) i=0 while i<n and l[i] >= f[l[i]] : i+=1 while i<n and f[l[i]] >= l[i] : l[i]=f[l[i]] i+=1 print(''.join(map(str,l))) main()
{ "input": [ "2\n33\n1 1 1 1 1 1 1 1 1\n", "4\n1337\n1 2 5 4 6 6 3 1 9\n", "5\n11111\n9 8 7 6 5 4 3 2 1\n" ], "output": [ "33", "1557", "99999" ] }
972
11
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has n different matryoshkas. Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i). You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka i can be nested inside matryoshka j if out_i ≤ in_j. So only the last doll will take space inside your bag. Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + ... + (in_{i_k} - out_{i_{k-1}}), where i_1, i_2, ..., i_k are the indices of the chosen dolls in the order they are nested in each other. Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property. You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index i such that one of the subsets contains the i-th doll, and another subset doesn't. Since the answer can be large, print it modulo 10^9 + 7. Input The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of matryoshkas. The next n lines contain a description of each doll: two integers out_i and in_i (1 ≤ in_i < out_i ≤ 10^9) — the outer and inners volumes of the i-th matryoshka. Output Print one integer — the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo 10^9 + 7. Example Input 7 4 1 4 2 4 2 2 1 5 4 6 4 3 2 Output 6 Note There are 6 big enough nested subsets with minimum possible extra space in the example: * \{1, 5\}: we can't add any other matryoshka and keep it nested; it's extra space is 1; * \{1, 6\}; * \{2, 4, 5\}; * \{2, 4, 6\}; * \{3, 4, 5\}; * \{3, 4, 6\}. There are no more "good" subsets because, for example, subset \{6, 7\} is not big enough (we can add the 4-th matryoshka to it) or subset \{4, 6, 7\} has extra space equal to 2.
from sys import stdin, stdout mod = 10**9+7 n = int(input()) dolls = [] for i in range(n): o, i = map(int, stdin.readline().split()) dolls.append((o, i)) dolls.sort() dolls = [(i, o) for (o, i) in dolls] #print(dolls) def bin_search(i): lo = -1 hi = n-1 while lo+1 < hi: mid = (lo+hi-1)//2 + 1 top = dolls[mid][1] if top <= i: lo = mid else: hi = mid return hi counts = [1]*(n+1) dp = [0]*(n+1) for k in range(n): i, o = dolls[k] m_prev = dp[k]+o-(dolls[k-1][1] if k > 0 else 0) kk = bin_search(i) m_with = dp[kk] + i-(dolls[kk-1][1] if kk > 0 else 0) if m_prev < m_with: dp[k+1] = m_prev counts[k+1] = counts[k] elif m_prev > m_with: dp[k+1] = m_with counts[k+1] = counts[kk] else: dp[k+1] = m_prev counts[k+1] = (counts[k]+counts[kk]) % mod #print(dp) #print(counts) best = 10**9+10 best_count = 0 maximal = max([i for i, o in dolls]) for i in range(bin_search(maximal), n): ii = bin_search(dolls[i][0]) cur = dp[ii] + dolls[i][0] - (dolls[ii-1][1] if ii > 0 else 0) #print(cur, "via", ii) if cur < best: best = cur best_count = counts[ii] elif cur == best: best_count += counts[ii] best_count %= mod print(best_count)
{ "input": [ "7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2\n" ], "output": [ "6" ] }
973
7
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases. Then q test cases follow. The only line of the test case contains four integers a, b, n and S (1 ≤ a, b, n, S ≤ 10^9) — the number of coins of value n, the number of coins of value 1, the value n and the required total value. Output For the i-th test case print the answer on it — YES (without quotes) if there exist such x and y that if you take x coins of value n and y coins of value 1, then the total value of taken coins will be S, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). Example Input 4 1 2 3 4 1 2 3 6 5 2 6 27 3 3 5 18 Output YES NO NO YES
def solve(a, b, n, S): return ['NO', 'YES'][min((S // n), a)*n + b >= S] for q in range(int(input())): a, b, n, S = map(int, input().split()) print(solve(a, b, n, S))
{ "input": [ "4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18\n" ], "output": [ "YES\nNO\nNO\nYES\n" ] }
974
7
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers. Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second. Scrooge signed exactly k papers throughout his life and all those signatures look the same. Find the total time Scrooge wasted signing the papers. Input The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters. Output Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6. Examples Input 2 1 0 0 10 0 Output 0.200000000 Input 5 10 3 1 -5 6 -2 -1 3 2 10 0 Output 6.032163204 Input 6 10 5 0 4 0 6 0 3 0 7 0 2 0 Output 3.000000000
n,k = map(int,input().split()) l=0 s=[] for a in range(n): s.append([int(j) for j in input().split()]) def f(x,y): a=(x[0]-y[0])**2 b=(x[1]-y[1])**2 return (a+b)**.5 for j in range(n-1): l+=f(s[j],s[j+1]) x=(l/50)*k print('%.6f'%x)
{ "input": [ "2 1\n0 0\n10 0\n", "6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0\n", "5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0\n" ], "output": [ "0.200000000\n", "3.000000000\n", "6.032163204\n" ] }
975
8
You are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n × m formed by following rule: c_{i, j} = a_i ⋅ b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too. How many subrectangles of size (area) k consisting only of ones are there in c? A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x_1, x_2, y_1, y_2 (1 ≤ x_1 ≤ x_2 ≤ n, 1 ≤ y_1 ≤ y_2 ≤ m) a subrectangle c[x_1 ... x_2][y_1 ... y_2] is an intersection of the rows x_1, x_1+1, x_1+2, ..., x_2 and the columns y_1, y_1+1, y_1+2, ..., y_2. The size (area) of a subrectangle is the total number of cells in it. Input The first line contains three integers n, m and k (1 ≤ n, m ≤ 40 000, 1 ≤ k ≤ n ⋅ m), length of array a, length of array b and required size of subrectangles. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1), elements of a. The third line contains m integers b_1, b_2, …, b_m (0 ≤ b_i ≤ 1), elements of b. Output Output single integer — the number of subrectangles of c with size (area) k consisting only of ones. Examples Input 3 3 2 1 0 1 1 1 1 Output 4 Input 3 5 4 1 1 1 1 1 1 1 1 Output 14 Note In first example matrix c is: <image> There are 4 subrectangles of size 2 consisting of only ones in it: <image> In second example matrix c is: <image>
def getInput(): return [sum([int(ele) for ele in rang]) for rang in input().replace(' ', '').split('0')] n, m, k = list(map(int, input().split())) recs = [(i+1, int(k / (i + 1))) for i in range(int(k ** 0.5)) if k % (i + 1) == 0] recs += [(p[1], p[0]) for p in recs if p[1] != p[0]] a = getInput() b = getInput() print(sum([sum([mp - x + 1 for mp in b if (mp - x) > -1]) * sum([np - y + 1 for np in a if (np - y) > -1]) for x, y in recs]))
{ "input": [ "3 5 4\n1 1 1\n1 1 1 1 1\n", "3 3 2\n1 0 1\n1 1 1\n" ], "output": [ "14\n", "4\n" ] }
976
7
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = 7. 2. Pay b dollars and increase or decrease both integers by 1. For example, if x = 0 and y = 7 there are two possible outcomes after this operation: * x = -1, y = 6; * x = 1, y = 8. Your goal is to make both given integers equal zero simultaneously, i.e. x = y = 0. There are no other requirements. In particular, it is possible to move from x=1, y=0 to x=y=0. Calculate the minimum amount of dollars you have to spend on it. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of testcases. The first line of each test case contains two integers x and y (0 ≤ x, y ≤ 10^9). The second line of each test case contains two integers a and b (1 ≤ a, b ≤ 10^9). Output For each test case print one integer — the minimum amount of dollars you have to spend. Example Input 2 1 3 391 555 0 0 9 4 Output 1337 0 Note In the first test case you can perform the following sequence of operations: first, second, first. This way you spend 391 + 555 + 391 = 1337 dollars. In the second test case both integers are equal to zero initially, so you dont' have to spend money.
def R(): return map(int, input().split()) t, = R() for _ in range(t): x, y = sorted(R()) a, b = R() print(min(2*a, b)*x + a*(y-x))
{ "input": [ "2\n1 3\n391 555\n0 0\n9 4\n" ], "output": [ "1337\n0\n" ] }
977
7
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist. An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains an integer t (1 ≤ t ≤ 5) — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^4) — the number of elements in the array a and the number that Ehab hates. The second line contains n space-separated integers a_1, a_2, …, a_{n} (0 ≤ a_i ≤ 10^4) — the elements of the array a. Output For each testcase, print the length of the longest subarray whose sum isn't divisible by x. If there's no such subarray, print -1. Example Input 3 3 3 1 2 3 3 4 1 2 3 2 2 0 6 Output 2 3 -1 Note In the first test case, the subarray [2,3] has sum of elements 5, which isn't divisible by 3. In the second test case, the sum of elements of the whole array is 6, which isn't divisible by 4. In the third test case, all subarrays have an even sum, so the answer is -1.
def main(): for _ in range(int(input())): input() print(len(set(input().split()))) main()
{ "input": [ "3\n3 3\n1 2 3\n3 4\n1 2 3\n2 2\n0 6\n" ], "output": [ "2\n3\n-1\n" ] }
978
8
The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved. Koa the Koala is at the beach! The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shore. She measured the depth of the sea at 1, 2, ..., n meters from the shore and saved them in array d. d_i denotes the depth of the sea at i meters from the shore for 1 ≤ i ≤ n. Like any beach this one has tide, the intensity of the tide is measured by parameter k and affects all depths from the beginning at time t=0 in the following way: * For a total of k seconds, each second, tide increases all depths by 1. * Then, for a total of k seconds, each second, tide decreases all depths by 1. * This process repeats again and again (ie. depths increase for k seconds then decrease for k seconds and so on ...). Formally, let's define 0-indexed array p = [0, 1, 2, …, k - 2, k - 1, k, k - 1, k - 2, …, 2, 1] of length 2k. At time t (0 ≤ t) depth at i meters from the shore equals d_i + p[t mod 2k] (t mod 2k denotes the remainder of the division of t by 2k). Note that the changes occur instantaneously after each second, see the notes for better understanding. At time t=0 Koa is standing at the shore and wants to get to the island. Suppose that at some time t (0 ≤ t) she is at x (0 ≤ x ≤ n) meters from the shore: * In one second Koa can swim 1 meter further from the shore (x changes to x+1) or not swim at all (x stays the same), in both cases t changes to t+1. * As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed l at integer points of time (or she will drown). More formally, if Koa is at x (1 ≤ x ≤ n) meters from the shore at the moment t (for some integer t≥ 0), the depth of the sea at this point — d_x + p[t mod 2k] — can't exceed l. In other words, d_x + p[t mod 2k] ≤ l must hold always. * Once Koa reaches the island at n+1 meters from the shore, she stops and can rest. Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there). Koa wants to know whether she can go from the shore to the island. Help her! Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows. The first line of each test case contains three integers n, k and l (1 ≤ n ≤ 3 ⋅ 10^5; 1 ≤ k ≤ 10^9; 1 ≤ l ≤ 10^9) — the number of meters of sea Koa measured and parameters k and l. The second line of each test case contains n integers d_1, d_2, …, d_n (0 ≤ d_i ≤ 10^9) — the depths of each meter of sea Koa measured. It is guaranteed that the sum of n over all test cases does not exceed 3 ⋅ 10^5. Output For each test case: Print Yes if Koa can get from the shore to the island, and No otherwise. You may print each letter in any case (upper or lower). Example Input 7 2 1 1 1 0 5 2 3 1 2 3 2 2 4 3 4 0 2 4 3 2 3 5 3 0 7 2 3 3 0 2 1 3 0 1 7 1 4 4 4 3 0 2 4 2 5 2 3 1 2 3 2 2 Output Yes No Yes Yes Yes No No Note In the following s denotes the shore, i denotes the island, x denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at 1, 2, ..., n meters from the shore. In test case 1 we have n = 2, k = 1, l = 1, p = [ 0, 1 ]. Koa wants to go from shore (at x = 0) to the island (at x = 3). Let's describe a possible solution: * Initially at t = 0 the beach looks like this: [\underline{s}, 1, 0, i]. * At t = 0 if Koa would decide to swim to x = 1, beach would look like: [s, \underline{2}, 1, i] at t = 1, since 2 > 1 she would drown. So Koa waits 1 second instead and beach looks like [\underline{s}, 2, 1, i] at t = 1. * At t = 1 Koa swims to x = 1, beach looks like [s, \underline{1}, 0, i] at t = 2. Koa doesn't drown because 1 ≤ 1. * At t = 2 Koa swims to x = 2, beach looks like [s, 2, \underline{1}, i] at t = 3. Koa doesn't drown because 1 ≤ 1. * At t = 3 Koa swims to x = 3, beach looks like [s, 1, 0, \underline{i}] at t = 4. * At t = 4 Koa is at x = 3 and she made it! We can show that in test case 2 Koa can't get to the island.
import math import sys def solve(): n, k, l = map(int, input().split()) a = list(map(int, input().split())) lt = -1 for i in range(n): lt += 1 if(a[i] > l): print("No") return if(l - a[i] >= k): lt = -1 continue l1 = 2 * k - (l - a[i]) r1 = 2 * k + (l - a[i]) if(lt == 0): lt = l1 continue if(lt > r1): print("No") return lt = max(lt, l1) print("Yes") t = int(input()) for tt in range(t): solve()
{ "input": [ "7\n2 1 1\n1 0\n5 2 3\n1 2 3 2 2\n4 3 4\n0 2 4 3\n2 3 5\n3 0\n7 2 3\n3 0 2 1 3 0 1\n7 1 4\n4 4 3 0 2 4 2\n5 2 3\n1 2 3 2 2\n" ], "output": [ "Yes\nNo\nYes\nYes\nYes\nNo\nNo\n" ] }
979
10
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
from collections import deque def dist(G, n, s): D = [None] * n;Q = deque();Q.append(s);D[s] = 0 while Q: f = Q.popleft() for t in G[f]: if D[t] is None:D[t] = D[f] + 1;Q.append(t) return D for ti in range(int(input())): n, a, b, da, db = map(int, input().split());a -= 1;b -= 1;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) Da = dist(G, n, a);me = max(enumerate(Da), key=lambda x: x[1])[0] print("Alice") if Da[b] <= da or db <= 2 * da or max(dist(G, n, me)) <= 2 * da else print("Bob")
{ "input": [ "4\n4 3 2 1 2\n1 2\n1 3\n1 4\n6 6 1 2 5\n1 2\n6 5\n2 3\n3 4\n4 5\n9 3 9 2 5\n1 2\n1 6\n1 9\n1 3\n9 5\n7 9\n4 8\n4 3\n11 8 11 3 3\n1 2\n11 9\n4 9\n6 5\n2 10\n3 2\n5 9\n8 3\n7 4\n7 10\n" ], "output": [ "Alice\nBob\nAlice\nAlice\n" ] }
980
12
You are given a string s consisting of lowercase Latin letters "a", "b" and "c" and question marks "?". Let the number of question marks in the string s be k. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s = "ac?b?c" then we can obtain the following strings: ["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"]. Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 10^{9} + 7. A subsequence of the string t is such a sequence that can be derived from the string t after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2, 5, 6) and a subsequence consisting of letters at positions (3, 5, 6). Input The first line of the input contains one integer n (3 ≤ n ≤ 200 000) — the length of s. The second line of the input contains the string s of length n consisting of lowercase Latin letters "a", "b" and "c" and question marks"?". Output Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 10^{9} + 7. Examples Input 6 ac?b?c Output 24 Input 7 ??????? Output 2835 Input 9 cccbbbaaa Output 0 Input 5 a???c Output 46 Note In the first example, we can obtain 9 strings: * "acabac" — there are 2 subsequences "abc", * "acabbc" — there are 4 subsequences "abc", * "acabcc" — there are 4 subsequences "abc", * "acbbac" — there are 2 subsequences "abc", * "acbbbc" — there are 3 subsequences "abc", * "acbbcc" — there are 4 subsequences "abc", * "accbac" — there is 1 subsequence "abc", * "accbbc" — there are 2 subsequences "abc", * "accbcc" — there are 2 subsequences "abc". So, there are 2 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.
def main(): n = eval(input()) s=input() mod = 1000000007 a=0 b=0 ab=0 sz=1 ans=0 for c in s: if(c=='a'): a=a+sz a=a%mod elif(c=='b'): ab=ab+a ab=ab%mod elif(c=='c'): ans=ans+ab ans=ans%mod else : ans=(ans*3+ab)%mod ab=(ab*3+a)%mod a=(a*3+sz)%mod sz=(sz*3)%mod print(ans) main()
{ "input": [ "9\ncccbbbaaa\n", "7\n???????\n", "5\na???c\n", "6\nac?b?c\n" ], "output": [ "0\n", "2835\n", "46\n", "24\n" ] }
981
11
You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph. Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n). Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph. Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively. Output Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n). Examples Input 5 4 5 3 4 2 1 1 3 2 2 2 4 2 Output 1 2 2 4 Input 6 8 3 1 1 3 6 2 5 4 2 4 2 2 6 1 1 5 2 1 3 2 3 1 5 4 Output 2 1 4 3 1 Input 7 10 7 5 5 2 3 3 4 7 1 5 3 6 2 7 6 6 2 6 3 7 6 4 2 1 3 1 4 1 7 4 Output 3 4 2 7 7 3
import io import os # import __pypy__ def dijkstra(*args): # return dijkstraHeap(*args) # return dijkstraHeapComparatorWrong(*args) return dijkstraHeapComparator(*args) # return dijkstraSegTree(*args) # return dijkstraSortedList(*args) def dijkstraHeap(source, N, getAdj): # Heap of (dist, node) # Use float for dist because max dist for this problem doesn't fit in 32-bit # Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff` from heapq import heappop, heappush inf = float("inf") dist = [inf] * N dist[source] = 0.0 queue = [(0.0, float(source))] # print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff # print(__pypy__.strategy(dist)) # FloatListStrategy while queue: d, u = heappop(queue) u = int(u) if dist[u] == d: for v, w in getAdj(u): cost = d + w if cost < dist[v]: dist[v] = cost heappush(queue, (cost, float(v))) return dist def dijkstraHeapComparatorWrong(source, N, getAdj): # Heap of nodes, sorted with a comparator # This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic # Note: normal SPFA will TLE since there's a uphack for it in testcase #62 inf = float("inf") dist = [inf] * N dist[source] = 0.0 inQueue = [0] * N inQueue[source] = 1 queue = [source] # print(__pypy__.strategy(queue)) # IntegerListStrategy def cmp_lt(u, v): return dist[u] < dist[v] heappush, heappop, _ = import_heapq(cmp_lt) while queue: u = heappop(queue) d = dist[u] inQueue[u] = 0 for v, w in getAdj(u): cost = d + w if cost < dist[v]: dist[v] = cost if not inQueue[v]: heappush(queue, v) inQueue[v] = 1 else: # If v is already in the queue, we were suppose to bubble it to fix heap invariant pass return dist def dijkstraHeapComparator(source, N, getAdj): # Same above, except correctly re-bubbling the key after updates inf = float("inf") dist = [inf] * N dist[source] = 0.0 def cmp_lt(u, v): return dist[u] < dist[v] heappush, heappop, _siftdown = import_heapq(cmp_lt) class ListWrapper: # Exactly like a regular list except with fast .index(x) meant to be used with heapq # Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop) def __init__(self, maxN): self.arr = [] self.loc = [-1] * maxN def append(self, x): arr = self.arr arr.append(x) self.loc[x] = len(arr) - 1 def pop(self): ret = self.arr.pop() self.loc[ret] = -1 return ret def index(self, x): return self.loc[x] def __setitem__(self, i, x): self.arr[i] = x self.loc[x] = i def __getitem__(self, i): return self.arr[i] def __len__(self): return len(self.arr) queue = ListWrapper(N) queue.append(source) # print(__pypy__.strategy(queue.arr)) # IntegerListStrategy while queue: u = heappop(queue) d = dist[u] for v, w in getAdj(u): cost = d + w if cost < dist[v]: dist[v] = cost heapIndex = queue.index(v) if heapIndex == -1: heappush(queue, v) else: _siftdown(queue, 0, heapIndex) return dist def dijkstraSegTree(start, n, getAdj): # From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55 # Modifications: # Use floats instead of ints for inf/_min # Fix typo: m -> self.m # Fix python 3 compatibility: __getitem__ # Cache self.data # Remove parent pointers if False: inf = -1 def _min(a, b): return a if b == inf or inf != a < b else b else: inf = float("inf") _min = min class DistanceKeeper: def __init__(self, n): m = 1 while m < n: m *= 2 self.m = m self.data = 2 * m * [inf] self.dist = n * [inf] def __getitem__(self, x): return self.dist[x] def __setitem__(self, ind, x): data = self.data self.dist[ind] = x ind += self.m data[ind] = x ind >>= 1 while ind: data[ind] = _min(data[2 * ind], data[2 * ind + 1]) ind >>= 1 def trav(self): m = self.m data = self.data dist = self.dist while data[1] != inf: x = data[1] ind = 1 while ind < m: ind = 2 * ind + (data[2 * ind] != x) ind -= m self[ind] = inf dist[ind] = x yield ind # P = [-1] * n D = DistanceKeeper(n) D[start] = 0.0 for node in D.trav(): for nei, weight in getAdj(node): new_dist = D[node] + weight if D[nei] == inf or new_dist < D[nei]: D[nei] = new_dist # P[nei] = node # print(__pypy__.strategy(D.dist)) # print(__pypy__.strategy(D.data)) return D.dist def dijkstraSortedList(source, N, getAdj): # Just for completeness # COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py 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)) # END COPY AND PASTE ##################################### inf = float("inf") dist = [inf] * N dist[source] = 0.0 queue = SortedList([(0.0, float(source))]) while queue: negD, u = queue.pop(-1) d = -negD u = int(u) for v, w in getAdj(u): prevCost = dist[v] cost = d + w if cost < prevCost: if prevCost != inf: queue.discard((-prevCost, float(v))) dist[v] = cost queue.add((-cost, float(v))) return dist def import_heapq(cmp_lt): # Python 2 has a heapq.cmp_lt but python 3 removed it # Add it back for pypy3 submissions import sys if sys.version_info < (3,): # Python 2 import heapq from heapq import heappush, heappop, _siftdown heapq.cmp_lt = cmp_lt else: # Python 3 # COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap) - 1) def heappop(heap): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup(heap, 0) return returnitem return lastelt def _siftdown(heap, startpos, pos): newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if cmp_lt(newitem, parent): heap[pos] = parent pos = parentpos continue break heap[pos] = newitem def _siftup(heap, pos): endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the smaller child until hitting a leaf. childpos = 2 * pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of smaller child. rightpos = childpos + 1 if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]): childpos = rightpos # Move the smaller child up. heap[pos] = heap[childpos] pos = childpos childpos = 2 * pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem _siftdown(heap, startpos, pos) # END COPY AND PASTE ############################### return heappush, heappop, _siftdown if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, M = [int(x) for x in input().split()] graph = [[] for i in range(N)] for i in range(M): u, v, w = [int(x) for x in input().split()] u -= 1 v -= 1 graph[u].append((v, w)) graph[v].append((u, w)) # Want shortest path except one edge is worth 0 and one edge is worth 2x # Track this with 2 bits of extra state def getAdj(node): u = node >> 2 state = node & 3 for v, w in graph[u]: vBase = v << 2 # Regular edge yield vBase | state, w if not state & 1: # Take max edge, worth 0 yield vBase | state | 1, 0 if not state & 2: # Take min edge, worth double yield vBase | state | 2, 2 * w if not state & 3: # Take both min and max edge, worth normal yield vBase | state | 3, w dist = dijkstra(0, 4 * N, getAdj) print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))
{ "input": [ "7 10\n7 5 5\n2 3 3\n4 7 1\n5 3 6\n2 7 6\n6 2 6\n3 7 6\n4 2 1\n3 1 4\n1 7 4\n", "5 4\n5 3 4\n2 1 1\n3 2 2\n2 4 2\n", "6 8\n3 1 1\n3 6 2\n5 4 2\n4 2 2\n6 1 1\n5 2 1\n3 2 3\n1 5 4\n" ], "output": [ "\n3 4 2 7 7 3 \n", "\n1 2 2 4 \n", "\n2 1 4 3 1 \n" ] }
982
11
You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing? Let a_i be how many numbers i (1 ≤ i ≤ k) you have. An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied: 1. The number of occupied cells doesn't exceed 3; 2. The numbers on each diagonal are distinct. Make a beautiful matrix of minimum size. Input The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases. The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively. The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have. It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5. Output For each t test case print a single integer n — the size of the beautiful matrix. In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up. Example Input 2 3 4 2 0 0 1 15 4 2 4 8 1 Output 2 4 1 0 1 5 3 0 0 2 2 3 2 3 3 0 0 1 0 4 0 3 0 0 0 0 2 1 3 3 3 Note Note that 0 in this problem represents a blank, not a number. Examples of possible answers for the first test case: \begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array} Examples of not beautiful matrices for the first test case: \begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array} The example of the not beautiful matrix for the second test case: \begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array} Everything is okay, except the left-top submatrix contains 4 numbers.
def cheak(x): return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx for test in range(int(input())): m,k=(int(i) for i in input().split()) a=[int(i) for i in input().split()] mx=max(a) z=0;y=m*4 while z!=y: x=(z+y)//2 if cheak(x): y=x else: z=x+1 else: x=z a=sorted(list(map(list,zip(a,range(1,len(a)+1))))) def get(): i=len(a) while i!=0: i-=1 while a[i][0]>0: a[i][0]-=1 yield a[i][1] yield 0 mt=[[0 for i in range(x)] for j in range(x)] t=1 it=get() for i in range(0,x,2): if t==0:break for j in range(1,x,2): t=next(it) if t:mt[i][j]=t else:break for i in range(0,x,2): if t==0:break for j in range(0,x,2): t=next(it) if t:mt[i][j]=t else:break for i in range(1,x,2): if t==0:break for j in range(0,x,2): t=next(it) if t:mt[i][j]=t else:break print(len(mt)) for i in mt: print(*i)
{ "input": [ "2\n3 4\n2 0 0 1\n15 4\n2 4 8 1\n" ], "output": [ "\n2\n4 1\n0 1\n5\n3 0 0 2 2\n3 2 3 3 0\n0 1 0 4 0\n3 0 0 0 0\n2 1 3 3 3" ] }
983
11
You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark. You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized. Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0. The value of a string s is the minimum value among f_i for all i from 1 to k. What is the maximum value the string can have? Input The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used. The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark. Output Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters. Examples Input 10 2 a??ab????b Output 4 Input 9 4 ????????? Output 2 Input 2 3 ?? Output 0 Input 15 3 ??b?babbc??b?aa Output 3 Input 4 4 cabd Output 1 Note In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4. In the second example one of the possible strings is "aabbccdda". In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.
N, K = list(map(int, input().split())) S = input().strip() S = [-1 if _ == '?' else ord(_) - ord('a') for _ in S] def check(x): p = [[N for i in range(N+1)] for k in range(K)] for k in range(K): keep = 0 for i in range(N-1, -1, -1): keep += 1 if S[i] != -1 and S[i] != k: keep = 0 p[k][i] = p[k][i+1] if keep >= x: p[k][i] = i + x - 1 d = [N for s in range(1<<K)] d [0] = -1 for s in range(1, 1<<K): for k in range(K): if (s&(1<<k)) and (d[s^(1<<k)]<N): d[s] = min(d[s], p[k][d[s^(1<<k)]+1]) # print('d[%d%d]=%d'%(s//2, s%2, d[s])) return d[(1<<K)-1] < N l, r = 0, N//K while l < r: mid = (l + r + 1) // 2 if check(mid): l = mid else: r = mid - 1 print(l)
{ "input": [ "2 3\n??\n", "10 2\na??ab????b\n", "9 4\n?????????\n", "4 4\ncabd\n", "15 3\n??b?babbc??b?aa\n" ], "output": [ "0\n", "4\n", "2\n", "1\n", "3\n" ] }
984
8
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b. <image> 10 pebbles are arranged in two rows, each row has 5 pebbles Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers c1, ..., ck, where: * c1 = n * ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1. * ck = 1 The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game. Input The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has. The input limitations for getting 30 points are: * 2 ≤ n ≤ 50 The input limitations for getting 100 points are: * 2 ≤ n ≤ 109 Output Print a single number — the maximum possible result of the game. Examples Input 10 Output 16 Input 8 Output 15 Note Consider the first example (c1 = 10). The possible options for the game development are: * Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11. * Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13. * Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
def sieve(x): i=2 while(i*i<=x): if(x%i==0): return x//i i+=1 else: return 1 n=int(input()) c=n ans=c while(c!=1): c= sieve(c) ans+=c print(ans)
{ "input": [ "10\n", "8\n" ], "output": [ "16\n", "15\n" ] }
985
7
The Little Elephant enjoys recursive functions. This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: * If x = 1, exit the function. * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order. Input A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation. Output In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists. Examples Input 1 Output 1 Input 2 Output 2 1
def f(l): return [n]+list(range(1,n)) n = int(input()) print(*f(n))
{ "input": [ "1\n", "2\n" ], "output": [ "1\n", "2 1\n" ] }
986
8
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: * <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), * <domain> is a non-empty string, consisting of lowercase English letters, * the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters. If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context). When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".". Help Vasya to restore the possible address of the recorded Internet resource. Input The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only. It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above. Output Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them. Examples Input httpsunrux Output http://sun.ru/x Input ftphttprururu Output ftp://http.ru/ruru Note In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru".
def s(): a = input() r = 'http://' if a[0] == 'h' else 'ftp://' if a[0] == 'h': a = a[4:] else: a = a[3:] c = a[0] a = a[1:].replace('ru','.ru/',1) print(r,c,a[:-1] if a[-1] == '/'else a,sep='') s()
{ "input": [ "httpsunrux\n", "ftphttprururu\n" ], "output": [ "http://sun.ru/x\n", "ftp://http.ru/ruru\n" ] }
987
11
You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1 end repeat Here y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value. Input In the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000). Output On the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note. Examples Input 1 10 11 Output No Input 2 3 4 4 Output Yes 1 1 2 1 2 2 2 2 2 1 2 1 1 1 1 2 Input 3 6 1 2 3 Output Yes 1 1 2 2 2 2 3 3 3 3 3 3 Note For simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers.
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w = map(int, input().split()) a = [0] + list(map(int, input().split())) total = sum(a) def ng(): print('No') exit() def ok(a): print('Yes') print(*a) exit() if w < 1 or total < w: ng() if n == 1: if w == a[1]: ok([1] * (a[1] * 2)) else: ng() if w == 1: if min(a[1:]) > 1: ng() min_i = a.index(1) ans = [] for i in range(1, n + 1): if i == min_i: continue ans += [i] * (a[i] * 2) ok([min_i] + ans + [min_i]) ans1, ans2, ans3 = [], [], [] w -= 2 if w: for i in range(1, 3): x = min(a[i] - 1, w) w -= x a[i] -= x ans3 += [i] * (2 * x) for i in range(3, n + 1): x = min(a[i], w) w -= x a[i] -= x ans3 += [i] * (2 * x) ans1 = [2] * ((a[2] - 1) * 2) for i in range(3, n + 1): ans1 += [i] * (a[i] * 2) ans1 = [1] + ans1 + [1] a[1] -= 1 ans2 = [2] + [1] * (a[1] * 2) + [2] if w == 0: ok(ans1 + ans2 + ans3) else: ng()
{ "input": [ "1 10\n11\n", "2 3\n4 4\n", "3 6\n1 2 3\n" ], "output": [ "No\n", "Yes\n1 2 2 2 2 2 2 1 2 1 1 1 1 2 1 1\n", "Yes\n1 1 2 2 2 2 3 3 3 3 3 3\n" ] }
988
11
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7). Input The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation. Output Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7). Examples Input 5 -1 -1 4 3 -1 Output 2 Note For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
MOD = 10**9+7 n = int(input()) notUsed = set(range(1, n+1)) chairs = set() for i, a in enumerate(map(int, input().split()), 1): if a == -1: chairs.add(i) else: notUsed -= {a} fixed = len(chairs & notUsed) m = len(notUsed) U = m fact = [0]*(U+1) fact[0] = 1 for i in range(1, U+1): fact[i] = fact[i-1]*i % MOD invfact = [0]*(U+1) invfact[U] = pow(fact[U], MOD-2, MOD) for i in reversed(range(U)): invfact[i] = invfact[i+1]*(i+1) % MOD def nCr(n, r): if r < 0 or n < r: return 0 return fact[n]*invfact[r]*invfact[n-r] ans = fact[m] for k in range(1, fixed+1): ans += nCr(fixed, k)*fact[m-k]*(-1)**k ans %= MOD print(ans)
{ "input": [ "5\n-1 -1 4 3 -1\n" ], "output": [ "2\n" ] }
989
7
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box). Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile. <image> Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than xi boxes on the top of i-th box. What is the minimal number of piles she needs to construct? Input The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers x1, x2, ..., xn (0 ≤ xi ≤ 100). Output Output a single integer — the minimal possible number of piles. Examples Input 3 0 0 10 Output 2 Input 5 0 1 2 3 4 Output 1 Input 4 0 0 0 0 Output 4 Input 9 0 1 0 2 0 1 1 2 10 Output 3 Note In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2. <image> In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom). <image>
def go(): n = int(input()) a = [int(i) for i in input().split(' ')] a.sort() o = 1 for i in range(n): if(a[i] < i // o): o += 1 return o print(go())
{ "input": [ "9\n0 1 0 2 0 1 1 2 10\n", "5\n0 1 2 3 4\n", "3\n0 0 10\n", "4\n0 0 0 0\n" ], "output": [ "3\n", "1\n", "2\n", "4\n" ] }
990
10
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i. In order not to get lost, Vasya decided to act as follows. * Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1. * Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end. Input The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room. Output Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input 2 1 2 Output 4 Input 4 1 1 2 3 Output 20 Input 5 1 1 1 1 1 Output 62
n = int(input()) A = [int(i) for i in input().split()] dp = [[10**10 for i in range(n+1)] for k in range(n+1)] import sys sys.setrecursionlimit(10**7) for i in range(n+1): dp[i][i] = 1 MOD = 10**9 + 7 def f(i, x): if dp[i][x] != 10**10: return dp[i][x] dp[i][x] = (1 + (f(A[i]-1, i))%MOD + (f(i+1, x))%MOD)%MOD return dp[i][x] print((f(0, n) - 1)%MOD)
{ "input": [ "2\n1 2\n", "5\n1 1 1 1 1\n", "4\n1 1 2 3\n" ], "output": [ "4\n", "62\n", "20\n" ] }
991
7
Pashmak has fallen in love with an attractive girl called Parmida since one year ago... Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones. Input The first line contains four space-separated x1, y1, x2, y2 ( - 100 ≤ x1, y1, x2, y2 ≤ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct. Output If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them. Note that x3, y3, x4, y4 must be in the range ( - 1000 ≤ x3, y3, x4, y4 ≤ 1000). Examples Input 0 0 0 1 Output 1 0 1 1 Input 0 0 1 1 Output 0 1 1 0 Input 0 0 1 2 Output -1
x1, y1, x2, y2 = map(int,input().split()) def garden(x1,y,x2,y2): a = abs(x1-x2) b = abs(y1-y2) if x1 == x2: print(x1+b,y1,x2+b,y2) elif y1 == y2: print(x1,y1+a,x2,y2+a) elif a!=b: print(-1) else: print(x1,y2,x2,y1) garden(x1,y1,x2,y2)
{ "input": [ "0 0 1 2\n", "0 0 0 1\n", "0 0 1 1\n" ], "output": [ "-1\n", "1 0 1 1\n", "0 1 1 0\n" ] }
992
11
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is directed rightwards in the city's direction, the Oy axis is directed upwards (to the sky). The cannon will make n more shots. The cannon balls' initial speeds are the same in all the shots and are equal to V, so that every shot is characterized by only one number alphai which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (π / 4). We disregard the cannon sizes and consider the firing made from the point (0, 0). The balls fly according to the known physical laws of a body thrown towards the horizon at an angle: vx(t) = V·cos(alpha) vy(t) = V·sin(alpha) – g·t x(t) = V·cos(alpha)·t y(t) = V·sin(alpha)·t – g·t2 / 2 Think of the acceleration of gravity g as equal to 9.8. Bertown defends m walls. The i-th wall is represented as a vertical segment (xi, 0) - (xi, yi). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (y = 0) and stops. If the ball exactly hits the point (xi, yi), it is considered stuck. Your task is to find for each ball the coordinates of the point where it will be located in the end. Input The first line contains integers n and V (1 ≤ n ≤ 104, 1 ≤ V ≤ 1000) which represent the number of shots and the initial speed of every ball. The second line contains n space-separated real numbers alphai (0 < alphai < π / 4) which represent the angles in radians at which the cannon will fire. The third line contains integer m (1 ≤ m ≤ 105) which represents the number of walls. Then follow m lines, each containing two real numbers xi and yi (1 ≤ xi ≤ 1000, 0 ≤ yi ≤ 1000) which represent the wall’s coordinates. All the real numbers have no more than 4 decimal digits. The walls may partially overlap or even coincide. Output Print n lines containing two real numbers each — calculate for every ball the coordinates of its landing point. Your answer should have the relative or absolute error less than 10 - 4. Examples Input 2 10 0.7853 0.3 3 5.0 5.0 4.0 2.4 6.0 1.9 Output 5.000000000 2.549499369 4.000000000 0.378324889 Input 2 10 0.7853 0.3 2 4.0 2.4 6.0 1.9 Output 10.204081436 0.000000000 4.000000000 0.378324889
import sys from array import array # noqa: F401 from math import pi, sin, cos from bisect import bisect_left def input(): return sys.stdin.buffer.readline().decode('utf-8') n, v = map(int, input().split()) v = float(v) alpha = [float(input()) for _ in range(n)] m = int(input()) wall = sorted(tuple(map(float, input().split())) for _ in range(m)) + [(1e9, 1e9)] max_angle = pi / 4 eps = 1e-9 a = [0.0] * m + [max_angle + eps] for i in range(m): ng_angle, ok_angle = 0.0, max_angle + eps for _ in range(50): mid_angle = (ok_angle + ng_angle) / 2 t = wall[i][0] / (v * cos(mid_angle)) if (v * sin(mid_angle) * t - 9.8 * t**2 / 2) - eps <= wall[i][1]: ng_angle = mid_angle else: ok_angle = mid_angle a[i] = max(a[i], ng_angle) a[i + 1] = max(a[i], a[i + 1]) ans = [''] * n for i in range(n): wi = bisect_left(a, alpha[i]) ok, ng = 0.0, 1e7 sin_a = sin(alpha[i]) for _ in range(50): t = (ok + ng) / 2 if v * sin_a * t - 9.8 * t**2 / 2 >= 0.0: ok = t else: ng = t x = v * cos(alpha[i]) * ok if x < wall[wi][0]: ans[i] = f'{x:.8f} {0:.8f}' else: ok, ng = 0.0, 1e7 cos_a = cos(alpha[i]) for _ in range(50): t = (ok + ng) / 2 if v * cos_a * t <= wall[wi][0]: ok = t else: ng = t y = v * sin_a * ok - 9.8 * ok**2 / 2 ans[i] = f'{wall[wi][0]:.8f} {y:.8f}' print('\n'.join(ans))
{ "input": [ "2 10\n0.7853\n0.3\n2\n4.0 2.4\n6.0 1.9\n", "2 10\n0.7853\n0.3\n3\n5.0 5.0\n4.0 2.4\n6.0 1.9\n" ], "output": [ "10.204081436 0.000000000\n4.000000000 0.378324889\n", "5.000000000 2.549499369\n4.000000000 0.378324889\n" ] }
993
7
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has? Please help Haruhi solve this problem. Input The first line of input will be a single string s (1 ≤ |s| ≤ 20). String s consists only of lowercase English letters. Output Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make. Examples Input a Output 51 Input hi Output 76 Note In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
def photograph(s): print((len(s)+1)*26-len(s)) s=input('') photograph(s)
{ "input": [ "hi\n", "a\n" ], "output": [ "76\n", "51\n" ] }
994
8
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: * the i-th letter occurs in the string no more than ai times; * the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once. Input The first line of the input contains a single integer n (2 ≤ n ≤ 26) — the number of letters in the alphabet. The next line contains n integers ai (1 ≤ ai ≤ 109) — i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string. Output Print a single integer — the maximum length of the string that meets all the requirements. Examples Input 3 2 5 5 Output 11 Input 3 1 1 2 Output 3 Note For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
def f(): input() a = list(map(int,input().split(' '))) a.sort() t = 10**9+1 r = 0 for i in reversed(a): t = i if i < t else t - 1 if t == 0: break r += t print(r) f()
{ "input": [ "3\n2 5 5\n", "3\n1 1 2\n" ], "output": [ "11\n", "3\n" ] }
995
10
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer. Input The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement. The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person. Output Print a single line containing the difference between richest and poorest peoples wealth. Examples Input 4 1 1 1 4 2 Output 2 Input 3 1 2 2 2 Output 0 Note Lets look at how wealth changes through day in the first sample. 1. [1, 1, 4, 2] 2. [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2 In second sample wealth will remain the same for each person.
import sys sys.stderr = sys.stdout def hood(n, k, C): C.sort() m, r = divmod(sum(C), n) m1 = (m + 1) if r else m c_lo = C[0] k_lo = k for i, c in enumerate(C): if c_lo == m: break c_m = min(c, m) dc = c_m - c_lo dk = i * dc if k_lo >= dk: k_lo -= dk c_lo = c_m else: dc = k_lo // i c_lo += dc break c_hi = C[-1] k_hi = k for i, c in enumerate(reversed(C)): if c_hi == m1: break c_m1 = max(c, m1) dc = c_hi - c_m1 dk = i * dc if k_hi >= dk: k_hi -= dk c_hi = c_m1 else: dc = k_hi // i c_hi -= dc break return c_hi - c_lo def main(): n, k = readinti() C = readintl() print(hood(n, k, C)) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main()
{ "input": [ "4 1\n1 1 4 2\n", "3 1\n2 2 2\n" ], "output": [ "2\n", "0\n" ] }
996
8
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
def f(): n = int(input()) a = [1,2,3,4] print("YES") for i in range(n): x = input().split() x = [int(j)%2 for j in x] print(a[x[2]*2+x[3]]) f()
{ "input": [ "8\n0 0 5 3\n2 -1 5 0\n-3 -4 2 -1\n-1 -1 2 0\n-3 0 0 5\n5 2 10 3\n7 -3 10 2\n4 -2 7 -1\n" ], "output": [ "YES\n1\n2\n3\n4\n3\n3\n4\n1\n" ] }
997
9
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w ≤ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that: * Every cup will contain tea for at least half of its volume * Every cup will contain integer number of milliliters of tea * All the tea from the teapot will be poured into cups * All friends will be satisfied. Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj. For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1. Input The first line contains two integer numbers n and w (1 ≤ n ≤ 100, <image>). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 100). Output Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them. If it's impossible to pour all the tea and satisfy all conditions then output -1. Examples Input 2 10 8 7 Output 6 4 Input 4 4 1 1 1 1 Output 1 1 1 1 Input 3 10 9 8 10 Output -1 Note In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
def main(): n, w = map(int, input().split()) aa = list(map(int, input().split())) x, y = sum(aa), sum(a & 1 for a in aa) if x < w or x + y > w * 2: print(-1) return res = [r + 1 if r * 2 < a else r for r, a in ((a * w // x, a) for a in aa)] for i in sorted(range(n), key=aa.__getitem__, reverse=True)[:w - sum(res)]: res[i] += 1 print(*res) if __name__ == '__main__': main()
{ "input": [ "2 10\n8 7\n", "3 10\n9 8 10\n", "4 4\n1 1 1 1\n" ], "output": [ "6 4 ", "-1\n", "1 1 1 1 " ] }
998
10
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other. The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean. The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help. Input The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other. The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same. Output Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day. Examples Input 3 2 1 1 1 2 3 2 3 3 Output 2 3 Input 4 1 1 2 3 1 2 3 Output 2 Note In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations. In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def euler_path(n,path): height = [0]*n+[10**10] euler,st,visi,he = [],[0],[1]+[0]*(n-1),0 first = [-1]*n while len(st): x = st[-1] euler.append(x) if first[x] == -1: first[x] = len(euler)-1 while len(path[x]) and visi[path[x][-1]]: path[x].pop() if not len(path[x]): he -= 1 st.pop() else: i = path[x].pop() he += 1 st.append(i) height[i],visi[i] = he,1 return height,euler,first def cons(euler,height): n = len(euler) xx = n.bit_length() dp = [[n]*n for _ in range(xx)] dp[0] = euler for i in range(1,xx): for j in range(n-(1<<i)+1): a,b = dp[i-1][j],dp[i-1][j+(1<<(i-1))] dp[i][j] = a if height[a] < height[b] else b return dp def lca(l,r,dp,height,first): l,r = first[l],first[r] if l > r: l,r = r,l xx1 = (r-l+1).bit_length()-1 a,b = dp[xx1][l],dp[xx1][r-(1<<xx1)+1] return a if height[a] < height[b] else b def solve(s,f,t,dp,height,first): a = lca(s,f,dp,height,first) b = lca(t,f,dp,height,first) ans = height[f]-max(height[a],height[b])+1 if a == b: x = lca(s,t,dp,height,first) ans += height[x]-height[a] return ans def main(): n,q = map(int,input().split()) path = [[] for _ in range(n)] for ind,i in enumerate(map(int,input().split())): path[ind+1].append(i-1) path[i-1].append(ind+1) height,euler,first = euler_path(n,path) dp = cons(euler,height) for _ in range(q): a,b,c = map(lambda xx:int(xx)-1,input().split()) print(max(solve(a,b,c,dp,height,first), solve(a,c,b,dp,height,first), solve(b,a,c,dp,height,first))) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
{ "input": [ "3 2\n1 1\n1 2 3\n2 3 3\n", "4 1\n1 2 3\n1 2 3\n" ], "output": [ "2\n3\n", "2\n" ] }
999
8
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process. There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems. You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day. Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days. Input The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106). The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost. Output Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities. If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes). Examples Input 2 6 5 1 1 0 5000 3 2 0 5500 2 2 0 6000 15 0 2 9000 9 0 1 7000 8 0 2 6500 Output 24500 Input 2 4 5 1 2 0 5000 2 1 0 4500 2 1 0 3000 8 0 1 6000 Output -1 Note The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more. In the second sample it is impossible to send jury member from city 2 back home from Metropolis.
# ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------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 avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(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 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()) incom=defaultdict(list) outgo=defaultdict(list) for i in range(m): d,f,t,cost=map(int,input().split()) if t==0: incom[d].append((f,cost)) else: outgo[d].append((t,cost)) cost=[9999999999999999999]*n cou=0 total_cost=0 l=[] for i in sorted(incom.keys()): for j in range(len(incom[i])): if cost[incom[i][j][0]-1]==9999999999999999999: total_cost+=incom[i][j][1] cou+=1 else: total_cost+=min(0,incom[i][j][1]-cost[incom[i][j][0]-1]) cost[incom[i][j][0]-1]=min(cost[incom[i][j][0]-1],incom[i][j][1]) if cou==n: l.append((i,total_cost)) if max(cost)==9999999999999999999: print(-1) sys.exit(0) cost=[9999999999999999999]*n cou=0 total_cost=0 l1=[] for i in sorted(outgo.keys(),reverse=True): for j in range(len(outgo[i])): if cost[outgo[i][j][0]-1]==9999999999999999999: total_cost+=outgo[i][j][1] cou+=1 else: total_cost+=min(0,outgo[i][j][1]-cost[outgo[i][j][0]-1]) cost[outgo[i][j][0]-1]=min(cost[outgo[i][j][0]-1],outgo[i][j][1]) if cou==n: l1.append((i,total_cost)) if max(cost)==9999999999999999999: print(-1) sys.exit(0) l1.reverse() mint=[0]*len(l1) mint[-1]=l1[-1][1] for i in range(len(l1)-2,-1,-1): mint[i]=min(l1[i][1],mint[i+1]) ans=9999999999999999 t=0 #print(l1,l,mint) for i in range(len(l)): d=l[i][0]+k+1 #print(d) f=0 if t==len(l1): break while(d>l1[t][0]): t+=1 if t==len(l1): f=1 break if f==0: ans=min(ans,l[i][1]+mint[t]) if ans==9999999999999999: print(-1) else: print(ans)
{ "input": [ "2 4 5\n1 2 0 5000\n2 1 0 4500\n2 1 0 3000\n8 0 1 6000\n", "2 6 5\n1 1 0 5000\n3 2 0 5500\n2 2 0 6000\n15 0 2 9000\n9 0 1 7000\n8 0 2 6500\n" ], "output": [ "-1", " 24500\n" ] }