contestId
int64
0
1.01k
name
stringlengths
2
54
prompt
stringlengths
297
7.35k
response
stringlengths
32
43.6k
32
Constellation
Title: Constellation Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A star map in Berland is a checked field *n*<=×<=*m* squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer *x* (radius of the constellation) the following is true: - the 2nd is on the same vertical line as the 1st, but *x* squares up - the 3rd is on the same vertical line as the 1st, but *x* squares down - the 4th is on the same horizontal line as the 1st, but *x* squares left - the 5th is on the same horizontal line as the 1st, but *x* squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index *k* by the given Berland's star map. Input Specification: The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=300,<=1<=≤<=*k*<=≤<=3·107) — height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1,<=1), and the lower-right — (*n*,<=*m*). Then there follow *n* lines, *m* characters each — description of the map. *j*-th character in *i*-th line is «*», if there is a star in the corresponding square, and «.» if this square is empty. Output Specification: If the number of the constellations is less than *k*, output -1. Otherwise output 5 lines, two integers each — coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Demo Input: ['5 6 1\n....*.\n...***\n....*.\n..*...\n.***..\n', '5 6 2\n....*.\n...***\n....*.\n..*...\n.***..\n', '7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*...\n'] Demo Output: ['2 5\n1 5\n3 5\n2 4\n2 6\n', '-1\n', '4 4\n1 4\n7 4\n4 1\n4 7\n'] Note: none
```python import sys input = sys.stdin.readline n, m, k = map(int, input().split()) s = [list(input().rstrip()) for _ in range(n)] c = 0 for k0 in range(1, min(n, m)): for i in range(k0, n - k0): l0 = min(i, n - i - 1) si = s[i] for j in range(k0, m - k0): if si[j] == ".": continue if si[j - k0] == si[j + k0] == "*": if s[i - k0][j] == s[i + k0][j] == "*": c += 1 if c == k: ans = [(i + 1, j + 1)] ans.append((i + 1 - k0, j + 1)) ans.append((i + 1 + k0, j + 1)) ans.append((i + 1, j + 1 - k0)) ans.append((i + 1, j + 1 + k0)) for i in range(5): ans[i] = " ".join(map(str, ans[i])) sys.stdout.write("\n".join(ans)) exit() print(-1) ```
18
Stripe
Title: Stripe Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Once Bob took a paper stripe of *n* squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem? Input Specification: The first input line contains integer *n* (1<=≤<=*n*<=≤<=105) — amount of squares in the stripe. The second line contains *n* space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value. Output Specification: Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only. Demo Input: ['9\n1 5 -6 7 9 -16 0 -2 2\n', '3\n1 1 1\n', '2\n0 0\n'] Demo Output: ['3\n', '0\n', '1\n'] Note: none
```python ##c def main(): n=int(input()) ans=0 A=list(map(int,input().split())) l=0 r=sum(A) for s in range(n-1): l+=A[s] r-=A[s] if ( r==l ): ans+=1 print(ans) main() ```
58
Calendar
Title: Calendar Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: BerOilGasDiamondBank has branches in *n* cities, at that *n* is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly *n*<=/<=2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol *d* is used as the separator of words in the calendar. The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the *n*<=/<=2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line. Help BerOilGasDiamondBank and construct the required calendar. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=104, *n* is even) which is the number of branches. Then follow *n* lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol *d* (*d* has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different. Output Specification: Print *n*<=/<=2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "&lt;" operator in the modern programming languages. Demo Input: ['4\nb\naa\nhg\nc\n.\n', '2\naa\na\n!\n', '2\naa\na\n|\n'] Demo Output: ['aa.b\nc.hg\n', 'a!aa\n', 'aa|a\n'] Note: none
```python from collections import deque n = int(input()) a = [input() for i in range(n)] a.sort() dq = deque(a) # print(dq) d = input() n //= 2 common_len = sum(len(s) for s in a) // n res = [] for i in range(n): s1 = dq.popleft() for s2 in dq: if len(s1) + len(s2) == common_len: dq.remove(s2) res.append(min(s1+d+s2, s2+d+s1)) break for x in sorted(res): print(x) ```
25
Test
Title: Test Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring *s*1, the second enters an infinite loop if the input data contains the substring *s*2, and the third requires too much memory if the input data contains the substring *s*3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions? Input Specification: There are exactly 3 lines in the input data. The *i*-th line contains string *s**i*. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 105. Output Specification: Output one number — what is minimal length of the string, containing *s*1, *s*2 and *s*3 as substrings. Demo Input: ['ab\nbc\ncd\n', 'abacaba\nabaaba\nx\n'] Demo Output: ['4\n', '11\n'] Note: none
```python from itertools import permutations def c(a,b): s=b+'#'+a n,j=len(s),0 dp=[0]*n lb=len(b) for i in range(1,n): while(j and s[i]!=s[j]):j=dp[j-1] if(s[i]==s[j]):j+=1 dp[i]=j if(j==lb):return a return a[:len(a)-dp[-1]]+b s=[input() for _ in range(3)] print(min(len(c(s[x[0]],c(s[x[1]],s[x[2]]))) for x in permutations([0,1,2]))) ```
6
Alice, Bob and Chocolate
Title: Alice, Bob and Chocolate Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Alice and Bob like games. And now they are ready to start a new game. They have placed *n* chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman. How many bars each of the players will consume? Input Specification: The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the amount of bars on the table. The second line contains a sequence *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=1000), where *t**i* is the time (in seconds) needed to consume the *i*-th bar (in the order from left to right). Output Specification: Print two numbers *a* and *b*, where *a* is the amount of bars consumed by Alice, and *b* is the amount of bars consumed by Bob. Demo Input: ['5\n2 9 8 2 7\n'] Demo Output: ['2 3\n'] Note: none
```python n = int(input()) lst = list(map(int,input().split())) ls , rs ,l,r= 0,0,0,n-1 while l<=r: if ls<=rs: ls+= lst[l] l+=1 else: rs += lst[r] r -=1 print(l,n-r-1) ```
76
Points
Title: Points Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: You are given *N* points on a plane. Write a program which will find the sum of squares of distances between all pairs of points. Input Specification: The first line of input contains one integer number *N* (1<=≤<=*N*<=≤<=100<=000) — the number of points. Each of the following *N* lines contain two integer numbers *X* and *Y* (<=-<=10<=000<=≤<=*X*,<=*Y*<=≤<=10<=000) — the coordinates of points. Two or more points may coincide. Output Specification: The only line of output should contain the required sum of squares of distances between all pairs of points. Demo Input: ['4\n1 1\n-1 -1\n1 -1\n-1 1\n'] Demo Output: ['32\n'] Note: none
```python import sys input = sys.stdin.readline n = int(input()) s, sx, sy = 0, 0, 0 for i in range(n) : x, y = map(int,input().split()) s += x*x + y*y sx += x sy += y print(s*n-sx**2-sy**2) ```
4
Registration System
Title: Registration System Time Limit: 5 seconds Memory Limit: 64 megabytes Problem Description: A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least *i* is found so that name*i* does not yet exist in the database. Input Specification: The first line contains number *n* (1<=≤<=*n*<=≤<=105). The following *n* lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters. Output Specification: Print *n* lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken. Demo Input: ['4\nabacaba\nacaba\nabacaba\nacab\n', '6\nfirst\nfirst\nsecond\nsecond\nthird\nthird\n'] Demo Output: ['OK\nOK\nabacaba1\nOK\n', 'OK\nfirst1\nOK\nsecond1\nOK\nthird1\n'] Note: none
```python import sys read = sys.stdin.readline write = sys.stdout.write d = {} def solve(): n = read() if n not in d: d[n] = 0 return "OK" d[n] += 1 return n[:-1] + str(d[n]) for _ in range(int(read())): write(solve() + "\n") ```
9
Interestring graph and Apples
Title: Interestring graph and Apples Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too. She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*), where *x**i*<=≤<=*y**i*, is lexicographically smaller than the set (*u*1,<=*v*1),<=(*u*2,<=*v*2),<=...,<=(*u**n*,<=*v**n*), where *u**i*<=≤<=*v**i*, provided that the sequence of integers *x*1,<=*y*1,<=*x*2,<=*y*2,<=...,<=*x**n*,<=*y**n* is lexicographically smaller than the sequence *u*1,<=*v*1,<=*u*2,<=*v*2,<=...,<=*u**n*,<=*v**n*. If you do not cope, Hexadecimal will eat you. ...eat you alive. Input Specification: The first line of the input data contains a pair of integers *n* and *m* (1<=≤<=*n*<=≤<=50, 0<=≤<=*m*<=≤<=2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers *x**i* and *y**i* (1<=≤<=*x**i*, *y**i*<=≤<=*n*) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops. Output Specification: In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output *k* — the amount of edges that should be added to the initial graph. Finally, output *k* lines: pairs of vertices *x**j* and *y**j*, between which edges should be drawn. The result may contain multiple edges and loops. *k* can be equal to zero. Demo Input: ['3 2\n1 2\n2 3\n'] Demo Output: ['YES\n1\n1 3\n'] Note: none
```python m, n = map(int, input().split()) degree = [0] * (m + 1) path = [] res = True father = [i for i in range(m + 1)] def find(i): if i == father[i]: return i father[i] = find(father[i]) return father[i] def union(x, y): father[find(y)] = find(x) def next1(): for i in range(1, m + 1): if degree[i] < 2: return i return 0 def next2(to): for i in range(1, m + 1): if degree[i] < 2 and find(to) != find(i): return i return 0 for _ in range(n): v1, v2 = map(int, input().split()) degree[v1] += 1 degree[v2] += 1 union(v1, v2) if degree[v1] > 2 or degree[v2] > 2: res = False if res: while True: left = next1() if left == 0: break degree[left] += 1 right = next2(left) if right == 0: right = next1() else: union(left, right) degree[right] += 1 path.append([left, right]) for i in range(1, m + 1): if find(i) != find(1): res = False break print("%s" %(res and "YES" or "NO")) if res: print(len(path)) for value in path: print("%d %d" %(value[0], value[1])) ```
95
Volleyball
Title: Volleyball Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has *n* junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths. Initially each junction has exactly one taxi standing there. The taxi driver from the *i*-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than *t**i* meters. Also, the cost of the ride doesn't depend on the distance and is equal to *c**i* bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially. At the moment Petya is located on the junction *x* and the volleyball stadium is on the junction *y*. Determine the minimum amount of money Petya will need to drive to the stadium. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=1000,<=0<=≤<=*m*<=≤<=1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to *n*, inclusive. The next line contains two integers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*). They are the numbers of the initial and final junctions correspondingly. Next *m* lines contain the roads' description. Each road is described by a group of three integers *u**i*, *v**i*, *w**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=1<=≤<=*w**i*<=≤<=109) — they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next *n* lines contain *n* pairs of integers *t**i* and *c**i* (1<=≤<=*t**i*,<=*c**i*<=≤<=109), which describe the taxi driver that waits at the *i*-th junction — the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character. Output Specification: If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Demo Input: ['4 4\n1 3\n1 2 3\n1 4 1\n2 4 1\n2 3 5\n2 7\n7 2\n1 2\n7 7\n'] Demo Output: ['9\n'] Note: An optimal way — ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.
```python ''' # Submitted By M7moud Ala3rj Don't Copy This Code, CopyRight . [email protected] © 2022-2023 :) ''' # Problem Name = "Volleyball" # Class: C import sys from heapq import * #sys.setrecursionlimit(2147483647) input = sys.stdin.readline def print(*args, end='\n', sep=' ') -> None: sys.stdout.write(sep.join(map(str, args)) + end) Inf = float("inf") def dij(root): global n, taxis, graph, y BC = {root : 0} ; BD = {root : 0} pq = [[0, root, 0, 1]] while pq: cost, u, d, use = heappop(pq) if u==y: print(cost) exit() dd, cc = taxis[u] if d < dd and use: heappush(pq, [cost + cc, u, dd, 0]) for v, l in graph[u]: xd = d - l if xd >= 0: if cost < BC.get(v, Inf) or xd > BD.get(v, -1): BC[v], BD[v] = cost, xd heappush(pq, [cost, v, xd, 1]) print(-1) def Solve(): global n, taxis, graph, y n, m = list(map(int, input().split())) graph = {x: set() for x in range(1, n+1)} x, y = list(map(int, input().split())) for _ in range(m): u, v, w = list(map(int, input().split())) graph[u].add((v, w)) ; graph[v].add((u, w)) taxis = [[0, 0]] * (n+1) for i in range(1, n+1): taxis[i] = list(map(int, input().split())) dij(x) if __name__ == "__main__": Solve() ```
24
Sequence of points
Title: Sequence of points Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: You are given the following points with integer coordinates on the plane: *M*0,<=*A*0,<=*A*1,<=...,<=*A**n*<=-<=1, where *n* is odd number. Now we define the following infinite sequence of points *M**i*: *M**i* is symmetric to *M**i*<=-<=1 according (for every natural number *i*). Here point *B* is symmetric to *A* according *M*, if *M* is the center of the line segment *AB*. Given index *j* find the point *M**j*. Input Specification: On the first line you will be given an integer *n* (1<=≤<=*n*<=≤<=105), which will be odd, and *j* (1<=≤<=*j*<=≤<=1018), where *j* is the index of the desired point. The next line contains two space separated integers, the coordinates of *M*0. After that *n* lines follow, where the *i*-th line contain the space separated integer coordinates of the point *A**i*<=-<=1. The absolute values of all input coordinates will not be greater then 1000. Output Specification: On a single line output the coordinates of *M**j*, space separated. Demo Input: ['3 4\n0 0\n1 1\n2 3\n-5 3\n', '3 1\n5 5\n1000 1000\n-1000 1000\n3 100\n'] Demo Output: ['14 0\n', '1995 1995\n'] Note: none
```python from sys import stdin N, J = [int(w) for w in stdin.readline().split()] J = J % (N + N) points = [] x, y = [int(w) for w in stdin.readline().split()] for _ in range(N): points.append([int(w) for w in stdin.readline().split()]) for i in range(J): i %= N x += (points[i][0] - x) * 2 y += (points[i][1] - y) * 2 print(x, y) ```
66
Petya and Post
Title: Petya and Post Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations. The total number of stations equals to *n*. One can fuel the car at the *i*-th station with no more than *a**i* liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the 1-st and the 2-nd station is *b*1 kilometers, the distance between the 2-nd and the 3-rd one is *b*2 kilometers, ..., between the (*n*<=-<=1)-th and the *n*-th ones the distance is *b**n*<=-<=1 kilometers and between the *n*-th and the 1-st one the distance is *b**n* kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all *a**i* is equal to the sum of all *b**i*. The *i*-th gas station and *i*-th post office are very close, so the distance between them is 0 kilometers. Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it? Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105). The second line contains *n* integers *a**i* — amount of gasoline on the *i*-th station. The third line contains *n* integers *b*1,<=*b*2,<=...,<=*b**n*. They are the distances between the 1-st and the 2-nd gas stations, between the 2-nd and the 3-rd ones, ..., between the *n*-th and the 1-st ones, respectively. The sum of all *b**i* equals to the sum of all *a**i* and is no more than 109. Each of the numbers *a**i*, *b**i* is no less than 1 and no more than 109. Output Specification: Print on the first line the number *k* — the number of possible post offices, from which the car can drive one circle along a circular road. Print on the second line *k* numbers in the ascending order — the numbers of offices, from which the car can start. Demo Input: ['4\n1 7 2 3\n8 1 1 3\n', '8\n1 2 1 2 1 2 1 2\n2 1 2 1 2 1 2 1\n'] Demo Output: ['2\n2 4\n', '8\n1 2 3 4 5 6 7 8\n'] Note: none
```python import sys N = 0 A = [] # gas of a station B = [] # dist to next station result = [] def read_input(): global N, A, B, result readline = sys.stdin.readline N = int(readline().strip()) A = [int(w) for w in readline().split()] B = [int(w) for w in readline().split()] result = [False] * N def solve(): gap, min_gap = 0, 0 for i in range(N): gap = gap + A[i] - B[i] min_gap = min(gap, min_gap) result[0] |= min_gap >= 0 for i in range(1, N): min_gap += - A[i - 1] + B[i - 1] if min_gap >= 0: result[i] = True # print(result) gap, min_gap = 0, 0 C = B[-1:] + B[:-1] for i in range(N - 1, -1, -1): gap = gap + A[i] - C[i] min_gap = min(gap, min_gap) result[-1] |= min_gap >= 0 # print(C) for i in range(N - 2, -1, -1): min_gap += C[i + 1] - A[i + 1] if min_gap >= 0: result[i] = True # print(result) def write_output(): buf = [i + 1 for i in range(N) if result[i]] print(len(buf)) print(*buf) read_input() solve() write_output() ```
81
Average Score
Title: Average Score Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received *n* marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark. Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received *a* Safety Studies marks and *b* PE marks (*a*<=+<=*b*<==<=*n*). Now Polycarp wants to write a subject's name in front of each mark so that: - there are exactly *a* Safety Studies marks, - there are exactly *b* PE marks, - the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the *x*1<=+<=*x*2, where *x*1 is the average score in the first subject (Safety Studies), and *x*2 is the average score in the second one (Physical Education). Input Specification: The first line contains an integer *n* (2<=≤<=*n*<=≤<=105), *n* is the number of marks in Polycarp's Journal. The second line contains two positive integers *a*,<=*b* (1<=≤<=*a*,<=*b*<=≤<=*n*<=-<=1,<=*a*<=+<=*b*<==<=*n*). The third line contains a sequence of integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=5), they are Polycarp's marks. Output Specification: Print the sequence of integers *f*1,<=*f*2,<=...,<=*f**n*, where *f**i* (1<=≤<=*f**i*<=≤<=2) is the number of a subject to which the *i*-th mark should be attributed. If there are several possible solutions, then print such that the sequence *f*1,<=*f*2,<=...,<=*f**n* is the smallest lexicographically. The sequence *p*1,<=*p*2,<=...,<=*p**n* is lexicographically less than *q*1,<=*q*2,<=...,<=*q**n* if there exists such *j* (1<=≤<=*j*<=≤<=*n*) that *p**i*<==<=*q**i* for all 1<=≤<=*i*<=&lt;<=*j*, аnd *p**j*<=&lt;<=*q**j*. Demo Input: ['5\n3 2\n4 4 5 4 4\n', '4\n2 2\n3 5 4 5\n', '6\n1 5\n4 4 4 5 4 4\n'] Demo Output: ['1 1 2 1 2 ', '1 1 2 2 ', '2 2 2 1 2 2 '] Note: In the first sample the average score in the first subject is equal to 4, and in the second one — to 4.5. The total average score is 8.5.
```python n=int(input()) a,b=list(map(int,input().split())) c=list(map(int,input().split())) if a<b: d=[1 for i in range(n)] e=[[] for i in range(5)] for i in range(n): e[c[i]-1].append(i) e=e[::-1] for i in range(5): e1=len(e[i]) if e1>a or a==0: for j in range(a,e1): d[e[i][j]]=2 a=0 else: a-=e1 print(*d) elif a==b: d=[1]*(n//2)+[2]*(n//2) print(*d) else: d=[2 for i in range(n)] e=[[] for i in range(5)] for i in range(n): e[c[i]-1].append(i) e=e[::-1] for i in range(5): e1=len(e[i]) if e1>b or b==0: for j in range(e1-b): d[e[i][j]]=1 b=0 else: b-=e1 print(*d) ```
74
Shift It!
Title: Shift It! Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There is a square box 6<=×<=6 in size. It contains 36 chips 1<=×<=1 in size. Those chips contain 36 different characters — "0"-"9" and "A"-"Z". There is exactly one chip with each character. You are allowed to make the following operations: you may choose one of 6 rows or one of 6 columns and cyclically shift the chips there to one position to the left or to the right (for the row) or upwards or downwards (for the column). Those operations are allowed to perform several times. To solve the puzzle is to shift the chips using the above described operations so that they were written in the increasing order (exactly equal to the right picture). An example of solving the puzzle is shown on a picture below. Write a program that finds the sequence of operations that solves the puzzle. That sequence should not necessarily be shortest, but you should not exceed the limit of 10000 operations. It is guaranteed that the solution always exists. Input Specification: The input data are represented by 6 lines containing 6 characters each. They are the puzzle's initial position. Those lines contain each character from the string "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" exactly once. Output Specification: On the first line print number *n*, which is the number of operations. On the next *n* lines print the sequence of operations one per line. An operation is described by a word consisting of two characters. The first character shows the direction where the row or the column will be shifted. The possible directions are "L", "R" (to the left, to the right correspondingly, we shift a row), "U", "D" (upwards, downwards correspondingly, we shift a column). The second character is the number of the row (or the column), it is an integer from "1" to "6". The rows are numbered from the top to the bottom, the columns are numbered from the left to the right. The number of operations should not exceed 104. If there are several solutions, print any of them. Demo Input: ['01W345\n729AB6\nCD8FGH\nIJELMN\nOPKRST\nUVQXYZ\n'] Demo Output: ['2\nR2\nU3\n'] Note: none
```python ls="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" s,cnt,a1,a2=[],0,[],[] for i in range(6): s.append(list(input())) def add(c,i): global cnt cnt+=1 a1.append(c) a2.append(i) def right(i): add('R',i+1) tmp=s[i][5] for j in range(5,0,-1): s[i][j]=s[i][j-1] s[i][0]=tmp def left(i): add('L',i+1) tmp=s[i][0] for j in range(5): s[i][j]=s[i][j+1] s[i][5]=tmp def up(j): add('U',j+1) tmp=s[0][j] for i in range(5): s[i][j]=s[i+1][j] s[5][j]=tmp def down(j): add('D',j+1) tmp=s[5][j] for i in range(5,0,-1): s[i][j]=s[i-1][j] s[0][j]=tmp def chg(i1,j1,i2,j2): if i1==i2: right(i1);up(j1);right(i1);down(j1) right(i1);up(j1);right(i1);down(j1) right(i1);up(j1);right(i1);right(i1);down(j1) else: down(j1);left(i1);down(j1);right(i1) down(j1);left(i1);down(j1);right(i1) down(j1);left(i1);down(j1);down(j1);right(i1) for i in range(6): for j in range(6): toch=ls[i*6+j] for ni in range(6): for nj in range(6): if s[ni][nj]==toch: ii,jj=ni,nj while jj>j: chg(ii,jj-1,ii,jj) jj-=1 while jj<j: chg(ii,jj,ii,jj+1) jj+=1 while ii>i: chg(ii-1,jj,ii,jj) ii-=1 print(cnt) for i in range(cnt): print(a1[i]+str(a2[i])) ```
79
Beaver
Title: Beaver Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string *s*, and she tried to remember the string *s* correctly. However, Ciel feels *n* strings *b*1,<=*b*2,<=... ,<=*b**n* are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of *s*. Determine the longest contiguous substring of *s* that does not contain any boring string, so that she can remember the longest part of Taro's response. Input Specification: In the first line there is a string *s*. The length of *s* will be between 1 and 105, inclusive. In the second line there is a single integer *n* (1<=≤<=*n*<=≤<=10). Next *n* lines, there is a string *b**i* (1<=≤<=*i*<=≤<=*n*). Each length of *b**i* will be between 1 and 10, inclusive. Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive. Output Specification: Output in the first line two space-separated integers *len* and *pos*: the length of the longest contiguous substring of *s* that does not contain any *b**i*, and the first position of the substring (0-indexed). The position *pos* must be between 0 and |*s*|<=-<=*len* inclusive, where |*s*| is the length of string *s*. If there are several solutions, output any. Demo Input: ['Go_straight_along_this_street\n5\nstr\nlong\ntree\nbiginteger\nellipse\n', 'IhaveNoIdea\n9\nI\nh\na\nv\ne\nN\no\nI\nd\n', 'unagioisii\n2\nioi\nunagi\n'] Demo Output: ['12 4\n', '0 0\n', '5 5\n'] Note: In the first sample, the solution is traight_alon. In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on. In the third sample, the solution is either nagio or oisii.
```python s, n = input(), int(input()) t = [input() for i in range(n)] def f(i): global t for j in range(n): if i < j: if len(t[j]) < len(t[i]) and t[j] in t[i]: return False elif j < i and t[j] in t[i]: return False return True t = [t[i] for i in range(n) if f(i)] n = len(s) r = [0] * n for p in t: i, m = -1, len(p) - 1 while True: i = s.find(p, i + 1) if i == -1: break r[i] += 1 r[i + m] += 2 d, j, q = 0, -1, [-1] for i in range(n): if r[i] & 1: q.append(i) if r[i] & 2: j = q.pop(0) if i - j > d: d, k = i - j, j j = q.pop(0) if n - j > d: d, k = n - j, j print(d - 1, k + 1) ```
111
Petya and Divisors
Title: Petya and Divisors Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Little Petya loves looking for numbers' divisors. One day Petya came across the following problem: You are given *n* queries in the form "*x**i* *y**i*". For each query Petya should count how many divisors of number *x**i* divide none of the numbers *x**i*<=-<=*y**i*,<=*x**i*<=-<=*y**i*<=+<=1,<=...,<=*x**i*<=-<=1. Help him. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=105). Each of the following *n* lines contain two space-separated integers *x**i* and *y**i* (1<=≤<=*x**i*<=≤<=105, 0<=≤<=*y**i*<=≤<=*i*<=-<=1, where *i* is the query's ordinal number; the numeration starts with 1). If *y**i*<==<=0 for the query, then the answer to the query will be the number of divisors of the number *x**i*. In this case you do not need to take the previous numbers *x* into consideration. Output Specification: For each query print the answer on a single line: the number of positive integers *k* such that Demo Input: ['6\n4 0\n3 1\n5 2\n6 2\n18 4\n10000 3\n'] Demo Output: ['3\n1\n1\n2\n2\n22\n'] Note: Let's write out the divisors that give answers for the first 5 queries: 1) 1, 2, 4 2) 3 3) 5 4) 2, 6 5) 9, 18
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def divisor(i): s = [] for j in range(1, int(i ** (1 / 2)) + 1): if i % j == 0: s.append(i // j) s.append(j) return sorted(set(s)) n = int(input()) l = pow(10, 5) + 5 la = [-1] * l ans = [] for i in range(n): x, y = map(int, input().split()) s = divisor(x) ans0 = 0 for j in s: if not i - y <= la[j]: ans0 += 1 la[j] = i ans.append(ans0) sys.stdout.write("\n".join(map(str, ans))) ```
91
Queue
Title: Queue Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the *n*-th walrus stands at the beginning of the queue. The *i*-th walrus has the age equal to *a**i*. The *i*-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such *j* (*i*<=&lt;<=*j*), that *a**i*<=&gt;<=*a**j*. The displeasure of the *i*-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the *i*-th one. That is, the further that young walrus stands from him, the stronger the displeasure is. The airport manager asked you to count for each of *n* walruses in the queue his displeasure. Input Specification: The first line contains an integer *n* (2<=≤<=*n*<=≤<=105) — the number of walruses in the queue. The second line contains integers *a**i* (1<=≤<=*a**i*<=≤<=109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one. Output Specification: Print *n* numbers: if the *i*-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the *i*-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus. Demo Input: ['6\n10 8 5 3 50 45\n', '7\n10 4 6 3 2 8 15\n', '5\n10 3 1 10 11\n'] Demo Output: ['2 1 0 -1 0 -1 ', '4 2 1 0 -1 -1 -1 ', '1 0 -1 -1 -1 '] Note: none
```python from sys import stdin,stdout # from bisect import bisect_left,bisect # from sys import setrecursionlimit # from collections import defaultdict # from math import gcd,ceil,sqrt # setrecursionlimit(int(1e5)) input,print = stdin.readline,stdout.write max_value = 100005 class Node: def __init__(self, age, id): self.age = age self.id = id s = [Node(0, 0)] * max_value n = 0 top = 1 n = int(input()) a = [-1]+list(map(int,input().split())) s[top] = Node(a[n], n) a[n] = -1 for i in range(n-1,0,-1): l = 1 r = top while l<=r: mid = (l+r)// 2 if s[mid].age>=a[i]: l = mid+1 else: r = mid-1 if l<=top: a[i] = s[l].id-i-1 else: top+=1 s[top]=Node(a[i], i) a[i]=-1 for i in range(1,n+1): print(str(a[i])+" ") print("\n") ```
67
Restoration of the Permutation
Title: Restoration of the Permutation Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Let *A*<==<={*a*1,<=*a*2,<=...,<=*a**n*} be any permutation of the first *n* natural numbers {1,<=2,<=...,<=*n*}. You are given a positive integer *k* and another sequence *B*<==<={*b*1,<=*b*2,<=...,<=*b**n*}, where *b**i* is the number of elements *a**j* in *A* to the left of the element *a**t*<==<=*i* such that *a**j*<=≥<=(*i*<=+<=*k*). For example, if *n*<==<=5, a possible *A* is {5,<=1,<=4,<=2,<=3}. For *k*<==<=2, *B* is given by {1,<=2,<=1,<=0,<=0}. But if *k*<==<=3, then *B*<==<={1,<=1,<=0,<=0,<=0}. For two sequences *X*<==<={*x*1,<=*x*2,<=...,<=*x**n*} and *Y*<==<={*y*1,<=*y*2,<=...,<=*y**n*}, let *i*-th elements be the first elements such that *x**i*<=≠<=*y**i*. If *x**i*<=&lt;<=*y**i*, then *X* is lexicographically smaller than *Y*, while if *x**i*<=&gt;<=*y**i*, then *X* is lexicographically greater than *Y*. Given *n*, *k* and *B*, you need to determine the lexicographically smallest *A*. Input Specification: The first line contains two space separated integers *n* and *k* (1<=≤<=*n*<=≤<=1000, 1<=≤<=*k*<=≤<=*n*). On the second line are *n* integers specifying the values of *B*<==<={*b*1,<=*b*2,<=...,<=*b**n*}. Output Specification: Print on a single line *n* integers of *A*<==<={*a*1,<=*a*2,<=...,<=*a**n*} such that *A* is lexicographically minimal. It is guaranteed that the solution exists. Demo Input: ['5 2\n1 2 1 0 0\n', '4 2\n1 0 0 0\n'] Demo Output: ['4 1 5 2 3 ', '2 3 1 4 '] Note: none
```python n, k = map(int, input().split()) b = list(map(int, input().split())) taken = [False for i in range(n + 2)] a = [] for i in range(n): has = -1 for j in range(1, n + 1): if not taken[j] and b[j - 1] == 0: has = j break a.append(has) taken[has] = True for j in range(1, has - k + 1): b[j - 1] -= 1 print(*a) ```
45
Prime Problem
Title: Prime Problem Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: In Berland prime numbers are fashionable — the respectable citizens dwell only on the floors with numbers that are prime numbers. The numismatists value particularly high the coins with prime nominal values. All the prime days are announced holidays! Yet even this is not enough to make the Berland people happy. On the main street of the capital stand *n* houses, numbered from 1 to *n*. The government decided to paint every house a color so that the sum of the numbers of the houses painted every color is a prime number. However it turned out that not all the citizens approve of this decision — many of them protest because they don't want many colored houses on the capital's main street. That's why it is decided to use the minimal possible number of colors. The houses don't have to be painted consecutively, but every one of *n* houses should be painted some color. The one-colored houses should not stand consecutively, any way of painting is acceptable. There are no more than 5 hours left before the start of painting, help the government find the way when the sum of house numbers for every color is a prime number and the number of used colors is minimal. Input Specification: The single input line contains an integer *n* (2<=≤<=*n*<=≤<=6000) — the number of houses on the main streets of the capital. Output Specification: Print the sequence of *n* numbers, where the *i*-th number stands for the number of color for house number *i*. Number the colors consecutively starting from 1. Any painting order is allowed. If there are several solutions to that problem, print any of them. If there's no such way of painting print the single number -1. Demo Input: ['8'] Demo Output: ['1 2 2 1 1 1 1 2'] Note: none
```python # primes below sum(1,...,6000) primes = [2] for i in range(3, 190000, 2): isPrime = True for k in primes: if k * k > i: break if i % k == 0: isPrime = False break if isPrime: primes.append(i) def is_prime(a): if a == 1: return False for i in range(2, a): if a % i == 0: return False if i*i > a: return True return True n = int(input()) su = n * (n+1) // 2 if n == 1: print(-1) elif n == 2: print("1 1") elif is_prime(su - 2): print("1 2" + " 1" * (n-2)) else: no3 = (su % 2 == 1) target = su - 3 if no3 else su for a in primes: if a > target: break if is_prime(target - a): ls = [] ab = a maxAllow = n if no3 and maxAllow == 3: maxAllow = 2 while ab > maxAllow: ls.append(maxAllow) ab -= maxAllow maxAllow -= 1 if no3 and maxAllow == 3: maxAllow = 2 if ab != 3 or not no3: ls.append(ab) else: ls.append(2); ls.append(1) output = "" for i in range(1, n+1): if no3 and i == 3: output += '3 ' elif i in ls: output += '1 ' else: output += '2 ' print(output[:-1]) break ```
12
Start of the session
Title: Start of the session Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size *n*<=×<=*n* (*n* is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to *n*<=-<=1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix. Input Specification: The first line contains one integer *n* (2<=≤<=*n*<=≤<=1000), *n* is even. Output Specification: Output *n* lines with *n* numbers each — the required matrix. Separate numbers with spaces. If there are several solutions, output any. Demo Input: ['2\n', '4\n'] Demo Output: ['0 1\n1 0\n', '0 1 3 2\n1 0 2 3\n3 2 0 1\n2 3 1 0\n'] Note: none
```python n = int(input()) a = [[0]*n for _ in range(n)] for i in range(n-1): for j in range(n-1): a[i][j] = 1+(i+j-1)%(n-1) for i in range(n-1): a[i][-1] = a[-1][i] = a[i][i] a[i][i] = 0 for r in a: print(*r) ```
77
Martian Food
Title: Martian Food Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Have you ever tasted Martian food? Well, you should. Their signature dish is served on a completely black plate with the radius of *R*, flat as a pancake. First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of *r* and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians. Then a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians. Further, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius. Each of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border. To determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the *k*-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy? Input Specification: The first line contains integer *t* (1<=≤<=*t*<=≤<=104) — amount of testcases. Each of the following *t* lines contain three positive integers: the radii of the plate and a portion of the Golden Honduras *R* and *r* (1<=≤<=*r*<=&lt;<=*R*<=≤<=104) and the number *k* (1<=≤<=*k*<=≤<=104). In the pretests 1<=≤<=*k*<=≤<=2. Output Specification: Print *t* lines — the radius of the *k*-th portion of the Green Bull Terrier for each test. The absolute or relative error of the answer should not exceed 10<=-<=6. Demo Input: ['2\n4 3 1\n4 2 2\n'] Demo Output: ['0.9230769231\n0.6666666667\n'] Note: Dish from the first sample looks like this: <img class="tex-graphics" src="https://espresso.codeforces.com/e15f6caf257ceae8305cd82507b96dfac1b579ee.png" style="max-width: 100.0%;max-height: 100.0%;"/> Dish from the second sample looks like this: <img class="tex-graphics" src="https://espresso.codeforces.com/625a74ccb42332c9df05a22f8e17f81f086476d5.png" style="max-width: 100.0%;max-height: 100.0%;"/>
```python #!/usr/bin/env python3 def solve(R,r,k): # Thanks to Numberphile's "Epic circles" video # Use the formula for radii of circles in Pappus chain r = r / R n = k answer = ((1-r)*r)/(2*((n**2)*((1-r)**2)+r)) # Note that in a Pappus chain the diameter of the circle is 1, so we need to scale up: answer = 2*R * answer print("%.10f" % answer) t = int(input()) for i in range(t): R,r,k = map(int, input().split()) solve(R,r,k) ```
21
Stripe 2
Title: Stripe 2 Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem? Input Specification: The first input line contains integer *n* (1<=≤<=*n*<=≤<=105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value. Output Specification: Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only. Demo Input: ['4\n1 2 3 3\n', '5\n1 2 3 4 5\n'] Demo Output: ['1\n', '0\n'] Note: none
```python import sys n = int(input()) a = list(map(int, input().split())) count=0 pref = [0]*(n+1) for i in range(1, n+1): pref[i] = pref[i-1] + a[i-1] s = pref[n] if s % 3 != 0: print(0) sys.exit() x, y = s//3, 2*s//3 count_x = 0 for i in range(1, n): if pref[i]==y: count += count_x if pref[i]==x: count_x += 1 print(count) ```
73
LionAge II
Title: LionAge II Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string *s*, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than *k* letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters *x* and *y* (*x* immediately precedes *y*) the bonus *c*(*x*,<=*y*) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most *k* letters in the name of the Vasya's character. Input Specification: The first line contains character's name *s* and an integer number *k* (0<=≤<=*k*<=≤<=100). The length of the nonempty string *s* does not exceed 100. The second line contains an integer number *n* (0<=≤<=*n*<=≤<=676) — amount of pairs of letters, giving bonus to the euphony. The next *n* lines contain description of these pairs «*x* *y* *c*», which means that sequence *xy* gives bonus *c* (*x*,<=*y* — lowercase Latin letters, <=-<=1000<=≤<=*c*<=≤<=1000). It is guaranteed that no pair *x* *y* mentioned twice in the input data. Output Specification: Output the only number — maximum possible euphony оf the new character's name. Demo Input: ['winner 4\n4\ns e 7\no s 8\nl o 13\no o 8\n', 'abcdef 1\n5\na b -10\nb c 5\nc d 5\nd e 5\ne f 5\n'] Demo Output: ['36', '20'] Note: In the first example the most euphony name will be *looser*. It is easy to calculate that its euphony is 36.
```python I,T,G=input,int,range;R,O=lambda:I().split(),lambda c:ord(c)-ord('a') s,k=R();m=len(s);k=T(k);n=T(I());d=[[0]*26 for _ in G(26)] for _ in G(n):x,y,c=R();d[O(x)][O(y)]=T(c) f=[[0]*26 for _ in G(k+1)] for i in G(m): f1=[[0]*26 for _ in G(k+1)] for j in G(k+1): for r in G(26): x=O(s[i]) c=d[x][r] if i<m-1 else 0 sub=f[j][x] if 0<=i-1 else 0#底 v=sub+c if j>0: for x in G(26): c=d[x][r] if i<m-1 else 0 sub=f[j-1][x] if 0<=i-1 else 0#底 v=max(v,c+sub) f1[j][r]=v f1,f=f,f1 print(f[k][0]) ```
61
Eternal Victory
Title: Eternal Victory Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal! He decided to visit all *n* cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these *n* cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities. All cities are numbered 1 to *n*. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city. Help Shapur find how much He should travel. Input Specification: First line contains a single natural number *n* (1<=≤<=*n*<=≤<=105) — the amount of cities. Next *n*<=-<=1 lines contain 3 integer numbers each *x**i*, *y**i* and *w**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*,<=0<=≤<=*w**i*<=≤<=2<=×<=104). *x**i* and *y**i* are two ends of a road and *w**i* is the length of that road. Output Specification: A single integer number, the minimal length of Shapur's travel. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Demo Input: ['3\n1 2 3\n2 3 4\n', '3\n1 2 3\n1 3 3\n'] Demo Output: ['7\n', '9\n'] Note: none
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) adj = [[] for _ in range(n)] deg = [100] + [0] * n for u, v, w in (map(int, input().split()) for _ in range(n - 1)): adj[u - 1].append((v - 1, w)) adj[v - 1].append((u - 1, w)) deg[u - 1] += 1 deg[v - 1] += 1 total_w = [0] * n max_w = [0] * n stack = [i for i in range(1, n) if deg[i] == 1] while stack: v = stack.pop() deg[v] = 0 for dest, w in adj[v]: if deg[dest] == 0: continue total_w[dest] += total_w[v] + w max_w[dest] = max(max_w[dest], max_w[v] + w) deg[dest] -= 1 if deg[dest] == 1: stack.append(dest) print(total_w[0] * 2 - max_w[0]) ```
38
Vasya the Architect
Title: Vasya the Architect Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once Vasya played bricks. All the bricks in the set had regular cubical shape. Vasya vas a talented architect, however the tower he built kept falling apart. Let us consider the building process. Vasya takes a brick and puts it on top of the already built tower so that the sides of the brick are parallel to the sides of the bricks he has already used. Let's introduce a Cartesian coordinate system on the horizontal plane, where Vasya puts the first brick. Then the projection of brick number *i* on the plane is a square with sides parallel to the axes of coordinates with opposite corners in points (*x**i*,<=1,<=*y**i*,<=1) and (*x**i*,<=2,<=*y**i*,<=2). The bricks are cast from homogeneous plastic and the weight of a brick *a*<=×<=*a*<=×<=*a* is *a*3 grams. It is guaranteed that Vasya puts any brick except the first one on the previous one, that is the area of intersection of the upper side of the previous brick and the lower side of the next brick is always positive. We (Vasya included) live in a normal world where the laws of physical statics work. And that is why, perhaps, if we put yet another brick, the tower will collapse under its own weight. Vasya puts the cubes consecutively one on top of the other until at least one cube loses the balance and falls down. If it happens, Vasya gets upset and stops the construction. Print the number of bricks in the maximal stable tower, that is the maximal number *m* satisfying the condition that all the towers consisting of bricks 1, 2, ..., *k* for every integer *k* from 1 to *m* remain stable. Input Specification: The first input file contains an integer *n* (1<=≤<=*n*<=≤<=100) which is the number of bricks. Each of the next *n* lines contains four numbers *x**i*,<=1,<=*y**i*,<=1,<=*x**i*,<=2,<=*y**i*,<=2 (*x**i*,<=1<=≠<=*x**i*,<=2,<=|*x**i*,<=1<=-<=*x**i*,<=2|<==<=|*y**i*,<=1<=-<=*y**i*,<=2|) which are the coordinates of the opposite angles of the base of the brick number *i*. The coordinates are integers and their absolute value does not exceed 50. The cubes are given in the order Vasya puts them. It is guaranteed that the area of intersection of the upper side of the brick number *i*<=-<=1 and the lower side of the brick number *i* is strictly strictly greater than zero for all *i*<=≥<=2. Output Specification: Print the number of bricks in the maximal stable tower. Demo Input: ['2\n0 0 3 3\n1 0 4 3\n', '2\n0 0 3 3\n2 0 5 3\n', '3\n0 0 3 3\n1 0 4 3\n2 0 5 3\n'] Demo Output: ['2\n', '1\n', '3\n'] Note: none
```python n = int(input()) l = [] m = [] for i in range(n): X1, Y1, X2, Y2 = map(int, input().split()) m1 = (abs(X2 - X1)) ** 3 l.append([X1, Y1, X2, Y2]) m.append(m1) X1, Y1, X2, Y2 = l[0][0], l[0][1], l[0][2], l[0][3] if X1 > X2: X2, X1 = X1, X2 if Y1 > Y2: Y1, Y2 = Y2, Y1 ans = n for i in range(1, n): for j in range(i, 0, -1): x1, y1, x2, y2 = l[j - 1][0], l[j - 1][1], l[j - 1][2], l[j - 1][3] if x1 > x2: x2, x1 = x1, x2 if y1 > y2: y1, y2 = y2, y1 numx, numy, den = 0, 0 , 0 for k in range(i, j - 1, -1): a = (l[k][0] + l[k][2]) / 2 b = (l[k][1] + l[k][3]) / 2 m = (abs(l[k][2] - l[k][0])) ** 3 numx += m * a numy += m * b den += m xcm = numx / den ycm = numy / den if x1 <= xcm <= x2 and y1 <= ycm <= y2: pass else: ans = i break if ans != n: break print(ans) ```
51
Three Base Stations
Title: Three Base Stations Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point — the *x**i* coordinate. The village consists of *n* houses, the *i*-th house is located in the point with coordinates of *x**i*. TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power *d* located in the point *t* provides with communication all the houses on the segment [*t*<=-<=*d*,<=*t*<=+<=*d*] (including boundaries). To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of *d*. Which minimal value of *d* is enough to provide all the houses in the village with cellular communication. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=2·105) which represents the number of houses in the village. The second line contains the coordinates of houses — the sequence *x*1,<=*x*2,<=...,<=*x**n* of integer numbers (1<=≤<=*x**i*<=≤<=109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order. Output Specification: Print the required minimal power *d*. In the second line print three numbers — the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them. Demo Input: ['4\n1 2 3 4\n', '3\n10 20 30\n', '5\n10003 10004 10001 10002 1\n'] Demo Output: ['0.500000\n1.500000 2.500000 3.500000\n', '0\n10.000000 20.000000 30.000000\n', '0.500000\n1.000000 10001.500000 10003.500000\n'] Note: none
```python from bisect import * #n, m = map(int, raw_input().split()) n = int(input()) k=3 sol = [0] * k a=sorted(list(map(int,input().split()))) def test(m): sol[0]=a[0] for i in range(1,k): sol[i]=sol[i-1] it = bisect(a,sol[i-1]+m) if it<n: sol[i]=a[it] return (sol[k - 1] + m) >= a[-1] l=-1 r=a[-1] while(l<r-1): m=(l+r)//2 if test(m): r=m else: l=m test(r) print("{:0.6F}".format(r/2)) print(' '.join(map(lambda x: "{:0.6F}".format(x+r/2),sol))) ```
83
Doctor
Title: Doctor Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number *i* in the queue will have to visit his office exactly *a**i* times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving *k* animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out. Input Specification: The first line of input data contains two space-separated integers *n* and *k* (1<=≤<=*n*<=≤<=105, 0<=≤<=*k*<=≤<=1014). In the second line are given space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator). Output Specification: If the doctor will overall carry out less than *k* examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted. Demo Input: ['3 3\n1 2 1\n', '4 10\n3 3 2 1\n', '7 10\n1 3 3 1 2 3 1\n'] Demo Output: ['2 ', '-1\n', '6 2 3 '] Note: In the first sample test: - Before examination: {1, 2, 3} - After the first examination: {2, 3} - After the second examination: {3, 2} - After the third examination: {2} In the second sample test: - Before examination: {1, 2, 3, 4, 5, 6, 7} - After the first examination: {2, 3, 4, 5, 6, 7} - After the second examination: {3, 4, 5, 6, 7, 2} - After the third examination: {4, 5, 6, 7, 2, 3} - After the fourth examination: {5, 6, 7, 2, 3} - After the fifth examination: {6, 7, 2, 3, 5} - After the sixth examination: {7, 2, 3, 5, 6} - After the seventh examination: {2, 3, 5, 6} - After the eighth examination: {3, 5, 6, 2} - After the ninth examination: {5, 6, 2, 3} - After the tenth examination: {6, 2, 3}
```python from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, k = map(int, input().split()) a = list(map(int, input().split())) sa = sum(a) if sa <= k: ans = -1 if sa ^ k else "" print(ans) exit() cnt = defaultdict(lambda : 0) for i in a: cnt[i] += 1 s = list(set(a)) s.sort() u, v = 0, n la = 0 for i in s: c = (i - la) * v if u <= k < u + c: z = i break la = i u += c v -= cnt[i] y = [] for i in range(n): if a[i] >= z: y.append(i + 1) l = len(y) c -= l for i in range(l): if a[y[i] - 1] == z and u + c < k: y[i] = 0 c += 1 d = (k - u) % l x = [y[(i + d) % l] for i in range(l)] ans = [] for i in x: if i: ans.append(i) sys.stdout.write(" ".join(map(str, ans))) ```
75
Big Maximum Sum
Title: Big Maximum Sum Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't. This problem is similar to a standard problem but it has a different format and constraints. In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum. But in this problem you are given *n* small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array. For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9. Can you help Mostafa solve this problem? Input Specification: The first line contains two integers *n* and *m*, *n* is the number of the small arrays (1<=≤<=*n*<=≤<=50), and *m* is the number of indexes in the big array (1<=≤<=*m*<=≤<=250000). Then follow *n* lines, the *i*-th line starts with one integer *l* which is the size of the *i*-th array (1<=≤<=*l*<=≤<=5000), followed by *l* integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains *m* integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to *n*. The small arrays are numbered from 1 to *n* in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded. Output Specification: Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d). Demo Input: ['3 4\n3 1 6 -2\n2 3 3\n2 -5 1\n2 3 1 3\n', '6 1\n4 0 8 -3 -10\n8 3 -2 -5 10 8 -9 -5 -4\n1 0\n1 -3\n3 -8 5 6\n2 9 6\n1\n'] Demo Output: ['9\n', '8\n'] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) l, r, s = [0], [0], [0] u = [[0]] inf = pow(10, 9) + 1 c = [0] for _ in range(n): ans0 = -inf a = list(map(int, input().split()))[1:] l0, r0, s0 = -inf, -inf, 0 mi = 0 for i in a: s0 += i ans0 = max(ans0, s0 - mi) l0 = max(l0, s0) mi = min(mi, s0) s0 = 0 for i in reversed(a): s0 += i r0 = max(r0, s0) l.append(l0) r.append(r0) s.append(s0) c.append(ans0) a = list(map(int, input().split())) b = [0] ans = -inf for i in a: ans = max(ans, c[i]) b.append(r[i]) ma = b[1] for i in range(1, m): ai = a[i] ans = max(ans, l[ai] + ma) ma += s[ai] ma = max(ma, b[i + 1]) print(ans) ```
62
Tyndex.Brome
Title: Tyndex.Brome Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the *F* error is calculated by the following rules: - for every letter *c**i* from the potential address *c* the closest position *j* of the letter *c**i* in the address (*s*) entered by the user is found. The absolute difference |*i*<=-<=*j*| of these positions is added to *F*. So for every *i* (1<=≤<=*i*<=≤<=|*c*|) the position *j* is chosen such, that *c**i*<==<=*s**j*, and |*i*<=-<=*j*| is minimal possible. - if no such letter *c**i* exists in the address entered by the user, then the length of the potential address |*c*| is added to *F*. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the *F* function for an address given by the user and some set of potential addresses. Good luck! Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=105). They are the number of potential addresses and the length of the address entered by the user. The next line contains *k* lowercase Latin letters. They are the address entered by the user (*s*). Each next *i*-th (1<=≤<=*i*<=≤<=*n*) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105. Output Specification: On each *n* line of the output file print a single number: the value of the error function when the current potential address is chosen. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Demo Input: ['2 10\ncodeforces\ncodeforces\ncodehorses\n', '9 9\nvkontakte\nvcontacte\nvkontrakte\nvkollapse\nvkrokodile\nvtopke\nvkapuste\nvpechke\nvk\nvcodeforcese\n'] Demo Output: ['0\n12\n', '18\n14\n36\n47\n14\n29\n30\n0\n84\n'] Note: none
```python from bisect import bisect_left n, k = map(int, input().split()) q = 'abcdefghijklmnopqrstuvwxyz' a = {i: [] for i in q} for i, j in enumerate(input()): a[j].append(i) def g(t): return [(t[i] + t[i - 1]) // 2 for i in range(1, len(t))] c = {i: g(a[i]) for i in q} def f(): global a, c s, t = 0, input() d = len(t) for i, j in enumerate(t): if a[j]: if c[j]: s += abs(i - a[j][bisect_left(c[j], i)]) else: s += abs(i - a[j][0]) else: s += d return str(s) print('\n'.join(f() for i in range(n))) ```
84
Biathlon
Title: Biathlon Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section. Of course, biathlon as any sport, proved very difficult in practice. It takes much time and effort. Workouts, workouts, and workouts, — that's what awaited Valera on his way to great achievements in biathlon. As for the workouts, you all probably know that every professional biathlete should ski fast and shoot precisely at the shooting range. Only in this case you can hope to be successful, because running and shooting are the two main components of biathlon. Valera has been diligent in his ski trainings, which is why he runs really fast, however, his shooting accuracy is nothing to write home about. On a biathlon base where Valera is preparing for the competition, there is a huge rifle range with *n* targets. Each target have shape of a circle, and the center of each circle is located on the *Ox* axis. At the last training session Valera made the total of *m* shots. To make monitoring of his own results easier for him, one rather well-known programmer (of course it is you) was commissioned to write a program that would reveal how many and which targets Valera hit. More specifically, for each target the program must print the number of the first successful shot (in the target), or "-1" if this was not hit. The target is considered hit if the shot is inside the circle or on its boundary. Valera is counting on you and perhaps, thanks to you he will one day win international competitions. Input Specification: The first line of the input file contains the integer *n* (1<=≤<=*n*<=≤<=104), which is the number of targets. The next *n* lines contain descriptions of the targets. Each target is a circle whose center is located on the *Ox* axis. Each circle is given by its coordinate of the center *x* (<=-<=2·104<=≤<=*x*<=≤<=2·104) and its radius *r* (1<=≤<=*r*<=≤<=1000). It is guaranteed that no two targets coincide, intersect or are nested into each other, but they can touch each other. The next line contains integer *m* (1<=≤<=*m*<=≤<=2·105), which is the number of shots. Next *m* lines contain descriptions of the shots, which are points on the plane, given by their coordinates *x* and *y* (<=-<=2·104<=≤<=*x*,<=*y*<=≤<=2·104). All the numbers in the input are integers. Targets and shots are numbered starting from one in the order of the input. Output Specification: Print on the first line a single number, the number of targets hit by Valera. Print on the second line for each of the targets the number of its first hit or "-1" (without quotes) if this number does not exist. Separate numbers with spaces. Demo Input: ['3\n2 1\n5 2\n10 1\n5\n0 1\n1 3\n3 0\n4 0\n4 0\n', '3\n3 2\n7 1\n11 2\n4\n2 1\n6 0\n6 4\n11 2\n'] Demo Output: ['2\n3 3 -1 \n', '3\n1 2 4 \n'] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) l = 2 * pow(10, 4) + 1005 s = [[] for _ in range(2 * l + 1)] xr = [] for i in range(n): x, r = map(int, input().split()) x += l for j in range(x - r, x + r + 1): s[j].append(i) xr.append((x, r * r)) m = int(input()) ans = [-1] * n for i in range(1, m + 1): x, y = map(int, input().split()) x += l for j in s[x]: if ans[j] ^ -1: continue x0, r = xr[j] if pow(abs(x - x0), 2) + pow(abs(y), 2) <= r: ans[j] = i c = n - ans.count(-1) print(c) sys.stdout.write(" ".join(map(str, ans))) ```
85
Embassy Queue
Title: Embassy Queue Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order. For each action several separate windows are singled out: *k*1 separate windows for the first action (the first type windows), *k*2 windows for the second one (the second type windows), and *k*3 for the third one (the third type windows). The service time for one person in any of the first type window equals to *t*1. Similarly, it takes *t*2 time to serve a person in any of the second type windows. And it takes *t*3 to serve one person in any of the third type windows. Thus, the service time depends only on the window type and is independent from the person who is applying for visa. At some moment *n* people come to the embassy, the *i*-th person comes at the moment of time *c**i*. The person is registered under some number. After that he sits in the hall and waits for his number to be shown on a special board. Besides the person's number the board shows the number of the window where one should go and the person goes there immediately. Let's consider that the time needed to approach the window is negligible. The table can show information for no more than one person at a time. The electronic queue works so as to immediately start working with the person who has approached the window, as there are no other people in front of the window. The Client Service Quality inspectors noticed that several people spend too much time in the embassy (this is particularly tiresome as the embassy has no mobile phone reception and 3G). It was decided to organise the system so that the largest time a person spends in the embassy were minimum. Help the inspectors organise the queue. Consider that all actions except for being served in at the window, happen instantly. Input Specification: The first line contains three space-separated integers *k*1, *k*2, *k*3 (1<=≤<=*k**i*<=≤<=109), they are the number of windows of the first, second and third type correspondingly. The second line contains three space-separated integers *t*1, *t*2, *t*3 (1<=≤<=*t**i*<=≤<=105), they are the periods of time needed to serve one person in the window of the first, second and third type correspondingly. The third line contains an integer *n* (1<=≤<=*n*<=≤<=105), it is the number of people. The fourth line contains *n* space-separated integers *c**i* (1<=≤<=*c**i*<=≤<=109) in the non-decreasing order; *c**i* is the time when the person number *i* comes to the embassy. Output Specification: Print the single number, the maximum time a person will spend in the embassy if the queue is organized optimally. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams (also you may use the %I64d specificator). Demo Input: ['1 1 1\n1 1 1\n5\n1 1 1 1 1\n', '2 1 1\n5 1 1\n5\n1 2 3 3 5\n'] Demo Output: ['7\n', '13\n'] Note: In the first test 5 people come simultaneously at the moment of time equal to 1. There is one window of every type, it takes 1 unit of time to be served at each window. That's why the maximal time a person spends in the embassy is the time needed to be served at the windows (3 units of time) plus the time the last person who comes to the first window waits (4 units of time). Windows in the second test work like this: The first window of the first type: [1, 6) — the first person, [6, 11) — third person, [11, 16) — fifth person The second window of the first type: [2, 7) — the second person, [7, 12) — the fourth person The only second type window: [6, 7) — first, [7, 8) — second, [11, 12) — third, [12, 13) — fourth, [16, 17) — fifth The only third type window: [7, 8) — first, [8, 9) — second, [12, 13) — third, [13, 14) — fourth, [17, 18) — fifth We can see that it takes most time to serve the fifth person.
```python q = zip(map(int, input().split()), map(int, input().split())) n = int(input()) c = list(map(int, input().split())) d = c[:] for k, t in q: for i in range(min(k, n)): c[i] += t for i in range(k, n): c[i] = max(c[i], c[i - k]) + t print(max(c[i] - d[i] for i in range(n))) ```
45
Road Problem
Title: Road Problem Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: The Berland capital (as you very well know) contains *n* junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions. The city administration noticed that in the cities of all the developed countries between any two roads one can drive along at least two paths so that the paths don't share any roads (but they may share the same junction). The administration decided to add the minimal number of roads so that this rules was fulfilled in the Berland capital as well. In the city road network should exist no more than one road between every pair of junctions before or after the reform. Input Specification: The first input line contains a pair of integers *n*, *m* (2<=≤<=*n*<=≤<=900,<=1<=≤<=*m*<=≤<=100000), where *n* is the number of junctions and *m* is the number of roads. Each of the following *m* lines contains a description of a road that is given by the numbers of the connected junctions *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*). The junctions are numbered from 1 to *n*. It is possible to reach any junction of the city from any other one moving along roads. Output Specification: On the first line print *t* — the number of added roads. Then on *t* lines print the descriptions of the added roads in the format of the input data. You can use any order of printing the roads themselves as well as the junctions linked by every road. If there are several solutions to that problem, print any of them. If the capital doesn't need the reform, print the single number 0. If there's no solution, print the single number -1. Demo Input: ['4 3\n1 2\n2 3\n3 4\n', '4 4\n1 2\n2 3\n2 4\n3 4\n'] Demo Output: ['1\n1 4\n', '1\n1 3\n'] Note: none
```python def dfs1(v): mark[v]=1 st.append(v) dp[v]=d[v] for u in adj[v]: if not mark[u]: d[u]=d[v]+1 dfs1(u) dp[v]=min(dp[u],dp[v]) elif d[u]<d[v]-1: dp[v]=min(dp[v],d[u]) if dp[v]==d[v]: ver[cnt[0]]=v prv =-1 while prv != v: prv = st.pop() if d[ver[cnt[0]]]<d[prv]: ver[cnt[0]]=prv col[prv]=cnt[0] for u in adj[prv]: if col[u]!=-1 and col[u]!= cnt[0]: child[cnt[0]].append(col[u]) cnt[0]+=1 cnt=[0] N = 100000 adj=[[]for i in range(N)] child=[[]for i in range(N)] ord=[] mark=[False]*N dp=[-1]*N d=[-1]*N st = [] col=[-1]*N ver =[-1]*N n,m = map(int,input().split()) if n == 2 and m == 1: print("-1") exit(0) for i in range(m): u,v = map(int,input().split()) adj[v-1].append(u-1) adj[u-1].append(v-1) dfs1(0) ver[cnt[0]-1] = 0 if cnt[0] == 1: print("0") exit(0) for i in range(cnt[0]): if len(child[i]) == 0: ord.append(i) if len(child[cnt[0]-1]) == 1: ord.append(cnt[0]-1); ans = int((len(ord)+1) /2) print(ans) ans1=0 ans2=0 for i in range(ans): ans1 = ver[ord[i]]+1 ans2 = ver[ord[min(len(ord),int(i+len(ord)/2))]]+1 print(ans1,ans2) ```
15
Laser
Title: Laser Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of *n*<=×<=*m* cells and a robotic arm. Each cell of the field is a 1<=×<=1 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized — if you move one of the lasers by a vector, another one moves by the same vector. The following facts about the experiment are known: - initially the whole field is covered with a chocolate bar of the size *n*<=×<=*m*, both lasers are located above the field and are active; - the chocolate melts within one cell of the field at which the laser is pointed; - all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells; - at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman. You are given *n*, *m* and the cells (*x*1,<=*y*1) and (*x*2,<=*y*2), where the lasers are initially pointed at (*x**i* is a column number, *y**i* is a row number). Rows are numbered from 1 to *m* from top to bottom and columns are numbered from 1 to *n* from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions. Input Specification: The first line contains one integer number *t* (1<=≤<=*t*<=≤<=10000) — the number of test sets. Each of the following *t* lines describes one test set. Each line contains integer numbers *n*, *m*, *x*1, *y*1, *x*2, *y*2, separated by a space (2<=≤<=*n*,<=*m*<=≤<=109, 1<=≤<=*x*1,<=*x*2<=≤<=*n*, 1<=≤<=*y*1,<=*y*2<=≤<=*m*). Cells (*x*1,<=*y*1) and (*x*2,<=*y*2) are distinct. Output Specification: Each of the *t* lines of the output should contain the answer to the corresponding input test set. Demo Input: ['2\n4 4 1 1 3 3\n4 3 1 1 2 2\n'] Demo Output: ['8\n2\n'] Note: none
```python for _ in range(int(input())): n,m,x1,y1,x2,y2=map(int,input().split()) a=abs(x1-x2) b=abs(y1-y2) print(n*m - 2*(n-a)*(m-b) + max(0,n-2*a)*max(0,m-2*b)) ```
16
Fish
Title: Fish Time Limit: 3 seconds Memory Limit: 128 megabytes Problem Description: *n* fish, numbered from 1 to *n*, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability *a**ij*, and the second will eat up the first with the probability *a**ji*<==<=1<=-<=*a**ij*. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=18) — the amount of fish in the lake. Then there follow *n* lines with *n* real numbers each — matrix *a*. *a**ij* (0<=≤<=*a**ij*<=≤<=1) — the probability that fish with index *i* eats up fish with index *j*. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: *a**ij*<==<=1<=-<=*a**ji*. All real numbers are given with not more than 6 characters after the decimal point. Output Specification: Output *n* space-separated real numbers accurate to not less than 6 decimal places. Number with index *i* should be equal to the probability that fish with index *i* will survive to be the last in the lake. Demo Input: ['2\n0 0.5\n0.5 0\n', '5\n0 1 1 1 1\n0 0 0.5 0.5 0.5\n0 0.5 0 0.5 0.5\n0 0.5 0.5 0 0.5\n0 0.5 0.5 0.5 0\n'] Demo Output: ['0.500000 0.500000 ', '1.000000 0.000000 0.000000 0.000000 0.000000 '] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) a = [list(map(float, input().split())) for _ in range(n)] pow2 = [1] for _ in range(n): pow2.append(2 * pow2[-1]) m = pow2[n] dp = [0] * m dp[-1] = 1 for i in range(m - 1, 0, -1): x = [] for j in range(n): if i & pow2[j]: x.append(j) u = len(x) * (len(x) - 1) // 2 if not u or not dp[i]: continue dpi = dp[i] for j in x: aj = a[j] for k in x: if j == k: continue l = i ^ pow2[k] dp[l] += dpi * aj[k] / u ans = [dp[i] for i in pow2[:-1]] sys.stdout.write(" ".join(map(str, ans))) ```
22
Scheme
Title: Scheme Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index *i* got a person with index *f**i*, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (*x**i*,<=*y**i*), which mean that person *x**i* has to call person *y**i* as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it? Input Specification: The first input line contains number *n* (2<=≤<=*n*<=≤<=105) — amount of BolgenOS community members. The second line contains *n* space-separated integer numbers *f**i* (1<=≤<=*f**i*<=≤<=*n*,<=*i*<=≠<=*f**i*) — index of a person, to whom calls a person with index *i*. Output Specification: In the first line output one number — the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any. Demo Input: ['3\n3 3 2\n', '7\n2 3 1 3 4 4 1\n'] Demo Output: ['1\n3 1\n', '3\n2 5\n2 6\n3 7\n'] Note: none
```python n = int(input()) g = [int(i) - 1 for i in input().split()] def solve(n, g): vertex_id = [-1]*n current_id = 0 starts_a_cycle = [-1]*n cycle_vertex_sample = [] start_on_cycle = [] cycle_index_by_ID = [] cycle_count = 0 for v in range(n): if vertex_id[v] != -1: continue current_vertex = v cycle_found = False while vertex_id[current_vertex] == -1: vertex_id[current_vertex] = current_id current_vertex = g[current_vertex] if vertex_id[current_vertex] == current_id: cycle_found = True cycle_count += 1 cycle_vertex_sample.append(current_vertex) start_on_cycle.append(current_vertex == v) if not cycle_found: if starts_a_cycle[current_vertex] != -1: starts_a_cycle[v] = starts_a_cycle[current_vertex] starts_a_cycle[current_vertex] = -1 cycle_index_by_ID.append(cycle_index_by_ID[vertex_id[current_vertex]]) cycle = cycle_index_by_ID[-1] if start_on_cycle[cycle]: starts_a_cycle[cycle_vertex_sample[cycle]] = -1 start_on_cycle[cycle] = False starts_a_cycle[v] = cycle else: starts_a_cycle[v] = cycle_count - 1 cycle_index_by_ID.append(cycle_count - 1) current_id += 1 expanded = [] for i in range(n): if starts_a_cycle[i] != -1: cycle = starts_a_cycle[i] v = cycle_vertex_sample[cycle] expanded.append([v, i]) if len(expanded) == 1 and expanded[0][0] == expanded[0][1]: print(0) return print(len(expanded)) for i in range(len(expanded)-1): v, u = expanded[i][0], expanded[i+1][1] print('{0} {1}'.format(v+1, u+1)) print('{0} {1}'.format(expanded[-1][0] + 1, expanded[0][1] + 1)) solve(n, g) ```
43
Race
Title: Race Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Today *s* kilometer long auto race takes place in Berland. The track is represented by a straight line as long as *s* kilometers. There are *n* cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior — the system of segments on each of which the speed of the car is constant. The *j*-th segment of the *i*-th car is pair (*v**i*,<=*j*,<=*t**i*,<=*j*), where *v**i*,<=*j* is the car's speed on the whole segment in kilometers per hour and *t**i*,<=*j* is for how many hours the car had been driving at that speed. The segments are given in the order in which they are "being driven on" by the cars. Your task is to find out how many times during the race some car managed to have a lead over another car. A lead is considered a situation when one car appears in front of another car. It is known, that all the leads happen instantly, i. e. there are no such time segment of positive length, during which some two cars drive "together". At one moment of time on one and the same point several leads may appear. In this case all of them should be taken individually. Meetings of cars at the start and finish are not considered to be counted as leads. Input Specification: The first line contains two integers *n* and *s* (2<=≤<=*n*<=≤<=100,<=1<=≤<=*s*<=≤<=106) — the number of cars and the length of the track in kilometers. Then follow *n* lines — the description of the system of segments for each car. Every description starts with integer *k* (1<=≤<=*k*<=≤<=100) — the number of segments in the system. Then *k* space-separated pairs of integers are written. Each pair is the speed and time of the segment. These integers are positive and don't exceed 1000. It is guaranteed, that the sum of lengths of all segments (in kilometers) for each car equals to *s*; and all the leads happen instantly. Output Specification: Print the single number — the number of times some car managed to take the lead over another car during the race. Demo Input: ['2 33\n2 5 1 2 14\n1 3 11\n', '2 33\n2 1 3 10 3\n1 11 3\n', '5 33\n2 1 3 3 10\n1 11 3\n2 5 3 3 6\n2 3 1 10 3\n2 6 3 3 5\n'] Demo Output: ['1\n', '0\n', '2\n'] Note: none
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, s = map(int, input().split()) data = [dict() for _ in range(n)] for i in range(n): k, *a = map(int, input().split()) cur = 0 for j in range(0, 2 * k, 2): data[i][cur] = a[j] cur += a[j + 1] data[i][cur] = 0 ans = 0 for i in range(n): for j in range(i + 1, n): state1 = 0 dist_i, dist_j = 0, 0 speed_i, speed_j = 0, 0 time = sorted(set(data[i].keys()) | set(data[j].keys())) for t1, t2 in zip(time, time[1:]): if t1 in data[i]: speed_i = data[i][t1] if t1 in data[j]: speed_j = data[j][t1] dist_i += (t2 - t1) * speed_i dist_j += (t2 - t1) * speed_j state2 = 0 if dist_i == dist_j else 1 if dist_i > dist_j else 2 if state2 != 0: if state1 | state2 == 3: ans += 1 state1 = state2 if dist_i == s or dist_j == s: break print(ans) ```
50
Happy Farm 5
Title: Happy Farm 5 Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them. For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum. The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to . The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd. Input Specification: The first line contains an integer *N* which represents the number of cows in the herd (1<=≤<=*N*<=≤<=105). Each of the next *N* lines contains two integers *X**i* and *Y**i* which represent the coordinates of one cow of (|*X**i*|,<=|*Y**i*|<=≤<=106). Several cows can stand on one point. Output Specification: Print the single number — the minimum number of moves in the sought path. Demo Input: ['4\n1 1\n5 1\n5 3\n1 3\n'] Demo Output: ['16\n'] Note: Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
```python n=int(input()) mh=sh=-10**7 ml=sl=10**7 for i in range(n): a,b=map(int,input().split()) m=a+b s=a-b mh=max(mh,m) ml=min(ml,m) sh=max(sh,s) sl=min(sl,s) print(mh-ml+sh-sl+4) ```
71
Nuclear Fusion
Title: Nuclear Fusion Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: There is the following puzzle popular among nuclear physicists. A reactor contains a set of *n* atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of *k* atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input Specification: The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=17). The second line contains space-separated symbols of elements of *n* atoms, which are available from the start. The third line contains space-separated symbols of elements of *k* atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output Specification: If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line «YES», and on the next *k* lines print the way of synthesizing each of *k* atoms as equations. Each equation has the following form: "*x*1+*x*2+...+*x**t*-&gt;*y**i*", where *x**j* is the symbol of the element of some atom from the original set, and *y**i* is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Demo Input: ['10 3\nMn Co Li Mg C P F Zn Sc K\nSn Pt Y\n', '2 1\nH H\nHe\n', '2 2\nBk Fm\nCf Es\n'] Demo Output: ['YES\nMn+C+K-&gt;Sn\nCo+Zn+Sc-&gt;Pt\nLi+Mg+P+F-&gt;Y\n', 'YES\nH+H-&gt;He\n', 'NO\n'] Note: The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6f2ce1bed492cbe40ff1bb4600fe53aebc680ace.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/edbd66c81b30040884ff79761e8a0ff37dc1fa9d.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9f68585680e3f916d2ec79a9aac68b2ee880cba7.png" style="max-width: 100.0%;max-height: 100.0%;"/> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints.
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, k = map(int, input().split()) a = list(input().rstrip().decode().split()) b = list(input().rstrip().decode().split()) x = ["?"] c = ["H", "He"] for i in c: x.append(i) c = ["Li", "Be", "B", "C", "N", "O", "F", "Ne"] for i in c: x.append(i) c = ["Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar"] for i in c: x.append(i) c = ["K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr"] for i in c: x.append(i) c = ["Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe"] for i in c: x.append(i) c = ["Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn"] for i in c: x.append(i) c = ["Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm"] for i in c: x.append(i) d = dict() for i in range(1, 101): d[x[i]] = i a = [d[i] for i in a] b = [d[i] for i in b] if sum(a) ^ sum(b): ans = "NO" print(ans) exit() pow2 = [1] for _ in range(n): pow2.append(2 * pow2[-1]) m = pow2[n] d0 = dict() d0[0] = 0 s = 0 for i in range(k): s += b[i] d0[s] = i + 1 y = [[] for _ in range(k + 1)] for i in range(m): s = 0 for j in range(n): if i & pow2[j]: s += a[j] if s in d0: y[d0[s]].append(i) dp = [-1] * m dp[0] = 0 for i in range(k): dp0 = [-1] * m for j in y[i]: if dp[j] >= 0: dp0[j] = j for j in range(m): if dp0[j] == -1: continue dpj = dp0[j] for l in range(n): pl = pow2[l] if j & pl: continue dp0[j ^ pl] = max(dp0[j ^ pl], dpj) for j in y[i + 1]: dp[j] = dp0[j] ans = "YES" if dp[-1] ^ -1 else "NO" print(ans) if ans == "NO": exit() ans = [] u = m - 1 for i in range(k - 1, -1, -1): ans0 = [] v = u ^ dp[u] for j in range(n): if v & pow2[j]: ans0.append(x[a[j]]) u = dp[u] ans0 = "+".join(ans0) + "->" + x[b[i]] ans.append(ans0) sys.stdout.write("\n".join(ans)) ```
91
Ski Base
Title: Ski Base Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains *n* ski junctions, numbered from 1 to *n*. Initially the junctions aren't connected in any way. In the constructing process *m* bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The *i*-th road connects the junctions with numbers *a**i* and *b**i*. Track is the route with the following properties: - The route is closed, that is, it begins and ends in one and the same junction.- The route contains at least one road. - The route doesn't go on one road more than once, however it can visit any junction any number of times. Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected. Two ski bases are considered different if they consist of different road sets. After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem. Input Specification: The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=105,<=1<=≤<=*m*<=≤<=105). They represent the number of junctions and the number of roads correspondingly. Then on *m* lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*) — the numbers of the connected junctions. There could be more than one road between a pair of junctions. Output Specification: Print *m* lines: the *i*-th line should represent the number of ways to build a ski base after the end of construction of the road number *i*. The numbers should be printed modulo 1000000009 (109<=+<=9). Demo Input: ['3 4\n1 3\n2 3\n1 2\n1 2\n'] Demo Output: ['0\n0\n1\n3\n'] Note: Let us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this: The land lot for the construction will look in the following way: We can choose a subset of roads in three ways: In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1.
```python import sys input = sys.stdin.readline def getp(a): if P[a] == a: return a P[a] = getp(P[a]) return P[a] def solve(): global P n, m = map(int, input().split()) P = list(range(n+1)) MOD = int(1e9+9) r = 0 for i in range(m): a, b = map(int, input().split()) a = getp(a) b = getp(b) if a == b: r += 1 else: P[a] = b print((pow(2, r, MOD)-1) % MOD) solve() ```
4
Mysterious Present
Title: Mysterious Present Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes *A*<==<={*a*1,<=<=*a*2,<=<=...,<=<=*a**n*}, where the width and the height of the *i*-th envelope is strictly higher than the width and the height of the (*i*<=<=-<=<=1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you. Input Specification: The first line contains integers *n*, *w*, *h* (1<=<=≤<=*n*<=≤<=5000, 1<=≤<=*w*,<=<=*h*<=<=≤<=106) — amount of envelopes Peter has, the card width and height respectively. Then there follow *n* lines, each of them contains two integer numbers *w**i* and *h**i* — width and height of the *i*-th envelope (1<=≤<=*w**i*,<=<=*h**i*<=≤<=106). Output Specification: In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line. Demo Input: ['2 1 1\n2 2\n2 2\n', '3 3 3\n5 4\n12 11\n9 8\n'] Demo Output: ['1\n1 \n', '3\n1 3 2 \n'] Note: none
```python import sys input = sys.stdin.readline n, width, height = map(int, input().split()) arr = [] for i in range(n): w, h = map(int, input().split()) if w > width and h > height: arr.append((w, h, i+1)) F = [1]*len(arr) parent = [-1]*len(arr) arr.sort(key=lambda x:x[0], reverse=True) for i in range(len(arr)): for j in range(i): if arr[j][0] > arr[i][0] and arr[j][1] > arr[i][1] and F[j]+1 > F[i]: F[i] = F[j]+1 parent[i] = j ind = -1 m = 0 for i in range(len(arr)): if F[i] > m: m = F[i] ind = i ans = [] print(m) while ind != -1: ans.append(arr[ind][2]) ind = parent[ind] if len(ans): print(*(ans)) ```
29
Mail Stamps
Title: Mail Stamps Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately. There are *n* stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) — amount of mail stamps on the envelope. Then there follow *n* lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city. Output Specification: Output *n*<=+<=1 numbers — indexes of cities in one of the two possible routes of the letter. Demo Input: ['2\n1 100\n100 2\n', '3\n3 1\n100 2\n3 2\n'] Demo Output: ['2 100 1 ', '100 2 3 1 '] Note: none
```python import sys def solve(): lines = sys.stdin.readlines() n = int(lines[0]) d = {} for i in range(1, n+1): a, b = map(int, lines[i].split()) if a not in d: d[a] = [] if b not in d: d[b] = [] d[a].append(b) d[b].append(a) start = -1 for k, v in d.items(): if len(v) == 1: start = k prev = -1 ans = [] while True: ans.append(start) v = d[start] next = v[0] if next == prev: if len(v) == 1: break next = v[1] prev, start = start, next sys.stdout.write(' '.join(map(str, ans))) solve() ```
15
Triangles
Title: Triangles Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Last summer Peter was at his granny's in the country, when a wolf attacked sheep in the nearby forest. Now he fears to walk through the forest, to walk round the forest, even to get out of the house. He explains this not by the fear of the wolf, but by a strange, in his opinion, pattern of the forest that has *n* levels, where *n* is an even number. In the local council you were given an area map, where the granny's house is marked by point *H*, parts of dense forest are marked grey (see the picture to understand better). After a long time at home Peter decided to yield to his granny's persuasions and step out for a breath of fresh air. Being prudent, Peter plans the route beforehand. The route, that Peter considers the most suitable, has the following characteristics: - it starts and ends in the same place — the granny's house; - the route goes along the forest paths only (these are the segments marked black in the picture); - the route has positive length (to step out for a breath of fresh air Peter has to cover some distance anyway); - the route cannot cross itself; - there shouldn't be any part of dense forest within the part marked out by this route; You should find the amount of such suitable oriented routes modulo 1000000009. The example of the area map for *n*<==<=12 is given in the picture. Since the map has a regular structure, you can construct it for other *n* by analogy using the example. Input Specification: The input data contain the only even integer *n* (2<=≤<=*n*<=≤<=106). Output Specification: Output the only number — the amount of Peter's routes modulo 1000000009. Demo Input: ['2\n', '4\n'] Demo Output: ['10\n', '74\n'] Note: none
```python n=int(input()) z=8 y=[] for i in range(n//2-1): y.append((z-3)%1000000009) z*=2 z%=1000000009 if n==2: print(10) else: a=4 for i in range(n//2,2,-1): a*=y[i-3] a+=4 a%=1000000009 a+=2 print(2*(a**2+1)%1000000009) ```
3
Least Cost Bracket Sequence
Title: Least Cost Bracket Sequence Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: This is yet another problem on regular bracket sequences. A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence. For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. Input Specification: The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow *m* lines, where *m* is the number of characters "?" in the pattern. Each line contains two integer numbers *a**i* and *b**i* (1<=≤<=*a**i*,<=<=*b**i*<=≤<=106), where *a**i* is the cost of replacing the *i*-th character "?" with an opening bracket, and *b**i* — with a closing one. Output Specification: Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. Demo Input: ['(??)\n1 2\n2 8\n'] Demo Output: ['4\n()()\n'] Note: none
```python s=[] cost,pre,pq=0,0,[] from heapq import heappop, heappush for i, c in enumerate(input()): if c=='?': c=')' x,y=map(int,input().split()) cost+=y heappush(pq, (x-y,i)) s.append(c) if c=='(': pre+=1 else: if pre==0: if not pq: pre=-1 break x,y=heappop(pq) cost+=x s[y]='(' pre+=1 else: pre-=1 if pre: print(-1) else: print(cost) print("".join(s)) ```
49
Common ancestor
Title: Common ancestor Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are *n* permissible substitutions. The substitution *a**i*-&gt;*b**i**c**i* means that any one symbol *a**i* can be replaced with two symbols *b**i**c**i*. Every substitution could happen an unlimited number of times. They say that two creatures with DNA sequences *s*1 and *s*2 can have a common ancestor if there exists such a DNA sequence *s*3 that throughout evolution it can result in *s*1 and *s*2, perhaps after a different number of stages. Your task is to find out by the given *s*1 and *s*2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestor’s DNA. Input Specification: The first line contains a non-empty DNA sequence *s*1, the second line contains a non-empty DNA sequence *s*2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer *n* (0<=≤<=*n*<=≤<=50) — the number of permissible substitutions. Then follow *n* lines each of which describes a substitution in the format *a**i*-&gt;*b**i**c**i*. The characters *a**i*, *b**i*, and *c**i* are lowercase Latin letters. Lines *s*1 and *s*2 can coincide, the list of substitutions can contain similar substitutions. Output Specification: If *s*1 and *s*2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence *s*3, from which *s*1 and *s*2 could have evolved. Demo Input: ['ababa\naba\n2\nc-&gt;ba\nc-&gt;cc\n', 'ababa\naba\n7\nc-&gt;ba\nc-&gt;cc\ne-&gt;ab\nz-&gt;ea\nb-&gt;ba\nd-&gt;dd\nd-&gt;ab\n', 'ababa\naba\n1\nc-&gt;ba\n'] Demo Output: ['2\n', '1\n', '-1\n'] Note: none
```python # 49 e - zeyuanxy import string def get_pos(s, rule): dp = set() for i in range(len(s), 0, -1): dp.add((i, i, s[i - 1])) for j in range(i + 1, len(s) + 1): for k in range(i, j): for r in rule: if (i, k, r[0]) in dp and (k + 1, j, r[1]) in dp: dp.add((i, j, r[2])) p = {} for i, j, c in dp: if (i, c) in p: p[i, c].add(j) else: p[i, c] = set([j]) return p if __name__ == "__main__": s1 = input() s2 = input() n = int(input()) rule = [] for _ in range(n): line = input() rule.append(line[3:] + line[0]) p1 = get_pos(s1, rule) p2 = get_pos(s2, rule) dp = {} dp[0, 0] = 0 for i in range(len(s1)): for j in range(len(s2)): if (i, j) in dp: for c in list(string.ascii_lowercase): if (i + 1, c) in p1 and (j + 1, c) in p2: for ii in p1[i + 1, c]: for jj in p2[j + 1, c]: if (ii, jj) in dp: dp[ii, jj] = min(dp[ii, jj], dp[i, j] + 1) else: dp[ii, jj] = dp[i, j] + 1 if ii == len(s1) and jj == len(s2) and dp[ii, jj] == 1: print(1) exit(0) if (len(s1), len(s2)) in dp: print(dp[len(s1), len(s2)]) else: print(-1) ```
109
Lucky Tree
Title: Lucky Tree Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya encountered a tree with *n* vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with *n* vertexes is an undirected connected graph that has exactly *n*<=-<=1 edges. Petya wondered how many vertex triples (*i*,<=*j*,<=*k*) exists that on the way from *i* to *j*, as well as on the way from *i* to *k* there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,<=2,<=3) is not equal to the triple (2,<=1,<=3) and is not equal to the triple (1,<=3,<=2). Find how many such triples of vertexes exist. Input Specification: The first line contains the single integer *n* (1<=≤<=*n*<=≤<=105) — the number of tree vertexes. Next *n*<=-<=1 lines contain three integers each: *u**i* *v**i* *w**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*,<=1<=≤<=*w**i*<=≤<=109) — the pair of vertexes connected by the edge and the edge's weight. Output Specification: On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. Demo Input: ['4\n1 2 4\n3 1 2\n1 4 7\n', '4\n1 2 4\n1 3 47\n1 4 7447\n'] Demo Output: ['16\n', '24\n'] Note: The 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2). In the second sample all the triples should be counted: 4·3·2 = 24.
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, rt = get_root(s), get_root(t) if not rs ^ rt: return if rank[s] == rank[t]: rank[rs] += 1 if rank[s] >= rank[t]: root[rt] = rs size[rs] += size[rt] else: root[rs] = rt size[rt] += size[rs] return def same(s, t): return True if get_root(s) == get_root(t) else False def get_size(s): return size[get_root(s)] n = int(input()) root = [i for i in range(n + 1)] rank = [1 for _ in range(n + 1)] size = [1 for _ in range(n + 1)] for _ in range(n - 1): u, v, w = map(int, input().split()) x = [0] * 10 for j in str(w): x[int(j)] = 1 ok = 1 for j in range(10): if j ^ 4 and j ^ 7 and x[j]: ok = 0 break if not ok: unite(u, v) ans = 0 for i in range(1, n + 1): if i ^ get_root(i): continue u = get_size(i) v = n - u ans += u * v * (v - 1) print(ans) ```
87
Interesting Game
Title: Interesting Game Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Two best friends Serozha and Gena play a game. Initially there is one pile consisting of *n* stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of *a*1<=&gt;<=*a*2<=&gt;<=...<=&gt;<=*a**k*<=&gt;<=0 stones. The piles should meet the condition *a*1<=-<=*a*2<==<=*a*2<=-<=*a*3<==<=...<==<=*a**k*<=-<=1<=-<=*a**k*<==<=1. Naturally, the number of piles *k* should be no less than two. The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way? Input Specification: The single line contains a single integer *n* (1<=≤<=*n*<=≤<=105). Output Specification: If Serozha wins, print *k*, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game. If Gena wins, print "-1" (without the quotes). Demo Input: ['3\n', '6\n', '100\n'] Demo Output: ['2\n', '-1\n', '8\n'] Note: none
```python # LUOGU_RID: 132710750 from functools import reduce n = int(input()) sg = [0 for _ in range(n + 1)] xorSum = [0 for _ in range(n + 1)] L = [[] for _ in range(n + 1)] len = 2 while True: if len * (len + 1) // 2 > n: break a1 = 1 while True: sum = (2 * a1 + len - 1) * len // 2 if sum > n: break L[sum].append((a1, a1 + len - 1)) a1 += 1 len += 1 for i in range(3, n + 1): S = set() for p in L[i]: S.add(xorSum[p[1]] ^ xorSum[p[0] - 1]) while sg[i] in S: sg[i] += 1 xorSum[i] = xorSum[i - 1] ^ sg[i] print(-1 if sg[n] == 0 else reduce(lambda x, y: min(x, y), map(lambda x: x[1] - x[0] + 1 if (xorSum[x[1]] ^ xorSum[x[0] - 1]) == 0 else n, L[n]))) ```
105
Dark Assembly
Title: Dark Assembly Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed. The Dark Assembly consists of *n* senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to 10%. Senators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If strictly more than half of the senators take a positive decision, the player's proposal is approved. If the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to *A*<=/<=(*A*<=+<=*B*), where *A* is the sum of levels of all player's characters and *B* is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved. Senators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by 10%. It's worth to mention that loyalty cannot exceed 100%. The player can take no more than *k* sweets to the courtroom. Candies should be given to the senators before the start of voting. Determine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way. Input Specification: The first line contains three integers *n*, *k* and *A* (1<=≤<=*n*,<=*k*<=≤<=8, 1<=≤<=*A*<=≤<=9999). Then *n* lines follow. The *i*-th of them contains two numbers — *b**i* and *l**i* — the *i*-th senator's level and his loyalty. The levels of all senators are integers in range from 1 to 9999 (inclusive). The loyalties of all senators are integers in range from 0 to 100 (inclusive) and all of them are divisible by 10. Output Specification: Print one real number with precision 10<=-<=6 — the maximal possible probability that the Dark Assembly approves the player's proposal for the best possible distribution of candies among the senators. Demo Input: ['5 6 100\n11 80\n14 90\n23 70\n80 30\n153 70\n', '5 3 100\n11 80\n14 90\n23 70\n80 30\n153 70\n', '1 3 20\n20 20\n'] Demo Output: ['1.0000000000\n', '0.9628442962\n', '0.7500000000\n'] Note: In the first sample the best way of candies' distribution is giving them to first three of the senators. It ensures most of votes. It the second sample player should give all three candies to the fifth senator.
```python from itertools import * def read(fn=int): return map(fn,input().split()) n,k,A = read() bl = [[*read()] for _ in range(n)] b,l = map(list,zip(*bl)) ans = 0 for p in combinations_with_replacement(range(n),k): for i in p: l[i] += 10 s = 0 for p2 in product(range(2),repeat=n): v = 1 B = 0 for i,x in enumerate(p2): if x: v *= min(l[i],100)/100 else: v *= 1-(min(l[i],100)/100) B += b[i] if sum(p2) > n//2: s += v else: s += (v)*(A/(A+B)) ans = max(ans,s) for i in p: l[i] -= 10 print(ans) ```
109
Lucky Sorting
Title: Lucky Sorting Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya got an array consisting of *n* numbers, it is the gift for his birthday. Now he wants to sort it in the non-decreasing order. However, a usual sorting is boring to perform, that's why Petya invented the following limitation: one can swap any two numbers but only if at least one of them is lucky. Your task is to sort the array according to the specified limitation. Find any possible sequence of the swaps (the number of operations in the sequence should not exceed 2*n*). Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements in the array. The second line contains *n* positive integers, not exceeding 109 — the array that needs to be sorted in the non-decreasing order. Output Specification: On the first line print number *k* (0<=≤<=*k*<=≤<=2*n*) — the number of the swaps in the sorting. On the following *k* lines print one pair of distinct numbers (a pair per line) — the indexes of elements to swap. The numbers in the array are numbered starting from 1. If it is impossible to sort the given sequence, print the single number -1. If there are several solutions, output any. Note that you don't have to minimize *k*. Any sorting with no more than 2*n* swaps is accepted. Demo Input: ['2\n4 7\n', '3\n4 2 1\n', '7\n77 66 55 44 33 22 11\n'] Demo Output: ['0\n', '1\n1 3\n', '7\n1 7\n7 2\n2 6\n6 7\n3 4\n5 3\n4 5\n'] Note: none
```python from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) a = [0] + list(map(int, input().split())) x = list(a) x.sort() s = 0 for i in range(1, n + 1): u = [0] * 10 for j in str(a[i]): u[int(j)] = 1 ok = 1 for j in range(10): if j ^ 4 and j ^ 7 and u[j]: ok = 0 break if ok: s = i break if not s: ans = 0 for i, j in zip(a, x): if i ^ j: ans = -1 break print(ans) exit() d = defaultdict(lambda : []) for i in range(1, n + 1): d[x[i]].append(i) for i in range(1, n + 1): a[i] = d[a[i]].pop() p = [0] * (n + 1) for i in range(1, n + 1): p[a[i]] = i y = a[s] ans = [] for i in range(1, n + 1): if i == y or i == p[i]: continue if i ^ s: ans.append(" ".join(map(str, (i, s)))) a[i], a[s] = a[s], a[i] p[a[i]], p[a[s]] = p[a[s]], p[a[i]] s = i u = p[i] if u ^ s: ans.append(" ".join(map(str, (u, s)))) a[u], a[s] = a[s], a[u] p[a[u]], p[a[s]] = p[a[s]], p[a[u]] s = u k = len(ans) print(k) sys.stdout.write("\n".join(ans)) ```
3
Lorry
Title: Lorry Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres). Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body. Input Specification: The first line contains a pair of integer numbers *n* and *v* (1<=≤<=*n*<=≤<=105; 1<=≤<=*v*<=≤<=109), where *n* is the number of waterborne vehicles in the boat depot, and *v* is the truck body volume of the lorry in cubic metres. The following *n* lines contain the information about the waterborne vehicles, that is a pair of numbers *t**i*,<=*p**i* (1<=≤<=*t**i*<=≤<=2; 1<=≤<=*p**i*<=≤<=104), where *t**i* is the vehicle type (1 – a kayak, 2 – a catamaran), and *p**i* is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file. Output Specification: In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them. Demo Input: ['3 2\n1 2\n2 7\n1 3\n'] Demo Output: ['7\n2\n'] Note: none
```python from heapq import nlargest from itertools import accumulate, chain import sys n, v = map(int, sys.stdin.readline().split()) a1, a2 = [], [] i1, i2 = [], [] for i in range(n): t, p = map(int, sys.stdin.readline().split()) if t == 1: a1.append(p) i1.append(i) else: a2.append(p) i2.append(i) acc1 = list(accumulate(sorted(a1, reverse=True), initial=0)) acc2 = list(accumulate(sorted(a2, reverse=True), initial=0)) best = (0, 0, 0) for n2 in range(min(v // 2, len(a2)) + 1): n1 = min(v - 2 * n2, len(a1)) best = max(best, (acc1[n1] + acc2[n2], n1, n2)) ans, n1, n2 = best sys.stdout.write(str(ans) + "\n") ii1 = sorted(range(len(a1)), key=a1.__getitem__)[len(a1) - n1 :] ii2 = sorted(range(len(a2)), key=a2.__getitem__)[len(a2) - n2 :] sys.stdout.write(" ".join(str(i1[i] + 1) for i in ii1)) sys.stdout.write(" ") sys.stdout.write(" ".join(str(i2[i] + 1) for i in ii2)) sys.stdout.write("\n") ```
45
School
Title: School Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* students studying in the 6th grade, in group "B" of a berland secondary school. Every one of them has exactly one friend whom he calls when he has some news. Let us denote the friend of the person number *i* by *g*(*i*). Note that the friendships are not mutual, i.e. *g*(*g*(*i*)) is not necessarily equal to *i*. On day *i* the person numbered as *a**i* learns the news with the rating of *b**i* (*b**i*<=≥<=1). He phones the friend immediately and tells it. While he is doing it, the news becomes old and its rating falls a little and becomes equal to *b**i*<=-<=1. The friend does the same thing — he also calls his friend and also tells the news. The friend of the friend gets the news already rated as *b**i*<=-<=2. It all continues until the rating of the news reaches zero as nobody wants to tell the news with zero rating. More formally, everybody acts like this: if a person *x* learns the news with a non-zero rating *y*, he calls his friend *g*(*i*) and his friend learns the news with the rating of *y*<=-<=1 and, if it is possible, continues the process. Let us note that during a day one and the same person may call his friend and tell him one and the same news with different ratings. Thus, the news with the rating of *b**i* will lead to as much as *b**i* calls. Your task is to count the values of *res**i* — how many students learned their first news on day *i*. The values of *b**i* are known initially, whereas *a**i* is determined from the following formula: Input Specification: The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=105) — the number of students and the number of days. The second line contains *n* space-separated integers *g*(*i*) (1<=≤<=*g*(*i*)<=≤<=*n*,<=*g*(*i*)<=≠<=*i*) — the number of a friend of the *i*-th student. The third line contains *m* space-separated integers *v**i* (1<=≤<=*v**i*<=≤<=107). The fourth line contains *m* space-separated integers *b**i* (1<=≤<=*b**i*<=≤<=107). Output Specification: Print *m* lines containing one number each. The *i*-th line should contain *res**i* — for what number of students the first news they've learned over the *m* days in question, was the news number *i*. The number of the news is the number of the day on which it can be learned. The days are numbered starting from one in the order in which they are given in the input file. Don't output *res*0. Demo Input: ['3 4\n2 3 1\n1 2 3 4\n1 2 3 4\n', '8 6\n7 6 4 2 3 5 5 7\n10 4 3 8 9 1\n1 1 1 2 2 2\n'] Demo Output: ['1\n1\n1\n0\n', '1\n1\n1\n2\n1\n1\n'] Note: none
```python maxn = 1000010 b = [0] * maxn v = [0] * maxn g = [0] * maxn vis = [0] * maxn n, m = map(int, input().split()) ans = 0 g[1:n+1] = map(int, input().split()) v[1:m+1] = map(int, input().split()) b[1:m+1] = map(int, input().split()) for i in range(1, m+1): a = (v[i] + ans - 1) % n + 1 t = b[i] ans = 0 while vis[a] < t and t: if not vis[a]: ans += 1 vis[a] = t a = g[a] t -= 1 print(ans)# 1692165781.120975 ```
59
Shortest Path
Title: Shortest Path Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: In Ancient Berland there were *n* cities and *m* two-way roads of equal length. The cities are numbered with integers from 1 to *n* inclusively. According to an ancient superstition, if a traveller visits three cities *a**i*, *b**i*, *c**i* in row, without visiting other cities between them, a great disaster awaits him. Overall there are *k* such city triplets. Each triplet is ordered, which means that, for example, you are allowed to visit the cities in the following order: *a**i*, *c**i*, *b**i*. Vasya wants to get from the city 1 to the city *n* and not fulfil the superstition. Find out which minimal number of roads he should take. Also you are required to find one of his possible path routes. Input Specification: The first line contains three integers *n*, *m*, *k* (2<=≤<=*n*<=≤<=3000,<=1<=≤<=*m*<=≤<=20000,<=0<=≤<=*k*<=≤<=105) which are the number of cities, the number of roads and the number of the forbidden triplets correspondingly. Then follow *m* lines each containing two integers *x**i*, *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*) which are the road descriptions. The road is described by the numbers of the cities it joins. No road joins a city with itself, there cannot be more than one road between a pair of cities. Then follow *k* lines each containing three integers *a**i*, *b**i*, *c**i* (1<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=*n*) which are the forbidden triplets. Each ordered triplet is listed mo more than one time. All three cities in each triplet are distinct. City *n* can be unreachable from city 1 by roads. Output Specification: If there are no path from 1 to *n* print -1. Otherwise on the first line print the number of roads *d* along the shortest path from the city 1 to the city *n*. On the second line print *d*<=+<=1 numbers — any of the possible shortest paths for Vasya. The path should start in the city 1 and end in the city *n*. Demo Input: ['4 4 1\n1 2\n2 3\n3 4\n1 3\n1 4 3\n', '3 1 0\n1 2\n', '4 4 2\n1 2\n2 3\n3 4\n1 3\n1 2 3\n1 3 4\n'] Demo Output: ['2\n1 3 4\n', '-1\n', '4\n1 3 2 3 4\n'] Note: none
```python import sys from collections import deque readline = sys.stdin.readline N = 0 graph = [] forbbiden = set() def read_input(): global N n, m, k = [int(w) for w in readline().split()] for _ in range(n + 1): graph.append([]) for _ in range(m): u, v = [int(w) for w in readline().split()] graph[u].append(v) graph[v].append(u) for _ in range(k): forbbiden.add(tuple(int(w) for w in readline().split())) N = n def solve()->list: def get_trail(t:tuple) -> list: buf = [] while t in seen: buf.append(t) t = seen[t] return [tmp[0] for tmp in buf][::-1] + [N] seen = {} que = deque() # parent, node, step que.append((0, 1, 0)) while que: p, node, step = que.popleft() for neigh in graph[node]: if (p, node, neigh) in forbbiden or (node, neigh) in seen: continue seen[(node, neigh)] = (p, node) if neigh == N: return get_trail((node, neigh)) que.append((node, neigh, step + 1)) return [] def write_output(result: list): print(len(result) - 1) if result: print(*result) read_input() write_output(solve()) ```
47
Cannon
Title: Cannon Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: 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 *alpha**i* 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: 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 (*x**i*,<=0)<=-<=(*x**i*,<=*y**i*). 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 (*x**i*,<=*y**i*), 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 Specification: 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 *alpha**i* (0<=&lt;<=*alpha**i*<=&lt;<=π<=/<=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 *x**i* and *y**i* (1<=≤<=*x**i*<=≤<=1000,<=0<=≤<=*y**i*<=≤<=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 Specification: 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. Demo Input: ['2 10\n0.7853\n0.3\n3\n5.0 5.0\n4.0 2.4\n6.0 1.9\n', '2 10\n0.7853\n0.3\n2\n4.0 2.4\n6.0 1.9\n'] Demo Output: ['5.000000000 2.549499369\n4.000000000 0.378324889\n', '10.204081436 0.000000000\n4.000000000 0.378324889\n'] Note: none
```python import sys from math import tan, sin, cos readline = sys.stdin.readline balls = [] walls = [] V = 0 def read_input(): global V n, v = list(map(int, readline().split())) V = v for i in range(n): balls.append([float(readline().strip()), i]) balls.sort() n = int(readline().strip()) for i in range(n): walls.append(list(map(float, readline().split()))) walls.sort() def solve()->list: g = 9.8 result = [] for alpha, idx in balls: b = tan(alpha) t = 2 * V * sin(alpha) / g a = - b / (V * cos(alpha) * t) result.append([- b/ a, 0.0, a, b, idx]) j = 0 for x1, y1 in walls: while j < len(result) and result[j][0] <= x1: j += 1 if j == len(result): break while j < len(result): x0, y0, a, b, idx = result[j] if 0<= a * x1 * x1 + b * x1 <= y1: result[j] = [x1, a * x1 * x1 + b * x1, a, b, idx] j += 1 else: break return result def write_output(result: list): result.sort(key = lambda x: x[-1]) for r in result: print(r[0], r[1]) read_input() write_output(solve()) # print(balls) # print(solve()) ```
8
Looking for Order
Title: Looking for Order Time Limit: 4 seconds Memory Limit: 512 megabytes Problem Description: Girl Lena likes it when everything is in order, and looks for order everywhere. Once she was getting ready for the University and noticed that the room was in a mess — all the objects from her handbag were thrown about the room. Of course, she wanted to put them back into her handbag. The problem is that the girl cannot carry more than two objects at a time, and cannot move the handbag. Also, if he has taken an object, she cannot put it anywhere except her handbag — her inherent sense of order does not let her do so. You are given the coordinates of the handbag and the coordinates of the objects in some Сartesian coordinate system. It is known that the girl covers the distance between any two objects in the time equal to the squared length of the segment between the points of the objects. It is also known that initially the coordinates of the girl and the handbag are the same. You are asked to find such an order of actions, that the girl can put all the objects back into her handbag in a minimum time period. Input Specification: The first line of the input file contains the handbag's coordinates *x**s*,<=*y**s*. The second line contains number *n* (1<=≤<=*n*<=≤<=24) — the amount of objects the girl has. The following *n* lines contain the objects' coordinates. All the coordinates do not exceed 100 in absolute value. All the given positions are different. All the numbers are integer. Output Specification: In the first line output the only number — the minimum time the girl needs to put the objects into her handbag. In the second line output the possible optimum way for Lena. Each object in the input is described by its index number (from 1 to *n*), the handbag's point is described by number 0. The path should start and end in the handbag's point. If there are several optimal paths, print any of them. Demo Input: ['0 0\n2\n1 1\n-1 1\n', '1 1\n3\n4 3\n3 4\n0 0\n'] Demo Output: ['8\n0 1 2 0 \n', '32\n0 1 2 0 3 0 \n'] Note: none
```python import functools INF=10**9 c=functools.lru_cache(maxsize=None) @c def p(i,j): q=lambda i,j: (d[i][0]-d[j][0])**2+(d[i][1]-d[j][1])**2 if j==0: return 2*q(i,j),(0,i,0) return q(0,i)+q(i,j)+q(j,0),(0,i,j,0) @c def u(m): l=len(m) if l==1: return 0,() a=(INF,()) for i in range(1,l): n=m[1:] if i!=l-1: n=m[1:i]+m[i+1:] h,f = u(n),p(m[0],m[i]) if h[0]+f[0]<a[0]: a=(h[0]+f[0],h[1]+f[1]) return a w=lambda:list(map(int,input().split())) d=[w()]+[w() for i in range(int(input()))] t=tuple(range(len(d)-1,-1,-1)) g=u(t) print(g[0]) print(' '.join([str(i) for i in g[1]]).replace(' 0 0 ',' 0 ')) ```
56
Domino Principle
Title: Domino Principle Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put *n* dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The *i*-th domino has the coordinate *x**i* and the height *h**i*. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate *x* and height *h* leads to the fall of all dominoes on the segment [*x*<=+<=1,<=*x*<=+<=*h*<=-<=1]. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=105) which is the number of dominoes. Then follow *n* lines containing two integers *x**i* and *h**i* (<=-<=108<=≤<=*x**i*<=≤<=108,<=2<=≤<=*h**i*<=≤<=108) each, which are the coordinate and height of every domino. No two dominoes stand on one point. Output Specification: Print *n* space-separated numbers *z**i* — the number of dominoes that will fall if Vasya pushes the *i*-th domino to the right (including the domino itself). Demo Input: ['4\n16 5\n20 5\n10 10\n18 2\n', '4\n0 10\n1 5\n9 10\n15 10\n'] Demo Output: ['3 1 4 1 ', '4 1 2 1 '] Note: none
```python import bisect import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def update(i, x, tree): i += l1 tree[i] = x i //= 2 while i: tree[i] = max(tree[2 * i], tree[2 * i + 1]) i //= 2 return def get_max(s, t, tree): s += l1 t += l1 ans = -inf while s <= t: if s % 2 == 0: s //= 2 else: ans = max(ans, tree[s]) s = (s + 1) // 2 if t % 2 == 1: t //= 2 else: ans = max(ans, tree[t]) t = (t - 1) // 2 return ans n = int(input()) d = dict() for i in range(n): x, h = map(int, input().split()) d[x] = (i, h) u = list(d.keys()) u.sort() inf = pow(10, 9) + 1 l1 = pow(2, n.bit_length()) l2 = 2 * l1 ma = [-inf] * l2 for i in range(n): ma[i + l1] = i + 1 for i in range(l1 - 1, 0, -1): ma[i] = max(ma[2 * i], ma[2 * i + 1]) ans = [0] * n for i in range(n - 1, -1, -1): x = u[i] j, h = d[x] r = bisect.bisect_left(u, x + h) - 1 l = i m = get_max(l, r, ma) ans[j] = m - i update(i, m, ma) sys.stdout.write(" ".join(map(str, ans))) ```
6
Exposition
Title: Exposition Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than *k* millimeters. The library has *n* volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is *h**i*. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task. Input Specification: The first line of the input data contains two integer numbers separated by a space *n* (1<=≤<=*n*<=≤<=105) and *k* (0<=≤<=*k*<=≤<=106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains *n* integer numbers separated by a space. Each number *h**i* (1<=≤<=*h**i*<=≤<=106) is the height of the *i*-th book in millimeters. Output Specification: In the first line of the output data print two numbers *a* and *b* (separate them by a space), where *a* is the maximum amount of books the organizers can include into the exposition, and *b* — the amount of the time periods, during which Berlbury published *a* books, and the height difference between the lowest and the highest among these books is not more than *k* milllimeters. In each of the following *b* lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work. Demo Input: ['3 3\n14 12 10\n', '2 0\n10 10\n', '4 5\n8 19 10 13\n'] Demo Output: ['2 2\n1 2\n2 3\n', '2 1\n1 2\n', '2 1\n3 4\n'] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def binary_search(c1, c2): m = (c1 + c2 + 1) // 2 while abs(c1 - c2) > 1: m = (c1 + c2 + 1) // 2 if ok(m): c1 = m else: c2 = m m = min(m + 1, n) while not ok(m): m -= 1 return m def ok(m): if m > n: return False elif m <= 0: return True x, y = slide_min(n, m, h), slide_max(n, m, h) for i, j in zip(y, x): if i - j <= k: return True return False def slide_min(n, k, a): ans, s = [], [] j = 0 for i in range(n): ai = a[i] while len(s) ^ j and a[s[-1]] >= ai: s.pop() s.append(i) while len(s) ^ j and s[j] + k <= i: j += 1 if i + 1 >= k: ans.append(a[s[j]]) return ans def slide_max(n, k, a): ans, s = [], [] j = 0 for i in range(n): ai = a[i] while len(s) ^ j and a[s[-1]] <= ai: s.pop() s.append(i) while len(s) ^ j and s[j] + k <= i: j += 1 if i + 1 >= k: ans.append(a[s[j]]) return ans n, k = map(int, input().split()) h = list(map(int, input().split())) a = binary_search(0, n + 1) ans = [] x, y = slide_min(n, a, h), slide_max(n, a, h) for i in range(n - a + 1): if y[i] - x[i] <= k: ans.append(" ".join(map(str, (i + 1, i + a)))) b = len(ans) print(a, b) sys.stdout.write("\n".join(ans)) ```
25
Roads in Berland
Title: Roads in Berland Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* cities numbered from 1 to *n* in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build *k* new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. Input Specification: The first line contains integer *n* (2<=≤<=*n*<=≤<=300) — amount of cities in Berland. Then there follow *n* lines with *n* integer numbers each — the matrix of shortest distances. *j*-th integer in the *i*-th row — *d**i*,<=*j*, the shortest distance between cities *i* and *j*. It is guaranteed that *d**i*,<=*i*<==<=0,<=*d**i*,<=*j*<==<=*d**j*,<=*i*, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer *k* (1<=≤<=*k*<=≤<=300) — amount of planned roads. Following *k* lines contain the description of the planned roads. Each road is described by three space-separated integers *a**i*, *b**i*, *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*,<=1<=≤<=*c**i*<=≤<=1000) — *a**i* and *b**i* — pair of cities, which the road connects, *c**i* — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. Output Specification: Output *k* space-separated integers *q**i* (1<=≤<=*i*<=≤<=*k*). *q**i* should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to *i*. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. Demo Input: ['2\n0 5\n5 0\n1\n1 2 3\n', '3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1\n'] Demo Output: ['3 ', '17 12 '] Note: none
```python def main(): n = int(input()) distances = [[float('inf') for _ in range(n)] for __ in range(n)] tot = 0 for i in range(n): row = list(map(int, input().split())) for j in range(n): distances[i][j] = row[j] distances[j][i] = row[j] tot += row[j] distances[i][i] = 0 distances[j][j] = 0 ans = [] tot //= 2 k = int(input()) # O(k * ) for _ in range(k): a,b,c = map(int, input().split()) a-=1 b-=1 if distances[a][b] > c: tot -= distances[a][b] tot += c distances[a][b] = c distances[b][a] = c for i in range(n): for j in range(i): old = distances[i][j] new = min(distances[i][a] + distances[a][b] + distances[b][j], distances[i][b] + distances[b][a] + distances[a][j]) if new < old: tot -= old tot += new distances[i][j] = new distances[j][i] = new ans.append(tot) print(*ans) main() ```
13
Letter A
Title: Letter A Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Little Petya learns how to write. The teacher gave pupils the task to write the letter *A* on the sheet of paper. It is required to check whether Petya really had written the letter *A*. You are given three segments on the plane. They form the letter *A* if the following conditions hold: - Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. - The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. - The third segment divides each of the first two segments in proportion not less than 1<=/<=4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1<=/<=4). Input Specification: The first line contains one integer *t* (1<=≤<=*t*<=≤<=10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length. Output Specification: Output one line for each test case. Print «YES» (without quotes), if the segments form the letter *A* and «NO» otherwise. Demo Input: ['3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1\n'] Demo Output: ['YES\nNO\nYES\n'] Note: none
```python import random from math import sqrt as s def dist(x1, y1, x2, y2): return s((x2 - x1) ** 2 + (y2 - y1) ** 2) def is_dot_on_line(c1, c2, dot): A = c1[1] - c2[1] B = c2[0] - c1[0] C = c1[0] * c2[1] - c2[0] * c1[1] maxx, minx = max(c1[0], c2[0]), min(c1[0], c2[0]) maxy, miny = max(c1[1], c2[1]), min(c1[1], c2[1]) res = A * dot[0] + B * dot[1] + C if res == 0 and minx <= dot[0] <= maxx and miny <= dot[1] <= maxy: return True return False def cosangle(x1, y1, x2, y2): return x1 * x2 + y1 * y2 def same(k11, k12, k21, k22, k31, k32): if k11 == k21 or k11 == k22 or k12 == k21 or k12 == k22: return 0, 1, 2 if k11 == k31 or k11 == k32 or k12 == k31 or k12 == k32: return 0, 2, 1 if k21 == k31 or k21 == k32 or k22 == k31 or k22 == k32: return 1, 2, 0 return False def is_a(c1, c2, c3, debug=-1): al = [c1, c2, c3] lines = same(*c1, *c2, *c3) if not lines: return False c1, c2, c3 = al[lines[0]], al[lines[1]], al[lines[2]] if c1[0] == c2[1]: c2[0], c2[1] = c2[1], c2[0] if c1[1] == c2[0]: c1[0], c1[1] = c1[1], c1[0] if not (is_dot_on_line(c1[0], c1[1], c3[0]) and is_dot_on_line(c2[0], c2[1], c3[1])): if not (is_dot_on_line(c1[0], c1[1], c3[1]) and is_dot_on_line(c2[0], c2[1], c3[0])): return False c3[0], c3[1] = c3[1], c3[0] cosa = cosangle(c1[0][0] - c1[1][0], c1[0][1] - c1[1][1], c2[0][0] - c2[1][0], c2[0][1] - c2[1][1]) if cosa < 0: return False l1 = dist(*c1[0], *c3[0]), dist(*c1[1], *c3[0]) l2 = dist(*c2[0], *c3[1]), dist(*c2[1], *c3[1]) if min(l1) / max(l1) < 1/4 or min(l2) / max(l2) < 1/4: return False return True n = int(input()) for i in range(n): c1 = list(map(int, input().split())) c2 = list(map(int, input().split())) c3 = list(map(int, input().split())) if is_a([c1[:2], c1[2:]], [c2[:2], c2[2:]], [c3[:2], c3[2:]], debug=i): print("YES") else: print("NO") ```
35
Fire Again
Title: Fire Again Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it *N* rows with *M* trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the *j*-th tree in the *i*-th row would have the coordinates of (*i*,<=*j*). However a terrible thing happened and the young forest caught fire. Now we must find the coordinates of the tree that will catch fire last to plan evacuation. The burning began in *K* points simultaneously, which means that initially *K* trees started to burn. Every minute the fire gets from the burning trees to the ones that aren’t burning and that the distance from them to the nearest burning tree equals to 1. Find the tree that will be the last to start burning. If there are several such trees, output any. Input Specification: The first input line contains two integers *N*,<=*M* (1<=≤<=*N*,<=*M*<=≤<=2000) — the size of the forest. The trees were planted in all points of the (*x*,<=*y*) (1<=≤<=*x*<=≤<=*N*,<=1<=≤<=*y*<=≤<=*M*) type, *x* and *y* are integers. The second line contains an integer *K* (1<=≤<=*K*<=≤<=10) — amount of trees, burning in the beginning. The third line contains *K* pairs of integers: *x*1,<=*y*1,<=*x*2,<=*y*2,<=...,<=*x**k*,<=*y**k* (1<=≤<=*x**i*<=≤<=*N*,<=1<=≤<=*y**i*<=≤<=*M*) — coordinates of the points from which the fire started. It is guaranteed that no two points coincide. Output Specification: Output a line with two space-separated integers *x* and *y* — coordinates of the tree that will be the last one to start burning. If there are several such trees, output any. Demo Input: ['3 3\n1\n2 2\n', '3 3\n1\n1 1\n', '3 3\n2\n1 1 3 3\n'] Demo Output: ['1 1\n', '3 3\n', '2 2'] Note: none
```python import sys sys.stdin = open("input.txt", "r") sys.stdout = open("output.txt", "w") input = sys.stdin.buffer.readline n, m = map(int, input().split()) k = int(input()) xy = list(map(int, input().split())) ma, u, v = 0, 1, 1 for i in range(1, n + 1): for j in range(1, m + 1): c = n + m for l in range(k): x, y = xy[2 * l], xy[2 * l + 1] c = min(c, abs(x - i) + abs(y - j)) if ma < c: ma, u, v = c, i, j ans = " ".join(map(str, (u, v))) print(ans) ```
28
DravDe saves the world
Title: DravDe saves the world Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: How horrible! The empire of galactic chickens tries to conquer a beautiful city "Z", they have built a huge incubator that produces millions of chicken soldiers a day, and fenced it around. The huge incubator looks like a polygon on the plane *Oxy* with *n* vertices. Naturally, DravDe can't keep still, he wants to destroy the chicken empire. For sure, he will start with the incubator. DravDe is strictly outside the incubator's territory in point *A*(*x**a*,<=*y**a*), and wants to get inside and kill all the chickens working there. But it takes a lot of doing! The problem is that recently DravDe went roller skating and has broken both his legs. He will get to the incubator's territory in his jet airplane LEVAP-41. LEVAP-41 flies at speed *V*(*x**v*,<=*y**v*,<=*z**v*). DravDe can get on the plane in point *A*, fly for some time, and then air drop himself. DravDe is very heavy, that's why he falls vertically at speed *F**down*, but in each point of his free fall DravDe can open his parachute, and from that moment he starts to fall at the wind speed *U*(*x**u*,<=*y**u*,<=*z**u*) until he lands. Unfortunately, DravDe isn't good at mathematics. Would you help poor world's saviour find such an air dropping plan, that allows him to land on the incubator's territory? If the answer is not unique, DravDe wants to find the plan with the minimum time of his flight on the plane. If the answers are still multiple, he wants to find the one with the minimum time of his free fall before opening his parachute Input Specification: The first line contains the number *n* (3<=≤<=*n*<=≤<=104) — the amount of vertices of the fence. Then there follow *n* lines containing the coordinates of these vertices (two integer numbers *x**i*,<=*y**i*) in clockwise or counter-clockwise order. It's guaranteed, that the fence does not contain self-intersections. The following four lines contain coordinates of point *A*(*x**a*,<=*y**a*), speeds *V*(*x**v*,<=*y**v*,<=*z**v*), *F**down* and speed *U*(*x**u*,<=*y**u*,<=*z**u*). All the input numbers are integer. All the coordinates don't exceed 104 in absolute value. It's guaranteed, that *z**v*<=&gt;<=0 and *F**down*,<=*z**u*<=&lt;<=0, and point *A* is strictly outside the incubator's territory. Output Specification: In the first line output two numbers *t*1,<=*t*2 such, that if DravDe air drops at time *t*1 (counting from the beginning of the flight), he lands on the incubator's territory (landing on the border is regarder as landing on the territory). If DravDe doesn't open his parachute, the second number should be equal to the duration of DravDe's falling down. If it's impossible for DravDe to get to the incubator's territory, output -1 -1. If the answer is not unique, output the answer with the minimum *t*1. If the answers are still multiple, output the answer with the minimum *t*2. Your answer must have an absolute or relative error less than 10<=-<=6. Demo Input: ['4\n0 0\n1 0\n1 1\n0 1\n0 -1\n1 0 1\n-1\n0 1 -1\n', '4\n0 0\n0 1\n1 1\n1 0\n0 -1\n-1 -1 1\n-1\n0 1 -1\n', '4\n0 0\n1 0\n1 1\n0 1\n0 -1\n1 1 1\n-1\n1 1 -1\n'] Demo Output: ['1.00000000 0.00000000\n', '-1.00000000 -1.00000000\n', '0.50000000 0.00000000\n'] Note: none
```python class Point: def __init__(self, x, y, z=0): self.x = x self.y = y self.z = z def main(): n = int(input()) pt = [Point(0, 0) for _ in range(n)] for i in range(n): pt[i].x, pt[i].y = map(float, input().split()) a = Point(0, 0) v = Point(0, 0, 0) u = Point(0, 0, 0) a.x, a.y= map(float, input().split()) v.x, v.y, v.z = map(float, input().split()) f = float(input()) u.x, u.y, u.z = map(float, input().split()) inf = 1e9 eps = 1e-9 a1 = v.x + u.x * v.z / abs(u.z) b1 = u.x * f / abs(u.z) c1 = a.x a2 = v.y + u.y * v.z / abs(u.z) b2 = u.y * f / abs(u.z) c2 = a.y ans1 = ans2 = inf for i in range(n): x1, y1 = pt[i].x, pt[i].y x2, y2 = pt[(i + 1) % n].x, pt[(i + 1) % n].y aa1 = a2 * (x2 - x1) - a1 * (y2 - y1) bb1 = b2 * (x2 - x1) - b1 * (y2 - y1) cc1 = (c2 - y2) * (x2 - x1) - (c1 - x2) * (y2 - y1) if abs(bb1) > eps: t1 = 0 t2 = -cc1 / bb1 if (a1 * t1 + b1 * t2 + c1 > min(x1, x2) - eps and a1 * t1 + b1 * t2 + c1 < max(x1, x2) + eps): if t2 > -eps and (a2 * t1 + b2 * t2 + c2 > min(y1, y2) - eps and a2 * t1 + b2 * t2 + c2 < max(y1, y2) + eps and v.z * t1 + f * t2 > -eps): if ans1 > t1 + eps: ans1 = t1 ans2 = t2 elif abs(ans1 - t1) < eps and ans2 > t2: ans2 = t2 if abs(aa1) > eps: t1 = -cc1 / aa1 t2 = 0 if t1 > -eps: if (a1 * t1 + b1 * t2 + c1 > min(x1, x2) - eps and a1 * t1 + b1 * t2 + c1 < max(x1, x2) + eps): if (a2 * t1 + b2 * t2 + c2 > min(y1, y2) - eps and a2 * t1 + b2 * t2 + c2 < max(y1, y2) + eps and v.z * t1 + f * t2 > -eps): if ans1 > t1 + eps: ans1 = t1 ans2 = t2 elif abs(ans1 - t1) < eps and ans2 > t2: ans2 = t2 A = a1 * b2 - a2 * b1 B = (c1 - x1) * b2 - (c2 - y1) * b1 if abs(A) > eps: t1 = -B / A B = (c2 - y1) * a1 - (c1 - x1) * a2 t2 = -B / A if t1 > -eps and t2 > -eps: if (a1 * t1 + b1 * t2 + c1 > min(x1, x2) - eps and a1 * t1 + b1 * t2 + c1 < max(x1, x2) + eps): if (a2 * t1 + b2 * t2 + c2 > min(y1, y2) - eps and a2 * t1 + b2 * t2 + c2 < max(y1, y2) + eps and v.z * t1 + f * t2 > -eps): if ans1 > t1 + eps: ans1 = t1 ans2 = t2 A = bb1 * v.z / f - aa1 B = cc1 if abs(A) > eps: t1 = B / A t2 = -v.z * t1 / f if t1 > -eps and t2 > -eps: if (a1 * t1 + b1 * t2 + c1 > min(x1, x2) - eps and a1 * t1 + b1 * t2 + c1 < max(x1, x2) + eps): if (a2 * t1 + b2 * t2 + c2 > min(y1, y2) - eps and a2 * t1 + b2 * t2 + c2 < max(y1, y2) + eps): if ans1 > t1 + eps: ans1 = t1 ans2 = t2 if ans1 == inf: ans1 = ans2 = -1 print(f"{ans1:.20f} {ans2:.20f}") if __name__ == "__main__": main()# 1693911700.4213545 ```
69
Subsegments
Title: Subsegments Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in , which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem. Input Specification: The first line contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=*n*) — the number of array elements and the length of the segment. Then follow *n* lines: the *i*-th one contains a single number *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109). Output Specification: Print *n*–*k*<=+<=1 numbers, one per line: on the *i*-th line print of the maximum number of those numbers from the subarray *a**i* *a**i*<=+<=1 … *a**i*<=+<=*k*<=-<=1 that occur in this subarray exactly 1 time. If there are no such numbers in this subarray, print "Nothing". Demo Input: ['5 3\n1\n2\n2\n3\n3\n', '6 4\n3\n3\n3\n4\n4\n2\n'] Demo Output: ['1\n3\n2\n', '4\nNothing\n3\n'] Note: none
```python # for I/O for local system import sys from os import path if(path.exists('Input.txt')): sys.stdin = open("Input.txt","r") sys.stdout = open("Output.txt","w") # For fast I/O input = sys.stdin.buffer.readline # input = sys.stdin.readline print = sys.stdout.write # Import libraries here whenever required from heapq import * from random import randint # Use this because normal dict can sometimes give TLE class mydict: def __init__(self, func=lambda: 0): self.random = randint(0, 1 << 32) self.default = func self.dict = {} def __getitem__(self, key): mykey = self.random ^ key if mykey not in self.dict: self.dict[mykey] = self.default() return self.dict[mykey] def get(self, key, default): mykey = self.random ^ key if mykey not in self.dict: return default return self.dict[mykey] def __setitem__(self, key, item): mykey = self.random ^ key self.dict[mykey] = item def getkeys(self): return [self.random ^ i for i in self.dict] def __str__(self): return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}' # Solver function def solve(): n, k = map(int, input().split()) a = [] for i in range(n): val = int(input()) a.append(val) d = mydict() heap = [] heapify(heap) numbers = n - k + 1 for i in range(n - numbers + 1): d[a[i]] += 1 ans = -10 ** 18 for i in d.getkeys(): if(d[i] == 1): heappush(heap, -i) ans = max(ans, i) if(ans == -10 ** 18): print("Nothing\n") else: print(str(ans) + "\n") l = 0 for i in range(n - numbers + 1, n): d[a[l]] -= 1 d[a[i]] += 1 if(d[a[i]] == 1): heappush(heap, -a[i]) if(d[a[l]] == 1): heappush(heap, -a[l]) l += 1 if(len(heap) == 0): print("Nothing\n") continue ans = -10 ** 18 while heap: val = -heappop(heap) if(d[val] != 1): continue ans = val heappush(heap, -ans) break if(ans == -10 ** 18): print("Nothing\n") else: print(str(ans) + "\n") # Main for _ in range(1): solve() ```
20
Dijkstra?
Title: Dijkstra? Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: You are given a weighted undirected graph. The vertices are enumerated from 1 to *n*. Your task is to find the shortest path between the vertex 1 and the vertex *n*. Input Specification: The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=105,<=0<=≤<=*m*<=≤<=105), where *n* is the number of vertices and *m* is the number of edges. Following *m* lines contain one edge each in form *a**i*, *b**i* and *w**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=1<=≤<=*w**i*<=≤<=106), where *a**i*,<=*b**i* are edge endpoints and *w**i* is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices. Output Specification: Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them. Demo Input: ['5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1\n', '5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1\n'] Demo Output: ['1 4 3 5 ', '1 4 3 5 '] Note: none
```python from heapq import * from sys import * f = lambda: map(int, stdin.readline().split()) inf = 1 << 40 n, m = f() k = n + 1 g = [[] for i in range(k)] for j in range(m): u, v, l = f() g[u].append((v, l)) g[v].append((u, l)) d = [inf] * k d[1] = 0 p = [0] * k q = [1] while q: h = heappop(q) v, l = h % k, h // k if d[v] != l: continue if v == n: break for u, l in g[v]: s = d[v] + l if s < d[u]: d[u], p[u] = s, v heappush(q, k * s + u) if d[n] == inf: print(-1) else: u, t = n, [] while u: t.append(u) u = p[u] t.reverse() print(' '.join(map(str, t))) ```
55
Beautiful numbers
Title: Beautiful numbers Time Limit: 4 seconds Memory Limit: 256 megabytes Problem Description: Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges. Input Specification: The first line of the input contains the number of cases *t* (1<=≤<=*t*<=≤<=10). Each of the next *t* lines contains two natural numbers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=9<=·1018). 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 Specification: Output should contain *t* numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (from *l**i* to *r**i*, inclusively). Demo Input: ['1\n1 9\n', '1\n12 15\n'] Demo Output: ['9\n', '2\n'] Note: none
```python import collections import math import os from heapq import heapify, heappop, heappush import queue from sys import stdin, stdout from itertools import * import bisect import sys from math import gcd MAXN = 100010 mod = 1000000007 inf = int(1e18) v=[0]*2525 dp=[[[-1 for k in range(2525)]for j in range(50)] for i in range(20)] cnt=0 a=[] for i in range(1,2521): if 2520%i==0: cnt+=1 v[i]=cnt def dfs(pos,nlcm,nsum,limit): global a if pos<0:return nsum%nlcm==0 if (limit==0 and dp[pos][v[nlcm]][nsum]!=-1): return dp[pos][v[nlcm]][nsum] #print(len(a)) up=a[pos] if limit else 9 ans=0 for i in range(up+1): lcc=i//math.gcd(i,nlcm)*nlcm if i else nlcm ans+=dfs(pos-1,lcc,(nsum*10+i)%2520,limit and i==up) if not limit: dp[pos][v[nlcm]][nsum]=ans return ans def solve(x): global a a=[] while x: a.append(x%10) x//=10 return dfs(len(a)-1,1,0,1) for _ in range(int(stdin.readline())): l,r=map(int,stdin.readline().split()) ans=solve(r)-solve(l-1) print(ans) ```
28
Bath Queue
Title: Bath Queue Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* students living in the campus. Every morning all students wake up at the same time and go to wash. There are *m* rooms with wash basins. The *i*-th of these rooms contains *a**i* wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms. Input Specification: The first line contains two positive integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=50) — the amount of students and the amount of rooms. The second line contains *m* integers *a*1,<=*a*2,<=... ,<=*a**m* (1<=≤<=*a**i*<=≤<=50). *a**i* means the amount of wash basins in the *i*-th room. Output Specification: Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10<=-<=9. Demo Input: ['1 1\n2\n', '2 2\n1 1\n', '2 3\n1 1 1\n', '7 5\n1 1 2 3 1\n'] Demo Output: ['1.00000000000000000000\n', '1.50000000000000000000\n', '1.33333333333333350000\n', '2.50216960000000070000\n'] Note: none
```python import sys MAX_N = 55 line = list(map(int, sys.stdin.readline().split(" "))) studc = line[0] roomc = line[1] arr = list(map(int, sys.stdin.readline().split(" "))) ncr = [[0 for i in range(MAX_N)] for j in range(MAX_N)] ncr[0][0] = 1 for i in range(1, MAX_N): ncr[i][0] = 1; for j in range(1, MAX_N): ncr[i][j] = ncr[i - 1][j - 1] + ncr[i - 1][j] upto = [0 for i in range(MAX_N)] # upto[i] of ways to pick such that no queue exceeds i people for i in range(1, MAX_N): dp = [[0 for j in range(MAX_N)] for k in range(MAX_N)] dp[0][0] = 1 for j in range(roomc): for k in range(0, min(studc, i * arr[j]) + 1): for l in range(0, studc - k + 1): dp[j + 1][k + l] += dp[j][l] * ncr[studc - l][k] upto[i] = dp[roomc][studc] ans = 0; for i in range(1, MAX_N): ans += (upto[i] - upto[i - 1]) * i print('%.12f' % (ans / (roomc ** studc))) ```
106
Treasure Island
Title: Treasure Island Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map. The treasure map can be represented as a rectangle *n*<=×<=*m* in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks. Besides, the map also has a set of *k* instructions. Each instruction is in the following form: "Walk *n* miles in the *y* direction" The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried. Unfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares. The captain wants to know which sights are worth checking. He asks you to help him with that. Input Specification: The first line contains two integers *n* and *m* (3<=≤<=*n*,<=*m*<=≤<=1000). Then follow *n* lines containing *m* integers each — the island map's description. "#" stands for the sea. It is guaranteed that all cells along the rectangle's perimeter are the sea. "." stands for a penetrable square without any sights and the sights are marked with uppercase Latin letters from "A" to "Z". Not all alphabet letters can be used. However, it is guaranteed that at least one of them is present on the map. All local sights are marked by different letters. The next line contains number *k* (1<=≤<=*k*<=≤<=105), after which *k* lines follow. Each line describes an instruction. Each instruction possesses the form "*dir* *len*", where *dir* stands for the direction and *len* stands for the length of the way to walk. *dir* can take values "N", "S", "W" and "E" for North, South, West and East correspondingly. At that, north is to the top, South is to the bottom, west is to the left and east is to the right. *len* is an integer from 1 to 1000. Output Specification: Print all local sights that satisfy to the instructions as a string without any separators in the alphabetical order. If no sight fits, print "no solution" without the quotes. Demo Input: ['6 10\n##########\n#K#..#####\n#.#..##.##\n#..L.#...#\n###D###A.#\n##########\n4\nN 2\nS 1\nE 1\nW 2\n', '3 4\n####\n#.A#\n####\n2\nW 1\nN 2\n'] Demo Output: ['AD', 'no solution'] Note: none
```python import sys input = sys.stdin.readline n, m = map(int, input().split()) a, pos = [], [] for i in range(n): a.append(input().rstrip()) for j in range(m): if a[i][j] != '.' and a[i][j] != '#': pos.append((i, j)) W = [[0]*(m+3) for i in range(n+3)] for i in range(n): for j in range(m): if a[i][j] != '#': W[i][j] = W[i][j-1] + 1 E = [[0]*(m+3) for i in range(n+3)] for i in range(n): for j in range(m-1, -1, -1): if a[i][j] != '#': E[i][j] = E[i][j+1] + 1 N = [[0]*(m+3) for i in range(n+3)] for j in range(m): for i in range(n): if a[i][j] != '#': N[i][j] = N[i-1][j] + 1 S = [[0]*(m+3) for i in range(n+3)] for j in range(m): for i in range(n-1, -1, -1): if a[i][j] != '#': S[i][j] = S[i+1][j] + 1 k = int(input()) d, l = [0]*k, [0]*k for i in range(k): di, li = input().split() d[i], l[i] = di, int(li) kq = [] for x, y in pos: ok, dut = 1, a[x][y] for i in range(k): if d[i] == 'E': if E[x][y] - 1 < l[i]: ok = 0 break else: y += l[i] if d[i] == 'W': if W[x][y] - 1 < l[i]: ok = 0 break else: y -= l[i] if d[i] == 'N': if N[x][y] - 1 < l[i]: ok = 0 break else: x -= l[i] continue if d[i] == 'S': if S[x][y] - 1 < l[i]: ok = 0 break else: x += l[i] if ok == 1: kq.append(dut) if len(kq) == 0: print('no solution') else: kq.sort() print(''.join(kq)) ```
19
Deletion of Repeats
Title: Deletion of Repeats Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length *x* is such a substring of length 2*x*, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat. You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above. Input Specification: The first input line contains integer *n* (1<=≤<=*n*<=≤<=105) — length of the string. The following line contains *n* space-separated integer numbers from 0 to 109 inclusive — numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times. Output Specification: In the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way. Demo Input: ['6\n1 2 3 1 2 3\n', '7\n4 5 6 5 6 7 7\n'] Demo Output: ['3\n1 2 3 \n', '1\n7 \n'] Note: none
```python import sys n=int(input()) a=list(map(int,input().split())) M=10**9+1 g={} for i in range(n): g[a[i]]=g.get(a[i],[])+[i] p=[1] for i in range(n): p+=[hash(M*p[-1])] h=[0]*(n+1) for i in range(n): h[i+1]=hash(h[i]*M+a[i]) gh=lambda k,l:hash(h[k+l]-h[k]*p[l])%sys.hash_info.modulus i,t=0,0 while i < n: for j in g[a[i]]: if j <= i: continue w=j-i if j+w<=n and gh(i,w)==gh(j,w): i=j-1 t=max(t,j) break i+=1 r=a[t:] print(len(r)) print(*r) ```
60
Mushroom Gnomes
Title: Mushroom Gnomes Time Limit: 3 seconds Memory Limit: 256 megabytes Problem Description: 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 Specification: The first line contains four integers *n*, *x*, *y*, *p* (1<=≤<=*n*<=≤<=106,<=0<=≤<=*x*,<=*y*<=≤<=1018,<=*x*<=+<=*y*<=&gt;<=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 *a**i* which represent the mushrooms' weight in the non-decreasing order (0<=≤<=*a**i*<=≤<=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 Specification: The answer should contain a single number which is the total weights of the mushrooms modulo *p* in the end after *x*<=+<=*y* minutes. Demo Input: ['2 1 0 657276545\n1 2\n', '2 1 1 888450282\n1 2\n', '4 5 0 10000\n1 2 3 4\n'] Demo Output: ['6\n', '14\n', '1825\n'] Note: none
```python def power(a, b, p): c = 1 while b: if b & 1: c = (c * a) % p a = (a * a) % p b //= 2 return c def get3(b, p): if b == 0: return 0 if b == 1: return 1 if b & 1: x = get3(b - 1, p) return (3 * x + 1) % p else: x = get3(b // 2, p) return (2 * x * (x + 1)) % p def fib(b, p): e = [[1, 0], [0, 1]] g = [[1, 1], [1, 0]] while b: if b & 1: w = [[0, 0], [0, 0]] for i in range(2): for j in range(2): for k in range(2): w[i][j] = (w[i][j] + e[i][k] * g[k][j]) % p for i in range(2): for j in range(2): e[i][j] = w[i][j] w = [[0, 0], [0, 0]] for i in range(2): for j in range(2): for k in range(2): w[i][j] = (w[i][j] + g[i][k] * g[k][j]) % p for i in range(2): for j in range(2): g[i][j] = w[i][j] b //= 2 return (e[0][0], e[0][1]) n, x, y, p = map(int, input().split()) a = list(map(int, input().split())) sum_a = sum(a) % p if n == 1: print(sum_a % p) exit() ans = (power(3, x, p) * sum_a - get3(x, p) * (a[0] + a[-1])) % p tmp = fib(x, p) A = a[0] B = (a[-1] * tmp[0] + a[-2] * tmp[1]) % p ans = (power(3, y, p) * ans - get3(y, p) * (A + B)) % p if ans < 0: ans += p print(ans)# 1694458405.418199 ```
5
Bindian Signalizing
Title: Bindian Signalizing Time Limit: 4 seconds Memory Limit: 256 megabytes Problem Description: Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by *n* hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night. In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other. An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills. Input Specification: The first line of the input data contains an integer number *n* (3<=≤<=*n*<=≤<=106), *n* — the amount of hills around the capital. The second line contains *n* numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109. Output Specification: Print the required amount of pairs. Demo Input: ['5\n1 2 4 5 3\n'] Demo Output: ['7\n'] Note: none
```python n,maxn,maxn_index=int(input()),0,0 s=list(map(int,input().split()))*2 L,R,C=[0]*1000007,[0]*1000007,[0]*1000007#L,R存储编号,C存储数值 #L[i]表示i左侧比第一个比i高(或等)的位置。 #R[i]表示i右侧第一个比i高(或等)的位置。 #C[i]表示从i到R[i]的左开右闭区间内高度等于i的山的数目 for i in range(len(s)//2): if s[i]>maxn: maxn=s[i] maxn_index=i s_new=s[maxn_index:maxn_index+len(s)//2]#更换为最高山在起点的序列 s_new.append(s_new[0])#末尾加一个元素 j=n-1 while j>=0: R[j]=j+1#由于在尾部添加了一座最高山,R[j]一定存在,可能在正右侧 while R[j]<n and s_new[R[j]]<s_new[j]:#当前山高于右侧山 R[j]=R[R[j]]#说明当前的山还不够高,需要向右边寻找更高的山 if R[j]<n and s_new[R[j]]==s_new[j]:#当前山右侧只有与它等高的山了 C[j]=C[R[j]]+1#区间山数目+1 R[j]=R[R[j]]#再向右看有没有更高的山 j-=1 ans=0 for i in range(n): ans+=C[i] if s_new [i]==s_new [0]:#与最高峰等高 continue#跳过本轮循环,因为 L[i]=i-1 while L[i]>0 and s_new[L[i]]<=s_new[i]: L[i]=L[L[i]]#向左边推 ans+=2 if L[i]==0 and R[i]==n: ans-=1 print(ans) ```
2
The least round way
Title: The least round way Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: There is a square matrix *n*<=×<=*n*, consisting of non-negative integer numbers. You should find such a way on it that - starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros. Input Specification: The first line contains an integer number *n* (2<=≤<=*n*<=≤<=1000), *n* is the size of the matrix. Then follow *n* lines containing the matrix elements (non-negative integer numbers not exceeding 109). Output Specification: In the first line print the least number of trailing zeros. In the second line print the correspondent way itself. Demo Input: ['3\n1 2 3\n4 5 6\n7 8 9\n'] Demo Output: ['0\nDDRR\n'] Note: none
```python import sys input = sys.stdin.readline n = int(input()) a = [] for i in range(n): a.append(list(map(int, input().split()))) r0 = [i for i in range(n)] r1 = [i for i in range(1, n)] def pow(n, k): c = 0 while(n and n % k == 0): n = n // k c += 1 return c def dp(k): b = [[pow(i, k) for i in c] for c in a] for i in r1: b[i][0] += b[i - 1][0] b[0][i] += b[0][i - 1] for i in r1: for j in r1: b[i][j] += min(b[i - 1][j], b[i][j - 1]) ans = '' i, j = n - 1, n - 1 while(i + j): if(i == 0 or (i * j and b[i - 1][j] > b[i][j - 1])): j -= 1 ans += 'R' else: i -= 1 ans += 'D' return (b[n - 1][n - 1], ans[::-1]) (p, ans) = min(dp(2), dp(5)) if(p > 1): for i in r0: for j in r0: if(a[i][j] == 0): p = 1 ans = 'R' * j + 'D' * (n - 1) + 'R' * (n - 1 - j) print(p) print(ans) ```
11
A Simple Task
Title: A Simple Task Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges. Input Specification: The first line of input contains two integers *n* and *m* (1<=≤<=*n*<=≤<=19, 0<=≤<=*m*) – respectively the number of vertices and edges of the graph. Each of the subsequent *m* lines contains two integers *a* and *b*, (1<=≤<=*a*,<=*b*<=≤<=*n*, *a*<=≠<=*b*) indicating that vertices *a* and *b* are connected by an undirected edge. There is no more than one edge connecting any pair of vertices. Output Specification: Output the number of cycles in the given graph. Demo Input: ['4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4\n'] Demo Output: ['7\n'] Note: The example graph is a clique and contains four cycles of length 3 and three cycles of length 4.
```python N, M = [int(w) for w in input().split()] graph = [[] for _ in range(N)] dp = [[0] * (2 ** N) for _ in range(N)] self_circles = 0 for _ in range(M): a, b = [int(w) - 1 for w in input().split()] if a == b: self_circles += 1 else: graph[a].append(b) graph[b].append(a) convert = {} for i in range(N): dp[i][1 << i] = 1 convert[1 << i] = i result = -M for i in range(1, 2 ** N): limit = convert[i&(-i)] for j in range(N): if dp[j][i] == 0: continue for k in graph[j]: if k < limit: continue nmask_k = i | (1 << k) if nmask_k == i: if k == limit: result += dp[j][i] else: dp[k][nmask_k] += dp[j][i] print(result//2) ```
61
Enemy is weak
Title: Enemy is weak Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number. In Shapur's opinion the weakness of an army is equal to the number of triplets *i*,<=*j*,<=*k* such that *i*<=&lt;<=*j*<=&lt;<=*k* and *a**i*<=&gt;<=*a**j*<=&gt;<=*a**k* where *a**x* is the power of man standing at position *x*. The Roman army has one special trait — powers of all the people in it are distinct. Help Shapur find out how weak the Romans are. Input Specification: The first line of input contains a single number *n* (3<=≤<=*n*<=≤<=106) — the number of men in Roman army. Next line contains *n* different positive integers *a**i* (1<=≤<=*i*<=≤<=*n*,<=1<=≤<=*a**i*<=≤<=109) — powers of men in the Roman army. Output Specification: A single integer number, the weakness of the Roman army. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Demo Input: ['3\n3 2 1\n', '3\n2 3 1\n', '4\n10 8 3 1\n', '4\n1 5 4 3\n'] Demo Output: ['1\n', '0\n', '4\n', '1\n'] Note: none
```python def update(bit ,i ) : while(i < len(bit)) : bit[i] += 1 i += (i & (-i)) def getsum(bit, i ) : res = 0 while (i >0 ) : res += bit[i] i -= (i & (-i)) return res n = int(input()) arr = list(map(int,input().split())) l = sorted(arr) d = {} ind =1 for i in range(n) : if not d.get(l[i] , 0) : d[l[i]] = ind ind +=1 for i in range(n) : arr[i] = d[arr[i]] small = [0]*n maxel = max(arr) bit = [0]*(maxel +1) for i in range(n) : c = getsum(bit, arr[i]-1) small[i] = i -c update(bit,arr[i]) bit = [0]*(maxel+1) large = [0]*n for i in range(n-1,-1,-1) : k = getsum(bit,arr[i] -1) update(bit,arr[i]) large[i] = k count = 0 for i in range(n) : count += small[i]*large[i] print(count) ```
67
Optical Experiment
Title: Optical Experiment Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Professor Phunsuk Wangdu has performed some experiments on rays. The setup for *n* rays is as follows. There is a rectangular box having exactly *n* holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?". Professor Wangdu now is in trouble and knowing your intellect he asks you to help him. Input Specification: The first line contains *n* (1<=≤<=*n*<=≤<=106), the number of rays. The second line contains *n* distinct integers. The *i*-th integer *x**i* (1<=≤<=*x**i*<=≤<=*n*) shows that the *x**i*-th ray enters from the *i*-th hole. Similarly, third line contains *n* distinct integers. The *i*-th integer *y**i* (1<=≤<=*y**i*<=≤<=*n*) shows that the *y**i*-th ray exits from the *i*-th hole. All rays are numbered from 1 to *n*. Output Specification: Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other. Demo Input: ['5\n1 4 5 2 3\n3 4 2 1 5\n', '3\n3 1 2\n2 3 1\n'] Demo Output: ['3\n', '2\n'] Note: For the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
```python import sys # from collections import deque from bisect import bisect_left # INPUT N, UP, DOWN = 0, [], [] # OUTPUT result = 1 def read_input(): global N, UP, DOWN readline = sys.stdin.readline N = int(readline().rstrip()) UP = [int(w) for w in readline().split()] DOWN = [int(w) for w in readline().split()] def solve(): global result idx = [-1] * (N + 1) for i in range(N): idx[UP[i]] = -i # que = deque() stk = [] for ray in DOWN: i = idx[ray] if not stk or i > stk[-1]: stk.append(i) else: pos = bisect_left(stk, i) stk[pos] = i result = len(stk) def write_output(): print(result) read_input() solve() write_output() ```
45
Dancing Lessons
Title: Dancing Lessons Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There are *n* people taking dancing lessons. Every person is characterized by his/her dancing skill *a**i*. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of *a**i* variable. Your task is to find out what pairs and in what order will start dancing. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of people. The next line contains *n* symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=107) — the dancing skill. People are specified from left to right in the order in which they lined up. Output Specification: Print the resulting number of couples *k*. Then print *k* lines containing two numerals each — the numbers of people forming the couple. The people are numbered with integers from 1 to *n* from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance. Demo Input: ['4\nBGBG\n4 2 4 3\n', '4\nBBGG\n4 6 1 5\n', '4\nBGBB\n1 1 2 3\n'] Demo Output: ['2\n3 4\n1 2\n', '2\n2 3\n1 4\n', '1\n1 2\n'] Note: none
```python from heapq import heappush, heappop, heapify def improve_arrangement(n, b, a): c = [] d = [0] * n e = [] ahead = [0] + [i for i in range(n)] after = [i + 1 for i in range(n)] + [0] num = 0 for i in range(n - 1): x = i y = i + 1 if b[x] != b[y]: c.append((abs(a[x] - a[y]), x, y)) heapify(c) while c: skill, cp1, cp2 = heappop(c) if d[cp1] + d[cp2] == 0: d[cp1], d[cp2] = 1, 1 e.append(str(cp1 + 1) + " " + str(cp2 + 1)) num += 1 if cp1 > 0 and cp2 < n - 1: x = ahead[cp1] y = after[cp2] ahead[y] = x after[x] = y if b[x] != b[y]: heappush(c, (abs(a[x] - a[y]), x, y)) return num, e if __name__ == "__main__": n = int(input()) b = list(input()) a = [int(i) for i in input().split()] num, e = improve_arrangement(n, b, a) print(num) print('\n'.join(e)) ```
44
Toys
Title: Toys Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her *n* toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=10) — the number of toys. Output Specification: In the first line print the number of different variants of arrangement of toys into piles. Then print all the ways of arranging toys into piles in the order in which Sasha should try them (i.e. every next way must result from the previous one through the operation described in the statement). Every way should be printed in the following format. In every pile the toys should be arranged in ascending order of the numbers. Then the piles should be sorted in ascending order of the numbers of the first toys there. Output every way on a single line. Cf. the example to specify the output data format. If the solution is not unique, output any of them. Demo Input: ['3\n'] Demo Output: ['5\n{1,2,3}\n{1,2},{3}\n{1},{2,3}\n{1},{2},{3}\n{1,3},{2}'] Note: none
```python def combinacoes(x): # Se for apenas 1 elemento retorna 1 arranjo if x == 1: return [[0]] else: # Adiciona os elementos a lista auxiliar aux = combinacoes(x - 1) pilha = [] par = 0 # Percorre a lista juntando os elementos nas possibilidades possíveis for element in aux: lmt = max(element) + 1 if par == 0: for j in range(lmt + 1): pilha.append(element + [j]) else: # Range invertido for j in range(lmt + 1)[::-1]: pilha.append(element + [j]) par = par ^ 1 return pilha n = int(input()) # Gera as combinações de pilhas de brinquedos possibilidades = combinacoes(n) # Imprime a quantidade de combinações print(len(possibilidades)) # Formata a Impressão como é pedido no problema for item in possibilidades: arranjos = '' limit = max(item) + 1 # Percorre os limites para descobrir em qual grupo o brinquedo pertence for group in range(limit): arranjos += '{' toys = '' for i in range(n): if item[i] == group: toys += '{0},'.format(i + 1) arranjos += toys[:-1] arranjos += '},' print(arranjos[:-1]) ```
89
Chip Play
Title: Chip Play Time Limit: 4 seconds Memory Limit: 256 megabytes Problem Description: Let's consider the following game. We have a rectangular field *n*<=×<=*m* in size. Some squares of the field contain chips. Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right. The player may choose a chip and make a move with it. The move is the following sequence of actions. The chosen chip is marked as the current one. After that the player checks whether there are more chips in the same row (or in the same column) with the current one that are pointed by the arrow on the current chip. If there is at least one chip then the closest of them is marked as the new current chip and the former current chip is removed from the field. After that the check is repeated. This process can be repeated several times. If a new chip is not found, then the current chip is removed from the field and the player's move ends. By the end of a move the player receives several points equal to the number of the deleted chips. By the given initial chip arrangement determine the maximum number of points that a player can receive during one move. Also determine the number of such moves. Input Specification: The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*,<=*n*<=×<=*m*<=≤<=5000). Then follow *n* lines containing *m* characters each — that is the game field description. "." means that this square is empty. "L", "R", "U", "D" mean that this square contains a chip and an arrow on it says left, right, up or down correspondingly. It is guaranteed that a field has at least one chip. Output Specification: Print two numbers — the maximal number of points a player can get after a move and the number of moves that allow receiving this maximum number of points. Demo Input: ['4 4\nDRLD\nU.UL\n.UUR\nRDDL\n', '3 5\n.D...\nRRRLL\n.U...\n'] Demo Output: ['10 1', '6 2'] Note: In the first sample the maximum number of points is earned by the chip in the position (3, 3). You can see its progress at the following picture: All other chips earn fewer points.
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) s = [list(input().rstrip()) for _ in range(n)] l = n * m d = {76:0, 82:1, 85:2, 68:3} dp0 = [[] for _ in range(l)] for i in range(n): si = s[i] x = [n * m] for j in range(m): if si[j] ^ 46: x.append(i * m + j) x.append(n * m) for j in range(1, len(x) - 1): u = x[j] dp0[u].append(x[j - 1]) dp0[u].append(x[j + 1]) for j in range(m): x = [n * m] for i in range(n): if s[i][j] ^ 46: x.append(i * m + j) x.append(n * m) for i in range(1, len(x) - 1): u = x[i] dp0[u].append(x[i - 1]) dp0[u].append(x[i + 1]) dp = [[0] * 4 for _ in range(l + 1)] ma, cnt = 0, 0 for i in range(n): si = s[i] for j in range(m): if not si[j] ^ 46: continue for k in range(l): dp0k = dp0[k] if not dp0k: continue dpk = dp[k] for u in range(4): dpk[u] = dp0k[u] now = i * m + j c = 0 while now ^ l: dpn = dp[now] for k in range(4): dp[dpn[k]][k ^ 1] = dpn[k ^ 1] now = dpn[d[s[now // m][now % m]]] c += 1 if ma < c: ma = c cnt = 0 if ma == c: cnt += 1 print(ma, cnt) ```
111
Petya and Coloring
Title: Petya and Coloring Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size *n*<=×<=*m* (*n* rows, *m* columns) in *k* colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings. Input Specification: The first line contains space-separated integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=1000,<=1<=≤<=*k*<=≤<=106) — the board's vertical and horizontal sizes and the number of colors respectively. Output Specification: Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109<=+<=7 (1000000007). Demo Input: ['2 2 1\n', '2 2 2\n', '3 2 2\n'] Demo Output: ['1\n', '8\n', '40\n'] Note: none
```python M, Mod = 10**3 + 3, 10**9 + 7 n, m, k = [int(x) for x in input().split()] if m == 0: print(0) elif m == 1: print(pow(k, n, Mod)) else: C = [[0 for j in range(M)] for i in range(M)] for i in range(n + 1): C[i][0] = 1 for j in range(1, i + 1): C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % Mod F = [0 for j in range(M)] for i in range(1, n + 1): F[i] = pow(i, n, Mod) for j in range(1, i): F[i] = (F[i] - F[j] * C[i][j] % Mod + Mod) % Mod R1, R2 = [1], [1] for i in range(1, n + 1): R1.append(R1[i-1] * pow(i, Mod-2, Mod) % Mod) for i in range(1, 2 * n + 1): if i > k: break R2.append(R2[i - 1] * (k - i + 1)%Mod) tot = 0 for i in range(n + 1): x = pow(i,(m-2)*n,Mod) for j in range(n - i + 1): if i + 2 * j > k: break tot = (tot + R2[2 * j + i] * R1[j] % Mod * R1[j] % Mod * R1[i] % Mod * F[i + j] % Mod * F[i + j] % Mod * x) % Mod; print(tot) ```
52
Circular RMQ
Title: Circular RMQ Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: You are given circular array *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. There are two types of operations with it: - *inc*(*lf*,<=*rg*,<=*v*) — this operation increases each element on the segment [*lf*,<=*rg*] (inclusively) by *v*; - *rmq*(*lf*,<=*rg*) — this operation returns minimal value on the segment [*lf*,<=*rg*] (inclusively). Assume segments to be circular, so if *n*<==<=5 and *lf*<==<=3,<=*rg*<==<=1, it means the index sequence: 3,<=4,<=0,<=1. Write program to process given sequence of operations. Input Specification: The first line contains integer *n* (1<=≤<=*n*<=≤<=200000). The next line contains initial state of the array: *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (<=-<=106<=≤<=*a**i*<=≤<=106), *a**i* are integer. The third line contains integer *m* (0<=≤<=*m*<=≤<=200000), *m* — the number of operartons. Next *m* lines contain one operation each. If line contains two integer *lf*,<=*rg* (0<=≤<=*lf*,<=*rg*<=≤<=*n*<=-<=1) it means *rmq* operation, it contains three integers *lf*,<=*rg*,<=*v* (0<=≤<=*lf*,<=*rg*<=≤<=*n*<=-<=1;<=-<=106<=≤<=*v*<=≤<=106) — *inc* operation. Output Specification: For each *rmq* operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Demo Input: ['4\n1 2 3 4\n4\n3 0\n3 0 -1\n0 1\n2 1\n'] Demo Output: ['1\n0\n0\n'] Note: none
```python import sys input = lambda: sys.stdin.readline().rstrip("\r\n") fast_print = lambda p: sys.stdout.write(str(p) + "\n") from math import inf def make_lazy_segment_tree(arr): N = len(arr) size = 1 << (N-1).bit_length() tree = [inf] * (2*size) lazy = [0] * (2*size) for k in range(N): tree[size+k] = arr[k] for k in range(size-1,-1,-1): tree[k] = min(tree[2*k], tree[2*k+1]) return tree, lazy def push(tree, lazy, v): tree[2 * v] += lazy[v] lazy[2*v] += lazy[v] tree[2 * v + 1] += lazy[v] lazy[2*v+1] += lazy[v] lazy[v] = 0 def build(tree, lazy, v): v >>= 1 while v: tree[v] = min(tree[2*v], tree[2*v+1]) + lazy[v] v >>= 1 def range_query(tree, lazy, l, r): res = inf l += len(tree) >> 1 r += (len(tree) >> 1) + 1 for k in range(l.bit_length()-1, 0, -1): push(tree, lazy, l >> k) for k in range((r-1).bit_length()-1,0,-1): push(tree, lazy, (r-1) >> k) while l < r: if l & 1: res = min(res, tree[l]) l += 1 if r & 1: r -= 1 res = min(res, tree[r]) l >>= 1 r >>= 1 return res def range_update(tree, lazy, l, r, val): l += len(tree) >> 1 r += (len(tree) >> 1) + 1 old_l, old_r = l, r while l < r: if l & 1: tree[l] += val lazy[l] += val l += 1 if r & 1: r -= 1 tree[r] += val lazy[r] += val l >>= 1 r >>= 1 build(tree, lazy, old_l) build(tree, lazy, old_r-1) n = int(input()) a = list(map(int,sys.stdin.readline().split())) m = int(input()) tree, lazy = make_lazy_segment_tree(a) def circular_range_update(l,r,val): # print(f"CRU called with l = {l}, r = {r}, v = {v}") if l <= r: range_update(tree, lazy, l, r, val) else: # print(f"circular query: calling {(l, n-1)} and {(0, r)}") range_update(tree, lazy, l, n-1, val) range_update(tree, lazy, 0, r, val) def circular_range_query(l, r): if l <= r: return range_query(tree, lazy, l, r) else: return min( range_query(tree, lazy, l, n-1), range_query(tree, lazy, 0, r), ) for _ in range(m): op_args = list(map(int,sys.stdin.readline().split())) if len(op_args) == 3: circular_range_update(op_args[0], op_args[1], op_args[2]) # print(f"result tree = {tree}") # print(f"result lazy = {lazy}") else: fast_print(circular_range_query(op_args[0], op_args[1])) ```
56
Changing a String
Title: Changing a String Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: There is a string *s*, consisting of capital Latin letters. Let's denote its current length as |*s*|. During one move it is allowed to apply one of the following operations to it: - INSERT *pos* *ch* — insert a letter *ch* in the string *s* in the position *pos* (1<=≤<=*pos*<=≤<=|*s*|<=+<=1,<=*A*<=≤<=*ch*<=≤<=*Z*). The letter *ch* becomes the *pos*-th symbol of the string *s*, at that the letters shift aside and the length of the string increases by 1. - DELETE *pos* — delete a character number *pos* (1<=≤<=*pos*<=≤<=|*s*|) from the string *s*. At that the letters shift together and the length of the string decreases by 1. - REPLACE *pos* *ch* — the letter in the position *pos* of the line *s* is replaced by *ch* (1<=≤<=*pos*<=≤<=|*s*|,<=*A*<=≤<=*ch*<=≤<=*Z*). At that the length of the string does not change. Your task is to find in which minimal number of moves one can get a *t* string from an *s* string. You should also find the sequence of actions leading to the required results. Input Specification: The first line contains *s*, the second line contains *t*. The lines consist only of capital Latin letters, their lengths are positive numbers from 1 to 1000. Output Specification: In the first line print the number of moves *k* in the given sequence of operations. The number should be the minimal possible one. Then print *k* lines containing one operation each. Print the operations in the format, described above. If there are several solutions, print any of them. Demo Input: ['ABA\nABBBA\n', 'ACCEPTED\nWRONGANSWER\n'] Demo Output: ['2\nINSERT 3 B\nINSERT 4 B\n', '10\nREPLACE 1 W\nREPLACE 2 R\nREPLACE 3 O\nREPLACE 4 N\nREPLACE 5 G\nREPLACE 6 A\nINSERT 7 N\nINSERT 8 S\nINSERT 9 W\nREPLACE 11 R\n'] Note: none
```python def editDistance(s, t): sl = len(s) tl = len(t) for i in range(tl + 1): dp[0][i] = i for i in range(sl + 1): dp[i][0] = i for i in range(1, sl + 1): for j in range(1, tl + 1): if s[i - 1] == t[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 return dp[-1][-1] def trace(s, t): n = len(s) m = len(t) while n > 0 and m > 0: if s[n - 1] == t[m - 1]: n -= 1 m -= 1 else: if dp[n - 1][m - 1] == dp[n][m] - 1: print('REPLACE', n, t[m - 1]) n -= 1 m -= 1 elif dp[n - 1][m] == dp[n][m] - 1: print('DELETE', n) n -= 1 else: print('INSERT', n + 1, t[m - 1]) m -= 1 while m > 0: print('INSERT', 1, t[m - 1]) m -= 1 while n > 0: print('DELETE', n) n -= 1 def solve(): s = input() t = input() global dp dp = [[0]*(len(t) + 1) for _ in range(len(s) + 1)] print(editDistance(s, t)) trace(s, t) if __name__ == '__main__': solve() ```
13
Holes
Title: Holes Time Limit: 1 seconds Memory Limit: 64 megabytes Problem Description: Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules: There are *N* holes located in a single row and numbered from left to right with numbers from 1 to *N*. Each hole has it's own power (hole number *i* has the power *a**i*). If you throw a ball into hole *i* it will immediately jump to hole *i*<=+<=*a**i*, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the *M* moves the player can perform one of two actions: - Set the power of the hole *a* to value *b*. - Throw a ball into the hole *a* and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations. Input Specification: The first line contains two integers *N* and *M* (1<=≤<=*N*<=≤<=105, 1<=≤<=*M*<=≤<=105) — the number of holes in a row and the number of moves. The second line contains *N* positive integers not exceeding *N* — initial values of holes power. The following *M* lines describe moves made by Petya. Each of these line can be one of the two types: - 0 *a* *b* - 1 *a* Output Specification: For each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made. Demo Input: ['8 5\n1 1 1 1 1 2 8 2\n1 1\n0 1 3\n1 1\n0 3 4\n1 2\n'] Demo Output: ['8 7\n8 5\n7 3\n'] Note: none
```python import sys input = sys.stdin.readline n, m = map(int, input().split()) p = list(map(int, input().split())) size = 320 block = [i // size for i in range(n)] par, cnt = [0] * n, [0] * n for i in range(n - 1, -1, -1): setelah = i + p[i] if setelah >= n: par[i] = i + n cnt[i] = 1 elif block[setelah] == block[i]: par[i] = par[setelah] cnt[i] = cnt[setelah] + 1 else: par[i] = setelah cnt[i] = 1 ans = [] for _ in range(m): s = input().strip() if s[0] == '0': Z, a, b = s.split() a = int(a) - 1 b = int(b) p[a] = b i = a while i >= 0 and block[i] == block[a]: setelah = i + p[i] if setelah >= n: par[i] = i + n cnt[i] = 1 elif block[i] == block[setelah]: par[i] = par[setelah] cnt[i] = cnt[setelah] + 1 else: par[i] = setelah cnt[i] = 1 i -= 1 else: Z, a = s.split() a = int(a) - 1 now = 0 while a < n: now += cnt[a] a = par[a] ans.append(str(a - n + 1) + ' ' + str(now)) print('\n'.join(ans)) ```
11
How Many Squares?
Title: How Many Squares? Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2<=×<=2. We are only interested in two types of squares: 1. squares with each side parallel to a side of the matrix; 1. squares with each side parallel to a diagonal of the matrix. Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal. How many squares are in the given matrix? Input Specification: The first line contains integer *t* (1<=≤<=*t*<=≤<=10000), where *t* is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=250), where *n* is the number of rows and *m* is the number of columns. The following *n* lines contain *m* characters each (0 or 1). The total number of characters in all test cases doesn't exceed 106 for any input file. Output Specification: You should output exactly *t* lines, with the answer to the *i*-th test case on the *i*-th line. Demo Input: ['2\n8 8\n00010001\n00101000\n01000100\n10000010\n01000100\n00101000\n11010011\n11000011\n10 10\n1111111000\n1000001000\n1011001000\n1011001010\n1000001101\n1001001010\n1010101000\n1001001000\n1000001000\n1111111000\n', '1\n12 11\n11111111111\n10000000001\n10111111101\n10100000101\n10101100101\n10101100101\n10100000101\n10100000101\n10111111101\n10000000001\n11111111111\n00000000000\n'] Demo Output: ['1\n2\n', '3\n'] Note: none
```python import sys input = sys.stdin.readline def find(x): while Group[x] != x: x=Group[x] return x def Union(x,y): if find(x) != find(y): if Nodes[find(x)] < Nodes[find(y)]: Nodes[find(y)] += Nodes[find(x)] Nodes[find(x)] = 0 Group[find(x)] = find(y) else: Nodes[find(x)] += Nodes[find(y)] Nodes[find(y)] = 0 Group[find(y)] = find(x) def calc(i,j,x): flag=1 if i+x<n and j+x<m: for k in range(x+1): if MAP[i+k][j]=="0": flag=0 break if MAP[i][j+k]=="0": flag=0 break if MAP[i+k][j+x]=="0": flag=0 break if MAP[i+x][j+k]=="0": flag=0 break else: flag=0 if flag==1: return True if j-x>=0 and j+x<m and i+x+x<n: for k in range(x+1): if MAP[i+k][j+k]=="0": return False if MAP[i+k][j-k]=="0": return False if MAP[i+2*x-k][j+k]=="0": return False if MAP[i+2*x-k][j-k]=="0": return False return True else: return False LANS=[] t=int(input()) for tests in range(t): n,m=map(int,input().split()) MAP=[input().strip() for i in range(n)] Group = [i for i in range(n*m)] # グループ分け Nodes = [1]*(n*m) # 各グループのノードの数 for i in range(n): for j in range(m): if MAP[i][j]=="1": if i+1<n and MAP[i+1][j]=="1": Union(i*m+j,(i+1)*m+j) if j+1<m and MAP[i][j+1]=="1": Union(i*m+j,i*m+j+1) if i+1<n and j+1<m and MAP[i+1][j+1]=="1": Union(i*m+j,(i+1)*m+j+1) if i+1<n and j-1>=0 and MAP[i+1][j-1]=="1": Union(i*m+j,(i+1)*m+j-1) USE=[0]*(n*m) ANS=0 for i in range(n): for j in range(m): if MAP[i][j]=="1" and USE[find(i*m+j)]==0: USE[find(i*m+j)]=1 if Nodes[find(i*m+j)]%4==0: x=Nodes[find(i*m+j)]//4 if calc(i,j,x)==True: ANS+=1 LANS.append(ANS) print("\n".join(map(str,LANS))) ```
101
Buses
Title: Buses Time Limit: 2 seconds Memory Limit: 265 megabytes Problem Description: Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly *n*<=+<=1 bus stops. All of them are numbered with integers from 0 to *n* in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number *n*. There are *m* buses running between the house and the school: the *i*-th bus goes from stop *s**i* to *t**i* (*s**i*<=&lt;<=*t**i*), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the *i*-th bus on any stop numbered from *s**i* to *t**i*<=-<=1 inclusive, but he can get off the *i*-th bus only on the bus stop *t**i*. Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house. Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109<=+<=7). Input Specification: The first line contains two space-separated integers: *n* and *m* (1<=≤<=*n*<=≤<=109,<=0<=≤<=*m*<=≤<=105). Then follow *m* lines each containing two integers *s**i*,<=*t**i*. They are the numbers of starting stops and end stops of the buses (0<=≤<=*s**i*<=&lt;<=*t**i*<=≤<=*n*). Output Specification: Print the only number — the number of ways to get to the school modulo 1000000007 (109<=+<=7). Demo Input: ['2 2\n0 1\n1 2\n', '3 2\n0 1\n1 2\n', '5 5\n0 1\n0 2\n0 3\n0 4\n0 5\n'] Demo Output: ['1\n', '0\n', '16\n'] Note: The first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two. In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0. In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 2<sup class="upper-index">4</sup> = 16.
```python from bisect import bisect_left from collections import defaultdict d=defaultdict(list) n,m=map(int,input().split()) bus=[] seen=set() for i in range(m): a,b=map(int,input().split()) d[b].append(a) seen.add(b) seen.add(a) seen=sorted(seen) if n not in seen: print(0) else : sum=[0] for el in seen: if el==0: sum.append(1) else : temp=0 for start in d[el]: ind=bisect_left(seen,start) temp+=sum[-1]-sum[ind] temp%=10**9+7 sum.append(sum[-1]+temp) sum[-1]%=10**9+7 print(temp) ```
23
Oranges and Apples
Title: Oranges and Apples Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: In 2*N*<=-<=1 boxes there are apples and oranges. Your task is to choose *N* boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges. Input Specification: The first input line contains one number *T* — amount of tests. The description of each test starts with a natural number *N* — amount of boxes. Each of the following 2*N*<=-<=1 lines contains numbers *a**i* and *o**i* — amount of apples and oranges in the *i*-th box (0<=≤<=*a**i*,<=*o**i*<=≤<=109). The sum of *N* in all the tests in the input doesn't exceed 105. All the input numbers are integer. Output Specification: For each test output two lines. In the first line output YES, if it's possible to choose *N* boxes, or NO otherwise. If the answer is positive output in the second line *N* numbers — indexes of the chosen boxes. Boxes are numbered from 1 in the input order. Otherwise leave the second line empty. Separate the numbers with one space. Demo Input: ['2\n2\n10 15\n5 7\n20 18\n1\n0 0\n'] Demo Output: ['YES\n1 3\nYES\n1\n'] Note: none
```python from sys import stdin # read = sys.stdin.readline T = int(stdin.readline()) for _ in range(T): N = int(stdin.readline()) M = N + N - 1 data = [ ] for i in range(M): data.append([int(w) for w in stdin.readline().split()] + [i + 1]) data.sort(reverse=True) # print(data) total = sum(d[1] for d in data) half = sum(d[1] for d in data[0::2]) print('YES') result = [] if half + half >= total: result.extend([d[2] for d in data[0::2]]) else: result.append(data[0][2]) result.extend([d[2] for d in data[1::2]]) print(*result) ```
29
Quarrel
Title: Quarrel Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Friends Alex and Bob live in Bertown. In this town there are *n* crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number *n*. One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads *n* and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task. Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving. The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3. If the required routes don't exist, your program should output -1. Input Specification: The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=500,<=1<=≤<=*m*<=≤<=10000) — the amount of crossroads and the amount of roads. Each of the following *m* lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road. Output Specification: If the required routes don't exist, output -1. Otherwise, the first line should contain integer *k* — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain *k*<=+<=1 integers — Bob's route, i.e. the numbers of *k*<=+<=1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them. Demo Input: ['2 1\n1 2\n', '7 5\n1 2\n2 7\n7 6\n2 3\n3 4\n', '7 6\n1 2\n2 7\n7 6\n2 3\n3 4\n1 5\n'] Demo Output: ['1\n1 2 \n2 1 \n', '-1\n', '6\n1 2 3 4 3 2 7 \n7 6 7 2 1 5 1 \n'] Note: none
```python import sys from collections import deque readline = sys.stdin.readline N, M = [int(w) for w in readline().split()] city = [[] for _ in range(N + 1)] edges = [] for _ in range(M): u, v = [int(w) for w in readline().split()] city[u].append(v) city[v].append(u) edges.append((u, v)) def gen_dists(node: int) -> list: result = [N + 1] * (N + 1) dq = deque([node]) result[node] = 1 while dq: u = dq.popleft() for v in city[u]: if result[v] <= result[u] + 1: continue result[v] = result[u] + 1 dq.append(v) return result dist_alex = gen_dists(1) dist_bob = gen_dists(N) if dist_alex[-1] > N: print(-1) exit(0) seen = {(1, N, 0): (-1, -1, -1)} step_cnt = {(1, N, 0): 0} que = deque([(1, N, 0, 0)]) target = (N, 1, 0) while que: u, v, status, step = que.popleft() if step >= N: break if status == 0: for v1 in city[v]: if (u, v1, 1) in seen: continue seen[(u, v1, 1)] = (u, v, status) if dist_alex[v1] < dist_alex[v]: que.appendleft((u, v1, 1, step)) else: que.append((u, v1, 1, step)) elif status == 1: for u1 in city[u]: if u1 == v: continue if (u1, v, 0) in seen: continue seen[(u1, v, 0)] = (u, v, status) if dist_bob[u1] < dist_bob[u]: que.appendleft((u1, v, 0, step + 1)) else: que.append((u1, v, 0, step + 1)) if target in seen: break if target in seen: break result = [[], []] while target in seen: if target[-1] == 0: result[0].append(target[0]) result[1].append(target[1]) target = seen[target] if result[0]: print(len(result[0]) - 1) print(*result[1]) print(*result[0]) else: print(-1) ```
7
Palindrome Degree
Title: Palindrome Degree Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: String *s* of length *n* is called *k*-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (*k*<=-<=1)-palindromes. By definition, any string (even empty) is 0-palindrome. Let's call the palindrome degree of string *s* such a maximum number *k*, for which *s* is *k*-palindrome. For example, "abaaba" has degree equals to 3. You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes. Input Specification: The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed 5·106. The string is case-sensitive. Output Specification: Output the only number — the sum of the polindrome degrees of all the string's prefixes. Demo Input: ['a2A\n', 'abacaba\n'] Demo Output: ['1', '6'] Note: none
```python # Eric # Tarea 5 Ejercicio 2 # B - Pasión por los Palíndromos import sys # Input s = sys.stdin.readline().rstrip() ls = len(s) # Variables power = 131 power_backwards = 1 mod = 1000000007 hash_forwards = 0 hash_backwards = 0 degrees = [0]*ls count = 0 # Processing for i in range(ls): #5*10^6 hash_forwards = (ord(s[i]) + hash_forwards * power) % mod hash_backwards = (ord(s[i]) * power_backwards + hash_backwards) % mod power_backwards = (power_backwards*power) % mod if hash_backwards == hash_forwards: degrees[i] = degrees[(i-1)//2] + 1 count += degrees[i] # Output sys.stdout.write(str(count) + "\n") ```
87
Beautiful Road
Title: Beautiful Road Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: A long time ago in some country in Asia were civil wars. Each of *n* cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city. Road making was difficult, so the country had few roads, exactly *n*<=-<=1. Also you could reach any city from any other city going on those roads. Even during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them. Recently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly *n*(*n*<=-<=1) attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees. Input Specification: The first line contains an integer *n* (2<=≤<=*n*<=≤<=105), which represents the number of cities. Next *n*<=-<=1 lines contain three integers each: the numbers of cities *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*), connected by the *i*-th road and the number of days *d**i* the army spends to go on it (1<=≤<=*d**i*<=≤<=109). The lengths of several roads may coincide. Output Specification: Print on the first line two integers — the number of beautiful trees on the most beautiful road and the number of the most beautiful roads. Print on the second line the list of the most beautiful roads in the sorted order by the numbers' increasing. The roads are numbered from 1 to *n*<=-<=1 in the order in which they are given in the input data. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator). Demo Input: ['2\n2 1 5\n', '6\n1 2 1\n1 3 5\n3 4 2\n3 5 3\n3 6 4\n'] Demo Output: ['2 1\n1 \n', '16 1\n2 \n'] Note: none
```python from collections import defaultdict import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, rt = get_root(s), get_root(t) if not rs ^ rt: return if rank[s] == rank[t]: rank[rs] += 1 if rank[s] >= rank[t]: root[rt] = rs size[rs] += size[rt] else: root[rs] = rt size[rt] += size[rs] return def same(s, t): return True if get_root(s) == get_root(t) else False def get_size(s): return size[get_root(s)] def bfs(u): q, k = [u], 0 visit[u] = 1 while len(q) ^ k: i = q[k] for j in G[i]: if not visit[j]: q.append(j) visit[j] = 1 parent[j] = i k += 1 return q n = int(input()) d = defaultdict(lambda : []) for i in range(1, n): a, b, c = map(int, input().split()) d[c].append((a, b, i)) root = [i for i in range(n + 1)] rank = [1 for _ in range(n + 1)] size = [1 for _ in range(n + 1)] x = [0] * (n + 1) y = [0] * (n + 1) color = [0] * (n + 1) z = [0] * n for c in sorted(d.keys()): l = 0 s = [0] for a, b, _ in d[c]: u, v = get_root(a), get_root(b) if color[u] ^ c: color[u], x[u], y[l + 1] = c, l + 1, a s.append(get_size(u)) l += 1 if color[v] ^ c: color[v], x[v], y[l + 1] = c, l + 1, b s.append(get_size(v)) l += 1 G = [[] for _ in range(l + 1)] e = dict() for a, b, i in d[c]: u, v = x[get_root(a)], x[get_root(b)] e[(u, v)], e[(v, u)] = i, i G[u].append(v) G[v].append(u) visit, parent = [0] * (l + 1), [-1] * (l + 1) for i in range(1, l + 1): if visit[i]: continue p = bfs(i) cnt = 0 for j in p: cnt += s[j] for j in p[::-1][:-1]: k = parent[j] s[k] += s[j] z[e[(j, k)]] = s[j] * (cnt - s[j]) for a, b, _ in d[c]: unite(a, b) m = max(z) ans = [] for i in range(1, n): if z[i] == m: ans.append(i) m *= 2 c = len(ans) print(m, c) sys.stdout.write(" ".join(map(str, ans))) ```
86
Powerful array
Title: Powerful array Time Limit: 5 seconds Memory Limit: 256 megabytes Problem Description: An array of positive integers *a*1,<=*a*2,<=...,<=*a**n* is given. Let us consider its arbitrary subarray *a**l*,<=*a**l*<=+<=1...,<=*a**r*, where 1<=≤<=*l*<=≤<=*r*<=≤<=*n*. For every positive integer *s* denote by *K**s* the number of occurrences of *s* into the subarray. We call the power of the subarray the sum of products *K**s*·*K**s*·*s* for every positive integer *s*. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite. You should calculate the power of *t* given subarrays. Input Specification: First line contains two integers *n* and *t* (1<=≤<=*n*,<=*t*<=≤<=200000) — the array length and the number of queries correspondingly. Second line contains *n* positive integers *a**i* (1<=≤<=*a**i*<=≤<=106) — the elements of the array. Next *t* lines contain two positive integers *l*, *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) each — the indices of the left and the right ends of the corresponding subarray. Output Specification: Output *t* lines, the *i*-th line of the output should contain single positive integer — the power of the *i*-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d). Demo Input: ['3 2\n1 2 1\n1 2\n1 3\n', '8 3\n1 1 2 2 1 3 1 1\n2 7\n1 6\n2 7\n'] Demo Output: ['3\n6\n', '20\n20\n20\n'] Note: Consider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored):
```python from collections import defaultdict from operator import itemgetter import math class Mo: def __init__(self, ls): self.ls = ls self.n = len(ls) self.m = max(ls)+1 self.b = math.ceil(math.sqrt(self.n)) def _init_states(self): self.ans = 0 self.cnt = [0]*self.m self.l = 0 self.r = 0 self.bucket = [[] for i in range(self.b+1)] def _add(self, i): self.cnt[self.ls[i]] += 1 k = self.cnt[self.ls[i]] a = self.ls[i] self.ans += (2*k-1)*a def _delete(self, i): k = self.cnt[self.ls[i]] a = self.ls[i] self.ans -= (2*k-1)*a self.cnt[self.ls[i]] -= 1 def _one_process(self, l, r): for i in range(self.r, r): self._add(i) for i in range(self.r-1, r-1, -1): self._delete(i) for i in range(self.l, l): self._delete(i) for i in range(self.l-1, l-1, -1): self._add(i) self.l = l self.r = r def process(self, queries): self._init_states() for i, (l, r) in enumerate(queries): # [l, r) self.bucket[l//self.b].append((l, r, i)) for i in range(len(self.bucket)): self.bucket[i].sort(key=itemgetter(1)) res = [-1]*len(queries) for bs in self.bucket: for l, r, i in bs: self._one_process(l, r) res[i] = self.ans return res import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def main(): n, q = map(int, input().split()) A = list(map(int, input().split())) Q = [] for i in range(q): l, r = map(int, input().split()) l, r = l-1, r-1 Q.append((l, r+1)) mo = Mo(A) ans = mo.process(Q) print(*ans, sep='\n') if __name__ == '__main__': main() ```
12
Ball
Title: Ball Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: *N* ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the *i*-th lady by *B**i*, her intellect by *I**i* and her richness by *R**i*. Then *i*-th lady is a probable self-murderer if there is some *j*-th lady that *B**i*<=&lt;<=*B**j*,<=*I**i*<=&lt;<=*I**j*,<=*R**i*<=&lt;<=*R**j*. Find the number of probable self-murderers. Input Specification: The first line contains one integer *N* (1<=≤<=*N*<=≤<=500000). The second line contains *N* integer numbers *B**i*, separated by single spaces. The third and the fourth lines contain sequences *I**i* and *R**i* in the same format. It is guaranteed that 0<=≤<=*B**i*,<=*I**i*,<=*R**i*<=≤<=109. Output Specification: Output the answer to the problem. Demo Input: ['3\n1 4 2\n4 3 2\n2 5 3\n'] Demo Output: ['1\n'] Note: none
```python from bisect import bisect_left as lower_bound from bisect import bisect_right as upper_bound # SortedList ( akin to ordered multiset ) # A = SortedList() or A = SortedList([123,456,321,77]) # A.insert(777) # A.pop(1) # A[0] , A[-1] # A.count(777) # A.lower_bound(456) # A.upper_bound(777) class FenwickTree: def __init__(self, x): bit = self.bit = list(x) size = self.size = len(bit) for i in range(size): j = i | (i + 1) if j < size: bit[j] += bit[i] def update(self, idx, x): """updates bit[idx] += x""" while idx < self.size: self.bit[idx] += x idx |= idx + 1 def __call__(self, end): """calc sum(bit[:end])""" x = 0 while end: x += self.bit[end - 1] end &= end - 1 return x def find_kth(self, k): """Find largest idx such that sum(bit[:idx]) <= k""" idx = -1 for d in reversed(range(self.size.bit_length())): right_idx = idx + (1 << d) if right_idx < self.size and self.bit[right_idx] <= k: idx = right_idx k -= self.bit[idx] return idx + 1, k class SortedList: block_size = 700 def __init__(self, iterable=()): self.macro = [] self.micros = [[]] self.micro_size = [0] self.fenwick = FenwickTree([0]) self.size = 0 for item in iterable: self.insert(item) def insert(self, x): i = lower_bound(self.macro, x) j = upper_bound(self.micros[i], x) self.micros[i].insert(j, x) self.size += 1 self.micro_size[i] += 1 self.fenwick.update(i, 1) if len(self.micros[i]) >= self.block_size: self.micros[i:i + 1] = self.micros[i][:self.block_size >> 1], self.micros[i][self.block_size >> 1:] self.micro_size[i:i + 1] = self.block_size >> 1, self.block_size >> 1 self.fenwick = FenwickTree(self.micro_size) self.macro.insert(i, self.micros[i + 1][0]) def pop(self, k=-1): i, j = self._find_kth(k) self.size -= 1 self.micro_size[i] -= 1 self.fenwick.update(i, -1) return self.micros[i].pop(j) def __getitem__(self, k): i, j = self._find_kth(k) return self.micros[i][j] def count(self, x): return self.upper_bound(x) - self.lower_bound(x) def __contains__(self, x): return self.count(x) > 0 def lower_bound(self, x): i = lower_bound(self.macro, x) return self.fenwick(i) + lower_bound(self.micros[i], x) def upper_bound(self, x): i = upper_bound(self.macro, x) return self.fenwick(i) + upper_bound(self.micros[i], x) def _find_kth(self, k): return self.fenwick.find_kth(k + self.size if k < 0 else k) def __len__(self): return self.size def __iter__(self): return (x for micro in self.micros for x in micro) def __repr__(self): return str(list(self)) n = int ( input ( ) ) B = list ( map ( int , input ( ) . split ( ) ) ) I = list ( map ( int , input ( ) . split ( ) ) ) R = list ( map ( int , input ( ) . split ( ) ) ) L = [ [ B[i] , I[i] , R[i] ] for i in range ( n ) ] L.sort(key = lambda x : x [0] ) D = SortedList() buf = [] cur = -1 ans = 0 for i in range ( n -1 , -1 , -1 ) : if L[i][0] != cur : for j in buf : u = L[j][1] v = L[j][2] ind = D.upper_bound((u,v)) ind -= 1 while ind >= 0 : if D[ind][1] <= v : D.pop(ind) ind -= 1 continue break ind = D.lower_bound((u,v)) if ind == len(D) or ( D[ind][0] > u and D[ind][1] < v ) : D.insert((u,v)) cur = L[i][0] buf = [] ind = D.upper_bound( ( L[i][1] , L[i][2] ) ) if ind != len(D) and D[ind][0] == L[i][1] : ind +=1 if ind < len(D) and D[ind][0] > L[i][1] and D[ind][1] > L[i][2] : ans += 1 buf += [i] print(ans) ```
103
Time to Raid Cowavans
Title: Time to Raid Cowavans Time Limit: 4 seconds Memory Limit: 70 megabytes Problem Description: As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to *n*, then we can formalize the popular model of abduction, known as the (*a*,<=*b*)-Cowavan Raid: first they steal a cow number *a*, then number *a*<=+<=*b*, then — number *a*<=+<=2·*b*, and so on, until the number of an abducted cow exceeds *n*. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made *p* scenarios of the (*a*,<=*b*)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen. Input Specification: The first line contains the only positive integer *n* (1<=≤<=*n*<=≤<=3·105) — the number of cows in the cowavan. The second number contains *n* positive integer *w**i*, separated by spaces, where the *i*-th number describes the mass of the *i*-th cow in the cowavan (1<=≤<=*w**i*<=≤<=109). The third line contains the only positive integer *p* — the number of scenarios of (*a*,<=*b*)-raids (1<=≤<=*p*<=≤<=3·105). Each following line contains integer parameters *a* and *b* of the corresponding scenario (1<=≤<=*a*,<=*b*<=≤<=*n*). Output Specification: Print for each scenario of the (*a*,<=*b*)-raid the total mass of cows, that can be stolen using only this scenario. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams of the %I64d specificator. Demo Input: ['3\n1 2 3\n2\n1 1\n1 2\n', '4\n2 3 5 7\n3\n1 3\n2 3\n2 2\n'] Demo Output: ['6\n4\n', '9\n3\n10\n'] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) w = [0] + list(map(int, input().split())) p = int(input()) x, s = [], [0] * (n + 3) for i in range(p): a, b = map(int, input().split()) s[b + 2] += 1 x.append(b) x.append(a * p + i) for i in range(3, n + 3): s[i] += s[i - 1] a = [0] * p d = [0] * p for i in range(0, 2 * p, 2): b = x[i] + 1 a0, j = divmod(x[i + 1], p) a[s[b]], d[s[b]] = a0, j s[b] += 1 ans = [0] * p c = [0] * (n + 1) for b in range(1, n + 1): if s[b] == s[b + 1]: continue s0 = set() for i in range(s[b], s[b + 1]): s0.add(a[i] % b) for i in s0: j = (n - i) // b * b + i c[j] = w[j] j -= b while j > 0: c[j] = c[j + b] + w[j] j -= b for i in range(s[b], s[b + 1]): ans[d[i]] = c[a[i]] sys.stdout.write("\n".join(map(str, ans))) ```
653
Paper task
Title: Paper task Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alex was programming while Valentina (his toddler daughter) got there and started asking many questions about the round brackets (or parenthesis) in the code. He explained her a bit and when she got it he gave her a task in order to finish his code on time. For the purpose of this problem we consider only strings consisting of opening and closing round brackets, that is characters '(' and ')'. The sequence of brackets is called correct if: 1. it's empty; 1. it's a correct sequence of brackets, enclosed in a pair of opening and closing brackets; 1. it's a concatenation of two correct sequences of brackets. For example, the sequences "()()" and "((()))(())" are correct, while ")(()", "(((((" and "())" are not. Alex took a piece of paper, wrote a string *s* consisting of brackets and asked Valentina to count the number of distinct non-empty substrings of *s* that are correct sequences of brackets. In other words, her task is to count the number of non-empty correct sequences of brackets that occur in a string *s* as a substring (don't mix up with subsequences). When Valentina finished the task, Alex noticed he doesn't know the answer. Help him don't loose face in front of Valentina and solve the problem! Input Specification: The first line of the input contains an integer *n* (1<=≤<=*n*<=≤<=500<=000) — the length of the string *s*. The second line contains a string *s* of length *n* consisting of only '(' and ')'. Output Specification: Print the number of distinct non-empty correct sequences that occur in *s* as substring. Demo Input: ['10\n()()()()()\n', '7\n)(())()\n'] Demo Output: ['5\n', '3\n'] Note: In the first sample, there are 5 distinct substrings we should count: "()", "()()", "()()()", "()()()()" and "()()()()()". In the second sample, there are 3 distinct substrings we should count: "()", "(())" and "(())()".
```python import bisect import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def suffix_array(s): l = len(s) x = [[] for _ in range(222)] for i in range(l): x[s[i]].append(i) y = [] z = [0] for x0 in x: for i in x0: y.append(i) z.append(len(y)) u = list(z) p = 1 for _ in range((l - 1).bit_length()): y0, s0, z0 = [0] * l, [0] * l, [0] for i in range(len(z) - 1): z1, z2 = z[i], z[i + 1] k = z1 for j in range(z1, z2): if y[j] - p >= 0: k = j break for _ in range(z2 - z1): j = s[(y[k] - p) % l] y0[u[j]] = (y[k] - p) % l u[j] += 1 k += 1 if k == z2: k = z1 i, u, v, c = 0, s[y0[0]], s[(y0[0] + p) % l], 0 for j in y0: if u ^ s[j] or v ^ s[(j + p) % l]: i += 1 u, v = s[j], s[(j + p) % l] z0.append(c) c += 1 s0[j] = i z0.append(l) u = list(z0) p *= 2 y, s, z = y0, s0, z0 if len(z) > l: break return y, s def lcp_array(s, sa): l = len(s) lcp, rank = [0] * l, [0] * l for i in range(l): rank[sa[i]] = i v = 0 for i in range(l): if not rank[i]: continue j = sa[rank[i] - 1] u = min(i, j) while u + v < l and s[i + v] == s[j + v]: v += 1 lcp[rank[i]] = v v = max(v - 1, 0) return lcp n = int(input()) s = list(input().rstrip()) + [0] s0 = list(s) sa, p = suffix_array(s0) lcp = lcp_array(s, sa) x = [0] for i in s: if not i & 1: x.append(x[-1] + 1) else: x.append(x[-1] - 1) x.pop() y = [[] for _ in range(n + 5)] for i in range(n + 1): y[x[i]].append(i) for i in range(n + 5): y[i].append(n + 5) z = [0] * n for i in range(1, n + 1): z[sa[i]] = lcp[i] ans = 0 for i in range(n - 1): if s[i] & 1: continue xi = x[i] u = y[xi - 1][bisect.bisect_left(y[xi - 1], i)] ans += max(bisect.bisect_left(y[xi], u) - bisect.bisect_right(y[xi], i + z[i]), 0) print(ans) ```
914
Sum the Fibonacci
Title: Sum the Fibonacci Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an array *s* of *n* non-negative integers. A 5-tuple of integers (*a*,<=*b*,<=*c*,<=*d*,<=*e*) is said to be valid if it satisfies the following conditions: - 1<=≤<=*a*,<=*b*,<=*c*,<=*d*,<=*e*<=≤<=*n* - (*s**a* | *s**b*) &amp; *s**c* &amp; (*s**d* ^ *s**e*)<==<=2*i* for some integer *i* - *s**a* &amp; *s**b*<==<=0 Here, '|' is the bitwise OR, '&amp;' is the bitwise AND and '^' is the bitwise XOR operation. Find the sum of *f*(*s**a*|*s**b*)<=*<=*f*(*s**c*)<=*<=*f*(*s**d*^*s**e*) over all valid 5-tuples (*a*,<=*b*,<=*c*,<=*d*,<=*e*), where *f*(*i*) is the *i*-th Fibonnaci number (*f*(0)<==<=0,<=*f*(1)<==<=1,<=*f*(*i*)<==<=*f*(*i*<=-<=1)<=+<=*f*(*i*<=-<=2)). Since answer can be is huge output it modulo 109<=+<=7. Input Specification: The first line of input contains an integer *n* (1<=≤<=*n*<=≤<=106). The second line of input contains *n* integers *s**i* (0<=≤<=*s**i*<=&lt;<=217). Output Specification: Output the sum as described above, modulo 109<=+<=7 Demo Input: ['2\n1 2\n', '3\n7 4 1\n', '10\n1 3 0 7 3 7 6 5 7 5\n', '10\n50 9 11 44 39 40 5 39 23 7\n'] Demo Output: ['32\n', '3520\n', '1235424\n', '113860062\n'] Note: none
```python P = 1000000007 def subset_zeta_transform(a): n = len(a) assert((n & (n - 1)) == 0) step = 1 while step < n: for i in range(n): if (i & step) == 0: a[i + step] += a[i] a[i + step] %= P step <<= 1 def subset_mobius_transform(a): n = len(a) assert((n & (n - 1)) == 0) step = 1 while step < n: for i in range(n): if (i & step) == 0: a[i + step] -= a[i] a[i + step] %= P step <<= 1 def superset_zeta_transform(a): n = len(a) assert((n & (n - 1)) == 0) step = 1 while step < n: for i in range(n): if (i & step) == 0: a[i] += a[i + step] a[i] %= P step <<= 1 def superset_mobius_transform(a): n = len(a) assert((n & (n - 1)) == 0) step = 1 while step < n: for i in range(n): if (i & step) == 0: a[i] -= a[i + step] a[i] %= P step <<= 1 def walsh_hadamard_transform(a, inverse = False): n = len(a) assert((n & (n - 1)) == 0) step = 1 while step < n: for i in range(n): if (i & step) == 0: x, y = a[i], a[i + step] a[i], a[i + step] = (x + y) % P, (x - y) % P step <<= 1 if inverse: inv = pow(n, P - 2, P) for i in range(n): a[i] = a[i] * inv % P def or_convolution(a, b): A, B = a[:], b[:] subset_zeta_transform(A) subset_zeta_transform(B) for i in range(len(A)): A[i] *= B[i] A[i] %= P subset_mobius_transform(A) return A def and_convolution(a, b): A, B = a[:], b[:] superset_zeta_transform(A) superset_zeta_transform(B) for i in range(len(A)): A[i] = A[i] * B[i] % P superset_mobius_transform(A) return A def xor_convolution(a, b): A, B = a[:], b[:] walsh_hadamard_transform(A) walsh_hadamard_transform(B) for i in range(len(A)): A[i] *= B[i] A[i] %= P walsh_hadamard_transform(A, True) return A def subset_convolution(a, b): n = len(a) assert((n & (n - 1)) == 0) bit = n.bit_length() A = [[0] * n for _ in range(bit)] B = [[0] * n for _ in range(bit)] C = [[0] * n for _ in range(bit)] for mask in range(n): A[bin(mask).count('1')][mask] = a[mask] B[bin(mask).count('1')][mask] = b[mask] for i in range(bit): subset_zeta_transform(A[i]) subset_zeta_transform(B[i]) for i in range(bit): for j in range(bit): if i + j >= bit: continue for mask in range(n): C[i + j][mask] += A[i][mask] * B[j][mask] % P C[i + j][mask] %= P for i in range(bit): subset_mobius_transform(C[i]) ans = [0] * n for mask in range(n): ans[mask] = C[bin(mask).count('1')][mask] return ans N = 1 << 17 f = [0] * N f[1] = 1 for i in range(2, N): f[i] = f[i - 1] + f[i - 2] f[i] %= P n = int(input()) s = list(map(int, input().split())) B = [0] * N for x in s: B[x] += 1 A = subset_convolution(B, B) C = xor_convolution(B, B) for mask in range(N): A[mask] = A[mask] * f[mask] % P B[mask] = B[mask] * f[mask] % P C[mask] = C[mask] * f[mask] % P g = and_convolution(A, and_convolution(B, C)) ans, step = 0, 1 while step < N: ans += g[step] ans %= P step <<= 1 print(ans) ```
725
Family Photos
Title: Family Photos Time Limit: None seconds Memory Limit: None megabytes Problem Description: Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are *n* stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks. Each photo is described by two non-negative integers *a* and *b*, indicating that it is worth *a* units of happiness to Alice and *b* units of happiness to Bonnie. Values of *a* and *b* might differ for different photos. It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively. The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has *x* happiness and Bonnie has *y* happiness at the end, you should print *x*<=-<=*y*. Input Specification: The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of two-photo stacks. Then follow *n* lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers *a*1, *b*1, *a*2 and *b*2, each not exceeding 109. *a*1 and *b*1 describe the top photo in the stack, while *a*2 and *b*2 describe the bottom photo in the stack. Output Specification: Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally. Demo Input: ['2\n12 3 4 7\n1 15 9 1\n', '2\n5 4 8 8\n4 12 14 0\n', '1\n0 10 0 10\n'] Demo Output: ['1\n', '4\n', '-10\n'] Note: none
```python # LUOGU_RID: 105175736 n=int(input()) ret,ans=[],0 for i in range(n): a1,b1,a2,b2=map(int,input().split()) if a1+b1>=a2+b2: ret.extend([a1+b1,a2+b2]) ans+=a1+a2 elif a1>b2: ans+=a1-b2 elif a2<b1: ans+=a2-b1 for x in sorted(ret)[::2]: ans-=x print(ans) ```
208
Blood Cousins
Title: Blood Cousins Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus got hold of a family relationship tree. The tree describes family relationships of *n* people, numbered 1 through *n*. Each person in the tree has no more than one parent. Let's call person *a* a 1-ancestor of person *b*, if *a* is the parent of *b*. Let's call person *a* a *k*-ancestor (*k*<=&gt;<=1) of person *b*, if person *b* has a 1-ancestor, and *a* is a (*k*<=-<=1)-ancestor of *b*'s 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an *x*-ancestor for himself, for some *x*, *x*<=&gt;<=0). Let's call two people *x* and *y* (*x*<=≠<=*y*) *p*-th cousins (*p*<=&gt;<=0), if there is person *z*, who is a *p*-ancestor of *x* and a *p*-ancestor of *y*. Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote *m* pairs of integers *v**i*, *p**i*. Help him to calculate the number of *p**i*-th cousins that person *v**i* has, for each pair *v**i*, *p**i*. Input Specification: The first input line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of people in the tree. The next line contains *n* space-separated integers *r*1,<=*r*2,<=...,<=*r**n*, where *r**i* (1<=≤<=*r**i*<=≤<=*n*) is the number of person *i*'s parent or 0, if person *i* has no parent. It is guaranteed that family relationships don't form cycles. The third line contains a single number *m* (1<=≤<=*m*<=≤<=105) — the number of family relationship queries Polycarus has. Next *m* lines contain pairs of space-separated integers. The *i*-th line contains numbers *v**i*, *p**i* (1<=≤<=*v**i*,<=*p**i*<=≤<=*n*). Output Specification: Print *m* space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input. Demo Input: ['6\n0 1 1 0 4 4\n7\n1 1\n1 2\n2 1\n2 2\n4 1\n5 1\n6 1\n'] Demo Output: ['0 0 1 0 0 1 1 \n'] Note: none
```python import sys import random from math import gcd, lcm, sqrt, isqrt, perm, comb, factorial, log2, ceil, floor from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush from copy import deepcopy from bisect import bisect_left, bisect_right from string import ascii_lowercase, ascii_uppercase inf = float('inf') input = lambda: sys.stdin.readline().strip() I = lambda: input() II = lambda: int(input()) MII = lambda: map(int, input().split()) LI = lambda: list(input().split()) LII = lambda: list(map(int, input().split())) GMI = lambda: map(lambda x: int(x) - 1, input().split()) LGMI = lambda: list(map(lambda x: int(x) - 1, input().split())) MOD = 10 ** 9 + 7 RANDOM = random.randint(1217, 2000) from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve(): n = II() fa = LGMI() g = [[] for _ in range(n)] for i, p in enumerate(fa): if p == -1: continue g[p].append(i) q = II() qs = [[] for _ in range(n)] qs2 = [[] for _ in range(n)] res = [0] * q for i in range(q): u, d = MII() qs[u - 1].append((d, i)) path = [] @bootstrap def dfs(u, depth): cnt_u = Counter() cnt_u[depth] += 1 path.append(u) for d, i in qs[u]: if d > depth: continue qs2[path[-d - 1]].append((d, i)) for v in g[u]: cnt_v = yield dfs(v, depth + 1) if len(cnt_v) > len(cnt_u): cnt_u, cnt_v = cnt_v, cnt_u for dep, cnt in cnt_v.items(): cnt_u[dep] += cnt cnt_v.clear() for d, i in qs2[u]: res[i] = cnt_u[depth + d] - 1 path.pop() yield cnt_u for i in range(n): if fa[i] == -1: dfs(i, 0) print(*res) solve() ```
216
Martian Luck
Title: Martian Luck Time Limit: None seconds Memory Limit: None megabytes Problem Description: You know that the Martians use a number system with base *k*. Digit *b* (0<=≤<=*b*<=&lt;<=*k*) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year *b* (by Martian chronology). A digital root *d*(*x*) of number *x* is a number that consists of a single digit, resulting after cascading summing of all digits of number *x*. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number. For example, *d*(35047)<==<=*d*((3<=+<=5<=+<=0<=+<=4)7)<==<=*d*(157)<==<=*d*((1<=+<=5)7)<==<=*d*(67)<==<=67. In this sample the calculations are performed in the 7-base notation. If a number's digital root equals *b*, the Martians also call this number lucky. You have string *s*, which consists of *n* digits in the *k*-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers. Note that substring *s*[*i*... *j*] of the string *s*<==<=*a*1*a*2... *a**n* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) is the string *a**i**a**i*<=+<=1... *a**j*. Two substrings *s*[*i*1... *j*1] and *s*[*i*2... *j*2] of the string *s* are different if either *i*1<=≠<=*i*2 or *j*1<=≠<=*j*2. Input Specification: The first line contains three integers *k*, *b* and *n* (2<=≤<=*k*<=≤<=109, 0<=≤<=*b*<=&lt;<=*k*, 1<=≤<=*n*<=≤<=105). The second line contains string *s* as a sequence of *n* integers, representing digits in the *k*-base notation: the *i*-th integer equals *a**i* (0<=≤<=*a**i*<=&lt;<=*k*) — the *i*-th digit of string *s*. The numbers in the lines are space-separated. Output Specification: Print a single integer — the number of substrings that are lucky numbers. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Demo Input: ['10 5 6\n3 2 0 5 6 1\n', '7 6 4\n3 5 0 4\n', '257 0 3\n0 0 256\n'] Demo Output: ['5', '1', '3'] Note: In the first sample the following substrings have the sought digital root: *s*[1... 2] = "3 2", *s*[1... 3] = "3 2 0", *s*[3... 4] = "0 5", *s*[4... 4] = "5" and *s*[2... 6] = "2 0 5 6 1".
```python from sys import stdin inp = stdin.readline k, b, n = map(int, inp().split()) s = [int(i) for i in inp().split()] a = b % (k-1) sums = {0: 1} def zero(): i, count2 = 0, 0 s.append(1) while i < n: if s[i] == 0: x = 0 while s[i] == 0: x += 1 i += 1 count2 += int(x*(x+1)/2) i += 1 return count2 if b != 0: curr, count = 0, 0 for i in range(n): curr = (curr + s[i]) % (k-1) x = (curr - a) % (k-1) count += sums.get(x, 0) sums[curr] = sums.get(curr, 0) + 1 if b == k-1: count -= zero() print(count) else: print(zero()) ```
438
The Child and Binary Tree
Title: The Child and Binary Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: Our child likes computer science very much, especially he likes binary trees. Consider the sequence of *n* distinct positive integers: *c*1,<=*c*2,<=...,<=*c**n*. The child calls a vertex-weighted rooted binary tree good if and only if for every vertex *v*, the weight of *v* is in the set {*c*1,<=*c*2,<=...,<=*c**n*}. Also our child thinks that the weight of a vertex-weighted tree is the sum of all vertices' weights. Given an integer *m*, can you for all *s* (1<=≤<=*s*<=≤<=*m*) calculate the number of good vertex-weighted rooted binary trees with weight *s*? Please, check the samples for better understanding what trees are considered different. We only want to know the answer modulo 998244353 (7<=×<=17<=×<=223<=+<=1, a prime number). Input Specification: The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=105). The second line contains *n* space-separated pairwise distinct integers *c*1,<=*c*2,<=...,<=*c**n*. (1<=≤<=*c**i*<=≤<=105). Output Specification: Print *m* lines, each line containing a single integer. The *i*-th line must contain the number of good vertex-weighted rooted binary trees whose weight exactly equal to *i*. Print the answers modulo 998244353 (7<=×<=17<=×<=223<=+<=1, a prime number). Demo Input: ['2 3\n1 2\n', '3 10\n9 4 3\n', '5 10\n13 10 6 4 15\n'] Demo Output: ['1\n3\n9\n', '0\n0\n1\n1\n0\n2\n4\n2\n6\n15\n', '0\n0\n0\n1\n0\n1\n0\n2\n0\n5\n'] Note: In the first example, there are 9 good vertex-weighted rooted binary trees whose weight exactly equal to 3:
```python standard_input, packages, dfs, hashing = 1, 1, 0, 0 if standard_input: import sys input = lambda: sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MII(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def LFI(): return list(map(float, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): return list(map(lambda x: int(x) - 1, input().split())) inf = float('inf') if packages: from io import BytesIO, IOBase import math import random import os import bisect import typing from collections import Counter, defaultdict, deque from copy import deepcopy from functools import cmp_to_key, lru_cache, reduce from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest from itertools import accumulate, combinations, permutations, count, product from operator import add, iand, ior, itemgetter, mul, xor from string import ascii_lowercase, ascii_uppercase, ascii_letters from typing import * BUFSIZE = 4096 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) sys.stdout = IOWrapper(sys.stdout) if dfs: from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc if hashing: RANDOM = random.getrandbits(20) class Wrapper(int): def __init__(self, x): int.__init__(x) def __hash__(self): return super(Wrapper, self).__hash__() ^ RANDOM read_from_file = 0 if read_from_file: file = open("input.txt", "r").readline().strip()[1:-1] fin = open(file, 'r') input = lambda: fin.readline().strip() output_file = open("output.txt", "w") def fprint(*args, **kwargs): print(*args, **kwargs, file=output_file) poly = 1 if poly: # 求平方根 def Tonelli_Shanks(N, p): if pow(N, p >> 1, p) == p - 1: return None if p%4==3: return pow(N, (p + 1) // 4, p) for nonresidue in range(1, p): if pow(nonresidue, p>>1, p)==p-1: break pp = p - 1 cnt = 0 while pp % 2 == 0: pp //= 2 cnt += 1 s = pow(N, pp, p) retu = pow(N, (pp + 1) // 2,p) for i in range(cnt - 2, -1, -1): if pow(s, 1 <<i, p) == p - 1: s *= pow(nonresidue, p >> 1 + i, p) s %= p retu *= pow(nonresidue, p >> 2 + i, p) retu %= p return retu mod = 998244353 imag = 911660635 iimag = 86583718 rate2 = (911660635, 509520358, 369330050, 332049552, 983190778, 123842337, 238493703, 975955924, 603855026, 856644456, 131300601, 842657263, 730768835, 942482514, 806263778, 151565301, 510815449, 503497456, 743006876, 741047443, 56250497, 867605899) irate2 = (86583718, 372528824, 373294451, 645684063, 112220581, 692852209, 155456985, 797128860, 90816748, 860285882, 927414960, 354738543, 109331171, 293255632, 535113200, 308540755, 121186627, 608385704, 438932459, 359477183, 824071951, 103369235) rate3 = (372528824, 337190230, 454590761, 816400692, 578227951, 180142363, 83780245, 6597683, 70046822, 623238099, 183021267, 402682409, 631680428, 344509872, 689220186, 365017329, 774342554, 729444058, 102986190, 128751033, 395565204) irate3 = (509520358, 929031873, 170256584, 839780419, 282974284, 395914482, 444904435, 72135471, 638914820, 66769500, 771127074, 985925487, 262319669, 262341272, 625870173, 768022760, 859816005, 914661783, 430819711, 272774365, 530924681) def butterfly(a): n = len(a) h = (n - 1).bit_length() len_ = 0 while len_ < h: if h - len_ == 1: p = 1 << (h - len_ - 1) rot = 1 for s in range(1 << len_): offset = s << (h - len_) for i in range(p): l = a[i + offset] r = a[i + offset + p] * rot % mod a[i + offset] = (l + r) % mod a[i + offset + p] = (l - r) % mod if s + 1 != 1 << len_: rot *= rate2[(~s & -~s).bit_length() - 1] rot %= mod len_ += 1 else: p = 1 << (h - len_ - 2) rot = 1 for s in range(1 << len_): rot2 = rot * rot % mod rot3 = rot2 * rot % mod offset = s << (h - len_) for i in range(p): a0 = a[i + offset] a1 = a[i + offset + p] * rot a2 = a[i + offset + p * 2] * rot2 a3 = a[i + offset + p * 3] * rot3 a1na3imag = (a1 - a3) % mod * imag a[i + offset] = (a0 + a2 + a1 + a3) % mod a[i + offset + p] = (a0 + a2 - a1 - a3) % mod a[i + offset + p * 2] = (a0 - a2 + a1na3imag) % mod a[i + offset + p * 3] = (a0 - a2 - a1na3imag) % mod if s + 1 != 1 << len_: rot *= rate3[(~s & -~s).bit_length() - 1] rot %= mod len_ += 2 def butterfly_inv(a): n = len(a) h = (n - 1).bit_length() len_ = h while len_: if len_ == 1: p = 1 << (h - len_) irot = 1 for s in range(1 << (len_ - 1)): offset = s << (h - len_ + 1) for i in range(p): l = a[i + offset] r = a[i + offset + p] a[i + offset] = (l + r) % mod a[i + offset + p] = (l - r) * irot % mod if s + 1 != (1 << (len_ - 1)): irot *= irate2[(~s & -~s).bit_length() - 1] irot %= mod len_ -= 1 else: p = 1 << (h - len_) irot = 1 for s in range(1 << (len_ - 2)): irot2 = irot * irot % mod irot3 = irot2 * irot % mod offset = s << (h - len_ + 2) for i in range(p): a0 = a[i + offset] a1 = a[i + offset + p] a2 = a[i + offset + p * 2] a3 = a[i + offset + p * 3] a2na3iimag = (a2 - a3) * iimag % mod a[i + offset] = (a0 + a1 + a2 + a3) % mod a[i + offset + p] = (a0 - a1 + a2na3iimag) * irot % mod a[i + offset + p * 2] = (a0 + a1 - a2 - a3) * irot2 % mod a[i + offset + p * 3] = (a0 - a1 - a2na3iimag) * irot3 % mod if s + 1 != (1 << (len_ - 2)): irot *= irate3[(~s & -~s).bit_length() - 1] irot %= mod len_ -= 2 # 积分 def integrate(a): a = a.copy() n = len(a) assert n > 0 a.pop() a.insert(0, 0) inv = [1, 1] for i in range(2, n): inv.append(-inv[mod % i] * (mod // i) % mod) a[i] = a[i] * inv[i] % mod return a # 求导 def differentiate(a): n = len(a) assert n > 0 for i in range(2, n): a[i] = a[i] * i % mod a.pop(0) a.append(0) return a # 卷积 def convolution_naive(a, b): n = len(a) m = len(b) ans = [0] * (n + m - 1) if n < m: for j in range(m): for i in range(n): ans[i + j] = (ans[i + j] + a[i] * b[j]) % mod else: for i in range(n): for j in range(m): ans[i + j] = (ans[i + j] + a[i] * b[j]) % mod return ans # 快速数论变换,卷积 def convolution_ntt(a, b): a = a.copy() b = b.copy() n = len(a) m = len(b) z = 1 << (n + m - 2).bit_length() a += [0] * (z - n) butterfly(a) b += [0] * (z - m) butterfly(b) for i in range(z): a[i] = a[i] * b[i] % mod butterfly_inv(a) a = a[:n + m - 1] iz = pow(z, mod - 2, mod) for i in range(n + m - 1): a[i] = a[i] * iz % mod return a # 自卷 def convolution_square(a): a = a.copy() n = len(a) z = 1 << (2 * n - 2).bit_length() a += [0] * (z - n) butterfly(a) for i in range(z): a[i] = a[i] * a[i] % mod butterfly_inv(a) a = a[:2 * n - 1] iz = pow(z, mod - 2, mod) for i in range(2 * n - 1): a[i] = a[i] * iz % mod return a # 卷积函数 def convolution(a, b): """It calculates (+, x) convolution in mod 998244353. Given two arrays a[0], a[1], ..., a[n - 1] and b[0], b[1], ..., b[m - 1], it calculates the array c of length n + m - 1, defined by > c[i] = sum(a[j] * b[i - j] for j in range(i + 1)) % 998244353. It returns an empty list if at least one of a and b are empty. Complexity ---------- > O(n log n), where n = len(a) + len(b). """ n = len(a) m = len(b) if n == 0 or m == 0: return [] if min(n, m) <= 60: return convolution_naive(a, b) if a is b: return convolution_square(a) return convolution_ntt(a, b) # 求逆 def inverse(a): n = len(a) assert n > 0 and a[0] != 0 res = [pow(a[0], mod - 2, mod)] m = 1 while m < n: f = a[:min(n, 2 * m)] + [0] * (2 * m - min(n, 2*m)) g = res + [0] * m butterfly(f) butterfly(g) for i in range(2 * m): f[i] = f[i] * g[i] % mod butterfly_inv(f) f = f[m:] + [0] * m butterfly(f) for i in range(2 * m): f[i] = f[i] * g[i] % mod butterfly_inv(f) iz = pow(2 * m, mod - 2, mod) iz = (-iz * iz) % mod for i in range(m): f[i] = f[i] * iz % mod res += f[:m] m <<= 1 return res[:n] # 取对数 def log(a): a = a.copy() n = len(a) assert n > 0 and a[0] == 1 a_inv = inverse(a) a = differentiate(a) a = convolution(a, a_inv)[:n] a = integrate(a) return a # 求指数 def exp(a): a = a.copy() n = len(a) assert n > 0 and a[0] == 0 g = [1] a[0] = 1 h_drv = a.copy() h_drv = differentiate(h_drv) m = 1 while m < n: f_fft = a[:m] + [0] * m butterfly(f_fft) if m > 1: _f = [f_fft[i] * g_fft[i] % mod for i in range(m)] butterfly_inv(_f) _f = _f[m // 2:] + [0] * (m // 2) butterfly(_f) for i in range(m): _f[i] = _f[i] * g_fft[i] % mod butterfly_inv(_f) _f = _f[:m//2] iz = pow(m, mod - 2, mod) iz *= -iz iz %= mod for i in range(m//2): _f[i] = _f[i] * iz % mod g.extend(_f) t = a[:m] t = differentiate(t) r = h_drv[:m - 1] r.append(0) butterfly(r) for i in range(m): r[i] = r[i] * f_fft[i] % mod butterfly_inv(r) im = pow(-m, mod - 2, mod) for i in range(m): r[i] = r[i] * im % mod for i in range(m): t[i] = (t[i] + r[i]) % mod t = [t[-1]] + t[:-1] t += [0] * m butterfly(t) g_fft = g + [0] * (2 * m - len(g)) butterfly(g_fft) for i in range(2 * m): t[i] = t[i] * g_fft[i] % mod butterfly_inv(t) t = t[:m] i2m = pow(2 * m, mod - 2, mod) for i in range(m): t[i] = t[i] * i2m % mod v = a[m:min(n, 2 * m)] v += [0] * (m - len(v)) t = [0] * (m - 1) + t + [0] t=integrate(t) for i in range(m): v[i] = (v[i] - t[m + i]) % mod v += [0] * m butterfly(v) for i in range(2 * m): v[i] = v[i] * f_fft[i] % mod butterfly_inv(v) v = v[:m] i2m = pow(2 * m, mod - 2, mod) for i in range(m): v[i] = v[i] * i2m % mod for i in range(min(n - m, m)): a[m + i] = v[i] m *= 2 return a # 求 k 次方:快速幂 def power(a,k): n = len(a) assert n > 0 if k == 0: return [1] + [0] * (n - 1) l = 0 while l < len(a) and not a[l]: l += 1 if l * k >= n: return [0] * n ic = pow(a[l], mod - 2, mod) pc = pow(a[l], k, mod) a = log([a[i] * ic % mod for i in range(l, len(a))]) for i in range(len(a)): a[i] = a[i] * k % mod a = exp(a) for i in range(len(a)): a[i] = a[i] * pc % mod a = [0] * (l * k) + a[:n - l * k] return a # 开根号 def sqrt(a): if len(a) == 0: return [] if a[0] == 0: for d in range(1, len(a)): if a[d]: if d & 1: return None if len(a) - 1 < d // 2: break res = sqrt(a[d:] + [0] * (d//2)) if res == None: return None res = [0] * (d // 2) + res return res return [0] * len(a) # 先求第一项能否找到对应的数字,接下来再凑 sqr = Tonelli_Shanks(a[0], mod) if sqr == None: return None T = [0] * (len(a)) T[0] = sqr res = T.copy() T[0] = pow(sqr, mod - 2, mod) #T:res^{-1} m = 1 two_inv = (mod + 1) // 2 F = [sqr] while m <= len(a) - 1: for i in range(m): F[i] *= F[i] F[i] %= mod butterfly_inv(F) iz = pow(m, mod-2, mod) for i in range(m): F[i] = F[i] * iz % mod delta = [0] * (2 * m) for i in range(m): delta[i + m] = F[i] - a[i] - (a[i + m] if i + m < len(a) else 0) butterfly(delta) G = [0] * (2 * m) for i in range(m): G[i] = T[i] butterfly(G) for i in range(2 * m): delta[i] *= G[i] delta[i] %= mod butterfly_inv(delta) iz = pow(2 * m, mod - 2, mod) for i in range(2 * m): delta[i] = delta[i] * iz % mod for i in range(m, min(2 * m, len(a))): res[i] = -delta[i] * two_inv%mod res[i] %= mod if 2 * m > len(a) - 1: break F = res[:2 * m] butterfly(F) eps = [F[i] * G[i] % mod for i in range(2 * m)] butterfly_inv(eps) for i in range(m): eps[i] = 0 iz = pow(2 * m, mod - 2, mod) for i in range(m,2*m): eps[i] = eps[i] * iz % mod butterfly(eps) for i in range(2 * m): eps[i] *= G[i] eps[i] %= mod butterfly_inv(eps) for i in range(m, 2 * m): T[i] = -eps[i]*iz T[i] %= mod iz = iz * iz % mod m <<= 1 return res mod = 998244353 n, m = MII() nums = LII() dp = [0] * (m + 1) for x in nums: if x <= m: dp[x] += 1 dp = [(- 4 * x) % mod for x in dp] dp[0] += 1 dp = sqrt(dp) dp[0] += 1 dp = inverse(dp) dp = [x * 2 % mod for x in dp] print(*(dp[i] for i in range(1, m + 1))) ```
448
Divisors
Title: Divisors Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bizon the Champion isn't just friendly, he also is a rigorous coder. Let's define function *f*(*a*), where *a* is a sequence of integers. Function *f*(*a*) returns the following sequence: first all divisors of *a*1 go in the increasing order, then all divisors of *a*2 go in the increasing order, and so on till the last element of sequence *a*. For example, *f*([2,<=9,<=1])<==<=[1,<=2,<=1,<=3,<=9,<=1]. Let's determine the sequence *X**i*, for integer *i* (*i*<=≥<=0): *X*0<==<=[*X*] ([*X*] is a sequence consisting of a single number *X*), *X**i*<==<=*f*(*X**i*<=-<=1) (*i*<=&gt;<=0). For example, at *X*<==<=6 we get *X*0<==<=[6], *X*1<==<=[1,<=2,<=3,<=6], *X*2<==<=[1,<=1,<=2,<=1,<=3,<=1,<=2,<=3,<=6]. Given the numbers *X* and *k*, find the sequence *X**k*. As the answer can be rather large, find only the first 105 elements of this sequence. Input Specification: A single line contains two space-separated integers — *X* (1<=≤<=*X*<=≤<=1012) and *k* (0<=≤<=*k*<=≤<=1018). Output Specification: Print the elements of the sequence *X**k* in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements. Demo Input: ['6 1\n', '4 2\n', '10 3\n'] Demo Output: ['1 2 3 6 \n', '1 1 2 1 2 4 \n', '1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10 \n'] Note: none
```python import sys solSaved = {} #diccionario donde se almacenan los divisores de un numero x, se toma como llave un string y se devuelve una lista solSavedPropios = {} #diccionario donde se almacenan los divisores propios de un numero x, se toma como llave un string y se devuelve una lista def DivisorsN(n): # n es un numero entero del cual se va obtener sus divisores key = solSaved.get(str(n)) # para saber si los divisore ya se han buscado con anterioridad y no tener que buscarlos nuevamente if key == None : divisors = [] # en esta lista se almacenan los divisores desde 1 hasta la raiz de n divisors2 = [] # en esta lista se almacenan los divisores desde raiz de n + 1 hasta n for i in range(1,int(n ** (1/2)) + 1): if n % i == 0 : if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int(i)) # para saber si el divisor es la raiz y ponerlo una sola vez else : divisors = divisors + [int(i)] divisors2 = [int(n/i)] + divisors2 divisors = divisors + divisors2 # concatenando todos los divisores solSaved[str(n)] = divisors.copy() # guardando los divisores ya obtenidos return divisors return key def DivisorsPropios(n) : key = solSavedPropios.get(str(n)) # para saber si los divisore ya se han buscado con anterioridad y no tener que buscarlos nuevamente if key == None : divisors = [] # en esta lista se almacenan los divisores desde 1 hasta la raiz de n divisors2 = [] # en esta lista se almacenan los divisores desde raiz de n + 1 hasta n for i in range(2,int(n ** (1/2)) + 1): if n % i == 0 : if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int(i)) # para saber si el divisor es la raiz y ponerlo una sola vez else : divisors = divisors + [int(i)] divisors2 = [int(n/i)] + divisors2 divisors = divisors + divisors2 # concatenando todos los divisores solSavedPropios[str(n)] = divisors.copy() # guardando los divisores ya obtenidos return divisors return key def DivisorsXk(x, k) : # x es el valor del cual se quieren obtener los divisores y k es el nivel de profundidad, es decir que tantos divisores de divisores de los divisores... de los divisores de x se quiere obtener if x == 1 : return 1 if k == 0 : return x if k == 1 : return DivisorsN(x) if k >= 10 ** 5 : # si el k > 10 a la 5, significa que al menos los primeros 10 a la 5 divisores van a ser el 1, y como solo se quiere saber los primeros 10 a la 5 elementos, entonces directamente se devuelve 10 a la 5 unos a = [] for i in range(10 ** 5) : a.append(1) return a Unos = [] sol = [] sol.append(1) # como el 1 es divisor de todos los numeros, y 1 es el divisor natural mas pequeño que hay, luego todos los divisores van a empzar con 1 actualDivisors = DivisorsPropios(x).copy() for i in range(k - 1) : Unos.append(1) if len(actualDivisors) == 0 : return [1] + Unos + [x] # Si x no tiene divisores propios, eso significa q la solucion va a ser los k unos mas x actualDivisors.append(x) for t in range(len(actualDivisors)) : if len(sol) >= 10 ** 5 : return sol # Si ya tengo los primeros 10 a la 5 elementos no hay necesidad de seguir buscando, ya que solo hacen falta los 10 a la 5 elementos newDivisorsPropios = DivisorsPropios(actualDivisors[t]).copy() # esto es para saber si uno de los divisores a su vez tiene divisores, en caso de q no tenga la solucion se genera poniendo k-1 unos, y luego el divisor, luego k - 2 unos y luego el divisor y as sucesivamente hasta llegar a k = 0 if len(newDivisorsPropios) == 0 : next = DivisorsXk(actualDivisors[t], k - 1) if type(next) == int : sol = sol + [next] else : sol = sol + next else : sol = sol + InsideDivisorsXk(actualDivisors[t], k - 1) return sol def InsideDivisorsXk(x, k) : # este metodo es parecido al anterior, pero este mas especificamente, sirve como complemento con el anterior, para que entre los dos, si un divisor a su vez tiene divisores, formar adecuadamente la solucion, ya que por cada divisor que tenga un divisor, se tiene q buscar un orden menor de por cada divisor de divisor que un numero.. y asi hasta q el divisor de divisor de divisor... no tenga divisores o hasta q el k >= 0 actualDivisors = DivisorsPropios(x) i = k - 1 sol = [] while i >= 1 : if len(sol) >= 10**5 : return sol sol = sol + [1] for t in range(len(actualDivisors)) : next = DivisorsXk(actualDivisors[t], i) if type(next) == int : sol = sol + [next] else : sol = sol + next i -= 1 return sol + DivisorsN(x) def Ejercicio448E() : a, b = input().split() x = int(a) k = int(b) sol = DivisorsXk(x,k) if type(sol) == int : print(sol) else : if(len(sol) >= 10 ** 5): for i in range(10 ** 5 - 1) : sys.stdout.write(str(sol[i]) + ' ') sys.stdout.write(str(sol[10**5 - 1])) else : for i in range(len(sol) - 1) : sys.stdout.write(str(sol[i]) + ' ') sys.stdout.write(str(sol[len(sol) - 1])) # print(Ejercicio448E()) Ejercicio448E() #print(DivisorsXk(100000000000,1)) #print(DivisorsXk(10,3)) #print(DivisorsXk(1221231,0)) #print(DivisorsXk(1111111111111,2)) #print(DivisorsXk(4,3)) #print(DivisorsXk(4,3)) #print(DivisorsXk(4,3)) #print(DivisorsXk(4,3)) #print(DivisorsXk(4,3)) ```
474
Ant colony
Title: Ant colony Time Limit: None seconds Memory Limit: None megabytes Problem Description: Mole is hungry again. He found one ant colony, consisting of *n* ants, ordered in a row. Each ant *i* (1<=≤<=*i*<=≤<=*n*) has a strength *s**i*. In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) and each pair of ants with indices between *l* and *r* (inclusively) will fight. When two ants *i* and *j* fight, ant *i* gets one battle point only if *s**i* divides *s**j* (also, ant *j* gets one battle point only if *s**j* divides *s**i*). After all fights have been finished, Mole makes the ranking. An ant *i*, with *v**i* battle points obtained, is going to be freed only if *v**i*<==<=*r*<=-<=*l*, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none. In order to choose the best sequence, Mole gives you *t* segments [*l**i*,<=*r**i*] and asks for each of them how many ants is he going to eat if those ants fight. Input Specification: The first line contains one integer *n* (1<=≤<=*n*<=≤<=105), the size of the ant colony. The second line contains *n* integers *s*1,<=*s*2,<=...,<=*s**n* (1<=≤<=*s**i*<=≤<=109), the strengths of the ants. The third line contains one integer *t* (1<=≤<=*t*<=≤<=105), the number of test cases. Each of the next *t* lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*), describing one query. Output Specification: Print to the standard output *t* lines. The *i*-th line contains number of ants that Mole eats from the segment [*l**i*,<=*r**i*]. Demo Input: ['5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5\n'] Demo Output: ['4\n4\n1\n1\n'] Note: In the first test battle points for each ant are *v* = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5. In the second test case battle points are *v* = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole. In the third test case battle points are *v* = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4. In the fourth test case battle points are *v* = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
```python import time import bisect import functools import math import os import random import re import sys import threading from collections import Counter, defaultdict, deque from copy import deepcopy from functools import cmp_to_key, lru_cache, reduce from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest from io import BytesIO, IOBase from itertools import accumulate, combinations, permutations from operator import add, iand, ior, itemgetter, mul, xor from string import ascii_lowercase, ascii_uppercase from typing import * BUFSIZE = 4096 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) sys.stdout = IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MII(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): return list(map(lambda x: int(x) - 1, input().split())) inf = float('inf') # from types import GeneratorType # def bootstrap(f, stack=[]): # def wrappedfunc(*args, **kwargs): # if stack: # return f(*args, **kwargs) # else: # to = f(*args, **kwargs) # while True: # if type(to) is GeneratorType: # stack.append(to) # to = next(to) # else: # stack.pop() # if not stack: # break # to = stack[-1].send(to) # return to # return wrappedfunc # RANDOM = random.getrandbits(32) # class Wrapper(int): # def __init__(self, x): # int.__init__(x) # def __hash__(self): # return super(Wrapper, self).__hash__() ^ RANDOM class SparseTable: def __init__(self, data, merge_method): self.note = [0] * (len(data) + 1) self.merge_method = merge_method l, r, v = 1, 2, 0 while True: for i in range(l, r): if i >= len(self.note): break self.note[i] = v else: l *= 2 r *= 2 v += 1 continue break self.ST = [[0] * len(data) for _ in range(self.note[-1]+1)] self.ST[0] = data for i in range(1, len(self.ST)): for j in range(len(data) - (1 << i) + 1): self.ST[i][j] = merge_method(self.ST[i-1][j], self.ST[i-1][j + (1 << (i-1))]) def query(self, l, r): pos = self.note[r-l+1] return self.merge_method(self.ST[pos][l], self.ST[pos][r - (1 << pos) + 1]) class SegmentTree: def __init__(self, n, merge): self.n = n self.tree = [[inf, 0]] * (2 * self.n) self._merge = merge def query(self, ql, qr): lans = [inf, 0] rans = [inf, 0] ql += self.n qr += self.n + 1 while ql < qr: if ql % 2: lans = self._merge(lans, self.tree[ql]) ql += 1 if qr % 2: qr -= 1 rans = self._merge(rans, self.tree[qr]) ql //= 2 qr //= 2 return self._merge(lans, rans) def update(self, index, value): index += self.n self.tree[index] = value while index: index //= 2 self.tree[index] = self._merge(self.tree[2 * index], self.tree[2 * index + 1]) n = II() nums = LII() st_gcd = SparseTable(nums, math.gcd) def merge_min(x, y): min1, cnt1 = x min2, cnt2 = y if min1 < min2: return [min1, cnt1] if min1 > min2: return [min2, cnt2] return [min1, cnt1 + cnt2] seg = SegmentTree(n, merge_min) for i, v in enumerate(nums): seg.update(i, [v, 1]) q = II() for _ in range(q): l, r = GMI() v = st_gcd.query(l, r) mi, c = seg.query(l, r) if v == mi: print(r - l + 1 - c) else: print(r - l + 1) ```
225
Unsolvable
Title: Unsolvable Time Limit: None seconds Memory Limit: None megabytes Problem Description: Consider the following equation: Let's find all integer *z* (*z*<=&gt;<=0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers *x* and *y* (*x*,<=*y*<=&gt;<=0), for which the given above equation holds. Let's write out all such *z* in the increasing order: *z*1,<=*z*2,<=*z*3, and so on (*z**i*<=&lt;<=*z**i*<=+<=1). Your task is: given the number *n*, find the number *z**n*. Input Specification: The first line contains a single integer *n* (1<=≤<=*n*<=≤<=40). Output Specification: Print a single integer — the number *z**n* modulo 1000000007 (109<=+<=7). It is guaranteed that the answer exists. Demo Input: ['1\n', '2\n', '3\n'] Demo Output: ['1', '3', '15'] Note: none
```python mod = 10**9+7 a = [2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279,2203,2281,3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243,110503,132049,216091,756839,859433,1257787,1398269,2976221,3021377,6972593,13466917,20996011] n = int(input()) print(pow(2,a[n-1]-1,mod)-1) ```
723
st-Spanning Tree
Title: st-Spanning Tree Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an undirected connected graph consisting of *n* vertices and *m* edges. There are no loops and no multiple edges in the graph. You are also given two distinct vertices *s* and *t*, and two values *d**s* and *d**t*. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex *s* doesn't exceed *d**s*, and the degree of the vertex *t* doesn't exceed *d**t*, or determine, that there is no such spanning tree. The spanning tree of the graph *G* is a subgraph which is a tree and contains all vertices of the graph *G*. In other words, it is a connected graph which contains *n*<=-<=1 edges and can be obtained by removing some of the edges from *G*. The degree of a vertex is the number of edges incident to this vertex. Input Specification: The first line of the input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=200<=000, 1<=≤<=*m*<=≤<=*min*(400<=000,<=*n*·(*n*<=-<=1)<=/<=2)) — the number of vertices and the number of edges in the graph. The next *m* lines contain the descriptions of the graph's edges. Each of the lines contains two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*, *u*<=≠<=*v*) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers *s*, *t*, *d**s*, *d**t* (1<=≤<=*s*,<=*t*<=≤<=*n*, *s*<=≠<=*t*, 1<=≤<=*d**s*,<=*d**t*<=≤<=*n*<=-<=1). Output Specification: If the answer doesn't exist print "No" (without quotes) in the only line of the output. Otherwise, in the first line print "Yes" (without quotes). In the each of the next (*n*<=-<=1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them. Demo Input: ['3 3\n1 2\n2 3\n3 1\n1 2 1 1\n', '7 8\n7 4\n1 3\n5 4\n5 7\n3 2\n2 4\n6 1\n1 2\n6 4 1 4\n'] Demo Output: ['Yes\n3 2\n1 3\n', 'Yes\n1 3\n5 7\n3 2\n7 4\n2 4\n6 1\n'] Note: none
```python import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, rt = get_root(s), get_root(t) if not rs ^ rt: return if rank[s] == rank[t]: rank[rs] += 1 if rank[s] >= rank[t]: root[rt] = rs size[rs] += size[rt] else: root[rs] = rt size[rt] += size[rs] return def same(s, t): return True if get_root(s) == get_root(t) else False def get_size(s): return size[get_root(s)] n, m = map(int, input().split()) e = [tuple(map(int, input().split())) for _ in range(m)] s, t, ds, dt = map(int, input().split()) ans = [] root = [i for i in range(n + 1)] rank = [1 for _ in range(n + 1)] size = [1 for _ in range(n + 1)] z = set([s, t]) c = [] f = 0 for u, v in e: if u in z and v in z: f = 1 elif u in z or v in z: c.append((u, v)) elif not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) s0, t0 = [0] * (n + 1), [0] * (n + 1) for u, v in c: if u == s: s0[get_root(v)] = 1 elif v == s: s0[get_root(u)] = 1 elif u == t: t0[get_root(v)] = 1 else: t0[get_root(u)] = 1 s1, t1 = [], [] for u, v in c: if u == s and not t0[get_root(v)] and not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) ds -= 1 elif v == s and not t0[get_root(u)] and not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) ds -= 1 elif u == t and not s0[get_root(v)] and not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) dt -= 1 elif v == t and not s0[get_root(u)] and not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) dt -= 1 elif not same(u, v) and (u == s or v == s): s1.append((u, v)) elif not same(u, v) and (u == t or v == t): t1.append((u, v)) for u, v in s1: if ds <= 0: break if not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) ds -= 1 for u, v in t1: if dt <= 0: break if not same(u, v): unite(u, v) ans.append(" ".join(map(str, (u, v)))) dt -= 1 if f and not same(s, t) and min(ds, dt) >= 1: unite(s, t) ans.append(" ".join(map(str, (s, t)))) ans0 = "Yes" if len(ans) == n - 1 and min(ds, dt) >= 0 else "No" print(ans0) if ans0 == "Yes": sys.stdout.write("\n".join(ans)) ```
370
Broken Monitor
Title: Broken Monitor Time Limit: None seconds Memory Limit: None megabytes Problem Description: Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus. Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention". Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that: - the frame's width is 1 pixel, - the frame doesn't go beyond the borders of the screen, - all white pixels of the monitor are located on the frame, - of all frames that satisfy the previous three conditions, the required frame must have the smallest size. Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is *d*<==<=3, then it consists of 8 pixels, if its size is *d*<==<=2, then it contains 4 pixels and if *d*<==<=1, then the frame is reduced to a single pixel. Input Specification: The first line contains the resolution of the monitor as a pair of integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=2000). The next *n* lines contain exactly *m* characters each — the state of the monitor pixels at the moment of the game. Character "." (period, ASCII code 46) corresponds to the black pixel, and character "w" (lowercase English letter w) corresponds to the white pixel. It is guaranteed that at least one pixel of the monitor is white. Output Specification: Print the monitor screen. Represent the sought frame by characters "+" (the "plus" character). The pixels that has become white during the game mustn't be changed. Print them as "w". If there are multiple possible ways to position the frame of the minimum size, print any of them. If the required frame doesn't exist, then print a single line containing number -1. Demo Input: ['4 8\n..w..w..\n........\n........\n..w..w..\n', '5 6\n......\n.w....\n......\n..w...\n......\n', '2 4\n....\n.w..\n', '2 6\nw..w.w\n...w..\n'] Demo Output: ['..w++w..\n..+..+..\n..+..+..\n..w++w..\n', '......\n+w+...\n+.+...\n++w...\n......\n', '....\n.w..\n', '-1\n'] Note: In the first sample the required size of the optimal frame equals 4. In the second sample the size of the optimal frame equals 3. In the third sample, the size of the optimal frame is 1. In the fourth sample, the required frame doesn't exist.
```python from itertools import chain def draw_square(ans, square_a, ymin, xmin) -> list: for i in range(square_a + 1): if(ans[ymin][xmin + i] != 'w'): ans[ymin] = ans[ymin][:xmin + i] + '+' + ans[ymin][xmin + i + 1:] if(ans[ymin + square_a][xmin + i] != 'w'): ans[ymin + square_a] = ans[ymin + square_a][:xmin + i] + '+' + ans[ymin + square_a][xmin + i + 1:] if(ans[ymin + i][xmin] != 'w'): ans[ymin + i] = ans[ymin + i][:xmin] + '+' + ans[ymin + i][xmin + 1:] if(ans[ymin + i][xmin + square_a] != 'w'): ans[ymin + i] = ans[ymin + i][:xmin + square_a] + '+' + ans[ymin + i][xmin + square_a + 1:] return ans def find_a(pixel, y, x) -> tuple: ymax = xmax = 0 ymin, xmin = y, x ymaxl, yminl, xmaxl, xminl = [], [], [], [] count_pixel = len(pixel) // 2 for i in range(count_pixel): if(ymax < pixel[2 * i]): ymax = pixel[2 * i] if(ymin > pixel[2 * i]): ymin = pixel[2 * i] if(xmax < pixel[2 * i + 1]): xmax = pixel[2 * i + 1] if(xmin > pixel[2 * i + 1]): xmin = pixel[2 * i + 1] for i in range(count_pixel): f = True if(pixel[2 * i] == ymax): f = False ymaxl.append(pixel[2 * i]) ymaxl.append(pixel[2 * i + 1]) if(pixel[2 * i] == ymin): f = False yminl.append(pixel[2 * i]) yminl.append(pixel[2 * i + 1]) if(pixel[2 * i + 1] == xmax): f = False xmaxl.append(pixel[2 * i]) xmaxl.append(pixel[2 * i + 1]) if(pixel[2 * i + 1] == xmin): f = False xminl.append(pixel[2 * i]) xminl.append(pixel[2 * i + 1]) if(f): print('-1') exit() return ymax, ymin, xmax, xmin, ymaxl, yminl, xmaxl, xminl if __name__ == '__main__': y, x = map(int, input().split()) scr = [] for i in range(y): scr.append(input()) pixel = [] for i in range(y): for j in range(x): if(scr[i][j] == 'w'): pixel.append(i) pixel.append(j) ymax, ymin, xmax, xmin, ymaxl, yminl, xmaxl, xminl = find_a(pixel, y, x) count_ymax, count_ymin, count_xmax, count_xmin = len(ymaxl)/2, len(yminl)/2, len(xmaxl)/2, len(xminl)/2 countx_ymax = ymaxl[1::2].count(xmax) + ymaxl[1::2].count(xmin) countx_ymin = yminl[1::2].count(xmax) + yminl[1::2].count(xmin) county_xmax = xmaxl[::2].count(ymax) + xmaxl[::2].count(ymin) county_xmin = xminl[::2].count(ymax) + xminl[::2].count(ymin) if(ymax - ymin > xmax - xmin): square_a = ymax - ymin if(county_xmax < count_xmax and county_xmin < count_xmin): if(xmax == xmin): if(xmin + square_a < x): xmax = xmin + square_a elif(xmax - square_a >= 0): xmin = xmax - square_a else: print('-1') exit() else: print('-1') exit() elif(county_xmax < count_xmax and county_xmin == count_xmin): xmin = xmax - square_a if(xmin < 0): print('-1') exit() elif(county_xmax == count_xmax and county_xmin < count_xmin): xmax = xmin + square_a if(xmax >= x): print('-1') exit() elif(county_xmax == count_xmax and county_xmin == count_xmin): if(square_a < x): if(xmin + square_a < x): xmax = xmin + square_a elif(xmax - square_a >= 0): xmin = xmax - square_a else: xmin = 0 xmax = xmin + square_a else: print('-1') exit() elif(ymax - ymin < xmax - xmin): square_a = xmax - xmin if(countx_ymax < count_ymax and countx_ymin < count_ymin): if(ymax == ymin): if(ymin + square_a < y): ymax = ymin + square_a elif(ymax - square_a >= 0): ymin = ymax - square_a else: print('-1') exit() else: print('-1') exit() elif(countx_ymax < count_ymax and countx_ymin == count_ymin): ymin = ymax - square_a if(ymin < 0): print('-1') exit() elif(countx_ymax == count_ymax and countx_ymin < count_ymin): ymax = ymin + square_a if(ymax >= y): print('-1') exit() elif(countx_ymax == count_ymax and countx_ymin == count_ymin): if(square_a < y): if(ymin + square_a < y): ymax = ymin + square_a elif(ymax - square_a >= 0): ymin = ymax -square_a else: ymin = 0 ymax = ymin + square_a else: print('-1') exit() elif(ymax - ymin == xmax - xmin): square_a = xmax - xmin ans = draw_square(scr, square_a, ymin, xmin) for i in range(y): print(ans[i]) ```
340
Maximal Area Quadrilateral
Title: Maximal Area Quadrilateral Time Limit: None seconds Memory Limit: None megabytes Problem Description: Iahub has drawn a set of *n* points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral. Input Specification: The first line contains integer *n* (4<=≤<=*n*<=≤<=300). Each of the next *n* lines contains two integers: *x**i*, *y**i* (<=-<=1000<=≤<=*x**i*,<=*y**i*<=≤<=1000) — the cartesian coordinates of *i*th special point. It is guaranteed that no three points are on the same line. It is guaranteed that no two points coincide. Output Specification: Output a single real number — the maximal area of a special quadrilateral. The answer will be considered correct if its absolute or relative error does't exceed 10<=-<=9. Demo Input: ['5\n0 0\n0 4\n4 0\n4 4\n2 3\n'] Demo Output: ['16.000000'] Note: In the test example we can choose first 4 points to be the vertices of the quadrilateral. They form a square by side 4, so the area is 4·4 = 16.
```python import sys s, n = 0, int(input()) t = list(map(int, sys.stdin.read().split())) p = [(t[2 * i], t[2 * i + 1]) for i in range(n)] for x, i in enumerate(p, 1): for j in p[x:]: a = b = 0 for k in p: d = (i[0] - k[0]) * (j[1] - k[1]) - (i[1] - k[1]) * (j[0] - k[0]) a, b = min(d, a), max(d, b) if a and b: s = max(s, b - a) print(s / 2) ```
501
Misha and Permutations Summation
Title: Misha and Permutations Summation Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's define the sum of two permutations *p* and *q* of numbers 0,<=1,<=...,<=(*n*<=-<=1) as permutation , where *Perm*(*x*) is the *x*-th lexicographically permutation of numbers 0,<=1,<=...,<=(*n*<=-<=1) (counting from zero), and *Ord*(*p*) is the number of permutation *p* in the lexicographical order. For example, *Perm*(0)<==<=(0,<=1,<=...,<=*n*<=-<=2,<=*n*<=-<=1), *Perm*(*n*!<=-<=1)<==<=(*n*<=-<=1,<=*n*<=-<=2,<=...,<=1,<=0) Misha has two permutations, *p* and *q*. Your task is to find their sum. Permutation *a*<==<=(*a*0,<=*a*1,<=...,<=*a**n*<=-<=1) is called to be lexicographically smaller than permutation *b*<==<=(*b*0,<=*b*1,<=...,<=*b**n*<=-<=1), if for some *k* following conditions hold: *a*0<==<=*b*0,<=*a*1<==<=*b*1,<=...,<=*a**k*<=-<=1<==<=*b**k*<=-<=1,<=*a**k*<=&lt;<=*b**k*. Input Specification: The first line contains an integer *n* (1<=≤<=*n*<=≤<=200<=000). The second line contains *n* distinct integers from 0 to *n*<=-<=1, separated by a space, forming permutation *p*. The third line contains *n* distinct integers from 0 to *n*<=-<=1, separated by spaces, forming permutation *q*. Output Specification: Print *n* distinct integers from 0 to *n*<=-<=1, forming the sum of the given permutations. Separate the numbers by spaces. Demo Input: ['2\n0 1\n0 1\n', '2\n0 1\n1 0\n', '3\n1 2 0\n2 1 0\n'] Demo Output: ['0 1\n', '1 0\n', '1 0 2\n'] Note: Permutations of numbers from 0 to 1 in the lexicographical order: (0, 1), (1, 0). In the first sample *Ord*(*p*) = 0 and *Ord*(*q*) = 0, so the answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8ce4cd76db7c3f712f9101b410c36891976581b8.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample *Ord*(*p*) = 0 and *Ord*(*q*) = 1, so the answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5684e4e2deb5ed60419a5c9e765f0cd4cb995652.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Permutations of numbers from 0 to 2 in the lexicographical order: (0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0). In the third sample *Ord*(*p*) = 3 and *Ord*(*q*) = 5, so the answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/da14f774ebda9f417649f5334d329ec7b7c07778.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
```python import sys class SegmTree(): def __init__(self, array=None): size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) for i in range(size): self.tree[i+self.N] = array[i] self.build() def build(self): for i in range(self.N - 1, 0, -1): self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1] def add(self, i, value=1): i += self.N while i > 0: self.tree[i] += value i >>= 1 def get_sum(self, l, r): N = self.N l += N r += N result = 0 while l < r: if l & 1: result += self.tree[l] l += 1 if r & 1: r -= 1 result += self.tree[r] l >>= 1 r >>= 1 return result def find_kth_nonzero(self, k): i = 1 if k < 1 or k > self.tree[1]: return -1 while i < self.N: i <<= 1 if self.tree[i] < k: k -= self.tree[i] i |= 1 return i - self.N reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) p = list(map(int, input().split())) q = list(map(int, input().split())) ord_p = [0] * n ord_q = [0] * n st = SegmTree([1] * n) for i, val in enumerate(p): ord_p[i] = st.get_sum(0, val) st.add(val, -1) st = SegmTree([1] * n) for i, val in enumerate(q): ord_q[i] = st.get_sum(0, val) st.add(val, -1) transfer = 0 for i in range(n-1, -1, -1): radix = n-i ord_p[i] = ord_p[i] + ord_q[i] + transfer if ord_p[i] < radix: transfer = 0 else: transfer = 1 ord_p[i] -= radix st = SegmTree([1] * n) for i in range(n): k = ord_p[i] + 1 ord_q[i] = st.find_kth_nonzero(k) st.add(ord_q[i], -1) print(*ord_q) ```
515
Drazil and Park
Title: Drazil and Park Time Limit: None seconds Memory Limit: None megabytes Problem Description: Drazil is a monkey. He lives in a circular park. There are *n* trees around the park. The distance between the *i*-th tree and (*i*<=+<=1)-st trees is *d**i*, the distance between the *n*-th tree and the first tree is *d**n*. The height of the *i*-th tree is *h**i*. Drazil starts each day with the morning run. The morning run consists of the following steps: - Drazil chooses two different trees - He starts with climbing up the first tree - Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it - Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees. If the two trees Drazil chooses are *x*-th and *y*-th, we can estimate the energy the morning run takes to him as 2(*h**x*<=+<=*h**y*)<=+<=*dist*(*x*,<=*y*). Since there are children on exactly one of two arcs connecting *x* and *y*, the distance *dist*(*x*,<=*y*) between trees *x* and *y* is uniquely defined. Now, you know that on the *i*-th day children play between *a**i*-th tree and *b**i*-th tree. More formally, if *a**i*<=≤<=*b**i*, children play around the trees with indices from range [*a**i*,<=*b**i*], otherwise they play around the trees with indices from . Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day. Input Specification: The first line contains two integer *n* and *m* (3<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=≤<=105), denoting number of trees and number of days, respectively. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d**i*<=≤<=109), the distances between consecutive trees. The third line contains *n* integers *h*1,<=*h*2,<=...,<=*h**n* (1<=≤<=*h**i*<=≤<=109), the heights of trees. Each of following *m* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children. Output Specification: For each day print the answer in a separate line. Demo Input: ['5 3\n2 2 2 2 2\n3 5 2 1 4\n1 3\n2 2\n4 5\n', '3 3\n5 1 4\n5 1 4\n3 3\n2 2\n1 1\n'] Demo Output: ['12\n16\n18\n', '17\n22\n11\n'] Note: none
```python from math import inf import sys input = lambda: sys.stdin.readline().rstrip("\r\n") fast_print = lambda p: sys.stdout.write(str(p) + "\n") n, m = [int(component) for component in input().split(" ")] d = [int(component) for component in input().split(" ")] h = [int(component) for component in input().split(" ")] ### prefix work def get_prefix_sums(arr): prefix = [0] * (len(arr)+1) for index in range(1,len(arr)+1): prefix[index] = prefix[index-1] + arr[index-1] return prefix prefix = get_prefix_sums(d) def get_dist(l, r): # print(f" called with {(l, r)}") return prefix[r] - prefix[l] def merge(s1, s2): # print(f" merge called with {s1} and {s2}") if s1 == None: return s2 if s2 == None: return s1 # if s1[3] > s2[3]: # s1, s2 = s2, s1 # print(f" reordered: {s1} and {s2}") llbm, lrbm, lism, ll, lr = s1 rlbm, rrbm, rism, rl, rr = s2 nlbm = max(llbm, get_dist(ll, rl) + rlbm) nrbm = max(lrbm + get_dist(lr, rr), rrbm) nism = max(lism, lrbm + get_dist(lr, rl) + rlbm, rism) return nlbm, nrbm, nism, ll, rr def make_segment_tree(d, h): N = len(d) size = 1 << (N-1).bit_length() tree = [None] * (2*size) for k in range(N): tree[size+k] = (2*h[k], 2*h[k], -inf, k, k) for k in range(size-1,0,-1): tree[k] = merge(tree[2*k], tree[2*k+1]) return tree def range_query(tree, l, r): # print(f"\nrange_query received {(l, r)}") lres = None rres = None l += len(tree) >> 1 r += (len(tree) >> 1) + 1 while l < r: if l & 1: # print(f" l & 1") lres = merge(lres, tree[l]) # print(f" now lres = {lres}") l += 1 if r & 1: # print(f" r & 1") r -= 1 rres = merge(tree[r], rres) # print(f" now rres = {rres}") l >>= 1 r >>= 1 res = merge(lres, rres) # print(f" final res = {res}") return res tree = make_segment_tree(d, h) # print() # print(tree) def complex_query(l, r): # print(f"received {(l, r)}") if l <= r: # print("l <= r") if l > 0 and r < n-1: # print("l > 0, r < n-1") llbm, _, lism, _, _ = range_query(tree, 0, l-1) # print(f"llbm = {llbm}, lism = {lism}") _, rrbm, rism, _, _ = range_query(tree, r+1, n-1) # print(f"rrbm = {rrbm}, rism = {rism}") return max(lism, rism, llbm + d[-1] + rrbm) elif l == 0: # print("l == 0") _, _, ism, _, _ = range_query(tree, r+1, n-1) return ism else: # print(f"r == {n-1}") _, _, ism, _, _ = range_query(tree, 0, l-1) return ism else: _, _, ism, _, _ = range_query(tree, r+1, l-1) return ism # print(m, m, d, h) for _ in range(m): a, b = [int(component) for component in input().split(" ")] fast_print(complex_query(a-1, b-1)) ```