name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p01459 Light Road
There is an evil creature in a square on N-by-M grid (2 \leq N, M \leq 100), and you want to kill it using a laser generator located in a different square. Since the location and direction of the laser generator are fixed, you may need to use several mirrors to reflect laser beams. There are some obstacles on the grid and you have a limited number of mirrors. Please find out whether it is possible to kill the creature, and if possible, find the minimum number of mirrors. There are two types of single-sided mirrors; type P mirrors can be placed at the angle of 45 or 225 degrees from east-west direction, and type Q mirrors can be placed with at the angle of 135 or 315 degrees. For example, four mirrors are located properly, laser go through like the following. <image> Note that mirrors are single-sided, and thus back side (the side with cross in the above picture) is not reflective. You have A type P mirrors, and also A type Q mirrors (0 \leq A \leq 10). Although you cannot put mirrors onto the squares with the creature or the laser generator, laser beam can pass through the square. Evil creature is killed if the laser reaches the square it is in. Input Each test case consists of several lines. The first line contains three integers, N, M, and A. Each of the following N lines contains M characters, and represents the grid information. '#', '.', 'S', 'G' indicates obstacle, empty square, the location of the laser generator, and the location of the evil creature, respectively. The first line shows the information in northernmost squares and the last line shows the information in southernmost squares. You can assume that there is exactly one laser generator and exactly one creature, and the laser generator emits laser beam always toward the south. Output Output the minimum number of mirrors used if you can kill creature, or -1 otherwise. Examples Input 3 3 2 S#. ... .#G Output 2 Input 3 3 1 S#. ... .#G Output -1 Input 3 3 1 S#G ... .#. Output 2 Input 4 3 2 S.. ... ..# .#G Output -1
```python from collections import deque N, M, A = map(int, input().split()) MP = [[0]*M for i in range(N)] sx = sy = gx = gy = -1 for i in range(N): for j, c in enumerate(input()): if c == '#': MP[i][j] = 1 elif c == 'S': sx = j; sy = i elif c == 'G': gx = j; gy = i U = [[set() for i in range(M)] for j in range(N)] DD = ((-1, 0), (0, -1), (1, 0), (0, 1)) que = deque([(sx, sy, 0, 0, 3)]) for i in range(A+1): for j in range(A+1): U[sy][sx].add((i, j, 1)) U[sy][sx].add((i, j, 3)) pp = ((sx, sy), (gx, gy)) while que: x, y, a, b, d = que.popleft() if (x, y) not in pp: d0 = (d-1) % 4 dx, dy = DD[d0] nx = x + dx; ny = y + dy if 0 <= nx < M and 0 <= ny < N and MP[ny][nx] == 0: if d % 2 == 0: if b < A and (a, b+1, d0) not in U[ny][nx]: U[ny][nx].add((a, b+1, d0)) que.append((nx, ny, a, b+1, d0)) else: if a < A and (a+1, b, d0) not in U[ny][nx]: U[ny][nx].add((a+1, b, d0)) que.append((nx, ny, a+1, b, d0)) d1 = (d+1) % 4 dx, dy = DD[d1] nx = x + dx; ny = y + dy if 0 <= nx < M and 0 <= ny < N and MP[ny][nx] == 0: if d % 2 == 0: if a < A and (a+1, b, d1) not in U[ny][nx]: U[ny][nx].add((a+1, b, d1)) que.append((nx, ny, a+1, b, d1)) else: if b < A and (a, b+1, d1) not in U[ny][nx]: U[ny][nx].add((a, b+1, d1)) que.append((nx, ny, a, b+1, d1)) dx, dy = DD[d] nx = x + dx; ny = y + dy if 0 <= nx < M and 0 <= ny < N and MP[ny][nx] == 0: if (a, b, d) not in U[ny][nx]: U[ny][nx].add((a, b, d)) que.append((nx, ny, a, b, d)) if U[gy][gx]: print(min(a+b for a, b, d in U[gy][gx])) else: print(-1) ```
p01905 Tournament
problem AOR Ika and you came to the tournament-style table tennis tournament singles section for reconnaissance. For AOR Ika-chan, who wants to record all the games, you decide to ask for the number of games that will be played in this tournament. There are $ N $ players in the tournament, each with a uniform number of $ 0, \ dots, N -1 $. Among them, $ M $ players abstained and did not participate in the match. The number of games in this tournament will be determined based on the following rules. * There are no seed players, and the number of wins required for any contestant to win is constant. * If the opponent is absent, the match will not be played and the player who participated will win. It is not counted in the number of games. * The tournament will end when the winner is decided. * A person who loses a match will not play the match again. In other words, there will be no repechage or third place playoff. * Since there is only one table tennis table, different games will not be played at the same time, and the winner will always be decided in each game (it will not be a draw). The definition of the tournament is as follows. The tournament is represented by a full binary tree with a height of $ L = \ log_2 N $, and each apex of the leaf has the participant's uniform number written on it. Assuming that the root depth is 0, in the $ i $ round ($ 1 \ le i \ le L $), the players with the numbers written on the children of each vertex of the depth $ L --i $ will play a match. Write the winner's uniform number at the top. <image> output Output the number of games played by the end of this tournament in one line. Also, output a line break at the end. Example Input 2 0 Output 1
```python N,M = map(int, input().split()) l = [] for i in range(M): l.append(int(input())) count = N - 1 - M print(count) ```
p02328 Largest Rectangle in a Histogram
A histogram is made of a number of contiguous bars, which have same width. For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area. Constraints * $1 \leq N \leq 10^5$ * $0 \leq h_i \leq 10^9$ Input The input is given in the following format. $N$ $h_1$ $h_2$ ... $h_N$ Output Print the area of the largest rectangle. Examples Input 8 2 1 3 5 3 4 2 1 Output 12 Input 3 2 0 1 Output 2
```python """ Writer:SPD_9X2 http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_3_C&lang=ja ヒストグラム上の最大長方形 またdpかな…? 参考: http://algorithms.blog55.fc2.com/blog-entry-132.html """ #最後に要素0を追加してくこと def Largest_rectangle_in_histgram(lis): stk = [] ans = 0 N = len(lis) for i in range(N): if len(stk) == 0: stk.append((lis[i],i)) elif stk[-1][0] < lis[i]: stk.append((lis[i],i)) elif stk[-1][0] == lis[i]: pass else: lastpos = None while len(stk) > 0 and stk[-1][0] > lis[i]: nh,np = stk[-1] lastpos = np del stk[-1] ans = max(ans , nh*(i-np)) stk.append((lis[i] , lastpos)) return ans N = int(input()) h = list(map(int,input().split())) h.append(0) print (Largest_rectangle_in_histgram(h)) ```
p02473 Difference of Big Integers
Difference of Big Integers Given two integers $A$ and $B$, compute the difference, $A - B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the difference in a line. Constraints * $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample Output 1 -3 Sample Input 2 100 25 Sample Output 2 75 Sample Input 3 -1 -1 Sample Output 3 0 Sample Input 4 12 -3 Sample Output 4 15 Example Input 5 8 Output -3
```python A, B = map(int, input().split()) print(A - B) ```
1016_A. Death Note
You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during n consecutive days. During the i-th day you have to write exactly a_i names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?). Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly m names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page. Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from 1 to n. Input The first line of the input contains two integers n, m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 10^9) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i means the number of names you will write in the notebook during the i-th day. Output Print exactly n integers t_1, t_2, ..., t_n, where t_i is the number of times you will turn the page during the i-th day. Examples Input 3 5 3 7 9 Output 0 2 1 Input 4 20 10 9 19 2 Output 0 0 1 1 Input 1 100 99 Output 0 Note In the first example pages of the Death Note will look like this [1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.
```python (n,m) = tuple(map(int, input().split(" "))) x = list(map(int, input().split(" "))) nib = 0 ans = [] cou = 0; for i in x: nib+=i if (nib<m): ans.append(nib//m) else: ans.append(nib//m) nib-=(nib//m)*m print (*ans) ```
103_A. Testing Pants for Sadness
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness". The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves. Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case? Input The first line contains a positive integer n (1 ≤ n ≤ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 ≤ ai ≤ 109), the number of answer variants to question i. Output Print a single number — the minimal number of clicks needed to pass the test it the worst-case scenario. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. Examples Input 2 1 1 Output 2 Input 2 2 2 Output 5 Input 1 10 Output 10 Note Note to the second sample. In the worst-case scenario you will need five clicks: * the first click selects the first variant to the first question, this answer turns out to be wrong. * the second click selects the second variant to the first question, it proves correct and we move on to the second question; * the third click selects the first variant to the second question, it is wrong and we go back to question 1; * the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; * the fifth click selects the second variant to the second question, it proves correct, the test is finished.
```python import sys,math s = int(input()) arr = list(map(int,input().split(' '))) m = 0 for i in range(0,s): m+=(arr[i]-1)*(i+1)+1 print(m) ''' 2 2 2 1+1 2 1+1+1 3 (1+1+1,1) 4 3 3 1+1+1 3 1+1+1+1+1 5 1+1+1,1+1+1,1 7 3 2 4 1 1+1 1+1+1+1+1+1+1 1 1+1+1+1 ''' ```
1062_B. Math
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer n, you can perform the following operations zero or more times: * mul x: multiplies n by x (where x is an arbitrary positive integer). * sqrt: replaces n with √{n} (to apply this operation, √{n} must be an integer). You can perform these operations as many times as you like. What is the minimum value of n, that can be achieved and what is the minimum number of operations, to achieve that minimum value? Apparently, no one in the class knows the answer to this problem, maybe you can help them? Input The only line of the input contains a single integer n (1 ≤ n ≤ 10^6) — the initial number. Output Print two integers: the minimum integer n that can be achieved using the described operations and the minimum number of operations required. Examples Input 20 Output 10 2 Input 5184 Output 6 4 Note In the first example, you can apply the operation mul 5 to get 100 and then sqrt to get 10. In the second example, you can first apply sqrt to get 72, then mul 18 to get 1296 and finally two more sqrt and you get 6. Note, that even if the initial value of n is less or equal 10^6, it can still become greater than 10^6 after applying one or more operations.
```python import math def sieve(n): mark = [0]*(n+1) prime = [] for i in range(3, n+1, 2): if not mark[i]: for j in range(3*i, n+1, i+i): mark[j] = 1 prime.append(2) for i in range(3, n+1, 2): if not mark[i]: prime.append(i) return prime def ispowerof2(x): if x and not (x & (x-1)): return 0 else: return 1 n = int(input()) #h = n prime = sieve(n) l = [] countp = 0 ans = 1 for i in prime: countp = 0 if n % i == 0: ans *= i while n % i == 0: n //= i countp += 1 l.append(countp) if n == 1: break if len(l) != 0: maxp = max(l) else: maxp = 0 flag = 0 for i in l: if i != maxp: flag = 1 temp = 0 if flag: temp = 1 else: temp = ispowerof2(maxp) if maxp == 1: maxp -= 1 elif maxp != 0: maxp = math.ceil(math.log2(maxp)) + temp print(ans, maxp) ```
1084_A. The Fair Nut and Elevator
The Fair Nut lives in n story house. a_i people live on the i-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening. It was decided that elevator, when it is not used, will stay on the x-th floor, but x hasn't been chosen yet. When a person needs to get from floor a to floor b, elevator follows the simple algorithm: * Moves from the x-th floor (initially it stays on the x-th floor) to the a-th and takes the passenger. * Moves from the a-th floor to the b-th floor and lets out the passenger (if a equals b, elevator just opens and closes the doors, but still comes to the floor from the x-th floor). * Moves from the b-th floor back to the x-th. The elevator never transposes more than one person and always goes back to the floor x before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the a-th floor to the b-th floor requires |a - b| units of electricity. Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the x-th floor. Don't forget than elevator initially stays on the x-th floor. Input The first line contains one integer n (1 ≤ n ≤ 100) — the number of floors. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 100) — the number of people on each floor. Output In a single line, print the answer to the problem — the minimum number of electricity units. Examples Input 3 0 2 1 Output 16 Input 2 1 1 Output 4 Note In the first example, the answer can be achieved by choosing the second floor as the x-th floor. Each person from the second floor (there are two of them) would spend 4 units of electricity per day (2 to get down and 2 to get up), and one person from the third would spend 8 units of electricity per day (4 to get down and 4 to get up). 4 ⋅ 2 + 8 ⋅ 1 = 16. In the second example, the answer can be achieved by choosing the first floor as the x-th floor.
```python n = int(input()) arr = list(map(int, input().split())) cur = 0 ans = 100000000 for x in range(n): cur = 0 for i in range(n): summ = 0 summ += abs(x - i) summ += i summ += x summ += x summ += i summ += abs(x - i) summ *= arr[i] cur += summ if cur < ans: ans = cur print(ans) ```
1131_C. Birthday
Cowboy Vlad has a birthday today! There are n children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible. Formally, let's number children from 1 to n in a circle order, that is, for every i child with number i will stand next to the child with number i+1, also the child with number 1 stands next to the child with number n. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other. Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of the children who came to the cowboy Vlad's birthday. The second line contains integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) denoting heights of every child. Output Print exactly n integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them. Examples Input 5 2 1 1 3 2 Output 1 2 3 2 1 Input 3 30 10 20 Output 10 20 30 Note In the first example, the discomfort of the circle is equal to 1, since the corresponding absolute differences are 1, 1, 1 and 0. Note, that sequences [2, 3, 2, 1, 1] and [3, 2, 1, 1, 2] form the same circles and differ only by the selection of the starting point. In the second example, the discomfort of the circle is equal to 20, since the absolute difference of 10 and 30 is equal to 20.
```python n = int(input()) arr = [int(i) for i in input().split()] arr1, arr2 = [], [] arr.sort(reverse = True) for i in range(n): if i%2==0: arr1.append(arr[i]) else: arr2.append(arr[i]) arr2.reverse() for i in arr2: arr1.append(i) print(*arr1) ```
1151_E. Number of Components
The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of n vertices. Each vertex i has its own value a_i. All vertices are connected in series by edges. Formally, for every 1 ≤ i < n there is an edge between the vertices of i and i+1. Denote the function f(l, r), which takes two integers l and r (l ≤ r): * We leave in the tree only vertices whose values ​​range from l to r. * The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$∑_{l=1}^{n} ∑_{r=l}^{n} f(l, r) $$$ Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of vertices in the tree. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the values of the vertices. Output Print one number — the answer to the problem. Examples Input 3 2 1 3 Output 7 Input 4 2 1 1 3 Output 11 Input 10 1 5 2 5 5 3 10 6 5 1 Output 104 Note In the first example, the function values ​​will be as follows: * f(1, 1)=1 (there is only a vertex with the number 2, which forms one component) * f(1, 2)=1 (there are vertices 1 and 2 that form one component) * f(1, 3)=1 (all vertices remain, one component is obtained) * f(2, 2)=1 (only vertex number 1) * f(2, 3)=2 (there are vertices 1 and 3 that form two components) * f(3, 3)=1 (only vertex 3) Totally out 7. In the second example, the function values ​​will be as follows: * f(1, 1)=1 * f(1, 2)=1 * f(1, 3)=1 * f(1, 4)=1 * f(2, 2)=1 * f(2, 3)=2 * f(2, 4)=2 * f(3, 3)=1 * f(3, 4)=1 * f(4, 4)=0 (there is no vertex left, so the number of components is 0) Totally out 11.
```python n = int(input()) + 1 res = 0 a = tuple(map(int, input().split())) for ai in a: res += ai * (n - ai) for ai, aj in map(sorted, zip(a, a[1:])): res -= ai * (n - aj) print(res) # ```
1173_D. Nauuo and Circle
Nauuo is a girl who loves drawing circles. One day she has drawn a circle and wanted to draw a tree on it. The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n. Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other. "Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges. Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once. After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes. The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her? It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen. Input The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v. It is guaranteed that the given edges form a tree. Output The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353. Examples Input 4 1 2 1 3 2 4 Output 16 Input 4 1 2 1 3 1 4 Output 24 Note Example 1 All valid permutations and their spanning trees are as follows. <image> Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed. <image> Example 2 Every permutation leads to a valid tree, so the answer is 4! = 24.
```python import sys n = int(sys.stdin.readline().strip()) D = [0] * n p = 998244353 for i in range (0, n - 1): u, v = list(map(int, sys.stdin.readline().strip().split())) D[u-1] = D[u-1] + 1 D[v-1] = D[v-1] + 1 ans = n for i in range (0, n): for j in range (0, D[i]): ans = (ans * (j + 1)) % p print(ans) ```
1191_A. Tokitsukaze and Enhancement
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP. In general, different values of HP are grouped into 4 categories: * Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is 1; * Category B if HP is in the form of (4 n + 3), that is, when divided by 4, the remainder is 3; * Category C if HP is in the form of (4 n + 2), that is, when divided by 4, the remainder is 2; * Category D if HP is in the form of 4 n, that is, when divided by 4, the remainder is 0. The above-mentioned n can be any integer. These 4 categories ordered from highest to lowest as A > B > C > D, which means category A is the highest and category D is the lowest. While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most 2 (that is, either by 0, 1 or 2). How much should she increase her HP so that it has the highest possible category? Input The only line contains a single integer x (30 ≤ x ≤ 100) — the value Tokitsukaze's HP currently. Output Print an integer a (0 ≤ a ≤ 2) and an uppercase letter b (b ∈ { A, B, C, D }), representing that the best way is to increase her HP by a, and then the category becomes b. Note that the output characters are case-sensitive. Examples Input 33 Output 0 A Input 98 Output 1 B Note For the first example, the category of Tokitsukaze's HP is already A, so you don't need to enhance her ability. For the second example: * If you don't increase her HP, its value is still 98, which equals to (4 × 24 + 2), and its category is C. * If you increase her HP by 1, its value becomes 99, which equals to (4 × 24 + 3), and its category becomes B. * If you increase her HP by 2, its value becomes 100, which equals to (4 × 25), and its category becomes D. Therefore, the best way is to increase her HP by 1 so that the category of her HP becomes B.
```python n=int(input()) d={} d[0]='1 A' d[1]='0 A' d[2]='1 B' d[3]='2 A' x=n%4 print(d[x]) ```
122_D. Lucky Transformation
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≤ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations. Input The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 109) — the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero. Output In the single line print the result without spaces — the number after the k operations are fulfilled. Examples Input 7 4 4727447 Output 4427477 Input 4 2 4478 Output 4478 Note In the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477. In the second sample: 4478 → 4778 → 4478.
```python n, k = map(int, input().split()) s = list(input()) cnt = 0 for i in range(n - 1): if cnt == k: break if s[i] == '4' and s[i + 1] == '7': if i & 1: if s[i - 1] == '4': if (cnt - k) & 1: s[i] = '7' print(''.join(s)) exit() s[i] = '7' else: if i != n - 2: if s[i + 2] == '7': if (cnt - k) & 1: s[i + 1] = '4' print(''.join(s)) exit() s[i + 1] = '4' cnt += 1 print(''.join(s)) ```
1251_C. Minimize The Integer
You are given a huge integer a consisting of n digits (n is between 1 and 3 ⋅ 10^5, inclusive). It may contain leading zeros. You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032867235 you can get the following integers in a single operation: * 302867235 if you swap the first and the second digits; * 023867235 if you swap the second and the third digits; * 032876235 if you swap the fifth and the sixth digits; * 032862735 if you swap the sixth and the seventh digits; * 032867325 if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions 2 and 4 because the positions are not adjacent. Also, you can't swap digits on positions 3 and 4 because the digits have the same parity. You can perform any number (possibly, zero) of such operations. Find the minimum integer you can obtain. Note that the resulting integer also may contain leading zeros. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. The only line of each test case contains the integer a, its length n is between 1 and 3 ⋅ 10^5, inclusive. It is guaranteed that the sum of all values n does not exceed 3 ⋅ 10^5. Output For each test case print line — the minimum integer you can obtain. Example Input 3 0709 1337 246432 Output 0079 1337 234642 Note In the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): 0 \underline{70} 9 → 0079. In the second test case, the initial integer is optimal. In the third test case you can perform the following sequence of operations: 246 \underline{43} 2 → 24 \underline{63}42 → 2 \underline{43} 642 → 234642.
```python # -*- coding: utf-8 -*- """ Created on Fri Nov 1 14:39:37 2019 @author: uditg """ ans={} test=int(input()) for each in range(test): num=input() n=len(num) num={i:int(num[i]) for i in range(n)} output={} even={} odd={} even_count=0 odd_count=0 for i in range(n): if num[i]%2==0: even[even_count]=num[i] even_count+=1 else: odd[odd_count]=num[i] odd_count+=1 num={} #print("even",even,"and",odd,"\n") i=0 j=0 count=0 while even and odd: output[count]=(min(even[i],odd[j])) if min(even[i],odd[j])==even[i]: del even[i] i+=1 else: del odd[j] j+=1 count+=1 if even: for every in range(i,max(even.keys())+1): output[count]=even[every] count+=1 #output+=[even[every] for every in range(i,max(even.keys())+1)] if odd: for every in range(j,max(odd.keys())+1): output[count]=odd[every] #print(output[count]) count+=1 #output+=[odd[every] for every in range(j,max(odd.keys())+1)] outputs=[str(output[me]) for me in range(max(output.keys())+1)] ans[each]="".join(outputs) for each in range(test): print(ans[each]) ```
1271_A. Suits
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets. The store does not sell single clothing items — instead, it sells suits of two types: * a suit of the first type consists of one tie and one jacket; * a suit of the second type consists of one scarf, one vest and one jacket. Each suit of the first type costs e coins, and each suit of the second type costs f coins. Calculate the maximum possible cost of a set of suits that can be composed from the delivered clothing items. Note that one item cannot be used in more than one suit (though some items may be left unused). Input The first line contains one integer a (1 ≤ a ≤ 100 000) — the number of ties. The second line contains one integer b (1 ≤ b ≤ 100 000) — the number of scarves. The third line contains one integer c (1 ≤ c ≤ 100 000) — the number of vests. The fourth line contains one integer d (1 ≤ d ≤ 100 000) — the number of jackets. The fifth line contains one integer e (1 ≤ e ≤ 1 000) — the cost of one suit of the first type. The sixth line contains one integer f (1 ≤ f ≤ 1 000) — the cost of one suit of the second type. Output Print one integer — the maximum total cost of some set of suits that can be composed from the delivered items. Examples Input 4 5 6 3 1 2 Output 6 Input 12 11 13 20 4 6 Output 102 Input 17 14 5 21 15 17 Output 325 Note It is possible to compose three suits of the second type in the first example, and their total cost will be 6. Since all jackets will be used, it's impossible to add anything to this set. The best course of action in the second example is to compose nine suits of the first type and eleven suits of the second type. The total cost is 9 ⋅ 4 + 11 ⋅ 6 = 102.
```python a = int(input()) b = int(input()) c = int(input()) d = int(input()) c1 = int(input()) c2 = int(input()) p = 0 if c2 > c1: m = min(b,c,d) b -= m c -= m d -= m p += m * c2 if d > 0: p += (min(a,d) * c1) else: m = min(a,d) a -= m d -= m p += m * c1 if d > 0: p += (min(b,c,d) * c2) print(p) ```
1294_B. Collecting Packages
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0, 0) doesn't contain a package. The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x, y) to the point (x + 1, y) or to the point (x, y + 1). As we say above, the robot wants to collect all n packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path. The string s of length n is lexicographically less than the string t of length n if there is some index 1 ≤ j ≤ n that for all i from 1 to j-1 s_i = t_i and s_j < t_j. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way. Input The first line of the input contains an integer t (1 ≤ t ≤ 100) — the number of test cases. Then test cases follow. The first line of a test case contains one integer n (1 ≤ n ≤ 1000) — the number of packages. The next n lines contain descriptions of packages. The i-th package is given as two integers x_i and y_i (0 ≤ x_i, y_i ≤ 1000) — the x-coordinate of the package and the y-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0, 0) doesn't contain a package. The sum of all values n over test cases in the test doesn't exceed 1000. Output Print the answer for each test case. If it is impossible to collect all n packages in some order starting from (0,0), print "NO" on the first line. Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable. Example Input 3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 Output YES RUUURRRRUU NO YES RRRRUUU Note For the first test case in the example the optimal path RUUURRRRUU is shown below: <image>
```python t=int(input()) for q in range(t): n=int(input()) a=[list(map(int,input().split())) for i in range(n)] a.sort() ans="" x,y=0,0 f=0 for i in range(n): if a[i][0]>=x and a[i][1]>=y: ans+='R'*(a[i][0]-x) x=a[i][0] ans+='U'*(a[i][1]-y) y=a[i][1] else: f=1 print('NO') break if f==0: print('YES') print(ans) ```
1315_B. Homecoming
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad. The crossroads are represented as a string s of length n, where s_i = A, if there is a bus station at i-th crossroad, and s_i = B, if there is a tram station at i-th crossroad. Currently Petya is at the first crossroad (which corresponds to s_1) and his goal is to get to the last crossroad (which corresponds to s_n). If for two crossroads i and j for all crossroads i, i+1, …, j-1 there is a bus station, one can pay a roubles for the bus ticket, and go from i-th crossroad to the j-th crossroad by the bus (it is not necessary to have a bus station at the j-th crossroad). Formally, paying a roubles Petya can go from i to j if s_t = A for all i ≤ t < j. If for two crossroads i and j for all crossroads i, i+1, …, j-1 there is a tram station, one can pay b roubles for the tram ticket, and go from i-th crossroad to the j-th crossroad by the tram (it is not necessary to have a tram station at the j-th crossroad). Formally, paying b roubles Petya can go from i to j if s_t = B for all i ≤ t < j. For example, if s="AABBBAB", a=4 and b=3 then Petya needs: <image> * buy one bus ticket to get from 1 to 3, * buy one tram ticket to get from 3 to 6, * buy one bus ticket to get from 6 to 7. Thus, in total he needs to spend 4+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character s_n) does not affect the final expense. Now Petya is at the first crossroad, and he wants to get to the n-th crossroad. After the party he has left with p roubles. He's decided to go to some station on foot, and then go to home using only public transport. Help him to choose the closest crossroad i to go on foot the first, so he has enough money to get from the i-th crossroad to the n-th, using only tram and bus tickets. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). The first line of each test case consists of three integers a, b, p (1 ≤ a, b, p ≤ 10^5) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string s, where s_i = A, if there is a bus station at i-th crossroad, and s_i = B, if there is a tram station at i-th crossroad (2 ≤ |s| ≤ 10^5). It is guaranteed, that the sum of the length of strings s by all test cases in one test doesn't exceed 10^5. Output For each test case print one number — the minimal index i of a crossroad Petya should go on foot. The rest of the path (i.e. from i to n he should use public transport). Example Input 5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB Output 2 1 3 1 6
```python t = int(input()) for _ in range(t): a, b, p = map(int, input().split()) s = input() d = {'A': a, 'B': b} i = len(s)-1 prev = len(s)-1 while i >= 0: i -= 1 curr = s[i] while s[i] == curr and i >= 0: i -= 1 i += 1 p -= d[curr] if p < 0: break prev = i print(prev+1) ```
1336_E1. Chiori and Doll Picking (easy version)
This is the easy version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved. Chiori loves dolls and now she is going to decorate her bedroom! <image> As a doll collector, Chiori has got n dolls. The i-th doll has a non-negative integer value a_i (a_i < 2^m, m is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are 2^n different picking ways. Let x be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls x = 0). The value of this picking way is equal to the number of 1-bits in the binary representation of x. More formally, it is also equal to the number of indices 0 ≤ i < m, such that \left⌊ (x)/(2^i) \right⌋ is odd. Tell her the number of picking ways with value i for each integer i from 0 to m. Due to the answers can be very huge, print them by modulo 998 244 353. Input The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 35) — the number of dolls and the maximum value of the picking way. The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i < 2^m) — the values of dolls. Output Print m+1 integers p_0, p_1, …, p_m — p_i is equal to the number of picking ways with value i by modulo 998 244 353. Examples Input 4 4 3 5 8 14 Output 2 2 6 6 0 Input 6 7 11 45 14 9 19 81 Output 1 2 11 20 15 10 5 0
```python import sys MOD = 998244353 BOUND = 21 n, m = map(int, input().split()) l = list(map(int,input().split())) basis = [] for p in range(m-1,-1,-1): p2 = pow(2,p) nex = -1 for i in range(n): if l[i] >= p2: nex = l[i] break if nex != -1: basis.append(nex) for i in range(n): if l[i] >= p2: l[i] ^= nex extra = n - len(basis) def add(a, b): out = [0] * (max(len(a), len(b))) for i in range(len(a)): out[i] = a[i] for i in range(len(b)): out[i] += b[i] out[i] %= MOD return out def addSh(a, b): out = [0] * (max(len(a) + 1, len(b))) for i in range(len(a)): out[i + 1] = a[i] for i in range(len(b)): out[i] += b[i] out[i] %= MOD return out i = 0 curr = dict() curr[0] = [1] for p in range(m-1,-1,-1): if p == m - 1 and p < BOUND: curr = [curr[i] if i in curr else [] for i in range(2 ** 20)] if p >= BOUND: p2 = pow(2,p) if i < len(basis) and basis[i] >= p2: currN = dict(curr) for v in curr: if v ^ basis[i] not in currN: currN[v ^ basis[i]] = [0] currN[v ^ basis[i]] = add(curr[v], currN[v ^ basis[i]]) curr = currN i += 1 lis = list(curr.keys()) for v in lis: if v >= p2: if v ^ p2 not in currN: curr[v ^ p2] = [0] curr[v ^ p2] = addSh(curr[v], curr[v ^ p2]) del curr[v] else: p2 = pow(2,p) if i < len(basis) and basis[i] >= p2: for v in range(p2): curr[v ^ basis[i]] = add(curr[v], curr[v ^ basis[i]]) curr[v] = curr[v ^ basis[i]] i += 1 for v in range(p2): curr[v] = addSh(curr[v ^ p2], curr[v]) if p == BOUND: curr = [curr[i] if i in curr else [] for i in range(2 ** BOUND)] out = curr[0] while len(out) < m + 1: out.append(0) for i in range(m + 1): out[i] *= pow(2, extra, MOD) out[i] %= MOD for v in out: sys.stdout.write(str(v)+' ') ```
1359_B. New Theatre Square
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pavement. You are given the picture of the squares: * if a_{i,j} = "*", then the j-th square in the i-th row should be black; * if a_{i,j} = ".", then the j-th square in the i-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: * 1 × 1 tiles — each tile costs x burles and covers exactly 1 square; * 1 × 2 tiles — each tile costs y burles and covers exactly 2 adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into 1 × 1 tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles. What is the smallest total price of the tiles needed to cover all the white squares? Input The first line contains a single integer t (1 ≤ t ≤ 500) — the number of testcases. Then the description of t testcases follow. The first line of each testcase contains four integers n, m, x and y (1 ≤ n ≤ 100; 1 ≤ m ≤ 1000; 1 ≤ x, y ≤ 1000) — the size of the Theatre square, the price of the 1 × 1 tile and the price of the 1 × 2 tile. Each of the next n lines contains m characters. The j-th character in the i-th line is a_{i,j}. If a_{i,j} = "*", then the j-th square in the i-th row should be black, and if a_{i,j} = ".", then the j-th square in the i-th row should be white. It's guaranteed that the sum of n × m over all testcases doesn't exceed 10^5. Output For each testcase print a single integer — the smallest total price of the tiles needed to cover all the white squares in burles. Example Input 4 1 1 10 1 . 1 2 10 1 .. 2 1 10 1 . . 3 3 3 7 ..* *.. .*. Output 10 1 20 18 Note In the first testcase you are required to use a single 1 × 1 tile, even though 1 × 2 tile is cheaper. So the total price is 10 burles. In the second testcase you can either use two 1 × 1 tiles and spend 20 burles or use a single 1 × 2 tile and spend 1 burle. The second option is cheaper, thus the answer is 1. The third testcase shows that you can't rotate 1 × 2 tiles. You still have to use two 1 × 1 tiles for the total price of 20. In the fourth testcase the cheapest way is to use 1 × 1 tiles everywhere. The total cost is 6 ⋅ 3 = 18.
```python cases=input() for i in range(0,int(cases)): inss=input() list=inss.split(' ') n=int(list[0]) m=int(list[1]) x=int(list[2]) y=int(list[3]) price=0 if 2*x > y: lame=True else: lame=False for count in range(0,n): data=input() ###print(data) ###list1=data.split('') ###print(list1) if lame: ##print("lame yes") sing=0 doub=0 lolz=False for item in data: ##print(item) if lolz: if item=='.': doub=doub+1 sing=sing-1 lolz=False else: lolz=False else: if item=='.': sing=sing+1 lolz=True ##print(doub,sing) price=price+(doub*y+sing*x) ##print(price,"1") else: ##print("lame no") for item in data: if item=='.': price=price+x print(price) ```
1379_D. New Passenger Trams
There are many freight trains departing from Kirnes planet every day. One day on that planet consists of h hours, and each hour consists of m minutes, where m is an even number. Currently, there are n freight trains, and they depart every day at the same time: i-th train departs at h_i hours and m_i minutes. The government decided to add passenger trams as well: they plan to add a regular tram service with half-hour intervals. It means that the first tram of the day must depart at 0 hours and t minutes, where 0 ≤ t < {m \over 2}, the second tram departs m \over 2 minutes after the first one and so on. This schedule allows exactly two passenger trams per hour, which is a great improvement. To allow passengers to board the tram safely, the tram must arrive k minutes before. During the time when passengers are boarding the tram, no freight train can depart from the planet. However, freight trains are allowed to depart at the very moment when the boarding starts, as well as at the moment when the passenger tram departs. Note that, if the first passenger tram departs at 0 hours and t minutes, where t < k, then the freight trains can not depart during the last k - t minutes of the day. <image> A schematic picture of the correct way to run passenger trams. Here h=2 (therefore, the number of passenger trams is 2h=4), the number of freight trains is n=6. The passenger trams are marked in red (note that the spaces between them are the same). The freight trains are marked in blue. Time segments of length k before each passenger tram are highlighted in red. Note that there are no freight trains inside these segments. Unfortunately, it might not be possible to satisfy the requirements of the government without canceling some of the freight trains. Please help the government find the optimal value of t to minimize the number of canceled freight trains in case all passenger trams depart according to schedule. Input The first line of input contains four integers n, h, m, k (1 ≤ n ≤ 100 000, 1 ≤ h ≤ 10^9, 2 ≤ m ≤ 10^9, m is even, 1 ≤ k ≤ {m \over 2}) — the number of freight trains per day, the number of hours and minutes on the planet, and the boarding time for each passenger tram. n lines follow, each contains two integers h_i and m_i (0 ≤ h_i < h, 0 ≤ m_i < m) — the time when i-th freight train departs. It is guaranteed that no freight trains depart at the same time. Output The first line of output should contain two integers: the minimum number of trains that need to be canceled, and the optimal starting time t. Second line of output should contain freight trains that need to be canceled. Examples Input 2 24 60 15 16 0 17 15 Output 0 0 Input 2 24 60 16 16 0 17 15 Output 1 0 2 Note In the first test case of the example the first tram can depart at 0 hours and 0 minutes. Then the freight train at 16 hours and 0 minutes can depart at the same time as the passenger tram, and the freight train at 17 hours and 15 minutes can depart at the same time as the boarding starts for the upcoming passenger tram. In the second test case of the example it is not possible to design the passenger tram schedule without cancelling any of the freight trains: if t ∈ [1, 15], then the freight train at 16 hours and 0 minutes is not able to depart (since boarding time is 16 minutes). If t = 0 or t ∈ [16, 29], then the freight train departing at 17 hours 15 minutes is not able to depart. However, if the second freight train is canceled, one can choose t = 0. Another possible option is to cancel the first train and choose t = 13.
```python from collections import defaultdict import sys input=sys.stdin.readline n,h,m,k=map(int,input().split()) l=[] a=[] start=0 for i in range(n): H,M=map(int,input().split()) M=M%(m//2) a.append(M) l.append((M+1,1,i)) l.append(((M+k)%(m//2),-1,i)) if (M+1)>(M+k)%(m//2): start+=1 l.append((0,0,0)) l.append((m//2-1,0,0)) l.sort() #print(l) p=-1 ans=(10000000000,0) for t,dire,ind in l: #print(start,t) if p!=-1 and p!=t: ans=min(ans,(start,p)) start+=dire p=t print(*ans) time=ans[1] if ans[0]>0: for i in range(n): #print(a[i]+1,(a[i]+k)%(m//2),time) if (a[i]+1)>(a[i]+k-1)%(m//2): if time>=a[i]+1 or time<=((a[i]+k-1)%(m//2)): print(i+1) else: if time>=a[i]+1 and time<=((a[i]+k-1)%(m//2)): print(i+1) ```
139_B. Wallpaper
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type. The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely. After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him. Input The first line contains a positive integer n (1 ≤ n ≤ 500) — the number of rooms in Boris's apartment. Each of the next n lines contains three space-separated positive integers — the length, width and height of the walls in a given room in meters, respectively. The next line contains a positive integer m (1 ≤ m ≤ 500) — the number of available wallpaper types. Each of the following m lines contains three space-separated positive integers — the length and width in meters of a given wallpaper and the price of one roll, respectively. All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper. Output Print a single number — the minimum total cost of the rolls. Examples Input 1 5 5 3 3 10 1 100 15 2 320 3 19 500 Output 640 Note Note to the sample: The total length of the walls (the perimeter) of the room is 20 m. One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700. A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640. One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.
```python #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now---------------------------------------------------- n = int(input()) rooms = [] for _ in range(n): rooms.append(list(map(int, input().split()))) m = int(input()) wallpapers = [] for _ in range(m): wallpapers.append(list(map(int, input().split()))) def room_cost(room, wallpapers): min_cost = 10**18 parimeter = 2 * (room[0] + room[1]) if room[2] == 0: return 0 for wallpaper in wallpapers: if wallpaper[1] != 0: stripes_needed = (parimeter + wallpaper[1] - 1) // wallpaper[1] stripes_from_one_roll = wallpaper[0] // room[2] if stripes_from_one_roll == 0: continue amount_of_rolls = (stripes_needed + stripes_from_one_roll - 1) // stripes_from_one_roll min_cost = min([min_cost, amount_of_rolls * wallpaper[2]]) return min_cost print(sum([room_cost(room, wallpapers) for room in rooms])) ```
1423_F. Coins
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them: All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting. Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad? Input The first line of input contains two integer numbers n and k (1 ≤ n ≤ 10^{9}, 0 ≤ k ≤ 2⋅10^5), where n denotes total number of pirates and k is the number of pirates that have any coins. The next k lines of input contain integers a_i and b_i (1 ≤ a_i ≤ n, 1 ≤ b_i ≤ 10^{9}), where a_i denotes the index of the pirate sitting at the round table (n and 1 are neighbours) and b_i the total number of coins that pirate a_i has at the start of the game. Output Print 1 if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations. Print -1 if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations. Examples Input 4 2 1 2 2 2 Output 1 Input 6 2 2 3 4 1 Output 1 Input 3 2 1 1 2 2 Output -1 Note In the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one.
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def main(): n, k = [int(x) for x in input().split()] p, s = 0, 0 for _ in range(k): a, b = [int(x) for x in input().split()] s += b p += a * b p %= n print(['-1', '1'][s < n or (s == n and p == (n * (n + 1) // 2) % n)]) main() ```
1468_G. Hobbits
The hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains. The mountain relief can be represented as a polyline with n points (x_i, y_i), numbered from 1 to n (x_i < x_{i + 1} for 1 ≤ i ≤ n - 1). Hobbits start their journey at the point (x_1, y_1) and should reach the point (x_n, y_n) to complete their mission. The problem is that there is a tower with the Eye of Sauron, which watches them. The tower is located at the point (x_n, y_n) and has the height H, so the Eye is located at the point (x_n, y_n + H). In order to complete the mission successfully, the hobbits have to wear cloaks all the time when the Sauron Eye can see them, i. e. when there is a direct line from the Eye to the hobbits which is not intersected by the relief. The hobbits are low, so their height can be considered negligibly small, but still positive, so when a direct line from the Sauron Eye to the hobbits only touches the relief, the Eye can see them. <image> The Sauron Eye can't see hobbits when they are in the left position, but can see them when they are in the right position. The hobbits do not like to wear cloaks, so they wear them only when they can be spotted by the Eye. Your task is to calculate the total distance the hobbits have to walk while wearing cloaks. Input The first line of the input contains two integers n and H (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ H ≤ 10^4) — the number of vertices in polyline and the tower height. The next n lines contain two integers x_i, y_i each (0 ≤ x_i ≤ 4 ⋅ 10^5; 0 ≤ y_i ≤ 10^4) — the coordinates of the polyline vertices. It is guaranteed that x_i < x_{i + 1} for 1 ≤ i ≤ n - 1. Output Print one real number — the total distance the hobbits have to walk while wearing cloaks. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6} — formally, if your answer is a, and the jury's answer is b, your answer will be accepted if (|a - b|)/(max(1, b)) ≤ 10^{-6}. Examples Input 6 10 10 40 20 10 25 30 30 15 50 15 65 30 Output 70.4034587602 Input 9 5 0 0 5 10 15 10 20 0 25 11 30 0 35 10 50 10 60 5 Output 27.2787986124 Input 2 10000 0 10000 400000 0 Output 400124.9804748512
```python import sys input = sys.stdin.readline n, H = map(int, input().split());points = [tuple(map(int, input().split())) for _ in range(n)];eye = (points[-1][0], points[-1][1] + H);peak = points[-1];out = 0 def dot(a,b): return a[0] * b[0] + a[1] * b[1] def sub(a,b): return (a[0] - b[0], a[1] - b[1]) def norm(a): return (a[0] ** 2 + a[1] ** 2) ** (0.5) for _ in range(n-2,-1,-1): p1 = points[_];p2 = points[_ + 1];vecP = sub(peak, eye);vecR = (vecP[1], -vecP[0]);vecP1 = sub(p1, eye);vecP2 = sub(p2, eye);h1 = dot(vecP1, vecR);h2 = dot(vecP2, vecR) if h2 >= 0: if h1 >= 0:out += norm(sub(p1,p2));peak = p1 else: if h1 >= 0:out += norm(sub(p1,p2)) * (h1/(h1-h2));peak = p1 print(out) ```
1493_A. Anti-knapsack
You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line contains the number of test cases T (1 ≤ T ≤ 100). Each of the next T lines contains two integers n and k (1 ≤ k ≤ n ≤ 1000) — the description of test cases. Output For each test case output two lines. In the first line output a single integer m — the number of chosen integers. In the second line output m distinct integers from 1 to n — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order. Example Input 3 3 2 5 3 1 1 Output 2 3 1 3 4 5 2 0
```python t=int(input()) for i in range(t): n,k = map(int,input().split()) ans=[] if n==1 and k==1: print(0) continue else: if k%2==0: for j in range(k//2,k): ans.append(j) for j in range(k+1,n+1): ans.append(j) else: for j in range(k//2+1,k): ans.append(j) for j in range(k+1,n+1): ans.append(j) print(len(ans)) print(*ans) ```
1515_G. Phoenix and Odometers
In Fire City, there are n intersections and m one-way roads. The i-th road goes from intersection a_i to b_i and has length l_i miles. There are q cars that may only drive along those roads. The i-th car starts at intersection v_i and has an odometer that begins at s_i, increments for each mile driven, and resets to 0 whenever it reaches t_i. Phoenix has been tasked to drive cars along some roads (possibly none) and return them to their initial intersection with the odometer showing 0. For each car, please find if this is possible. A car may visit the same road or intersection an arbitrary number of times. The odometers don't stop counting the distance after resetting, so odometers may also be reset an arbitrary number of times. Input The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of intersections and the number of roads, respectively. Each of the next m lines contain three integers a_i, b_i, and l_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i; 1 ≤ l_i ≤ 10^9) — the information about the i-th road. The graph is not necessarily connected. It is guaranteed that between any two intersections, there is at most one road for each direction. The next line contains an integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of cars. Each of the next q lines contains three integers v_i, s_i, and t_i (1 ≤ v_i ≤ n; 0 ≤ s_i < t_i ≤ 10^9) — the initial intersection of the i-th car, the initial number on the i-th odometer, and the number at which the i-th odometer resets, respectively. Output Print q answers. If the i-th car's odometer may be reset to 0 by driving through some roads (possibly none) and returning to its starting intersection v_i, print YES. Otherwise, print NO. Examples Input 4 4 1 2 1 2 3 1 3 1 2 1 4 3 3 1 1 3 1 2 4 4 0 1 Output YES NO YES Input 4 5 1 2 1 2 3 1 3 1 2 1 4 1 4 3 2 2 1 2 4 4 3 5 Output YES YES Note The illustration for the first example is below: <image> In the first query, Phoenix can drive through the following cities: 1 → 2 → 3 → 1 → 2 → 3 → 1. The odometer will have reset 3 times, but it displays 0 at the end. In the second query, we can show that there is no way to reset the odometer to 0 and return to intersection 1. In the third query, the odometer already displays 0, so there is no need to drive through any roads. Below is the illustration for the second example: <image>
```python import sys from sys import stdin import math from collections import deque import sys class scc_graph: def __init__(self, N): self.N = N self.edges = [] def csr(self): self.start = [0]*(self.N+1) self.elist = [0]*len(self.edges) for e in self.edges: self.start[e[0]+1] += 1 for i in range(1, self.N+1): self.start[i] += self.start[i-1] counter = self.start[:] for e in self.edges: self.elist[counter[e[0]]] = e[1] counter[e[0]] += 1 def add_edge(self, v, w): self.edges.append((v, w)) def scc_ids(self): self.csr() N = self.N now_ord = group_num = 0 visited = [] low = [0]*N order = [-1]*N ids = [0]*N parent = [-1]*N stack = [] for i in range(N): if order[i] == -1: stack.append(i) stack.append(i) while stack: v = stack.pop() if order[v] == -1: low[v] = order[v] = now_ord now_ord += 1 visited.append(v) for i in range(self.start[v], self.start[v+1]): to = self.elist[i] if order[to] == -1: stack.append(to) stack.append(to) parent[to] = v else: low[v] = min(low[v], order[to]) else: if low[v] == order[v]: while True: u = visited.pop() order[u] = N ids[u] = group_num if u == v: break group_num += 1 if parent[v] != -1: low[parent[v]] = min(low[parent[v]], low[v]) for i, x in enumerate(ids): ids[i] = group_num-1-x return group_num, ids def scc(self): group_num, ids = self.scc_ids() groups = [[] for _ in range(group_num)] for i, x in enumerate(ids): groups[x].append(i) return groups """ def SCC(N,M,elis): lis = [ [] for i in range(N) ] rlis = [ [] for i in range(N)] for u,v in elis: lis[u].append(v) rlis[v].append(u) stk = [] nind = [0] * N visit = [False] * N leave = [None] * N nl = 0 for loop in range(N): if visit[loop] == False: visit[loop] = True stk.append(loop) while stk: if nind[stk[-1]] >= len(lis[stk[-1]]): leave[stk[-1]] = nl nl += 1 del stk[-1] else: nexv = lis[stk[-1]][nind[stk[-1]]] nind[stk[-1]] += 1 if not visit[nexv]: stk.append(nexv) visit[nexv] = True visit = [False] * N mv = [ (leave[i],i) for i in range(N) ] mv.sort() ret = [] while mv: tmp,v = mv[-1] del mv[-1] if not visit[v]: visit[v] = True q = [v] nlinks = [] while q: x = q[-1] del q[-1] nlinks.append(x) for nex in rlis[x]: if not visit[nex]: visit[nex] = True q.append(nex) ret.append(nlinks) return ret """ n,m = map(int,stdin.readline().split()) N = n sg = scc_graph(n) lis = [ [] for i in range(n)] elis = [] for i in range(m): a,b,l = map(int,stdin.readline().split()) a -= 1 b -= 1 lis[a].append((b,l)) sg.add_edge(a,b) SC = sg.scc() sclis = [None] * N for i in range(len(SC)): for j in SC[i]: sclis[j] = i scgcd = [None] * len(SC) d = [None] * N for i in range(N): if scgcd[sclis[i]] == None: ngcd = float("inf") q = deque([i]) d[i] = 0 while q: v = q.popleft() for nex,l in lis[v]: if sclis[nex] == sclis[v]: if d[nex] == None: d[nex] = d[v] + l q.append(nex) elif abs(d[nex]-d[v]-l) != 0: if ngcd == float("inf"): ngcd = abs(d[nex] - d[v]-l) else: ngcd = math.gcd(ngcd,abs(d[nex]-d[v]-l)) scgcd[sclis[i]] = ngcd q = int(stdin.readline()) ANS = [] #print (SC) #print (scgcd) for loop in range(q): vi,si,ti = map(int,stdin.readline().split()) vi -= 1 if scgcd[sclis[vi]] == float("inf"): if si == 0: ANS.append("YES") else: ANS.append("NO") else: if ((-1*si) % ti) % math.gcd(scgcd[sclis[vi]] , ti) == 0: ANS.append("YES") else: ANS.append("NO") print ("\n".join(ANS)) ```
171_A. Mysterious numbers - 1
Input The input contains two integers a1, a2 (0 ≤ ai ≤ 109), separated by a single space. Output Output a single integer. Examples Input 3 14 Output 44 Input 27 12 Output 48 Input 100 200 Output 102
```python from math import floor x, y = input().split() x = int(x) y = int(y) rev = 0 while y > 0: a = int(y % 10) rev = rev * 10 + a y = floor(y / 10) b = x + rev print(b) ```
190_D. Non-Secret Cypher
Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much. The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message. Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers. Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj). Input The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array. Output Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 2 1 2 1 2 Output 3 Input 5 3 1 2 1 1 3 Output 2 Input 3 1 1 1 1 Output 6 Note In the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2). In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1). In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
```python def answer(): ans,count,j=0,0,0 d=dict() for i in range(n): while(j==0 or d[a[j-1]] < k): if(j==n): j+=1 break try:d[a[j]]+=1 except:d[a[j]]=1 count += 1 m=n-count+1 j+=1 if(j > n):break ans+=m d[a[i]] -= 1 return ans n,k=map(int,input().split()) a=list(map(int,input().split())) print(answer()) ```
238_D. Tape Programming
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. * Current character pointer (CP); * Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right. We repeat the following steps until the first moment that CP points to somewhere outside the sequence. * If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. * If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated. It's obvious the every program in this language terminates after some steps. We have a sequence s1, s2, ..., sn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language. Input The first line of input contains two integers n and q (1 ≤ n, q ≤ 105) — represents the length of the sequence s and the number of queries. The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces. The next q lines each contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query. Output For each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input. Examples Input 7 4 1&gt;3&gt;22&lt; 1 3 4 7 7 7 1 7 Output 0 1 0 1 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 2 1 0 0 0 0 0 0
```python n, q = map(int, input().split()) s = input() for _ in range(q): l, r = map(int, input().split()) t = list(s[l-1:r]) p, d = 0, 1 res = [0] * 10 while 0 <= p < len(t): if '0' <= t[p] <= '9': k = int(t[p]) res[k] += 1 if k > 0: t[p] = str(k-1) p += d else: t.pop(p) if d == -1: p += d else: d = -1 if t[p] == '<' else 1 if 0 <= p+d < len(t) and not ('0' <= t[p+d] <= '9'): t.pop(p) if d == -1: p += d else: p += d print(*res) ```
263_B. Squares
Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square. Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly k drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits. Input The first line contains two space-separated integers n, k (1 ≤ n, k ≤ 50). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). It is guaranteed that all given squares are distinct. Output In a single line print two space-separated integers x and y (0 ≤ x, y ≤ 109) — the coordinates of the point that belongs to exactly k squares. If there are multiple answers, you are allowed to print any of them. If there is no answer, print "-1" (without the quotes). Examples Input 4 3 5 1 3 4 Output 2 1 Input 3 1 2 4 1 Output 4 0 Input 4 50 5 1 10 2 Output -1
```python def ans(k,a): a.sort() if(k>len(a)): return "-1" else: if(k!=0): return a[len(a)-k] n,k=map(int,input().split(" ")) arr=list(map(int,input().split(" "))) if (ans(k,arr)=="-1"): print("-1") else: print(ans(k,arr)," ",ans(k,arr)) ```
287_B. Pipeline
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters. A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. <image> The figure shows a 4-output splitter Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible. Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters. Input The first line contains two space-separated integers n and k (1 ≤ n ≤ 1018, 2 ≤ k ≤ 109). 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. Output Print a single integer — the minimum number of splitters needed to build the pipeline. If it is impossible to build a pipeline with the given splitters, print -1. Examples Input 4 3 Output 2 Input 5 5 Output 1 Input 8 4 Output -1
```python n, k = map(int, input().split()) def prod(n): if n%2: return n*((n+1)//2) else: return (n//2)*(n+1) def total_count(n, k): if k >= n: return (0, 0, 1) else: count = 0 l = 1; r = k s = prod(k) while l <= r: mid = (l+r)//2 if n > s - prod(mid) + mid: r = mid-1 else: l = mid+1 n = n - (s - prod(l) + l) count += (k-l+1) k = l-1 return (n, k, count) if prod(k) - (k-1) < n: print(-1) elif n == 1: print(0) elif k >= n: print(1) else: n = n-k k = k-2 count = 1 while n > 0: (n, k, temp) = total_count(n, k) count += temp print(count) ```
312_B. Archer
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is <image> for SmallR while <image> for Zanoes. The one who shoots in the target first should be the winner. Output the probability that SmallR will win the match. Input A single line contains four integers <image>. Output Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 1 2 1 2 Output 0.666666666667
```python a, b, c, d = map(int, input().split(' ')) x = a/b y = c/d print(x / (1-(1-x) * (1-y))) ```
401_C. Team
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that: * there wouldn't be a pair of any side-adjacent cards with zeroes in a row; * there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way. Input The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1. Output In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1. Examples Input 1 2 Output 101 Input 4 8 Output 110110110101 Input 4 10 Output 11011011011011 Input 1 5 Output -1
```python mod = 1000000007 ii = lambda : int(input()) si = lambda : input() dgl = lambda : list(map(int, input())) f = lambda : map(int, input().split()) il = lambda : list(map(int, input().split())) ls = lambda : list(input()) n0, n1 = f() s='0'*(n0+n1) if n1<n0-1: print(-1) elif n1==n0-1 or n1==n0: s=s.replace('0','01') print(s[:(n0+n1)]) elif n1==n0+1: s=s.replace('0','10') print(s[:(n0+n1)]) elif n1>n0+1 and n1<=2*(n0+1): s=s.replace('0','10') s=s[:(2*n0+1)] s=s.replace('1','11',(n1-n0-1)) print(s[:(n0+n1)]) else: print(-1) ```
429_D. Tricky Function
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task. You're given an (1-based) array a with n elements. Let's define function f(i, j) (1 ≤ i, j ≤ n) as (i - j)2 + g(i, j)2. Function g is calculated by the following pseudo-code: int g(int i, int j) { int sum = 0; for (int k = min(i, j) + 1; k <= max(i, j); k = k + 1) sum = sum + a[k]; return sum; } Find a value mini ≠ j f(i, j). Probably by now Iahub already figured out the solution to this problem. Can you? Input The first line of input contains a single integer n (2 ≤ n ≤ 100000). Next line contains n integers a[1], a[2], ..., a[n] ( - 104 ≤ a[i] ≤ 104). Output Output a single integer — the value of mini ≠ j f(i, j). Examples Input 4 1 0 0 -1 Output 1 Input 2 1 -1 Output 2
```python import os import math cumsum = [int(x) for x in os.read(0, os.fstat(0).st_size).split()] n = cumsum[0] cumsum[0] = 0 for i in range(n): cumsum[i+1] += cumsum[i] def work(besta, i, sqrtbesta, lowerbound, upperbound, cumsumi): for j in range(i+1, min(n, i - 1 + sqrtbesta) + 1): if lowerbound < cumsum[j] < upperbound and (j-i)**2 + (cumsum[j] - cumsumi)**2 < besta: besta = (j-i)**2 + (cumsum[j] - cumsumi)**2 return besta besta = 10100**2 for i in range(1, n): sqrtbesta = int(math.sqrt(besta)) + 1 lowerbound = -sqrtbesta + cumsum[i] upperbound = sqrtbesta + cumsum[i] besta = work(besta, i, sqrtbesta, lowerbound, upperbound, cumsum[i]) print(besta) ```
451_B. Sort the Array
Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers. Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes. Input The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109). Output Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them. Examples Input 3 3 2 1 Output yes 1 3 Input 4 2 1 3 4 Output yes 1 2 Input 4 3 1 2 4 Output no Input 2 1 2 Output yes 1 1 Note Sample 1. You can reverse the entire array to get [1, 2, 3], which is sorted. Sample 3. No segment can be reversed such that the array will be sorted. Definitions A segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r]. If you have an array a of size n and you reverse its segment [l, r], the array will become: a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].
```python # coding=utf-8 if __name__ == '__main__': n = int(input()) line = str(input()).split() line = [int(it) for it in line] temp_line = line.copy() temp_line.sort() ptr_head = 0 ptr_tail = n - 1 while line[ptr_head] == temp_line[ptr_head]: if ptr_head == ptr_tail: break ptr_head += 1 while line[ptr_tail] == temp_line[ptr_tail]: if ptr_head == ptr_tail: break ptr_tail -= 1 flag = False for i in range(ptr_head, ptr_tail + 1): if line[i] != temp_line[ptr_tail - (i - ptr_head)]: flag = True break if flag: print('no') else: print('yes') print(str(ptr_head + 1) + ' ' + str(ptr_tail + 1)) ```
474_A. Keyboard
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way: qwertyuiop asdfghjkl; zxcvbnm,./ Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input). We have a sequence of characters he has typed and we want to find the original message. Input First line of the input contains one letter describing direction of shifting ('L' or 'R' respectively for left or right). Second line contains a sequence of characters written by Mole. The size of this sequence will be no more than 100. Sequence contains only symbols that appear on Mole's keyboard. It doesn't contain spaces as there is no space on Mole's keyboard. It is guaranteed that even though Mole hands are moved, he is still pressing buttons on keyboard and not hitting outside it. Output Print a line that contains the original message. Examples Input R s;;upimrrfod;pbr Output allyouneedislove
```python move=input() ans="" s=input() keyboard=["qwertyuiop","asdfghjkl;","zxcvbnm,./"] if move =="R": for i in range(len(s)): for j in range(len(keyboard)): if s[i] in keyboard[j]: ans+=keyboard[j][keyboard[j].index(s[i])-1] elif move =="L": for i in range(len(s)): for j in range(len(keyboard)): if s[i] in keyboard[j]: ans+=keyboard[j][keyboard[j].index(s[i])+1] print(ans) ```
521_A. DNA Alignment
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): <image> where <image> is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6 Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: <image>. Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7. Input The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT". Output Print a single number — the answer modulo 109 + 7. Examples Input 1 C Output 1 Input 2 AG Output 4 Input 3 TTT Output 1 Note Please note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one. In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0. In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4. In the third sample, ρ("TTT", "TTT") = 27
```python # problem statement: https://codeforces.com/problemset/problem/520/C modulo = 1000000007 n = int(input()) char_count = [0] * 256 s = input() for i in range(n): char_count[ord(s[i])] += 1 max_char_count = max(char_count) num_max_char = 0 for i in range(256): if char_count[i] == max_char_count: num_max_char += 1 print(pow(num_max_char, n) % modulo) ```
596_C. Wilbur and Points
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set. Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' ≥ x and y' ≥ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4. Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w1, w2,..., wn, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to wi, that is s(xi, yi) = yi - xi = wi. Now Wilbur asks you to help him with this challenge. Input The first line of the input consists of a single integer n (1 ≤ n ≤ 100 000) — the number of points in the set Wilbur is playing with. Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≤ x, y ≤ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y, are also present in the input. The last line of the input contains n integers. The i-th of them is wi ( - 100 000 ≤ wi ≤ 100 000) — the required special value of the point that gets number i in any aesthetically pleasing numbering. Output If there exists an aesthetically pleasant numbering of points in the set, such that s(xi, yi) = yi - xi = wi, then print "YES" on the first line of the output. Otherwise, print "NO". If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them. Examples Input 5 2 0 0 0 1 0 1 1 0 1 0 -1 -2 1 0 Output YES 0 0 1 0 2 0 0 1 1 1 Input 3 1 0 0 0 2 0 0 1 2 Output NO Note In the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and yi - xi = wi. In the second sample, the special values of the points in the set are 0, - 1, and - 2 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist.
```python from collections import defaultdict def solve(): N = int(input()) maxx = 0 maxy = 0 WS = defaultdict(list) for i in range(N): x, y = map(int, input().split()) WS[y - x].append((x, y)) maxx = max(maxx, x) maxy = max(maxy, y) for w in WS: WS[w].sort(reverse=True) W = list(map(int, input().split())) ans = [None] * N mx = [0] * (maxy + 1) my = [0] * (maxx + 1) for i in range(N): w = W[i] if WS[w]: ans[i] = ax, ay = WS[w].pop() if mx[ay] == ax and my[ax] == ay: mx[ay] = ax + 1 my[ax] = ay + 1 else: print('NO') return else: print('NO') return print('YES') for a in ans: print(a[0], a[1]) if __name__ == '__main__': solve() ```
617_E. XOR and Favorite Number
Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k. Input The first line of the input contains integers n, m and k (1 ≤ n, m ≤ 100 000, 0 ≤ k ≤ 1 000 000) — the length of the array, the number of queries and Bob's favorite number respectively. The second line contains n integers ai (0 ≤ ai ≤ 1 000 000) — Bob's array. Then m lines follow. The i-th line contains integers li and ri (1 ≤ li ≤ ri ≤ n) — the parameters of the i-th query. Output Print m lines, answer the queries in the order they appear in the input. Examples Input 6 2 3 1 2 1 1 0 3 1 6 3 5 Output 7 0 Input 5 3 1 1 1 1 1 1 1 5 2 4 1 3 Output 9 4 4 Note In the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query. In the second sample xor equals 1 for all subarrays of an odd length.
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if not True else 1): #n = int(input()) n, m, k = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() pre = [0] for i in range(n): pre += [a[i] ^ pre[-1]] BLOCK_SIZE = 320 queries = [[] for __ in range(BLOCK_SIZE)] ans = [0]*m for i in range(m): l, r = map(int, input().split()) queries[l // BLOCK_SIZE] += [[l - 1, r, i]] count = [0] * (1 << 20) for i in range(len(queries)): queries[i] = sorted(queries[i], key=lambda x: x[1]) if not queries[i]: continue left = right = BLOCK_SIZE * i count[pre[left]] += 1 res = 0 for l, r, index in queries[i]: while right < r: right += 1 res += count[pre[right] ^ k] count[pre[right]] += 1 while left < l: left += 1 count[pre[left - 1]] -= 1 res -= count[pre[left - 1] ^ k] while left > l: left -= 1 res += count[pre[left] ^ k] count[pre[left]] += 1 ans[index] = res while left <= right: left += 1 count[pre[left - 1]] -= 1 res -= count[pre[left - 1] ^ k] assert res == 0 for each in ans: print(each) ```
638_B. Making Genome in Berland
Berland scientists face a very important task - given the parts of short DNA fragments, restore the dinosaur DNA! The genome of a berland dinosaur has noting in common with the genome that we've used to: it can have 26 distinct nucleotide types, a nucleotide of each type can occur at most once. If we assign distinct English letters to all nucleotides, then the genome of a Berland dinosaur will represent a non-empty string consisting of small English letters, such that each letter occurs in it at most once. Scientists have n genome fragments that are represented as substrings (non-empty sequences of consecutive nucleotides) of the sought genome. You face the following problem: help scientists restore the dinosaur genome. It is guaranteed that the input is not contradictory and at least one suitable line always exists. When the scientists found out that you are a strong programmer, they asked you in addition to choose the one with the minimum length. If there are multiple such strings, choose any string. Input The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of genome fragments. Each of the next lines contains one descriptions of a fragment. Each fragment is a non-empty string consisting of distinct small letters of the English alphabet. It is not guaranteed that the given fragments are distinct. Fragments could arbitrarily overlap and one fragment could be a substring of another one. It is guaranteed that there is such string of distinct letters that contains all the given fragments as substrings. Output In the single line of the output print the genome of the minimum length that contains all the given parts. All the nucleotides in the genome must be distinct. If there are multiple suitable strings, print the string of the minimum length. If there also are multiple suitable strings, you can print any of them. Examples Input 3 bcd ab cdef Output abcdef Input 4 x y z w Output xyzw
```python n = int(input()) genom = dict() heads = set() for i in range(n): part = input() heads.add(part[0]) for i in range(len(part)): prev = None next = None if i - 1 >= 0: prev = part[i - 1] if i + 1 < len(part): next = part[i + 1] if part[i] in genom: if not genom[part[i]][0]: genom[part[i]][0] = prev if not genom[part[i]][1]: genom[part[i]][1] = next else: genom[part[i]] = [prev, next] new_heads = set() for head in heads: if not genom[head][0]: new_heads.add(head) res = '' for head in new_heads: el = head while el: res += el el = genom[el][1] print(res) ```
712_B. Memory and Trident
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: * An 'L' indicates he should move one unit left. * An 'R' indicates he should move one unit right. * A 'U' indicates he should move one unit up. * A 'D' indicates he should move one unit down. But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string. Input The first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given. Output If there is a string satisfying the conditions, output a single integer — the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1. Examples Input RRU Output -1 Input UDUR Output 1 Input RUUR Output 2 Note In the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk. In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.
```python s = input() ud = lr = 0 for ch in s: if(ch=='R'): lr = lr+1 if(ch=='L'): lr = lr-1 if(ch=='U'): ud = ud+1 if(ch=='D'): ud = ud-1 if((abs(lr) + abs(ud))%2==1): print(-1) else: print(int((abs(lr) + abs(ud))/2)) ```
733_A. Grasshopper And the String
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump. Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability. <image> The picture corresponds to the first example. The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'. Input The first line contains non-empty string consisting of capital English letters. It is guaranteed that the length of the string does not exceed 100. Output Print single integer a — the minimum jump ability of the Grasshopper (in the number of symbols) that is needed to overcome the given string, jumping only on vowels. Examples Input ABABBBACFEYUKOTT Output 4 Input AAA Output 1
```python def solve(a): l = [0] li = [] j = 0 for i in range(len(a)): if a[i] == "A" or a[i] == "E" or a[i] == "I" or a[i] == "O" or a[i] == "U" or a[i] == "Y": l.append(i + 1) j += 1 li.append(l[j] - l[j-1]) l.append(i + 1) j += 1 li.append(l[j] - l[j-1] + 1) li.sort() print(li[-1]) solve(input()) ```
757_B. Bash's Big Day
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases. But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition). Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself. Input The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon. Output Print single integer — the maximum number of Pokemons Bash can take. Examples Input 3 2 3 4 Output 2 Input 5 2 3 4 6 7 Output 3 Note gcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}. In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2. In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
```python def function1(n,s): if n==1: return 1 pokemonj=0 pokecage=[0 for i in range(100001)] for i in range(n): pokecage[s[i]]+=1 maxyincage=min(pokecage[1],1) a = [i for i in range(100001)] a[1] = 0 i = 2 while i <= 100000: if a[i] != 0: pokemonj=0 for j in range(i, 100001, i): a[j] = 0 pokemonj+=pokecage[j] if pokemonj>maxyincage: maxyincage=pokemonj i += 1 return(maxyincage) def main(): n=int(input()) s=list(map(int,input().split())) print(function1(n,s)) if __name__=='__main__': main() ```
778_D. Parquet Re-laying
Peter decided to lay a parquet in the room of size n × m, the parquet consists of tiles of size 1 × 2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it. The workers decided that removing entire parquet and then laying it again is very difficult task, so they decided to make such an operation every hour: remove two tiles, which form a 2 × 2 square, rotate them 90 degrees and put them back on the same place. <image> They have no idea how to obtain the desired configuration using these operations, and whether it is possible at all. Help Peter to make a plan for the workers or tell that it is impossible. The plan should contain at most 100 000 commands. Input The first line contains integer n and m, size of the room (1 ≤ n, m ≤ 50). At least one of them is even number. The following n lines contain m characters each, the description of the current configuration of the parquet tiles. Each character represents the position of the half-tile. Characters 'L', 'R', 'U' and 'D' correspond to the left, right, upper and lower halves, respectively. The following n lines contain m characters each, describing the desired configuration in the same format. Output In the first line output integer k, the number of operations. In the next k lines output description of operations. The operation is specified by coordinates (row and column) of the left upper half-tile on which the operation is performed. If there is no solution, output -1 in the first line. Examples Input 2 3 ULR DLR LRU LRD Output 2 1 2 1 1 Input 4 3 ULR DLR LRU LRD ULR DUU UDD DLR Output 3 3 1 3 2 2 2 Note In the first sample test first operation is to rotate two rightmost tiles, after this all tiles lie vertically. Second operation is to rotate two leftmost tiles, after this we will get desired configuration. <image>
```python #!/usr/bin/env python3 board = [] n, m = 0, 0 def rotate(x, y): if board[x][y] == 'L': board[x][y] = board[x][y+1] = 'U' board[x+1][y] = board[x+1][y+1] = 'D' else: board[x][y] = board[x+1][y] = 'L' board[x][y+1] = board[x+1][y+1] = 'R' def fix(x, y, moves): if board[x+1][y] == 'U': if board[x+1][y+1] == 'L': fix(x+1, y+1, moves) rotate(x+1, y) moves.append((x+2, y+1)) rotate(x, y) moves.append((x+1, y+1)) def solve_board(moves): global board, n, m board = [] for _ in range(n): board.append(list(input())) for i in range(n-1): for j in range(m): if board[i][j] == 'L': fix(i, j, moves) def main(): global n, m n, m = map(int, input().split()) moves1 = []; moves2 = [] solve_board(moves1) solve_board(moves2) print(len(moves1) + len(moves2)) for move in moves1: print(str(move[0]) + ' ' + str(move[1])) for move in reversed(moves2): print(str(move[0]) + ' ' + str(move[1])) if __name__ == '__main__': main() ```
802_G. Fake News (easy)
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... Input The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z). Output Output YES if the string s contains heidi as a subsequence and NO otherwise. Examples Input abcheaibcdi Output YES Input hiedi Output NO Note A string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p.
```python li = list(input()) def f(n,s): global li while True: if li[n] != s: li.pop(n) else: break try: f(0,'h') f(1,'e') f(2,'i') f(3,'d') f(4,'i') except: print("NO") else: print("YES") ```
825_C. Multi-judge Solving
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty <image> (no matter on what online judge was it). Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k. With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces. Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another. Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces. Input The first line contains two integer numbers n, k (1 ≤ n ≤ 103, 1 ≤ k ≤ 109). The second line contains n space-separated integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109). Output Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces. Examples Input 3 3 2 1 9 Output 1 Input 4 20 10 3 6 3 Output 0 Note In the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3. In the second example he can solve every problem right from the start.
```python n,k=map(int,input().split()) ar=sorted(list(map(int,input().split()))) ans=0 for x in ar: if k <= x <= k*2: k=x while x/2 > k: ans+=1 k*=2 if k <= x <= k*2: k=x print(ans) ```
848_A. From Y to Y
From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t from the set, and add their concatenation s + t to the set. The cost of such operation is defined to be <image>, where f(s, c) denotes the number of times character c appears in string s. Given a non-negative integer k, construct any valid non-empty set of no more than 100 000 letters, such that the minimum accumulative cost of the whole process is exactly k. It can be shown that a solution always exists. Input The first and only line of input contains a non-negative integer k (0 ≤ k ≤ 100 000) — the required minimum cost. Output Output a non-empty string of no more than 100 000 lowercase English letters — any multiset satisfying the requirements, concatenated to be a string. Note that the printed string doesn't need to be the final concatenated string. It only needs to represent an unordered multiset of letters. Examples Input 12 Output abababab Input 3 Output codeforces Note For the multiset {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'}, one of the ways to complete the process is as follows: * {"ab", "a", "b", "a", "b", "a", "b"}, with a cost of 0; * {"aba", "b", "a", "b", "a", "b"}, with a cost of 1; * {"abab", "a", "b", "a", "b"}, with a cost of 1; * {"abab", "ab", "a", "b"}, with a cost of 0; * {"abab", "aba", "b"}, with a cost of 1; * {"abab", "abab"}, with a cost of 1; * {"abababab"}, with a cost of 8. The total cost is 12, and it can be proved to be the minimum cost of the process.
```python # def ap(l): # d = set() # for i in range(1, len(l)): # d.add(l[i]-l[i-1]) # if(len(d) == 1): # return d.pop() # else: # return "re" # def app(ll, oo, nm, ooo): # k = [] # for j in range(n): # if(j%oo !=0): # k.append(ll[j]) # if(ap(k) != "re" and ap(k) != ooo): # return True # else: # return False # err = 1 # n = int(input()) # l = [int(x) for x in input().split()] # m = [] # for i in range(2, n): # k = [] # for j in range(0, n, i): # k.append(l[j]) # print(k) # m.append(k) # final = [] # for i in range(n-2): # r = 1 # if(ap(m[i]) != "re"): # final.append([ap(m[i]), i+2]) # print(final) # for i in final: # if(app(l, i[1], n, i[0])): # print(i) # # print("Yes") # err = 0 # break # if(err): # print("No") # else: # print("Yes") k = int(input()) for i in range(26): tt = 1 while((tt*(tt+1))//2 <=k): tt+=1 k-=((tt*(tt-1))//2) print(chr(97+i)*(tt), end = "") print("") ```
967_B. Watering System
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole. Arkady can block some of the holes, and then pour A liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes s_1, s_2, …, s_n. In other words, if the sum of sizes of non-blocked holes is S, and the i-th hole is not blocked, (s_i ⋅ A)/(S) liters of water will flow out of it. What is the minimum number of holes Arkady should block to make at least B liters of water flow out of the first hole? Input The first line contains three integers n, A, B (1 ≤ n ≤ 100 000, 1 ≤ B ≤ A ≤ 10^4) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole. The second line contains n integers s_1, s_2, …, s_n (1 ≤ s_i ≤ 10^4) — the sizes of the holes. Output Print a single integer — the number of holes Arkady should block. Examples Input 4 10 3 2 2 2 2 Output 1 Input 4 80 20 3 2 1 4 Output 0 Input 5 10 10 1000 1 1 1 1 Output 4 Note In the first example Arkady should block at least one hole. After that, (10 ⋅ 2)/(6) ≈ 3.333 liters of water will flow out of the first hole, and that suits Arkady. In the second example even without blocking any hole, (80 ⋅ 3)/(10) = 24 liters will flow out of the first hole, that is not less than 20. In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.
```python n, a, b = [int(i) for i in input().split(' ')] sizes = [int(i) for i in input().split(' ')] st = sum(sizes) s = (sizes[0] * a) / b sb = st - s blockable = sorted(sizes[1:], reverse=True) blocked_no = 0 blocked_amount = 0 for i in range(len(blockable)): if blocked_amount < sb: blocked_no += 1 blocked_amount += blockable[i] else: break print(blocked_no) ```
993_B. Open Communication
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers. Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not. Input The first line contains two integers n and m (1 ≤ n, m ≤ 12) — the number of pairs the first participant communicated to the second and vice versa. The second line contains n pairs of integers, each between 1 and 9, — pairs of numbers communicated from first participant to the second. The third line contains m pairs of integers, each between 1 and 9, — pairs of numbers communicated from the second participant to the first. All pairs within each set are distinct (in particular, if there is a pair (1,2), there will be no pair (2,1) within the same set), and no pair contains the same number twice. It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number. Output If you can deduce the shared number with certainty, print that number. If you can with certainty deduce that both participants know the shared number, but you do not know it, print 0. Otherwise print -1. Examples Input 2 2 1 2 3 4 1 5 3 4 Output 1 Input 2 2 1 2 3 4 1 5 6 4 Output 0 Input 2 3 1 2 4 5 1 2 1 3 2 3 Output -1 Note In the first example the first participant communicated pairs (1,2) and (3,4), and the second communicated (1,5), (3,4). Since we know that the actual pairs they received share exactly one number, it can't be that they both have (3,4). Thus, the first participant has (1,2) and the second has (1,5), and at this point you already know the shared number is 1. In the second example either the first participant has (1,2) and the second has (1,5), or the first has (3,4) and the second has (6,4). In the first case both of them know the shared number is 1, in the second case both of them know the shared number is 4. You don't have enough information to tell 1 and 4 apart. In the third case if the first participant was given (1,2), they don't know what the shared number is, since from their perspective the second participant might have been given either (1,3), in which case the shared number is 1, or (2,3), in which case the shared number is 2. While the second participant does know the number with certainty, neither you nor the first participant do, so the output is -1.
```python import sys #sys.stdin=open("data.txt") input=sys.stdin.readline n,m=map(int,input().split()) possible1=[set() for _ in range(200)] possible2=[set() for _ in range(200)] weird=[0]*15 p1=list(map(int,input().split())) p2=list(map(int,input().split())) for i in range(n): for j in range(m): a=sorted(p1[i*2:i*2+2]) b=sorted(p2[j*2:j*2+2]) if a==b: continue got=-1 if a[0] in b: got=a[0] if a[1] in b: got=a[1] if got==-1: continue weird[got]=1 possible1[a[0]*11+a[1]].add(got) possible2[b[0]*11+b[1]].add(got) if sum(weird)==1: print(weird.index(1)) elif max(len(i) for i in possible1)==1 and max(len(i) for i in possible2)==1: print(0) else: print(-1) ```
p02628 AtCoder Beginner Contest 171 - Mix Juice
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.) Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits. Constraints * 1 \leq K \leq N \leq 1000 * 1 \leq p_i \leq 1000 * All values in input are integers. Input Input is given from Standard Input in the following format: N K p_1 p_2 \ldots p_N Output Print an integer representing the minimum possible total price of fruits. Examples Input 5 3 50 100 80 120 80 Output 210 Input 1 1 1000 Output 1000
```python _,K,*P=map(int,open(0).read().split()) print(sum(sorted(P)[:K])) ```
p02759 AtCoder Beginner Contest 157 - Duplex Printing
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper. At least how many sheets of paper does he need? Constraints * N is an integer. * 1 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 5 Output 3 Input 2 Output 1 Input 100 Output 50
```python N = int(input()) print(str(N//2+N%2)) ```
p02894 AtCoder Grand Contest 039 - Incenters
Given are N points on the circumference of a circle centered at (0,0) in an xy-plane. The coordinates of the i-th point are (\cos(\frac{2\pi T_i}{L}),\sin(\frac{2\pi T_i}{L})). Three distinct points will be chosen uniformly at random from these N points. Find the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points. Constraints * 3 \leq N \leq 3000 * N \leq L \leq 10^9 * 0 \leq T_i \leq L-1 * T_i<T_{i+1} * All values in input are integers. Input Input is given from Standard Input in the following format: N L T_1 : T_N Output Print the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points. Your output will be considered correct when the absolute or relative error is at most 10^{-9}. Examples Input 3 4 0 1 3 Output 0.414213562373095 -0.000000000000000 Input 4 8 1 3 5 6 Output -0.229401949926902 -0.153281482438188 Input 10 100 2 11 35 42 54 69 89 91 93 99 Output 0.352886583546338 -0.109065017701873
```python from math import cos, sin, pi from itertools import combinations N, L = map(int, input().split()) T = [int(input()) for _ in range(N)] PI2oL = 2*pi/L csum, ssum = 0, 0 count = 0 for i, j in combinations(range(N), 2): count += 1 mid1, num2 = (T[i] + T[j]) / 2, j - i - 1 mid2, num1 = (mid1 + L/2) % L, N - num2 - 2 csum += cos(PI2oL*mid1) * num1 + cos(PI2oL*mid2) * num2 ssum += sin(PI2oL*mid1) * num1 + sin(PI2oL*mid2) * num2 print(csum/count/(N-2)*3, ssum/count/(N-2)*3) ```
p03029 AtCoder Beginner Contest 128 - Apple Pie
We have A apples and P pieces of apple. We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan. Find the maximum number of apple pies we can make with what we have now. Constraints * All values in input are integers. * 0 \leq A, P \leq 100 Input Input is given from Standard Input in the following format: A P Output Print the maximum number of apple pies we can make with what we have. Examples Input 1 3 Output 3 Input 0 1 Output 0 Input 32 21 Output 58
```python A, P = map(int, input().split()) print(((A*3)+P)//2) ```
p03170 Educational DP Contest - Stones
There is a set A = \\{ a_1, a_2, \ldots, a_N \\} consisting of N positive integers. Taro and Jiro will play the following game against each other. Initially, we have a pile consisting of K stones. The two players perform the following operation alternately, starting from Taro: * Choose an element x in A, and remove exactly x stones from the pile. A player loses when he becomes unable to play. Assuming that both players play optimally, determine the winner. Constraints * All values in input are integers. * 1 \leq N \leq 100 * 1 \leq K \leq 10^5 * 1 \leq a_1 < a_2 < \cdots < a_N \leq K Input Input is given from Standard Input in the following format: N K a_1 a_2 \ldots a_N Output If Taro will win, print `First`; if Jiro will win, print `Second`. Examples Input 2 4 2 3 Output First Input 2 5 2 3 Output Second Input 2 7 2 3 Output First Input 3 20 1 2 3 Output Second Input 3 21 1 2 3 Output First Input 1 100000 1 Output Second
```python n, k = [int(i) for i in input().split()] A = [int(i) for i in input().split()] DP = [False] * (k + 1) for i in range(1, k+1): DP[i] = any(not DP[i-a] for a in A if i - a >= 0) print('First' if DP[k] else 'Second') ```
p03315 AtCoder Beginner Contest 101 - Eating Symbols Easy
There is always an integer in Takahashi's mind. Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is `+` or `-`. When he eats `+`, the integer in his mind increases by 1; when he eats `-`, the integer in his mind decreases by 1. The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat. Find the integer in Takahashi's mind after he eats all the symbols. Constraints * The length of S is 4. * Each character in S is `+` or `-`. Input Input is given from Standard Input in the following format: S Output Print the integer in Takahashi's mind after he eats all the symbols. Examples Input +-++ Output 2 Input -+-- Output -2 Input ---- Output -4
```python s=list(input()) print(s.count("+")*2-4) ```
p03472 AtCoder Beginner Contest 085 - Katana Thrower
You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order: * Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times. * Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana. The monster will vanish when the total damage it has received is H points or more. At least how many attacks do you need in order to vanish it in total? Constraints * 1 ≤ N ≤ 10^5 * 1 ≤ H ≤ 10^9 * 1 ≤ a_i ≤ b_i ≤ 10^9 * All input values are integers. Input Input is given from Standard Input in the following format: N H a_1 b_1 : a_N b_N Output Print the minimum total number of attacks required to vanish the monster. Examples Input 1 10 3 5 Output 3 Input 2 10 3 5 2 6 Output 2 Input 4 1000000000 1 1 1 10000000 1 30000000 1 99999999 Output 860000004 Input 5 500 35 44 28 83 46 62 31 79 40 43 Output 9
```python import math N,H=map(int,input().split()) ab=[[int(x) for x in input().split()] for _ in range(N)] a,_=max(ab) B=sorted([b for _,b in ab if b > a], reverse=True) sb=sum(B) if sb < H: print(len(B)+math.ceil((H-sb)/a)) else: B.insert(0, 0) for i in range(1, len(B)): B[i] += B[i-1] if B[i] >= H: break print(i) ```
p03634 AtCoder Beginner Contest 070 - Transit Tree Path
You are given a tree with N vertices. Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices. The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i. You are also given Q queries and an integer K. In the j-th query (1≤j≤Q): * find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K. Constraints * 3≤N≤10^5 * 1≤a_i,b_i≤N (1≤i≤N-1) * 1≤c_i≤10^9 (1≤i≤N-1) * The given graph is a tree. * 1≤Q≤10^5 * 1≤K≤N * 1≤x_j,y_j≤N (1≤j≤Q) * x_j≠y_j (1≤j≤Q) * x_j≠K,y_j≠K (1≤j≤Q) Input Input is given from Standard Input in the following format: N a_1 b_1 c_1 : a_{N-1} b_{N-1} c_{N-1} Q K x_1 y_1 : x_{Q} y_{Q} Output Print the responses to the queries in Q lines. In the j-th line j(1≤j≤Q), print the response to the j-th query. Examples Input 5 1 2 1 1 3 1 2 4 1 3 5 1 3 1 2 4 2 3 4 5 Output 3 2 4 Input 7 1 2 1 1 3 3 1 4 5 1 5 7 1 6 9 1 7 11 3 2 1 3 4 5 6 7 Output 5 14 22 Input 10 1 2 1000000000 2 3 1000000000 3 4 1000000000 4 5 1000000000 5 6 1000000000 6 7 1000000000 7 8 1000000000 8 9 1000000000 9 10 1000000000 1 1 9 10 Output 17000000000
```python import sys input = sys.stdin.readline N = int(input()) G = [[] * N for _ in range(N)] for _ in range(N - 1): a, b, c = map(int, input().split()) G[a - 1].append((b - 1, c)) G[b - 1].append((a - 1, c)) Q, K = map(int, input().split()) D = [-1] * N s = [(K - 1, 0)] while s: v, c = s.pop() D[v] = c for vv, cc in G[v]: if D[vv] < 0: s.append((vv, cc + c)) for _ in range(Q): x, y = map(int, input().split()) print(D[x - 1] + D[y - 1]) ```
p03792 Mujin Programming Challenge 2017 - Row to Column
There is a square-shaped grid with N vertical rows and N horizontal columns. We will denote the square at the i-th row from the top and the j-th column from the left as (i,\ j). Initially, each square is either white or black. The initial color of the grid is given to you as characters a_{ij}, arranged in a square shape. If the square (i,\ j) is white, a_{ij} is `.`. If it is black, a_{ij} is `#`. You are developing a robot that repaints the grid. It can repeatedly perform the following operation: * Select two integers i, j (1 ≤ i,\ j ≤ N). Memorize the colors of the squares (i,\ 1), (i,\ 2), ..., (i,\ N) as c_1, c_2, ..., c_N, respectively. Then, repaint the squares (1,\ j), (2,\ j), ..., (N,\ j) with the colors c_1, c_2, ..., c_N, respectively. Your objective is to turn all the squares black. Determine whether it is possible, and find the minimum necessary number of operations to achieve it if the answer is positive. Constraints * 2 ≤ N ≤ 500 * a_{ij} is either `.` or `#`. Input The input is given from Standard Input in the following format: N a_{11}...a_{1N} : a_{N1}...a_{NN} Output If it is possible to turn all the squares black, print the minimum necessary number of operations to achieve the objective. If it is impossible, print `-1` instead. Examples Input 2 #. .# Output 3 Input 2 . .# Output 3 Input 2 .. .. Output -1 Input 2 Output 0 Input 3 .#. .#. Output 2 Input 3 ... .#. ... Output 5
```python def main(): n = int(input()) grid = [input() for _ in [0]*n] for i in grid: if "#" in i: break else: print(-1) return ans = 10**20 # i行目に何個黒があるか black_cnt = [0]*n # i列目に黒が一つでもあればTrue exist = [False]*n for i in range(n): for j in range(n): if grid[i][j] == "#": black_cnt[i] += 1 exist[j] = True # 縦一列が既に黒の列の数 all_cnt = 0 for j in range(n): for i in range(n): if grid[i][j] == ".": break else: all_cnt += 1 for i in range(n): if exist[i]: ans = min(ans, n-black_cnt[i]+n-all_cnt) else: ans = min(ans, 2*n-black_cnt[i]-all_cnt+1) print(ans) main() ```
p03961 CODE FESTIVAL 2016 qual C - Encyclopedia of Permutations
One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order. Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it. His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i. He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7. Constraints * 1 ≤ N ≤ 500000 * 0 ≤ P_i ≤ N * P_i ≠ P_j if i ≠ j (1 ≤ i, j ≤ N), P_i ≠ 0 and P_j ≠ 0. Input The input is given from Standard Input in the following format: N P_1 P_2 ... P_N Output Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7. Examples Input 4 0 2 3 0 Output 23 Input 3 0 0 0 Output 21 Input 5 1 2 3 5 4 Output 2 Input 1 0 Output 1 Input 10 0 3 0 0 1 0 4 0 0 0 Output 953330050
```python import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(max(1000, 10**9)) write = lambda x: sys.stdout.write(x+"\n") M = 10**9+7 n = int(input()) p = list(map(int, input().split())) g1 = [None]*(n+10) v = 1 g1[0] = 1 for i in range(1,len(g1)): v *= i v %= M g1[i] = v def init(bit, values): for i,v in enumerate(values): add(bit,i+1,v) #a1 ~ aiまでの和 O(logn) def query(bit,i): res = 0 while i > 0: res += bit[i] i -= i&(-i) return res #ai += x(logN) def add(bit,i,x): if i==0: raise RuntimeError while i <= len(bit)-1: bit[i] += x i += i&(-i) return index = [i for i,num in enumerate(p) if num==0] used = [False]*n for i in range(n): if p[i]>0: used[p[i]-1] = True nl = [] for i in range(n): if not used[i]: nl.append(i+1) nl.sort() scores = [0]*(n+1) # scores[i]: nlのうちiより大きいものの個数 v = len(nl) cur = 0 for i in range(1,n+1): if nl and cur<len(nl) and nl[cur]<i: # if nl and nl[cur]<i: cur += 1 v -= 1 scores[i] = v ans = 0 bit = [0]*(n+1) s = set(index) val = 0 pp = len(index) # 欠損の個数 ss = sum(nl) num = 0 inv2 = pow(2, M-2, M) for i in range(n): if i in s: ans += (g1[pp-1] * (ss - pp - val - pp*(num)*inv2)) * g1[n-i-1] num += 1 else: ans += (g1[pp] * (p[i]-query(bit, p[i])-1) - g1[pp-1]*num*(len(nl)-scores[p[i]])) * g1[n-i-1] add(bit, p[i], 1) val += scores[p[i]] ans %= M # print(ans, val) print((ans + g1[pp])%M) ```
p00052 Factorial II
n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1 Is called the factorial of n. For example, the factorial of 12 12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600 And there are two consecutive 0s at the end. Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of n !. However, n is a positive integer less than or equal to 20000. Input Multiple data are given. Each piece of data is given n (n ≤ 20000) on one line. When n is 0, it is the last input. The number of data does not exceed 20. Output For each data, output the number of 0s that are consecutively arranged at the end of n! On one line. Example Input 2 12 10000 0 Output 0 2 2499
```python import sys f = sys.stdin while True: n = int(f.readline()) if n == 0: break zero_count = 0 while n: n //= 5 zero_count += n print(zero_count) ```
p00338 Programming Contest II
White Tiger University holds a programming contest every year. The contest starts with a score of 0 for all teams, and points are added according to the answer status. In this contest, rankings will be made in descending order of score. When the total number of teams is N, each team is assigned a number from 1 to N. If the scores are the same, the one with the smaller number will be ranked higher. White Tiger University is developing a ranking system for watching games to liven up the contest. As a member of the development team, you are responsible for creating the programs that are part of this system. Create a program that updates the score and reports the number and score of the team in the specified ranking according to the instructions given. Input The input is given in the following format. N C command1 command2 :: commandC The number of teams N (2 ≤ N ≤ 100000) and the number of instructions C (1 ≤ C ≤ 100000) are given on the first line. Instructions are given line by line to the following C line. Each instruction is given in the following format. 0 t p Or 1 m When the first number is 0, it indicates an update command, and when it is 1, it represents a report command. The update instruction adds the integer score p (1 ≤ p ≤ 109) to the team with the specified number t (1 ≤ t ≤ N). The reporting order reports the number and score of the team with the specified rank m (1 ≤ m ≤ N). However, the reporting order shall appear at least once. Output For each report command, the number and score of the team with the specified rank are output on one line separated by blanks. Examples Input 3 11 0 2 5 0 1 5 0 3 4 1 1 1 2 1 3 0 3 2 1 1 0 2 1 1 2 1 3 Output 1 5 2 5 3 4 3 6 3 6 1 5 Input 5 2 1 1 1 2 Output 1 0 2 0
```python from bisect import bisect_left as bl def main(): n, c = map(int, input().split()) ranking = [(0, i) for i in range(n)] points = [0 for _ in range(n)] for _ in range(c): com = input().split() if com[0] == "1": m = int(com[1]) - 1 print(ranking[m][-1] + 1, -ranking[m][0]) else: t, p = map(int, com[1:]) t -= 1 point = points[t] index = bl(ranking, (point, t)) ranking.pop(index) new_point = point - p new_index = bl(ranking, (new_point, t)) ranking.insert(new_index, (new_point, t)) points[t] = new_point main() ```
p00837 Book Replacement
The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have to copy pages of many reference books in the library. All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain a copy of a reference book’s page, a student should ask the librarian to make it. The librarian brings books out of the storeroom and makes page copies according to the requests. The overall situation is shown in Figure 1. Students queue up in front of the counter. Only a single book can be requested at a time. If a student has more requests, the student goes to the end of the queue after the request has been served. In the storeroom, there are m desks D1, ... , Dm, and a shelf. They are placed in a line in this order, from the door to the back of the room. Up to c books can be put on each of the desks. If a student requests a book, the librarian enters the storeroom and looks for it on D1, ... , Dm in this order, and then on the shelf. After finding the book, the librarian takes it and gives a copy of a page to the student. <image> Then the librarian returns to the storeroom with the requested book, to put it on D1 according to the following procedure. * If D1 is not full (in other words, the number of books on D1 < c), the librarian puts the requested book there. * If D1 is full, the librarian * temporarily puts the requested book on the non-full desk closest to the entrance or, in case all the desks are full, on the shelf, * finds the book on D1 that has not been requested for the longest time (i.e. the least recently used book) and takes it, * puts it on the non-full desk (except D1 ) closest to the entrance or, in case all the desks except D1 are full, on the shelf, * takes the requested book from the temporary place, * and finally puts it on D1 . Your task is to write a program which simulates the behaviors of the students and the librarian, and evaluates the total cost of the overall process. Costs are associated with accessing a desk or the shelf, that is, putting/taking a book on/from it in the description above. The cost of an access is i for desk Di and m + 1 for the shelf. That is, an access to D1, ... , Dm , and the shelf costs 1, ... , m, and m + 1, respectively. Costs of other actions are ignored. Initially, no books are put on desks. No new students appear after opening the library. Input The input consists of multiple datasets. The end of the input is indicated by a line containing three zeros separated by a space. It is not a dataset. The format of each dataset is as follows. m c n k1 b11 . . . b1k1 . . . kn bn1 . . . bnkn Here, all data items are positive integers. m is the number of desks not exceeding 10. c is the number of books allowed to put on a desk, which does not exceed 30. n is the number of students not exceeding 100. ki is the number of books requested by the i-th student, which does not exceed 50. bij is the ID number of the book requested by the i-th student on the j-th turn. No two books have the same ID number. Note that a student may request the same book more than once. bij is less than 100. Here we show you an example of cost calculation for the following dataset. 3 1 2 3 60 61 62 2 70 60 In this dataset, there are 3 desks (D1, D2, D3 ). At most 1 book can be put on each desk. The number of students is 2. The first student requests 3 books of which IDs are 60, 61, and 62, respectively, and the second student 2 books of which IDs are 70 and 60, respectively. The calculation of the cost for this dataset is done as follows. First, for the first request of the first student, the librarian takes the book 60 from the shelf and puts it on D1 and the first student goes to the end of the queue, costing 5. Next, for the first request of the second student, the librarian takes the book 70 from the shelf, puts it on D2, moves the book 60 from D1 to D3 , and finally moves the book 70 from D2 to D1 , costing 13. Similarly, the cost for the books 61, 60, and 62, are calculated as 14, 12, 14, respectively. Therefore, the total cost is 58. Output For each dataset, output the total cost of processing all the requests, in a separate line. Example Input 2 1 1 1 50 2 1 2 1 50 1 60 2 1 2 2 60 61 1 70 4 2 3 3 60 61 62 1 70 2 80 81 3 1 2 3 60 61 62 2 70 60 1 2 5 2 87 95 3 96 71 35 2 68 2 3 3 18 93 2 57 2 2 2 1 5 1 2 1 3 1 0 0 0 Output 4 16 28 68 58 98 23
```python def solve(): from collections import deque from sys import stdin f_i = stdin ans = [] while True: m, c, n = map(int, f_i.readline().split()) if m == 0: break book_pos = dict() studens = deque() shelf = m + 1 for i in range(n): k = int(f_i.readline()) books = deque(map(int, f_i.readline().split())) for b in books: book_pos[b] = shelf studens.append(books) desk = [0] * (m + 1) # number of books on the desk D1 = deque() cost = 0 while studens: s = studens.popleft() b = s.popleft() # get the book pos = book_pos[b] cost += pos if pos == 1: D1.remove(b) elif pos != shelf: desk[pos] -= 1 if len(D1) == c: for i, cnt in enumerate(desk[2:], start=2): if cnt < c: # put the book on the i-th desk desk[i] += 1 book_pos[b] = i cost += i b_pos = i break else: # put the book on the shelf book_pos[b] = shelf cost += shelf b_pos = shelf # get the unrequested book on D1 unrequested = D1.popleft() cost += 1 if b_pos == shelf: # put the unrequested book to the shelf book_pos[unrequested] = shelf cost += shelf else: for i, cnt in enumerate(desk[b_pos:], start=b_pos): if cnt < c: # put the unrequested book to i-th desk desk[i] += 1 book_pos[unrequested] = i cost += i break else: # put the unrequested book to the shelf book_pos[unrequested] = shelf cost += shelf # take the book from the temporary place to D1 if b_pos != shelf: desk[b_pos] -= 1 D1.append(b) book_pos[b] = 1 cost += (b_pos + 1) else: # return the book to D1 D1.append(b) book_pos[b] = 1 cost += 1 if s: studens.append(s) ans.append(cost) print('\n'.join(map(str, ans))) solve() ```
p00969 Arithmetic Progressions
Arithmetic Progressions An arithmetic progression is a sequence of numbers $a_1, a_2, ..., a_k$ where the difference of consecutive members $a_{i+1} - a_i$ is a constant ($1 \leq i \leq k-1$). For example, the sequence 5, 8, 11, 14, 17 is an arithmetic progression of length 5 with the common difference 3. In this problem, you are requested to find the longest arithmetic progression which can be formed selecting some numbers from a given set of numbers. For example, if the given set of numbers is {0, 1, 3, 5, 6, 9}, you can form arithmetic progressions such as 0, 3, 6, 9 with the common difference 3, or 9, 5, 1 with the common difference -4. In this case, the progressions 0, 3, 6, 9 and 9, 6, 3, 0 are the longest. Input The input consists of a single test case of the following format. $n$ $v_1$ $v_2$ ... $v_n$ $n$ is the number of elements of the set, which is an integer satisfying $2 \leq n \leq 5000$. Each $v_i$ ($1 \leq i \leq n$) is an element of the set, which is an integer satisfying $0 \leq v_i \leq 10^9$. $v_i$'s are all different, i.e., $v_i \ne v_j$ if $i \ne j$. Output Output the length of the longest arithmetic progressions which can be formed selecting some numbers from the given set of numbers. Sample Input 1 6 0 1 3 5 6 9 Sample Output 1 4 Sample Input 2 7 1 4 7 3 2 6 5 Sample Output 2 7 Sample Input 3 5 1 2 4 8 16 Sample Output 3 2 Example Input 6 0 1 3 5 6 9 Output 4
```python #!/usr/bin/python3 import os import sys def main(): N = read_int() V = read_ints() print(solve(N, V)) def solve(N, V): V.sort() pos = {} for i, a in enumerate(V): pos[a] = i best = 2 done = [[False] * N for _ in range(N)] for i in range(N): a = V[i] for j in range(i + 1, N): if done[i][j]: continue b = V[j] d = b - a c = 2 done[i][j] = True k = j v = b + d while v in pos: done[k][pos[v]] = True k = pos[v] c += 1 v += d best = max(best, c) return best ############################################################################### # AUXILIARY FUNCTIONS DEBUG = 'DEBUG' in os.environ def inp(): return sys.stdin.readline().rstrip() def read_int(): return int(inp()) def read_ints(): return [int(e) for e in inp().split()] def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) if __name__ == '__main__': main() ```
p01101 Taro's Shopping
Taro's Shopping Mammy decided to give Taro his first shopping experience. Mammy tells him to choose any two items he wants from those listed in the shopping catalogue, but Taro cannot decide which two, as all the items look attractive. Thus he plans to buy the pair of two items with the highest price sum, not exceeding the amount Mammy allows. As getting two of the same item is boring, he wants two different items. You are asked to help Taro select the two items. The price list for all of the items is given. Among pairs of two items in the list, find the pair with the highest price sum not exceeding the allowed amount, and report the sum. Taro is buying two items, not one, nor three, nor more. Note that, two or more items in the list may be priced equally. Input The input consists of multiple datasets, each in the following format. n m a1 a2 ... an A dataset consists of two lines. In the first line, the number of items n and the maximum payment allowed m are given. n is an integer satisfying 2 ≤ n ≤ 1000. m is an integer satisfying 2 ≤ m ≤ 2,000,000. In the second line, prices of n items are given. ai (1 ≤ i ≤ n) is the price of the i-th item. This value is an integer greater than or equal to 1 and less than or equal to 1,000,000. The end of the input is indicated by a line containing two zeros. The sum of n's of all the datasets does not exceed 50,000. Output For each dataset, find the pair with the highest price sum not exceeding the allowed amount m and output the sum in a line. If the price sum of every pair of items exceeds m, output `NONE` instead. Sample Input 3 45 10 20 30 6 10 1 2 5 8 9 11 7 100 11 34 83 47 59 29 70 4 100 80 70 60 50 4 20 10 5 10 16 0 0 Output for the Sample Input 40 10 99 NONE 20 Example Input 3 45 10 20 30 6 10 1 2 5 8 9 11 7 100 11 34 83 47 59 29 70 4 100 80 70 60 50 4 20 10 5 10 16 0 0 Output 40 10 99 NONE 20
```python while True: n,m = map(int,input().split(" ")) if n == 0: break items = [] for i in input().split(" "): items.append(int(i)) #全探索 items2 = items sums = [] for i in range(len(items)): for j in range(len(items)): if i == j: continue sums.append(items[i] + items2[j]) sums.sort(reverse=True) for i in range(len(sums)): if sums[i] <= m: print(sums[i]) break if i == len(sums) - 1: print("NONE") ```
p01400 Seishun 18 Kippu
Problem C: Seishun 18 Kippu A student at R University, sirokurostone, was about to attend a training camp at Atsu University. Other members plan to use the Shinkansen, but sirokurostone was going to use the Seishun 18 Ticket. Similarly, a person who likes 2D with a youth 18 ticket was also trying to participate in the training camp. Sirokurostone, who wanted to go with him anyway, decided to pick up him who likes 2D at the station on the way. sirokurostone wants to check the delay situation before leaving R University and take a route that takes less time to reach the station where Atsu University is located. sirokurostone intends to give that information to him who likes 2D after the route is confirmed. However, sirokurostone is in trouble because he does not know which route to take to reach the station where Atsu University is located sooner even if he sees the delay situation. So your job is to find out how long it will take to get to the station where Atsu University is located on behalf of sirokurostone from the delay situation. Between each station, there is a distance between stations and an estimated delay time. The train shall maintain 40km / h after it starts moving. The travel time between points a and b is * Distance / 40+ estimated delay time Can be obtained at. The stop time at each station can be ignored. Input A sequence of multiple datasets is given as input. The number of datasets is guaranteed to be 50 or less. Each dataset has the following format: n m s p g a1 b1 d1 t1 ... ai bi di ti ... am bm dm tm The integers n (3 ≤ n ≤ 500) and m (2 ≤ m ≤ 5000) represent the total number of stations and the number of tracks between each station, respectively. s, p, and g are character strings that indicate the location of the station where sirokurostone rides, the station where a person who likes 2D rides, and the station where Atsu University is located, respectively. s, p, and g are different character strings. The following m line represents the information between stations. ai and bi are character strings indicating stations connected by railroad tracks. ai and bi can go back and forth in both directions. ai and bi never match. The integer di (40 ≤ di ≤ 10000) represents the distance between ai and bi. di is guaranteed to be a multiple of 40. The integer ti (0 ≤ ti ≤ 20) indicates the estimated delay time between ai and bi. The character string representing the station name is represented by a character string of 20 characters or less consisting of all lowercase and uppercase letters of the alphabet. There is at most one track between stations. The end of the input is represented by a line containing two zeros. Output For each input dataset, output the arrival time (unit: time) to the station where Atsu University is located. It is guaranteed that there is a route from the station where sirokurostone rides to the station where 2D lovers ride, and a route from the station where 2D lovers ride to the station where Atsu University is located. Sample Input 4 4 A B G A B 40 3 B C 80 0 A G 40 0 B G 80 0 5 6 Kusatsu Tokyo Aizu Tokyo Nagoya 120 3 Kusatsu Nagoya 40 0 Kusatsu Kanazawa 40 0 Kanazawa Aizu 40 0 Tokyo Kanazawa 40 0 Tokyo Aizu 80 4 0 0 Output for Sample Input Five Four Example Input 4 4 A B G A B 40 3 B C 80 0 A G 40 0 B G 80 0 5 6 Kusatsu Tokyo Aizu Tokyo Nagoya 120 3 Kusatsu Nagoya 40 0 Kusatsu Kanazawa 40 0 Kanazawa Aizu 40 0 Tokyo Kanazawa 40 0 Tokyo Aizu 80 4 0 0 Output 5 4
```python from heapq import heappush, heappop while True: n, m = map(int, input().split()) if n == 0:break s, p, g = input().split() edges = {} for _ in range(m): a, b, d, t = input().split() if a not in edges:edges[a] = [] if b not in edges:edges[b] = [] d = int(d) t = int(t) edges[a].append((b, d // 40 + t)) edges[b].append((a, d // 40 + t)) INF = 10 ** 20 def score(start, goal): dist = {name:INF for name in edges.keys()} dist[start] = 0 que = [] heappush(que, (0, start)) while que: total, name = heappop(que) if name == goal: return total for to, cost in edges[name]: if dist[to] > total + cost: dist[to] = total + cost heappush(que, (total + cost, to)) print(score(s, p) + score(p, g)) ```
p01553 Hakone
Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station. So, look at it and tell us how many possible passage orders for each team at the previous relay station. The number of possible transit orders can be very large, so answer by the remainder divided by 1,000,000,007. Input The input is given in the form: > n > c1 > c2 > ... > cn > The number n (1 ≤ n ≤ 200) representing the number of teams is on the first line, and the ranking changes from the previous relay station in order from the first place on the following n lines. If it is'`U`', the ranking is up, if it is'`-`', the ranking is not changed) is written. Output Please output in one line by dividing the number of passages that could have been the previous relay station by 1,000,000,007. Examples Input 3 - U D Output 1 Input 5 U U - D D Output 5 Input 8 U D D D D D D D Output 1 Input 10 U D U D U D U D U D Output 608 Input 2 D U Output 0
```python #!/usr/bin/env python3 import sys import math from bisect import bisect_right as br from bisect import bisect_left as bl sys.setrecursionlimit(2147483647) from heapq import heappush, heappop,heappushpop from collections import defaultdict from itertools import accumulate from collections import Counter from collections import deque from operator import itemgetter from itertools import permutations mod = 10**9 + 7 inf = float('inf') def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) # 参考にしました(参考というよりほぼ写経) # https://drken1215.hatenablog.com/entry/2019/10/05/173700 n = I() dp = [[0] * (n+2) for _ in range(n+1)] # 今回の順位と前回の順位を結んだグラフを考える # dp[i][j] := i番目まで見たときに, j個繋がっているときの場合の数 dp[0][0] = 1 for i in range(n): s = input() if s == 'U': # Uのとき,今回順位から前回順位に向かう辺は必ず下向きなので # i+1番目まで見たときに今回順位からの辺によってjが増加することはない # jが増加するのは前回順位からの辺が上に伸びている場合 # このとき,対応するペアを今回順位の中からi-j個の中から選ぶ for j in range(n): dp[i+1][j] += dp[i][j]# 今回順位からも前回順位からも下へ伸びている場合 dp[i+1][j+1] += dp[i][j] * (i - j)# 今回順位からは下へ,前回順位からは上へ伸びている場合 dp[i+1][j+1] %= mod elif s == '-': # -のとき,今回順位から前回順位に向かう辺は必ず同じ位置であり, # 前回順位から今回順位へ向かう辺も必ず同じ位置である # つまり,jが1だけ増加する for j in range(n): dp[i+1][j+1] += dp[i][j] else: # Dのとき,今回順位から前回順位に向かう辺は必ず上向きなので # i+1番目まで見たときに今回順位からの辺によって必ずjが増加する # 前回順位から今回順位へ向かう辺が上向きの場合は,両方ともjが増加するのでj+2 # 前回順位から今回順位へ向かう辺が下向きの場合は,jが増加しないのでj+1 for j in range(n): dp[i+1][j+2] += dp[i][j] * (i - j) * (i - j)# 今回順位からも前回順位からも上へ伸びている場合 dp[i+1][j+2] %= mod dp[i+1][j+1] += dp[i][j] * (i - j)# 今回順位からは上へ,前回順位からは下へ伸びている場合 dp[i+1][j+1] %= mod print(dp[n][n]) ```
p01854 Pots
Problem statement Here are N mysteriously shaped vases. The i-th jar is a shape in which K_i right-sided cylinders are vertically connected in order from the bottom. The order in which they are connected cannot be changed. Mr. A has a volume of water of M. Pour this water into each jar in any amount you like. It does not matter if there is a jar that does not contain any water. Also, when all the vases are filled with water, no more water can be poured. Find the maximum sum of the heights of the water surface of each jar. input N \ M K_1 \ S_ {11} \ H_ {11} \… \ S_ {1 K_1} \ H_ {1 K_1} K_2 \ S_ {21} \ H_ {21} \… \ S_ {2 K_2} \ H_ {2 K_2} ... K_N \ S_ {N1} \ H_ {N1} \… \ S_ {N K_N} \ H_ {N K_N} N and M are entered in the first line, and the information of the i-th jar is entered in the 1 + i line. K_i is the number of right-sided cylinders, and S_ {ij} and H_ {ij} are the base area and height of the j-th right-sided cylinder that makes up the jar, respectively. Constraint * An integer * 1 ≤ N ≤ 200 * 1 ≤ M ≤ 200 * 1 ≤ K_i ≤ 20 * 1 ≤ S_ {ij} ≤ 20 * 1 ≤ H_ {ij} ≤ 20 output Output the answer in one line. It may include an absolute error of 0.00001 or less. sample Sample input 1 2 15 2 3 3 7 2 2 7 1 1 4 Sample output 1 6.33333333 Sample input 2 2 14 1 2 4 2 5 2 1 4 Sample output 2 6 The input and output of samples 1 and 2 are shown below. <image> Sample input 3 2 25 4 8 9 1 9 6 5 2 8 4 1 7 4 4 1 6 4 3 Sample output 3 13 Example Input 2 15 2 3 3 7 2 2 7 1 1 4 Output 6.33333333
```python def main(): n, m = map(int, input().split()) height = [] for _ in range(n): lst = list(map(int, input().split())) k = lst[0] ss = lst[1::2] hs = lst[2::2] v_acc = 0 h_acc = 0 index = 0 s, h = ss[0], hs[0] save = [] for i in range(m + 1): if i < v_acc + s * h: save.append(h_acc + (i - v_acc) / s) else: v_acc = i h_acc += h index += 1 save.append(h_acc) if index == k:break s, h = ss[index], hs[index] height.append(save) dp = [0] * (m + 1) for i in range(n): hi = height[i] for j in range(m, -1, -1): dp[j] = max([dp[j - v] + hi[v] for v in range(min(len(hi), j + 1))]) print(dp[-1]) main() ```
p01989 Internet Protocol Address
A: IP Address (Internet Protocol Address) problem Since one number string is given, find the number of valid delimiters for IPv4 IP addresses. However, the effective delimiters for IPv4 IP addresses are as follows. * The sequence of numbers is divided into four, and each of the separated columns satisfies all of the following. * Not an empty string. * When read as a decimal number, it is an integer between 0 and 255. * If the number is 0, then the column is `0` (` 00` etc. are not allowed). * If the number is non-zero, the first digit is not `0` (`01` etc. are not allowed). Input format S Constraint * 4 \ leq | S | \ leq 12 * S contains only numbers. Output format Output the number on one line according to the valid delimiter. Input example 1 123456789 Output example 1 1 There is one valid delimiter, `123.45.67.89`. Input example 2 768426 Output example 2 6 Example Input 123456789 Output 1
```python def check(num): if num == "":return False if num[0] == "0":return num == "0" return 0 <= int(num) <= 255 s = input() ans = 0 for i in range(1, 4): for j in range(1, 4): for k in range(1, 4): n1 = s[:i] n2 = s[i:i+j] n3 = s[i+j:i+j+k] n4 = s[i+j+k:] if check(n1) and check(n2) and check(n3) and check(n4):ans += 1 print(ans) ```
p02276 Partition
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q. In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r). Your task is to read a sequence A and perform the Partition based on the following pseudocode: Partition(A, p, r) 1 x = A[r] 2 i = p-1 3 for j = p to r-1 4 do if A[j] <= x 5 then i = i+1 6 exchange A[i] and A[j] 7 exchange A[i+1] and A[r] 8 return i+1 Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r]. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ Ai ≤ 100,000 Input The first line of the input includes an integer n, the number of elements in the sequence A. In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters. Output Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [ ]. Example Input 12 13 19 9 5 12 8 7 4 21 2 6 11 Output 9 5 8 7 4 2 6 [11] 21 13 19 12
```python def partition(A, p, r): i = p - 1 x = A[r] for j in range(p,r): if A[j] <= x: i += 1 A[i], A[j] = A[j], A[i] A[i+1], A[r] = A[r], A[i+1] return i n = int(input()) A = list(map(int, input().split())) i = partition(A, 0, n-1) str_A = list(map(str,A)) str_A[i+1] = "[" + str_A[i+1] + "]" print(" ".join(str_A)) ```
p02423 Bit Operation I
Given a non-negative decimal integer $x$, convert it to binary representation $b$ of 32 bits. Then, print the result of the following operations to $b$ respecitvely. * Inversion: change the state of each bit to the opposite state * Logical left shift: shift left by 1 * Logical right shift: shift right by 1 Constraints * $0 \leq x \leq 2^{32} - 1$ Input The input is given in the following format. $x$ Output Print the given bits, results of inversion, left shift and right shift in a line respectively. Examples Input 8 Output 00000000000000000000000000001000 11111111111111111111111111110111 00000000000000000000000000010000 00000000000000000000000000000100 Input 13 Output 00000000000000000000000000001101 11111111111111111111111111110010 00000000000000000000000000011010 00000000000000000000000000000110
```python x = int(input()) print('{:032b}'.format(x)) print('{:032b}'.format(~x & (2 ** 32 - 1))) print('{:032b}'.format(x << 1 & (2 ** 32 - 1))) print('{:032b}'.format(x >> 1)) ```
1027_A. Palindromic Twist
You are given a string s consisting of n lowercase Latin letters. n is even. For each position i (1 ≤ i ≤ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once. For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'. That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' → 'd', 'o' → 'p', 'd' → 'e', 'e' → 'd', 'f' → 'e', 'o' → 'p', 'r' → 'q', 'c' → 'b', 'e' → 'f', 's' → 't'). String s is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not. Your goal is to check if it's possible to make string s a palindrome by applying the aforementioned changes to every position. Print "YES" if string s can be transformed to a palindrome and "NO" otherwise. Each testcase contains several strings, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (1 ≤ T ≤ 50) — the number of strings in a testcase. Then 2T lines follow — lines (2i - 1) and 2i of them describe the i-th string. The first line of the pair contains a single integer n (2 ≤ n ≤ 100, n is even) — the length of the corresponding string. The second line of the pair contains a string s, consisting of n lowercase Latin letters. Output Print T lines. The i-th line should contain the answer to the i-th string of the input. Print "YES" if it's possible to make the i-th string a palindrome by applying the aforementioned changes to every position. Print "NO" otherwise. Example Input 5 6 abccba 2 cf 4 adfa 8 abaazaba 2 ml Output YES NO YES NO NO Note The first string of the example can be changed to "bcbbcb", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters. The second string can be changed to "be", "bg", "de", "dg", but none of these resulting strings are palindromes. The third string can be changed to "beeb" which is a palindrome. The fifth string can be changed to "lk", "lm", "nk", "nm", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings "ll" or "mm".
```python def get_mask(inp): return(5 << ord(inp) - ord('a')) n = int(input()) for i in range(0, n): input() st = input() ls = [] for j in st: ls.append(get_mask(j)) for j in range(0, len(ls) // 2): if(ls[j] & ls[-1 * (j + 1)] == 0): print("NO") break else: print("YES") ```
106_D. Treasure Island
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 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 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. Examples Input 6 10 ########## #K#..##### #.#..##.## #..L.#...# ###D###A.# ########## 4 N 2 S 1 E 1 W 2 Output AD Input 3 4 #### #.A# #### 2 W 1 N 2 Output no solution
```python #!/usr/bin/env python3 from sys import stdin n, m = map(int, stdin.readline().rstrip().split()) island = [] pos = {} for i in range(n): island.append(stdin.readline().rstrip()) for j, c in enumerate(island[i]): if c >= 'A' and c <= 'Z': pos[c] = [i, j] l_reach = [[-1 for j in range(m)] for i in range(n)] r_reach = [[-1 for j in range(m)] for i in range(n)] u_reach = [[-1 for j in range(m)] for i in range(n)] d_reach = [[-1 for j in range(m)] for i in range(n)] for i in range(1, n-1): for j in range(1, m-1): if island[i][j] != '#': l_reach[i][j] = 1 + l_reach[i][j-1] u_reach[i][j] = 1 + u_reach[i-1][j] for i in range(n-2, 0, -1): for j in range(m-2, 0, -1): if island[i][j] != '#': r_reach[i][j] = 1 + r_reach[i][j+1] d_reach[i][j] = 1 + d_reach[i+1][j] dir = [None] * 100 dir[ord('N')] = [-1, 0, u_reach] dir[ord('W')] = [0, -1, l_reach] dir[ord('S')] = [1, 0, d_reach] dir[ord('E')] = [0, 1, r_reach] for c in range(int(stdin.readline().rstrip())): x, y, d = dir[ord(stdin.read(1))] c = int(stdin.readline()[1:-1]) to_delete = [] for k, v in pos.items(): if c > d[v[0]][v[1]]: to_delete.append(k) else: v[0] += c * x v[1] += c * y for k in to_delete: del pos[k] ans = ''.join(sorted(pos.keys())) print(ans if ans else 'no solution') ```
1091_C. New Year and the Sphere Transmission
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well. The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes the ball to his k-th neighbour in the direction of increasing ids, that person passes the ball to his k-th neighbour in the same direction, and so on until the person with the id 1 gets the ball back. When he gets it back, people do not pass the ball any more. For instance, if n = 6 and k = 4, the ball is passed in order [1, 5, 3, 1]. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be 1 + 5 + 3 = 9. Find and report the set of possible fun values for all choices of positive integer k. It can be shown that under the constraints of the problem, the ball always gets back to the 1-st player after finitely many steps, and there are no more than 10^5 possible fun values for given n. Input The only line consists of a single integer n (2 ≤ n ≤ 10^9) — the number of people playing with the ball. Output Suppose the set of all fun values is f_1, f_2, ..., f_m. Output a single line containing m space separated integers f_1 through f_m in increasing order. Examples Input 6 Output 1 5 9 21 Input 16 Output 1 10 28 64 136 Note In the first sample, we've already shown that picking k = 4 yields fun value 9, as does k = 2. Picking k = 6 results in fun value of 1. For k = 3 we get fun value 5 and with k = 1 or k = 5 we get 21. <image> In the second sample, the values 1, 10, 28, 64 and 136 are achieved for instance for k = 16, 8, 4, 10 and 11, respectively.
```python n=int(input()) a={1} for i in range(2,int(n**0.5)+1): if n%i==0: a.add(i) a.add(n//i) ans=[1] a=list(a) for i in a: term=n//i ans.append((term*(2+(term-1)*i))//2) ans.sort() print(*ans) ```
1110_A. Parity
You are given an integer n (n ≥ 0) represented with k digits in base (radix) b. So, $$$n = a_1 ⋅ b^{k-1} + a_2 ⋅ b^{k-2} + … a_{k-1} ⋅ b + a_k.$$$ For example, if b=17, k=3 and a=[11, 15, 7] then n=11⋅17^2+15⋅17+7=3179+255+7=3441. Determine whether n is even or odd. Input The first line contains two integers b and k (2≤ b≤ 100, 1≤ k≤ 10^5) — the base of the number and the number of digits. The second line contains k integers a_1, a_2, …, a_k (0≤ a_i < b) — the digits of n. The representation of n contains no unnecessary leading zero. That is, a_1 can be equal to 0 only if k = 1. Output Print "even" if n is even, otherwise print "odd". You can print each letter in any case (upper or lower). Examples Input 13 3 3 2 7 Output even Input 10 9 1 2 3 4 5 6 7 8 9 Output odd Input 99 5 32 92 85 74 4 Output odd Input 2 2 1 0 Output even Note In the first example, n = 3 ⋅ 13^2 + 2 ⋅ 13 + 7 = 540, which is even. In the second example, n = 123456789 is odd. In the third example, n = 32 ⋅ 99^4 + 92 ⋅ 99^3 + 85 ⋅ 99^2 + 74 ⋅ 99 + 4 = 3164015155 is odd. In the fourth example n = 2.
```python b,k=map(int,input().split()) arr=list(map(int,input().split())) arr.insert(0,0) s=0 for i in range(1,len(arr)): s=s+(arr[-i]*pow(b,i-1,1000000000)) if(s&1): print("odd") else: print("even") ```
1158_B. The minimal unique substring
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010" is an unique substring of s, because l = 2 is the only one suitable number. But, for example t = "10" isn't a unique substring of s, because l = 1 and l = 3 are suitable. And for example t ="00" at all isn't a substring of s, because there is no suitable l. Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him. You are given 2 positive integers n and k, such that (n mod 2) = (k mod 2), where (x mod 2) is operation of taking remainder of x by dividing on 2. Find any string s consisting of n symbols "0" or "1", such that the length of its minimal unique substring is equal to k. Input The first line contains two integers n and k, separated by spaces (1 ≤ k ≤ n ≤ 100 000, (k mod 2) = (n mod 2)). Output Print a string s of length n, consisting of symbols "0" and "1". Minimal length of the unique substring of s should be equal to k. You can find any suitable string. It is guaranteed, that there exists at least one such string. Examples Input 4 4 Output 1111 Input 5 3 Output 01010 Input 7 3 Output 1011011 Note In the first test, it's easy to see, that the only unique substring of string s = "1111" is all string s, which has length 4. In the second test a string s = "01010" has minimal unique substring t ="101", which has length 3. In the third test a string s = "1011011" has minimal unique substring t ="110", which has length 3.
```python # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code if __name__ == "__main__": n,k = map(int,input().split()) a = (n - k)//2 ps = '0'*a + '1' s = "" i = 0 while i + a + 1 <= n: s += ps i += a+1 if i < n: x = n - i s += ps[:x] print(s) ```
1180_A. Alex and a Rhombus
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 × 1 (i.e just a cell). A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look at the picture to understand it better). <image> Alex asks you to compute the number of cells in a n-th order rhombus. Input The first and only input line contains integer n (1 ≤ n ≤ 100) — order of a rhombus whose numbers of cells should be computed. Output Print exactly one integer — the number of cells in a n-th order rhombus. Examples Input 1 Output 1 Input 2 Output 5 Input 3 Output 13 Note Images of rhombus corresponding to the examples are given in the statement.
```python n = int(input()) print(sum(range(n)) * 4 + 1) ```
1199_A. City Day
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct. The mayor knows that citizens will watch the weather x days before the celebration and y days after. Because of that, he says that a day d is not-so-rainy if a_d is smaller than rain amounts at each of x days before day d and and each of y days after day d. In other words, a_d < a_j should hold for all d - x ≤ j < d and d < j ≤ d + y. Citizens only watch the weather during summer, so we only consider such j that 1 ≤ j ≤ n. Help mayor find the earliest not-so-rainy day of summer. Input The first line contains three integers n, x and y (1 ≤ n ≤ 100 000, 0 ≤ x, y ≤ 7) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i denotes the rain amount on the i-th day. Output Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists. Examples Input 10 2 2 10 9 6 7 8 3 2 1 4 5 Output 3 Input 10 2 3 10 9 6 7 8 3 2 1 4 5 Output 8 Input 5 5 5 100000 10000 1000 100 10 Output 5 Note In the first example days 3 and 8 are not-so-rainy. The 3-rd day is earlier. In the second example day 3 is not not-so-rainy, because 3 + y = 6 and a_3 > a_6. Thus, day 8 is the answer. Note that 8 + y = 11, but we don't consider day 11, because it is not summer.
```python import sys,heapq,math from collections import deque,defaultdict printn = lambda x: sys.stdout.write(x) inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) DBG = True # and False R = 10**9 + 7 def ddprint(x): if DBG: print(x) n,x,y = inm() a = inl() for i in range(n): ok = True mn = max(0,i-x) mx = min(n-1,i+y) for j in range(mn,mx+1): if j!=i and a[j]<=a[i]: ok = False break if ok: print(i+1) exit() ```
1215_F. Radio Stations
In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of two radio stations x_i and y_i are not covering some parts of the city, and demanded that the signal of at least one of these stations can be received in the whole city. Of cousre, the mayor of Bertown is currently working to satisfy these complaints. A new radio tower has been installed in Bertown, it can transmit a signal with any integer power from 1 to M (let's denote the signal power as f). The mayor has decided that he will choose a set of radio stations and establish a contract with every chosen station. To establish a contract with the i-th station, the following conditions should be met: * the signal power f should be not less than l_i, otherwise the signal of the i-th station won't cover the whole city; * the signal power f should be not greater than r_i, otherwise the signal will be received by the residents of other towns which haven't established a contract with the i-th station. All this information was already enough for the mayor to realise that choosing the stations is hard. But after consulting with specialists, he learned that some stations the signals of some stations may interfere with each other: there are m pairs of stations (u_i, v_i) that use the same signal frequencies, and for each such pair it is impossible to establish contracts with both stations. If stations x and y use the same frequencies, and y and z use the same frequencies, it does not imply that x and z use the same frequencies. The mayor finds it really hard to analyze this situation, so he hired you to help him. You have to choose signal power f and a set of stations to establish contracts with such that: * all complaints are satisfied (formally, for every i ∈ [1, n] the city establishes a contract either with station x_i, or with station y_i); * no two chosen stations interfere with each other (formally, for every i ∈ [1, m] the city does not establish a contract either with station u_i, or with station v_i); * for each chosen station, the conditions on signal power are met (formally, for each chosen station i the condition l_i ≤ f ≤ r_i is met). Input The first line contains 4 integers n, p, M and m (2 ≤ n, p, M, m ≤ 4 ⋅ 10^5) — the number of complaints, the number of radio stations, maximum signal power and the number of interfering pairs, respectively. Then n lines follow, which describe the complains. Each line contains two integers x_i and y_i (1 ≤ x_i < y_i ≤ p) — the indices of the radio stations mentioned in the i-th complaint). All complaints are distinct. Then p lines follow, which describe the radio stations. Each line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ M) — the constrains on signal power that should be satisfied if the city establishes a contract with the i-th station. Then m lines follow, which describe the pairs of interfering radio stations. Each line contains two integers u_i and v_i (1 ≤ u_i < v_i ≤ p) — the indices of interfering radio stations. All these pairs are distinct. Output If it is impossible to choose signal power and a set of stations to meet all conditions, print -1. Otherwise print two integers k and f in the first line — the number of stations in the chosen set and the chosen signal power, respectively. In the second line print k distinct integers from 1 to p — the indices of stations to establish contracts with (in any order). If there are multiple answers, print any of them; you don't have to minimize/maximize the number of chosen stations, and the same applies to signal power. Examples Input 2 4 4 2 1 3 2 3 1 4 1 2 3 4 1 4 1 2 3 4 Output 2 3 1 3 Input 2 4 4 2 1 3 2 4 1 2 1 2 3 4 3 4 1 2 3 4 Output -1
```python # ------------------- fast io -------------------- import os import sys input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] SCC = SCC[::-1] cx = [-1] * (len(graph)) for i in range(len(SCC)): for j in SCC[i]: cx[j] = i return cx for _ in range(int(input()) if not True else 1): # n = int(input()) n, p, M, m = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() graph = [[] for __ in range(2 * p + 2 * M + 1)] for i in range(n): x, y = map(int, input().split()) x2 = (x + p) y2 = (y + p) graph[x2] += [y] graph[y2] += [x] for x in range(1, p + 1): l, r = map(int, input().split()) x2 = (x + p) l += 2 * p r += 2 * p + 1 graph[l+M] += [x2] graph[x] += [l] if r + M != 2 * p + 2 * M + 1: graph[r] += [x2] graph[x] += [r + M] for i in range(m): x, y = map(int, input().split()) x2 = (x + p) y2 = (y + p) graph[x] += [y2] graph[y] += [x2] for i in range(1, M): graph[2 * p + i + M] += [2 * p + i + M + 1] graph[2 * p + i + 1] += [2 * p + i] cx = find_SCC(graph) ans = [] for i in range(1, p + 1): if cx[i] > cx[i + p]: ans += [i] if not ans: print(-1) quit() for freq in range(M, 0, -1): if cx[2 * p + freq] > cx[2 * p + freq + M]: break print(len(ans), freq) print(*ans) ```
1239_A. Ivan the Fool and the Probability Theory
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side. Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7. Input The only line contains two integers n and m (1 ≤ n, m ≤ 100 000), the number of rows and the number of columns of the field. Output Print one integer, the number of random pictures modulo 10^9 + 7. Example Input 2 3 Output 8 Note The picture below shows all possible random pictures of size 2 by 3. <image>
```python n, m = map(int, input().split()) mod = 10**9+7 a = [] a.append(0) a.append(2) a.append(4) for i in range(3, max(n, m)+1): a.append((a[i-1]+a[i-2])%mod) print((a[m]-2 + a[n])%mod) ```
1257_C. Dominated Subarray
Let's call an array t dominated by value v in the next situation. At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1, 2, 3, 4, 5, 2], [11, 11] and [3, 2, 3, 2, 3] are dominated (by 2, 11 and 3 respectevitely) but arrays [3], [1, 2] and [3, 3, 2, 2, 1] are not. Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not. You are given array a_1, a_2, ..., a_n. Calculate its shortest dominated subarray or say that there are no such subarrays. The subarray of a is a contiguous part of the array a, i. e. the array a_i, a_{i + 1}, ..., a_j for some 1 ≤ i ≤ j ≤ n. Input The first line contains single integer T (1 ≤ T ≤ 1000) — the number of test cases. Each test case consists of two lines. The first line contains single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the corresponding values of the array a. It's guaranteed that the total length of all arrays in one test doesn't exceed 2 ⋅ 10^5. Output Print T integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or -1 if there are no such subarrays. Example Input 4 1 1 6 1 2 3 4 5 1 9 4 1 2 4 5 4 3 2 1 4 3 3 3 3 Output -1 6 3 2 Note In the first test case, there are no subarrays of length at least 2, so the answer is -1. In the second test case, the whole array is dominated (by 1) and it's the only dominated subarray. In the third test case, the subarray a_4, a_5, a_6 is the shortest dominated subarray. In the fourth test case, all subarrays of length more than one are dominated.
```python import collections ii = lambda: int(input()) iia = lambda: list(map(int,input().split())) isa = lambda: list(input().split()) t = ii() for i in range(t): n = ii() x = iia() if(n==1): print('-1') else: dist = collections.defaultdict(lambda : n) last = collections.defaultdict(lambda : -1) mini = n flag = 0 for i in range(n): if(dist[x[i]] == n and last[x[i]] == -1): last[x[i]] = i elif(last[x[i]] != -1 and dist[x[i]] > i-last[x[i]]): dist[x[i]] = i-last[x[i]]+1 last[x[i]] = i mini = min(dist[x[i]], mini) flag = 1 if(flag == 0): print(-1) else: print(mini) ```
1300_C. Anu Has a Function
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems. A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible? Input The first line contains a single integer n (1 ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different. Output Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any. Examples Input 4 4 0 11 6 Output 11 6 4 0 Input 1 13 Output 13 Note In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9. [11, 4, 0, 6] is also a valid answer.
```python import sys,os,io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) a = [int(i) for i in input().split()] m = 0 mi = 0 b = [-1]*(35) for i in range (len(a)): bi = bin(a[i])[2:][::-1] for j in range (len(bi)): if bi[j]=='1': if b[j]==-1: b[j] = i elif b[j]>=0: b[j] = -2 for i in range(34,-1,-1): if b[i]>=0: a[b[i]],a[0] = a[0],a[b[i]] break print(*a) ```
1324_D. Pair of Topics
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students. The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher). Your task is to find the number of good pairs of topics. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of topics. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the interestingness of the i-th topic for the teacher. The third line of the input contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 10^9), where b_i is the interestingness of the i-th topic for the students. Output Print one integer — the number of good pairs of topic. Examples Input 5 4 8 2 6 2 4 5 4 1 3 Output 7 Input 4 1 3 2 4 1 3 2 4 Output 0
```python R = lambda:map(int,input().split()) n = int(input()) a = list(R()) b = list(R()) dif = [(b[i] - a[i], 1) for i in range(n)] for x in dif: if x[0] < 0: dif.append((-x[0], 0)) dif = sorted(dif) count = 0 ans = 0 for i in range(1, len(dif)): if dif[i][1] == 1: count += 1 if dif[i][1] == 0: ans += count count = max(0, count-1) print(ans) ```
1343_C. Alternating Subsequence
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2]. You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence). Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements. In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a. It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a. Example Input 4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000 Output 2 -1 6 -2999999997 Note In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2]. In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3]. In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]. In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
```python t = int(input()) for tt in range(t): n = int(input()) arr = list(map(int,input().split())) mx = arr[0] sm = 0 for j in range(n): if (arr[j] * mx < 0 ): sm += mx mx = arr[j] else: mx = max(mx , arr[j]) print(sm + mx) ```
1365_D. Solve The Maze
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following: * Empty — '.' * Wall — '#' * Good person — 'G' * Bad person — 'B' The only escape from the maze is at cell (n, m). A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through. Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions. It is guaranteed that the cell (n,m) is empty. Vivek can also block this cell. Input The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers n, m (1 ≤ n, m ≤ 50) — the number of rows and columns in the maze. Each of the next n lines contain m characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person. Output For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No" You may print every letter in any case (upper or lower). Example Input 6 1 1 . 1 2 G. 2 2 #B G. 2 3 G.# B#. 3 3 #B. #.. GG. 2 2 #B B. Output Yes Yes No No Yes Yes Note For the first and second test cases, all conditions are already satisfied. For the third test case, there is only one empty cell (2,2), and if it is replaced with a wall then the good person at (1,2) will not be able to escape. For the fourth test case, the good person at (1,1) cannot escape. For the fifth test case, Vivek can block the cells (2,3) and (2,2). For the last test case, Vivek can block the destination cell (2, 2).
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- import collections def block(s,b): global m global n global maze broke=False if b>0: if maze[s][b-1]==".": maze[s][b-1]="#" elif maze[s][b-1]=="G": broke=True if b<m-1: if maze[s][b+1]==".": maze[s][b+1]="#" elif maze[s][b+1]=="G": broke=True if s>0: if maze[s-1][b]==".": maze[s-1][b]="#" elif maze[s-1][b]=="G": broke=True if s<n-1: if maze[s+1][b]==".": maze[s+1][b]="#" elif maze[s+1][b]=="G": broke=True return broke testcases=int(input()) for j in range(testcases): n,m=map(int,input().split()) #n is rows,m is columns maze=[] for s in range(n): row=[k for k in input()] maze.append(row) #block all the bad guys in, surround them all in with walls b1=False dict1={} for s in range(n): for b in range(m): dict1[(s,b)]=[] for s in range(n): for b in range(m): if maze[s][b]=="B": broke=block(s,b) if broke==True: b1=True break good=0 for s in range(n): for b in range(m): if maze[s][b]!="#": if maze[s][b]=="G": good+=1 if b>0: if maze[s][b-1]!="#": dict1[(s,b)].append((s,b-1)) if b<m-1: if maze[s][b+1]!="#": dict1[(s,b)].append((s,b+1)) if s>0: if maze[s-1][b]!="#": dict1[(s,b)].append((s-1,b)) if s<n-1: if maze[s+1][b]!="#": dict1[(s,b)].append((s+1,b)) visited=set([]) for s in dict1.keys(): if not(s in visited) and maze[s[0]][s[1]]=="G": queue=collections.deque([]) vis=set([s]) for b in dict1[s]: queue.append(b) vis.add(b) visited.add(b) while len(queue)>0: v0=queue.popleft() for b in dict1[v0]: if not(b in vis): vis.add(b) queue.append(b) if b in visited: vis.add((n-1,m-1)) break visited.add(b) if (n-1,m-1) in vis: continue else: b1=True break if good>=1 and maze[n-1][m-1]=="#": b1=True if b1==True: print("No") else: print("Yes") ```
1385_D. a-Good String
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The length of s is greater than 1, the first half of the string consists of only the character c (i.e. s_1=s_2=...=s_{n/2}=c) and the second half of the string (i.e. the string s_{n/2 + 1}s_{n/2 + 2} ... s_n) is a (c+1)-good string; * The length of s is greater than 1, the second half of the string consists of only the character c (i.e. s_{n/2 + 1}=s_{n/2 + 2}=...=s_n=c) and the first half of the string (i.e. the string s_1s_2 ... s_{n/2}) is a (c+1)-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good. In one move, you can choose one index i from 1 to n and replace s_i with any lowercase Latin letter (any character from 'a' to 'z'). Your task is to find the minimum number of moves required to obtain an 'a'-good string from s (i.e. c-good string for c= 'a'). It is guaranteed that the answer always exists. You have to answer t independent test cases. Another example of an 'a'-good string is as follows. Consider the string s = "cdbbaaaa". It is an 'a'-good string, because: * the second half of the string ("aaaa") consists of only the character 'a'; * the first half of the string ("cdbb") is 'b'-good string, because: * the second half of the string ("bb") consists of only the character 'b'; * the first half of the string ("cd") is 'c'-good string, because: * the first half of the string ("c") consists of only the character 'c'; * the second half of the string ("d") is 'd'-good string. Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 131~072) — the length of s. It is guaranteed that n = 2^k for some integer k ≥ 0. The second line of the test case contains the string s consisting of n lowercase Latin letters. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case, print the answer — the minimum number of moves required to obtain an 'a'-good string from s (i.e. c-good string with c = 'a'). It is guaranteed that the answer exists. Example Input 6 8 bbdcaaaa 8 asdfghjk 8 ceaaaabb 8 bbaaddcc 1 z 2 ac Output 0 7 4 5 1 1
```python import sys input = sys.stdin.readline def print(val): sys.stdout.write(str(val) + '\n') def solve(s,l,r,c): if l+1 == r: return int(s[l] != c) replace1 = replace2 = 0 for i in range(l,(l+r)//2): if s[i] != c: replace1 += 1 for i in range((l+r)//2, r): if s[i] != c: replace2 += 1 return min(replace2 + solve(s,l,(l+r)//2,chr(ord(c) + 1)),\ replace1 + solve(s,(l+r)//2,r,chr(ord(c) + 1))) def prog(): for _ in range(int(input())): n = int(input()) s = list(input().strip()) print(solve(s,0,n,'a')) prog() ```
1407_B. Big Vova
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years. You're given n positive integers a_1, a_2, ..., a_n. Using each of them exactly at once, you're to make such sequence b_1, b_2, ..., b_n that sequence c_1, c_2, ..., c_n is lexicographically maximal, where c_i=GCD(b_1,...,b_i) - the greatest common divisor of the first i elements of b. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it. A sequence a is lexicographically smaller than a sequence b if and only if one of the following holds: * a is a prefix of b, but a ≠ b; * in the first position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^3). Description of the test cases follows. The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3) — the length of the sequence a. The second line of each test case contains n integers a_1,...,a_n (1 ≤ a_i ≤ 10^3) — the sequence a. It is guaranteed that the sum of n over all test cases does not exceed 10^3. Output For each test case output the answer in a single line — the desired sequence b. If there are multiple answers, print any. Example Input 7 2 2 5 4 1 8 2 3 3 3 8 9 5 64 25 75 100 50 1 42 6 96 128 88 80 52 7 5 2 4 8 16 17 Output 5 2 8 2 1 3 9 3 8 100 50 25 75 64 42 128 96 80 88 52 7 17 2 4 8 16 Note In the first test case of the example, there are only two possible permutations b — [2, 5] and [5, 2]: for the first one c=[2, 1], for the second one c=[5, 1]. In the third test case of the example, number 9 should be the first in b, and GCD(9, 3)=3, GCD(9, 8)=1, so the second number of b should be 3. In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation b.
```python import sys,bisect,string,math,time,functools,random,fractions from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby rep=range;R=range def Golf():n,*t=map(int,open(0).read().split()) def I():return int(input()) def S_():return input() def IS():return input().split() def LS():return [i for i in input().split()] def MI():return map(int,input().split()) def LI():return [int(i) for i in input().split()] def LI_():return [int(i)-1 for i in input().split()] def NI(n):return [int(input()) for i in range(n)] def NI_(n):return [int(input())-1 for i in range(n)] def NLI(n):return [[int(i) for i in input().split()] for i in range(n)] def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)] def StoLI():return [ord(i)-97 for i in input()] def ItoS(n):return chr(n+97) def LtoS(ls):return ''.join([chr(i+97) for i in ls]) def RA():return map(int,open(0).read().split()) def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)] def RI(a=1,b=10):return random.randint(a,b) def Rtest(T): case,err=0,0 for i in range(T): inp=INP() a1,ls=naive(*inp) a2=solve(*inp) if a1!=a2: print((a1,a2),inp) err+=1 case+=1 print('Tested',case,'case with',err,'errors') def GI(V,E,ls=None,Directed=False,index=1): org_inp=[];g=[[] for i in range(V)] FromStdin=True if ls==None else False for i in range(E): if FromStdin: inp=LI() org_inp.append(inp) else: inp=ls[i] if len(inp)==2: a,b=inp;c=1 else: a,b,c=inp if index==1:a-=1;b-=1 aa=(a,c);bb=(b,c);g[a].append(bb) if not Directed:g[b].append(aa) return g,org_inp def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1): #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage mp=[boundary]*(w+2);found={} for i in R(h): s=input() for char in search: if char in s: found[char]=((i+1)*(w+2)+s.index(char)+1) mp_def[char]=mp_def[replacement_of_found] mp+=[boundary]+[mp_def[j] for j in s]+[boundary] mp+=[boundary]*(w+2) return h+2,w+2,mp,found def TI(n):return GI(n,n-1) def accum(ls): rt=[0] for i in ls:rt+=[rt[-1]+i] return rt def bit_combination(n,base=2): rt=[] for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s] return rt def gcd(x,y): if y==0:return x if x%y==0:return y while x%y!=0:x,y=y,x%y return y def YN(x):print(['NO','YES'][x]) def Yn(x):print(['No','Yes'][x]) def show(*inp,end='\n'): if show_flg:print(*inp,end=end) mo=10**9+7 #mo=998244353 inf=float('inf') FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb)) l_alp=string.ascii_lowercase #sys.setrecursionlimit(10**9) read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip() ## return prime factors of N as dictionary {prime p:power of p} ## within 2 sec for N = 2*10**20+7 def primeFactor(N): i,n=2,N ret={} d,sq=2,99 while i<=sq: k=0 while n%i==0: n,k,ret[i]=n//i,k+1,k+1 if k>0 or i==97: sq=int(n**(1/2)+0.5) if i<4: i=i*2-1 else: i,d=i+d,d^6 if n>1: ret[n]=1 return ret ## return divisors of n as list def divisor(n): div=[1] for i,j in primeFactor(n).items(): div=[(i**k)*d for d in div for k in range(j+1)] return div ## return the list of prime numbers in [2,N], using eratosthenes sieve ## around 800 ms for N = 10**6 by PyPy3 (7.3.0) @ AtCoder def PrimeNumSet(N): M=int(N**0.5) seachList=[i for i in range(2,N+1)] primes=[] while seachList: if seachList[0]>M: break primes.append(seachList[0]) tmp=seachList[0] seachList=[i for i in seachList if i%tmp!=0] return primes+seachList ## retrun LCM of numbers in list b ## within 2sec for no of B = 10*5 and Bi < 10**6 def LCM(b,mo=10**9+7): prs=PrimeNumSet(max(b)) M=dict(zip(prs,[0]*len(prs))) for i in b: dc=primeFactor(i) for j,k in dc.items(): M[j]=max(M[j],k) r=1 for j,k in M.items(): if k!=0: r*=pow(j,k,mo) r%=mo return r show_flg=False show_flg=True ans=0 for _ in range(I()): n=I() a=LI() a=sorted(a) m=a.pop() ans=[m] v=[0]*(n-1) ko=[[]for i in range(m+1)] for i in range(n-1): c=a[i] for j in divisor(c): ko[j]+=i, #show(ko) #for i in range(n): ans=[] g=m while g>1: dm=sorted(divisor(g))[::-1] tmp=[] for d in dm: if ko[d]: for x in ko[d]: if v[x]==0: v[x]=1 tmp+=x, if tmp: g=gcd(g,a[tmp[0]]) ans+=tmp break if sum(v)==n-1: break t=[m]+[a[i] for i in ans] print(*t) #show(a) ```
1474_F. 1 2 3 4 ...
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard. Igor generated sequence p using the following algorithm: 1. initially, p = [x]; 2. for each 1 ≤ i ≤ n he did the following operation |d_i| times: * if d_i ≥ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p; * if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p. For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5]. Igor decided to calculate the length of the longest increasing subsequence of p and the number of them. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element. For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}]. Input The first line contains a single integer n (1 ≤ n ≤ 50) — the length of the sequence d. The second line contains a single integer x (-10^9 ≤ x ≤ 10^9) — the integer on the blackboard. The third line contains n integers d_1, d_2, …, d_n (-10^9 ≤ d_i ≤ 10^9). Output Print two integers: * the first integer should be equal to the length of the longest increasing subsequence of p; * the second should be equal to the number of them modulo 998244353. You should print only the second number modulo 998244353. Examples Input 3 3 1 -1 2 Output 3 3 Input 3 100 5 -3 6 Output 9 7 Input 3 1 999999999 0 1000000000 Output 2000000000 1 Input 5 34 1337 -146 42 -69 228 Output 1393 3876 Note The first test case was explained in the statement. In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108]. In the third test case p = [1, 2, …, 2000000000].
```python import sys, io, os if os.environ['USERNAME']=='kissz': inp=open('in55.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def debug(*args): pass def mexp(size,power): A=[] for i in range(size): A.append([int(j<=(i//2)*2) for j in range(size)]) powers={1: A} p=1 while p*2<=power: powers[p*2]=mmmult(powers[p],powers[p]) p*=2 A=powers[p] power-=p while power>0: p=p//2 if p<=power: A=mmmult(A,powers[p]) power-=p return A def mvmult(A,V): res=[] for i in range(len(A)): res.append(sum(a*v for a,v in zip(A[i],V)) % 998244353 ) return res def mmmult(A,B): res=[] for i in range(len(A)): res.append([sum(a*B[j][k] for j,a in enumerate(A[i])) for k in range(len(B[0]))]) return res def get_rep(corners): corners[0]-=1 corners[-1]+=1 bps=sorted(list(set(corners))) m=len(bps) X=[1] active=[1] for i in range(1,m): x,y=bps[i-1],bps[i] d=y-x A=mexp(len(active),d) X=mvmult(A,X) #debug(active,X) #debug(A) if i<m-1: for j,c in enumerate(corners): if c==y: if j%2: # top: j and j+1 in active idx=active.index(j) X[idx+2]+=X[idx] active.pop(idx) active.pop(idx) X.pop(idx) X.pop(idx) else: # bottom active+=[j,j+1] active.sort() idx=active.index(j) X=X[:idx]+[0,X[idx-1]]+X[idx:] else: return X[0] n=int(inp()) inp() d,*D=map(int,inp().split()) if d==0 and all(dd==0 for dd in D): print(1,1) else: while d==0: d,*D=D up=(d>=0) corners=[0,d] for d in D: x=corners[-1]+d if up==(d>=0): corners[-1]=x if up!=(d>=0): up=(d>=0) corners.append(x) debug(corners) cands=[(-1,0,0)] low=(0,0) maxdiff=(0,0,0) for i,corner in enumerate(corners): if corner<low[0]: low=(corner,i) if corner-low[0]>=cands[0][0]: if corner-low[0]==cands[0][0] and low[1]>cands[0][1]: cands+=[(corner-low[0],low[1],i)] else: cands=[(corner-low[0],low[1],i)] L=cands[0][0]+1 if L>1: X=0 debug(cands) for _, starti, endi in cands: #debug(corners[starti:endi+1]) X+=get_rep(corners[starti:endi+1]) else: X=1-corners[-1] print(L,X % 998244353) ```
14_C. Four Segments
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him. Input The input data contain four lines. Each of these lines contains four integers x1, y1, x2, y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — coordinates of segment's beginning and end positions. The given segments can degenerate into points. Output Output the word «YES», if the given four segments form the required rectangle, otherwise output «NO». Examples Input 1 1 6 1 1 0 6 0 6 0 6 1 1 1 1 0 Output YES Input 0 0 0 3 2 0 0 0 2 2 2 0 0 2 2 2 Output NO
```python def is_rect(es): v = set([]) for e in es: if not ((e[0] == e[2]) or (e[1] == e[3])): return False v.add((e[0], e[1])) v.add((e[2], e[3])) if len(v) != 4: return False xs = set([]) ys = set([]) for vi in v: xs.add(vi[0]) ys.add(vi[1]) if len(xs) != 2 or len(ys) != 2: return False t = b = r = l = False for e in es: t = t or (e[1] == e[3] and e[0] != e[2] and e[1] == max(ys)) b = b or (e[1] == e[3] and e[0] != e[2] and e[1] == min(ys)) r = r or (e[0] == e[2] and e[1] != e[3] and e[0] == max(xs)) l = l or (e[0] == e[2] and e[1] != e[3] and e[0] == min(xs)) return t and b and l and r e1 = list(map(int, input().split(' '))) e2 = list(map(int, input().split(' '))) e3 = list(map(int, input().split(' '))) e4 = list(map(int, input().split(' '))) if is_rect((e1, e2, e3, e4)): print("YES") else: print("NO") ```
156_B. Suspects
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i). Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth? Input The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth. Output Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime. Examples Input 1 1 +1 Output Truth Input 3 2 -1 -2 -3 Output Not defined Not defined Not defined Input 4 1 +2 -3 +4 -1 Output Lie Not defined Lie Not defined Note The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth. In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not. In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.
```python n, m = map(int, input().split()) t = [int(input()) for i in range(n)] s, p = 0, [0] * (n + 1) for i in t: if i < 0: m -= 1 p[-i] -= 1 else: p[i] += 1 q = {i for i in range(1, n + 1) if p[i] == m} if len(q) == 0: print('Not defined\n' * n) elif len(q) == 1: j = q.pop() print('\n'.join(['Truth' if i == j or (i < 0 and i + j) else 'Lie' for i in t])) else: q.update({-i for i in q}) print('\n'.join(['Not defined' if i in q else ('Truth' if i < 0 else 'Lie') for i in t])) ```
177_F1. Script Generation
The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series. There are n single men and n single women among the main characters. An opinion poll showed that viewers like several couples, and a marriage of any of them will make the audience happy. The Smart Beaver formalized this fact as k triples of numbers (h, w, r), where h is the index of the man, w is the index of the woman, and r is the measure of the audience's delight in case of the marriage of this couple. The same poll showed that the marriage of any other couple will leave the audience indifferent, so the screenwriters decided not to include any such marriages in the plot. The script allows you to arrange several marriages between the heroes or not to arrange marriages at all. A subset of some of the k marriages is considered acceptable if each man and each woman is involved in at most one marriage of the subset (the series won't allow any divorces). The value of the acceptable set of marriages is the total delight the spectators will get from the marriages included in this set. Obviously, there is a finite number of acceptable sets, and they all describe some variants of the script. The screenwriters do not want to choose a set with maximum value — it would make the plot too predictable. So the Smart Beaver offers the following option: sort all the acceptable sets in increasing order of value and choose the t-th set from the sorted list. Thus, t = 1 corresponds to a plot without marriages, t = 2 — to a single marriage resulting in minimal delight for the audience, and so on. Help the Beaver to implement the algorithm for selecting the desired set. Input The first input line contains integers n, k and t (1 ≤ k ≤ min(100, n2), 1 ≤ t ≤ 2·105), separated by single spaces. Next k lines contain triples of integers (h, w, r) (1 ≤ h, w ≤ n; 1 ≤ r ≤ 1000), separated by single spaces, which describe the possible marriages. It is guaranteed that the input data is correct: t doesn't exceed the total number of acceptable sets, and each pair (h, w) is present in at most one triple. The input limitations for getting 30 points are: * 1 ≤ n ≤ 5 The input limitations for getting 100 points are: * 1 ≤ n ≤ 20 Output Print a single number — the value of the t-th acceptable variant. Examples Input 2 4 3 1 1 1 1 2 2 2 1 3 2 2 7 Output 2 Input 2 4 7 1 1 1 1 2 2 2 1 3 2 2 7 Output 8 Note The figure shows 7 acceptable sets of marriages that exist in the first sample. <image>
```python I=lambda:list(map(int,input().split())) n,k,T=I() t=[I()for _ in '0'*k] def b(h,w,r,a): if h>n:a+=[r] else: b(h+1,w,r,a) for f,s,v in t: if f==h and s in w:b(h+1,w-set([s]),r+v,a) return a print(sorted(b(1,set(range(1,n+1)), 0,[]))[T-1]) ```
199_C. About Bacteria
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high. At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kx + b bacteria. The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point. For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment. Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment. Input The first line contains four space-separated integers k, b, n and t (1 ≤ k, b, n, t ≤ 106) — the parameters of bacterial growth, the time Qwerty needed to grow z bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly. Output Print a single number — the minimum number of seconds Qwerty needs to grow at least z bacteria in the tube. Examples Input 3 1 3 5 Output 2 Input 1 4 4 7 Output 3 Input 2 2 4 100 Output 0
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M=10**9+7 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def canMake(iter): pass k,b,n,t=value() z=1 reduced=0 # for i in range(n): # z=z*k+b # print(z) # print() # z=t # for i in range(n): # z=z*k+b # print(z) while(z<=t): reduced+=1 z=z*k+b print(max(0,n-reduced+1)) ```
222_D. Olympiad
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances. Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad. Input The first line contains two space-separated integers n, x (1 ≤ n ≤ 105; 0 ≤ x ≤ 2·105) — the number of Olympiad participants and the minimum number of points Vasya earned. The second line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the participants' points in the first tour. The third line contains n space-separated integers: b1, b2, ..., bn (0 ≤ bi ≤ 105) — the participants' points in the second tour. The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers i, j (1 ≤ i, j ≤ n) such, that ai + bj ≥ x. Output Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad. Examples Input 5 2 1 1 1 1 1 1 1 1 1 1 Output 1 5 Input 6 7 4 3 5 6 4 4 8 6 0 4 3 4 Output 1 5 Note In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place. In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}. In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour. In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
```python from sys import stdin from collections import deque n,x = [int(x) for x in stdin.readline().split()] s1 = deque(sorted([int(x) for x in stdin.readline().split()])) s2 = deque(sorted([int(x) for x in stdin.readline().split()])) place = 0 for score in s1: if s2[-1] + score >= x: place += 1 s2.pop() else: s2.popleft() print(1,place) ```
246_B. Increase and Decrease
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: * he chooses two elements of the array ai, aj (i ≠ j); * he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus. Input The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array. Output Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation. Examples Input 2 2 1 Output 1 Input 3 1 4 1 Output 3
```python x=int(input()) sm=sum(list(map(int,input().split())))%x if sm==0: print(x) else: print(x-1) ```
271_C. Secret
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order. We'll say that the secret is safe if the following conditions are hold: * for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set; * the union of sets U1, U2, ..., Uk is set (1, 2, ..., n); * in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold). Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't. Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition. Input The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space. Output If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret. If there are multiple solutions, print any of them. Examples Input 11 3 Output 3 1 2 1 1 2 3 2 2 3 1 Input 5 2 Output -1
```python import sys; class MyReader: # file = null; def __init__(self): filename = "file.in"; if self.isLocal(): self.file = open(filename); self.str = [""]; self.ind = 1; def isLocal(self): return len(sys.argv) > 1 and sys.argv[1] == "SCHULLZ"; def nextString(self): if self.isLocal(): return self.file.read(); else: return input(); def nextInt(self): return int(self.nextToken()); def nextToken(self): if (self.ind >= len(self.str)): self.ind = 0; self.str = self.nextString().split(); self.ind += 1; return self.str[self.ind - 1]; def SoLvE(): rdr = MyReader(); n = rdr.nextInt(); m = rdr.nextInt(); if n // m < 3: print(-1); return; a = []; for i in range(0, n): a.append(-1); cur = 0; for i in range(0, m): a[cur] = i + 1; cur += 1; for i in range(0, m): a[cur] = i + 1; cur += 1; for i in range(0, m - 1): a[cur] = i + 2; cur += 1; a[cur] = 1; cur += 1; for cc in range(cur, n): a[cc] = cc % m + 1; cc += 1; for i in range(0, n): sys.stdout.write(str(a[i])); sys.stdout.write(" "); sys.stdout.flush() SoLvE(); ```
318_C. Perfect Pair
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y). What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect? Input Single line of the input contains three integers x, y and m ( - 1018 ≤ x, y, m ≤ 1018). Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier. Output Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one. Examples Input 1 2 5 Output 2 Input -1 4 15 Output 4 Input 0 -1 5 Output -1 Note In the first sample the following sequence of operations is suitable: (1, 2) <image> (3, 2) <image> (5, 2). In the second sample: (-1, 4) <image> (3, 4) <image> (7, 4) <image> (11, 4) <image> (15, 4). Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations.
```python from sys import stdin from math import ceil x, y, m = map(int, stdin.readline().split()) ans = 0 if x >= m or y >= m: print(ans) elif x + y > min(x, y): ma, mi = max(x, y), min(x, y) ans += ((ma - mi) // ma) # + ((ma - mi) % ma) mi, ma = min(ma, mi + ans * ma), max(ma, mi + ans * ma) while ma < m: ma, mi = ma + mi, ma ans += 1 print(ans) else: print(-1) ```
342_C. Cupboard and Balloons
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius r (the cupboard's top) and two walls of height h (the cupboard's sides). The cupboard's depth is r, that is, it looks like a rectangle with base r and height h + r from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right). <image> Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius <image>. Help Xenia calculate the maximum number of balloons she can put in her cupboard. You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin. Input The single line contains two integers r, h (1 ≤ r, h ≤ 107). Output Print a single integer — the maximum number of balloons Xenia can put in the cupboard. Examples Input 1 1 Output 3 Input 1 2 Output 5 Input 2 1 Output 2
```python if __name__=='__main__': inp = input() arr = inp.split(" ") r = int(arr[0]) h = int(arr[1]) ans = 2*(h//r) d = h%r if d*2>=r: ans+=2 if 4*d*d >= 3*r*r: ans+=1 else: ans+=1 print(ans) ```
389_D. Fox and Minimal path
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k? Input The first line contains a single integer k (1 ≤ k ≤ 109). Output You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them. Examples Input 2 Output 4 NNYY NNYY YYNN YYNN Input 9 Output 8 NNYYYNNN NNNNNYYY YNNNNYYY YNNNNYYY YNNNNYYY NYYYYNNN NYYYYNNN NYYYYNNN Input 1 Output 2 NY YN Note In first example, there are 2 shortest paths: 1-3-2 and 1-4-2. In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2.
```python n, m, cnt = int(input()), 148, 0 ans = [['N'] * m for i in range(m)] def edge(i, j): ans[i][j] = ans[j][i] = 'Y' def node(*adj): global cnt i = cnt cnt += 1 for j in adj: edge(i, j) return i start, end, choice = node(), node(), node() if n&1: edge(choice, end) for i in range(1, 30): end, choice = node(node(end), node(end)), node(node(choice)) if n&(1<<i): edge(choice, end) edge(start, choice) print(m) for line in ans: print(''.join(line)) ```
409_G. On a plane
Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of points on a plane. Each of the next n lines contains two real coordinates xi and yi of the <image> point, specified with exactly 2 fractional digits. All coordinates are between - 1000 and 1000, inclusive. Output Output a single real number θ — the answer to the problem statement. The absolute or relative error of your answer should be at most 10 - 2. Examples Input 8 -2.14 2.06 -1.14 2.04 -2.16 1.46 -2.14 0.70 -1.42 0.40 -0.94 -0.48 -1.42 -1.28 -2.16 -1.62 Output 5.410 Input 5 2.26 1.44 2.28 0.64 2.30 -0.30 1.58 0.66 3.24 0.66 Output 5.620 Input 8 6.98 2.06 6.40 1.12 5.98 0.24 5.54 -0.60 7.16 0.30 7.82 1.24 8.34 0.24 8.74 -0.76 Output 5.480 Input 5 10.44 2.06 10.90 0.80 11.48 -0.48 12.06 0.76 12.54 2.06 Output 6.040 Input 8 16.94 2.42 15.72 2.38 14.82 1.58 14.88 0.50 15.76 -0.16 16.86 -0.20 17.00 0.88 16.40 0.92 Output 6.040 Input 7 20.62 3.00 21.06 2.28 21.56 1.36 21.66 0.56 21.64 -0.52 22.14 2.32 22.62 3.04 Output 6.720
```python n = int(input()) ab = 0 for i in range(n): x, y = map(float, input().split()) ab += y print(5 + ab / n) ```
437_B. The Child and Set
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks. Fortunately, Picks remembers something about his set S: * its elements were distinct integers from 1 to limit; * the value of <image> was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation). Can you help Picks and find any set S, that satisfies all the above conditions? Input The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 105). Output In the first line print an integer n (1 ≤ n ≤ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them. If it's impossible to find a suitable set, print -1. Examples Input 5 5 Output 2 4 5 Input 4 3 Output 3 2 3 1 Input 5 1 Output -1 Note In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5. In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.
```python s, limit = list(map(int, input().split())) ans = [] for i in range(limit, 0, -1): k = i & (i ^(i-1)) if s >= k: s-=k ans.append(i) if s: print(-1) else: print(len(ans)) print(*ans) ```
45_D. Event Dates
On a history lesson the teacher asked Vasya to name the dates when n famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [li, ri] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose such n dates of famous events that will fulfill both conditions. It is guaranteed that it is possible. Input The first line contains one integer n (1 ≤ n ≤ 100) — the number of known events. Then follow n lines containing two integers li and ri each (1 ≤ li ≤ ri ≤ 107) — the earliest acceptable date and the latest acceptable date of the i-th event. Output Print n numbers — the dates on which the events took place. If there are several solutions, print any of them. It is guaranteed that a solution exists. Examples Input 3 1 2 2 3 3 4 Output 1 2 3 Input 2 1 3 1 3 Output 1 2
```python # http://codeforces.com/contest/45/problem/D from sys import stdin inFile = stdin tokens = [] tokens_next = 0 def next_str(): global tokens, tokens_next while tokens_next >= len(tokens): tokens = inFile.readline().split() tokens_next = 0 tokens_next += 1 return tokens[tokens_next - 1] def nextInt(): return int(next_str()) n = nextInt() intervals = [(nextInt(), nextInt(), i) for i in range(n)] intervals.sort(key=lambda x: (x[1], x[0])) # for i in intervals: # print(i[0], i[1]) seen = set() for i in range(n): cur = intervals[i][0] while cur in seen: cur += 1 seen.add(cur) intervals[i] = (intervals[i][0], intervals[i][1], intervals[i][2], cur) intervals.sort(key=lambda x: x[2]) for i in range(n): print(intervals[i][3], end=' ') print() ```
52_B. Right Triangles
You are given a n × m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input The first line contains two positive integer numbers n and m (1 ≤ n, m ≤ 1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed. Output Output a single number — total number of square triangles in the field. 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). Examples Input 2 2 ** *. Output 1 Input 3 4 *..* .**. *.** Output 9
```python n, m = map(int, input().split()) grid = [input() for _ in range(n)] a = [[0 for _ in range(m)] for i in range(n)] b = [[0 for _ in range(m)] for i in range(n)] for i in range(n): for j in range(m): a[i][j] = a[i][j - 1] + (grid[i][j] == '*') if i: b[i][j] = b[i - 1][j] b[i][j] += grid[i][j] == '*' ans = 0 for i in range(n): for j in range(m): if grid[i][j] == '*': l = r = u = d = 0 if j: l = a[i][j - 1] r = a[i][-1] - a[i][j] if i: u = b[i - 1][j] d = b[-1][j] - b[i][j] ans += (l + r) * (u + d) print(ans) ```