name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1428_A. Box is Pull
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by 1 unit. <image> For example, if the box is at the point (1,2) and Wabbit is standing at the point (2,2), he can pull the box right by 1 unit, with the box ending up at the point (2,2) and Wabbit ending at the point (3,2). Also, Wabbit can move 1 unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly 1 unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located. Wabbit can start at any point. It takes 1 second to travel 1 unit right, left, up, or down, regardless of whether he pulls the box while moving. Determine the minimum amount of time he needs to move the box from (x_1,y_1) to (x_2,y_2). Note that the point where Wabbit ends up at does not matter. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000): the number of test cases. The description of the test cases follows. Each of the next t lines contains four space-separated integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_2 ≤ 10^9), describing the next test case. Output For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from (x_1,y_1) to (x_2,y_2). Example Input 2 1 2 2 2 1 1 2 2 Output 1 4 Note In the first test case, the starting and the ending points of the box are (1,2) and (2,2) respectively. This is the same as the picture in the statement. Wabbit needs only 1 second to move as shown in the picture in the statement. In the second test case, Wabbit can start at the point (2,1). He pulls the box to (2,1) while moving to (3,1). He then moves to (3,2) and then to (2,2) without pulling the box. Then, he pulls the box to (2,2) while moving to (2,3). It takes 4 seconds.
```python for i in range(int(input())): x1,y1,x2,y2=map(int,input().split()) q=abs(x1-x2)+abs(y1-y2) print(q if x1==x2 or y1==y2 else q+2) ```
1451_A. Subtract or Divide
Ridbit starts with an integer n. In one move, he can perform one of the following operations: * divide n by one of its proper divisors, or * subtract 1 from n if n is greater than 1. A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 20 itself is not. What is the minimum number of moves Ridbit is required to make to reduce n to 1? Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The only line of each test case contains a single integer n (1 ≤ n ≤ 10^9). Output For each test case, output the minimum number of moves required to reduce n to 1. Example Input 6 1 2 3 4 6 9 Output 0 1 2 2 2 3 Note For the test cases in the example, n may be reduced to 1 using the following operations in sequence 1 2 \xrightarrow{} 1 3 \xrightarrow{} 2 \xrightarrow{} 1 4 \xrightarrow{} 2 \xrightarrow{} 1 6 \xrightarrow{} 2 \xrightarrow{} 1 9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1
```python for _ in range(int(input())): k = 3 n = int(input()) if n == 1: print("0") elif n == 2: print("1") elif n == 3: print("2") elif n%2==0: print("2") else: print("3") ```
1475_A. Odd Divisor
You are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x > 1) that n is divisible by x and x is odd). For example, if n=6, then there is x=3. If n=4, then such a number does not exist. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (2 ≤ n ≤ 10^{14}). Please note, that the input for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language. Output For each test case, output on a separate line: * "YES" if n has an odd divisor, greater than one; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 6 2 3 4 5 998244353 1099511627776 Output NO YES NO YES YES NO
```python test_cases = 1 test_cases = int(input()) for ttttt in range(test_cases): n = int(input()) while n%2==0: n/=2 if n==1: print("NO") else: print("YES") ```
14_D. Two Paths
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities). It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company. Input The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n). Output Output the maximum possible profit. Examples Input 4 1 2 2 3 3 4 Output 1 Input 7 1 2 1 3 1 4 1 5 1 6 1 7 Output 0 Input 6 1 2 2 3 2 4 5 4 6 4 Output 4
```python import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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 bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u,p): global m r=0 m1=-1 m2=-1 for j in adj[u]: if j!=p: r1=yield dfs(j,u) r=max(r,r1+1) if r1>=m1: m2=m1 m1=r1 elif r1>=m2: m2=r1 m=max(m,r) m=max(m,m1+m2+2) yield r n=int(input()) adj=[[] for i in range(n+1)] edges=[] for j in range(n-1): u,v=map(int,input().split()) adj[u].append(v) adj[v].append(u) edges.append([u,v]) ans=0 for edge in edges: m=0 u,v=edge[0],edge[1] adj[u].remove(v) adj[v].remove(u) dfs(u,0) d1=m m = 0 dfs(v,0) d2=m ans=max(ans,d1*d2) adj[u].append(v) adj[v].append(u) print(ans) ```
1525_A. Potion-making
You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly k\ \% magic essence and (100 - k)\ \% water. In one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it. A small reminder: if you pour e liters of essence and w liters of water (e + w > 0) into the cauldron, then it contains (e)/(e + w) ⋅ 100\ \% (without rounding) magic essence and (w)/(e + w) ⋅ 100\ \% water. Input The first line contains the single t (1 ≤ t ≤ 100) — the number of test cases. The first and only line of each test case contains a single integer k (1 ≤ k ≤ 100) — the percentage of essence in a good potion. Output For each test case, print the minimum number of steps to brew a good potion. It can be proved that it's always possible to achieve it in a finite number of steps. Example Input 3 3 100 25 Output 100 1 4 Note In the first test case, you should pour 3 liters of magic essence and 97 liters of water into the cauldron to get a potion with 3\ \% of magic essence. In the second test case, you can pour only 1 liter of essence to get a potion with 100\ \% of magic essence. In the third test case, you can pour 1 liter of magic essence and 3 liters of water.
```python import math for i in range(int(input())): n=int(input()) a=100-n b=n if n==100: print(1) else: g=math.gcd(a,b) print(a//g+b//g) ```
156_C. Cipher
Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≤ p < |s|) and perform one of the following actions: * either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; * or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed. Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations. Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7). Input The input data contains several tests. The first line contains the only integer t (1 ≤ t ≤ 104) — the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ. Output For each word you should print the number of different other words that coincide with it in their meaning — not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7). Examples Input 1 ab Output 1 Input 1 aaaaaaaaaaa Output 0 Input 2 ya klmbfxzb Output 24 320092793 Note Some explanations about the operation: * Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y". * Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b". * Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0. Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b" → "c"), and the fifth one — with the preceding one ("f" → "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants — there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 — the number 3320092814 modulo 109 + 7
```python S, N = 2501, 101 m = 1000000007 k = 26 p = [[0] * (S + k) for i in range(N)] p[0][0] = 1 for n in range(1, N): for s in range(S): p[n][s] = (p[n][s - 1] + p[n - 1][s] - p[n - 1][s - k]) % m r = [] for j in range(int(input())): t = input() s = sum(ord(q) - 97 for q in t) print(p[len(t)][s] - 1) ```
199_D. Jumping on Walls
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous. Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: * climb one area up; * climb one area down; * jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon. The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on. The level is considered completed if the ninja manages to get out of the canyon. After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. Input The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. Output Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). Examples Input 7 3 ---X--X -X--XX- Output YES Input 6 2 --X-X- X--XX- Output NO Note In the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon.
```python from collections import deque l, j = [int(i) for i in input().split(' ')] wallA = list(input()) wallB = list(input()) g = {} for i in range(l): # Each 4-tuple represents: (Visited?, Current Height, Current Water Height, Drowned?) if wallA[i] == '-': g[(1,i+1)] = (-1, 0, 0, False) if wallB[i] == '-': g[(-1,i+1)] = (-1, 0, 0, False) g[(1, 1)] = ('VISITED', 1, 0, False) q = deque([(1, 1)]) while q: c = q.popleft() up = (c[0], c[1]+1) down = (c[0], c[1]-1) jump = (c[0]*-1, c[1] + j) if g[c][1] <= g[c][2]: g[c] = (g[c][0], g[c][1], g[c][2], True) if up in g and g[up][0] == -1: q.append(up) g[up] = ('VISITED', g[c][1] + 1, g[c][2] + 1, g[c][3]) if down in g and g[down][0] == -1: q.append(down) g[down] = ('VISITED', g[c][1] - 1, g[c][2] + 1, g[c][3]) if jump in g and g[jump][0] == -1: q.append(jump) g[jump] = ('VISITED', g[c][1] + j, g[c][2] + 1, g[c][3]) def graphHasEscape(graph): for node in graph: result = graph[node] if result[0] == 'VISITED' and ((result[1] + 1 > l) or (result[1] + j > l)) and not result[3]: return True break return False if graphHasEscape(g): print('YES') else: print('NO') ```
222_E. Decoding Genome
Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most m different nucleotides, numbered from 1 to m. Special characteristics of the Martian DNA prevent some nucleotide pairs from following consecutively in this chain. For example, if the nucleotide 1 and nucleotide 2 can not follow consecutively in the Martian DNA, then the chain of nucleotides [1, 2] is not a valid chain of Martian DNA, but the chain of nucleotides [2, 1] can be a valid chain (if there is no corresponding restriction). The number of nucleotide pairs that can't follow in the DNA chain consecutively, is k. The needs of gene research required information about the quantity of correct n-long chains of the Martian DNA. Your task is to write a program that will calculate this value. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 1015, 1 ≤ m ≤ 52, 0 ≤ k ≤ m2). Next k lines contain two characters each, without a space between them, representing a forbidden nucleotide pair. The first character represents the first nucleotide in the forbidden pair, the second character represents the second nucleotide. The nucleotides with assigned numbers from 1 to 26 are represented by English alphabet letters from "a" to "z" (1 is an "a", 2 is a "b", ..., 26 is a "z"). Nucleotides with assigned numbers from 27 to 52 are represented by English alphabet letters from "A" to "Z" (27 is an "A", 28 is a "B", ..., 52 is a "Z"). It is guaranteed that each forbidden pair occurs at most once in the input. It is guaranteed that nucleotide's numbers in all forbidden pairs cannot be more than m. Note that order is important in nucleotide pairs. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output Print a single integer — the sought number modulo 1000000007 (109 + 7). Examples Input 3 3 2 ab ba Output 17 Input 3 3 0 Output 27 Input 2 1 1 aa Output 0 Note In the second test case all possible three-nucleotide DNAs are permitted. Each nucleotide can take one of three values, thus in total there are 27 distinct three nucleotide DNAs. In the third test sample we cannot make any DNA of two nucleotides — the only possible nucleotide "a" cannot occur two times consecutively.
```python import sys def pyes_no(condition) : if condition : print ("YES") else : print ("NO") def plist(a, s = ' ') : print (s.join(map(str, a))) def rint() : return int(sys.stdin.readline()) def rints() : return map(int, sys.stdin.readline().split()) def rfield(n, m = None) : if m == None : m = n field = [] for i in xrange(n) : chars = sys.stdin.readline().strip() assert(len(chars) == m) field.append(chars) return field def pfield(field, separator = '') : print ('\n'.join(map(lambda x: separator.join(x), field))) def check_field_equal(field, i, j, value) : if i >= 0 and i < len(field) and j >= 0 and j < len(field[i]) : return value == field[i][j] return None def digits(x, p) : digits = [] while x > 0 : digits.append(x % p) x /= p return digits def modpower(a, n, mod) : r = a ** (n % 2) if n > 1 : r *= modpower(a, n / 2, mod) ** 2 return r % mod def modmatrixproduct(a, b, mod) : n, m1 = len(a), len(a[0]) m2, k = len(b), len(b[0]) assert(m1 == m2) m = m1 r = [[0] * k for i in range(n)] for i in range(n) : for j in range(k) : for l in range(m) : r[i][j] += a[i][l] * b[l][j] r[i][j] %= mod return r def modmatrixpower(a, n, mod) : magic = 2 for m in [2, 3, 5, 7] : if n % m == 0 : magic = m break r = None if n < magic : r = a n -= 1 else : s = modmatrixpower(a, n // magic, mod) r = s for i in range(magic - 1) : r = modmatrixproduct(r, s, mod) for i in range(n % magic) : r = modmatrixproduct(r, a, mod) return r def gcd(a, b) : if a > b : a, b = b, a while a > 0 : a, b = b % a, a return b n, m, k = rints() charn = dict(zip('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', range(52))) matrix = [[1] * m for i in range(m)] for i in range(k) : a, b = map(lambda c: charn[c], list(sys.stdin.readline().strip())) matrix[a][b] = 0 mod = 1000000007 if n > 1 : matrix = modmatrixpower(matrix, n - 1, mod) results = modmatrixproduct([[1] * m], matrix, mod) print (sum(map(sum, results)) % mod) else : print (m) ```
246_C. Beauty Pageant
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants. All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier. On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers. Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty. Input The first line contains two integers n, k (1 ≤ n ≤ 50; 1 ≤ k ≤ <image>) — the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty. Output Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1 ≤ ci ≤ n) — the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1, i, p2, i, ..., pci, i — the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them. Examples Input 3 3 1 2 3 Output 1 1 1 2 2 3 2 Input 2 1 7 12 Output 1 12
```python n, k = map(int, input().split()) p = list(map(int, input().split())) p.sort() t = [[i] for i in p] for i in range(1, n): t += [t[-1] + i for i in t[: n - i]] print('\n'.join(str(len(i)) + ' ' + ' '.join(map(str, i)) for i in t[: k])) ```
271_D. Good Substrings
You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad. A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2...s|s| (where |s| is the length of string s) is string slsl + 1...sr. The substring s[l...r] is good, if among the letters sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear). Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] ≠ s[p...q]. Input The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer k (0 ≤ k ≤ |s|) — the maximum acceptable number of bad characters in a good substring. Output Print a single integer — the number of distinct good substrings of string s. Examples Input ababab 01000000000000000000000000 1 Output 5 Input acbacbacaa 00000000000000000000000000 2 Output 8 Note In the first example there are following good substrings: "a", "ab", "b", "ba", "bab". In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".
```python import collections as cc import sys input=sys.stdin.readline I=lambda:list(map(int,input().split())) S=lambda :list(input().strip()) s=S() t=S() k,=I() ans=0 prev='' ss=sorted([s[i:] for i in range(len(s))]) for j in ss: now=0 f=0 for i in range(len(j)): if i>=len(prev) or j[i]!=prev[i]: f=1 now+=t[ord(j[i])-ord('a')]=='0' if now>k: break if f: ans+=1 prev=j print(ans) ```
295_A. Greg and Array
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di. Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≤ xi ≤ yi ≤ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array. Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg. Input The first line contains integers n, m, k (1 ≤ n, m, k ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≤ li ≤ ri ≤ n), (0 ≤ di ≤ 105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≤ xi ≤ yi ≤ m). The numbers in the lines are separated by single spaces. Output On a single line print n integers a1, a2, ..., an — the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 3 3 3 1 2 3 1 2 1 1 3 2 2 3 4 1 2 1 3 2 3 Output 9 18 17 Input 1 1 1 1 1 1 1 1 1 Output 2 Input 4 3 6 1 2 3 4 1 2 1 2 3 2 3 4 4 1 2 1 3 2 3 1 2 1 3 2 3 Output 5 18 31 20
```python import sys input=sys.stdin.readline n,m,k=map(int,input().split()) a=list(map(int,input().split())) query=[] times=[] x=[0]*(m+2) y=[0]*(n+2) for i in range(m): query.append(list(map(int,input().split()))) for i in range(k): times.append(list(map(int,input().split()))) for i in range(k): l,r=times[i] x[l]+=1 x[r+1]-=1 s=0 for i in range(m+2): s+=x[i] x[i]=s for i in range(m): query[i][2]*=x[i+1] for i in range(m): l,r,d=query[i] y[l]+=d y[r+1]-=d s=0 for i in range(n+2): s+=y[i] y[i]=s for i in range(n): a[i]+=y[i+1] print(*a) ```
366_A. Dima and Guards
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift. In order to pass through a guardpost, one needs to bribe both guards. The shop has an unlimited amount of juice and chocolate of any price starting with 1. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend exactly n rubles on it. Help him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that! Input The first line of the input contains integer n (1 ≤ n ≤ 105) — the money Dima wants to spend. Then follow four lines describing the guardposts. Each line contains four integers a, b, c, d (1 ≤ a, b, c, d ≤ 105) — the minimum price of the chocolate and the minimum price of the juice for the first guard and the minimum price of the chocolate and the minimum price of the juice for the second guard, correspondingly. Output In a single line of the output print three space-separated integers: the number of the guardpost, the cost of the first present and the cost of the second present. If there is no guardpost Dima can sneak Inna through at such conditions, print -1 in a single line. The guardposts are numbered from 1 to 4 according to the order given in the input. If there are multiple solutions, you can print any of them. Examples Input 10 5 6 5 6 6 6 7 7 5 8 6 6 9 9 9 9 Output 1 5 5 Input 10 6 6 6 6 7 7 7 7 4 4 4 4 8 8 8 8 Output 3 4 6 Input 5 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 Output -1 Note Explanation of the first example. The only way to spend 10 rubles to buy the gifts that won't be less than the minimum prices is to buy two 5 ruble chocolates to both guards from the first guardpost. Explanation of the second example. Dima needs 12 rubles for the first guardpost, 14 for the second one, 16 for the fourth one. So the only guardpost we can sneak through is the third one. So, Dima can buy 4 ruble chocolate for the first guard and 6 ruble juice of the second guard.
```python import itertools as it n = int(input()) res = None for i in range(4): a = list(map(int, input().split())) for v in list(it.product(a[:2], a[2:])): if sum(v) <= n: res = [i + 1, v[0], n - v[0]] break if res is not None: break print(-1 if res is None else ' '.join(map(str, res))) ```
389_E. Fox and Card Game
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty. Suppose Ciel and Jiro play optimally, what is the score of the game? Input The first line contain an integer n (1 ≤ n ≤ 100). Each of the next n lines contains a description of the pile: the first integer in the line is si (1 ≤ si ≤ 100) — the number of cards in the i-th pile; then follow si positive integers c1, c2, ..., ck, ..., csi (1 ≤ ck ≤ 1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile. Output Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally. Examples Input 2 1 100 2 1 10 Output 101 10 Input 1 9 2 8 6 5 9 4 7 1 3 Output 30 15 Input 3 3 1 3 2 3 5 4 6 2 8 7 Output 18 18 Input 3 3 1000 1000 1000 6 1000 1000 1000 1000 1000 1000 5 1000 1000 1000 1000 1000 Output 7000 7000 Note In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10. In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.
```python n = int(input()) lista = [] aux = [] somaA = 0 somaB = 0 for i in range(n): a = [int(i) for i in input().split()][1:] if len(a) > 1: somaA += sum(a[0:len(a)//2]) somaB += sum(a[-(len(a)//2):]) if len(a) % 2 == 1: aux.append(a[len(a)//2]) aux.sort(reverse=True) for i in range(0, len(aux), 2): somaA += aux[i] for i in range(1, len(aux), 2): somaB += aux[i] print(somaA, somaB) ```
409_H. A + B Strikes Back
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? Input The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space. Output Output the sum of the given integers. Examples Input 5 14 Output 19 Input 381 492 Output 873
```python import sys import os a,b=input().split() a=int(a) b=int(b) print(a+b) ```
437_C. The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed. Help the child to find out, what is the minimum total energy he should spend to remove all n parts. Input The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n. Output Output the minimum total energy the child should spend to remove all n parts of the toy. Examples Input 4 3 10 20 30 40 1 4 1 2 2 3 Output 40 Input 4 4 100 100 100 100 1 2 2 3 2 4 3 4 Output 400 Input 7 10 40 10 20 10 20 80 40 1 5 4 7 4 5 5 2 5 7 6 4 1 6 1 3 4 3 1 4 Output 160 Note One of the optimal sequence of actions in the first sample is: * First, remove part 3, cost of the action is 20. * Then, remove part 2, cost of the action is 10. * Next, remove part 4, cost of the action is 10. * At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum. In the second sample, the child will spend 400 no matter in what order he will remove the parts.
```python def mlt(): return map(int, input().split()) x, y = mlt() s = [0] + list(mlt()) res = 0 for n in range(y): a, b = mlt() res += min(s[a], s[b]) print(res) ```
506_D. Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly. Input The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries. Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi. Output For each query, print the answer in a separate line. Examples Input 4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4 Output 2 1 0 Input 5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4 Output 1 1 1 1 2 Note Let's consider the first sample. <image> The figure above shows the first sample. * Vertex 1 and vertex 2 are connected by color 1 and 2. * Vertex 3 and vertex 4 are connected by color 3. * Vertex 1 and vertex 4 are not connected by any single color.
```python #make a table n,m = map(int,input().split()) arr = [[] for i in range(n+1)] for i in range(1,m+1): l = list(map(int,input().split())) arr[l[0]].append((l[1],l[2])) arr[l[1]].append((l[0],l[2])) #dfs def dfs(a,b,k): if a == b: return True seen.append(a) for i in arr[a]: x,c = i if c == k and x not in seen: if dfs(x,b,k): return True return False query = int(input()) count = 0 score = [0]*(query) seen = [] #get destination inputs for i in range(query): a,b = map(int,input().split()) for k in range(1,101): seen = [] if dfs(a,b,k): count += 1 score[i] = count count = 0 print("\n".join(list(map(str,score)))) ```
52_C. Circular RMQ
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it: * inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v; * rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively). Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1. Write program to process given sequence of operations. Input The first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation. Output For each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 4 1 2 3 4 4 3 0 3 0 -1 0 1 2 1 Output 1 0 0
```python import math,sys,bisect,heapq,os from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 def input(): return sys.stdin.readline().rstrip('\r\n') #input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ aj = lambda: list(map(int, input().split())) def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) def solve(): n=int(input()) a=list(map(int,input().split())) class st: def __init__(self, size): n = size h = int(math.log2(n-1))+1 if n>1 else 0 N = 2**h self.t = [float('inf')]*(2*N) self.d = [0]*N self.N = N self.h = h def apply(self, p, value): self.t[p] += value if (p < self.N): self.d[p] += value def build(self, p): t = self.t d = self.d while p > 1: p >>= 1 t[p] = min(t[p<<1], t[p<<1|1]) + d[p] def rebuild(self): t = self.t for p in reversed(range(1, self.N)): t[p] = min(t[p<<1], t[p<<1|1]) def push(self, p): d = self.d for s in range(self.h, 0, -1): i = p >> s if d[i] != 0: self.apply(i<<1, d[i]) self.apply(i<<1|1, d[i]) d[i] = 0 def inc(self, l, r, value): if l > r: return l += self.N r += self.N+1 l0, r0 = l, r while l < r: if l & 1: self.apply(l, value) l += 1 if r & 1: r -= 1 self.apply(r, value) l >>= 1 r >>= 1 self.build(l0) self.build(r0 - 1) def query(self, l, r): if l > r: return float('inf') t = self.t l += self.N r += self.N+1 self.push(l) self.push(r - 1) res = float('inf') while l < r: if l & 1: res = min(res, t[l]) l += 1 if r & 1: r -= 1 res = min(t[r], res) l >>= 1 r >>= 1 return res se=st(n) N=se.N for i in range(n): se.t[i+N]=a[i] se.rebuild() q=int(input()) for i in range(q): b=list(map(int,input().split())) if len(b)==2: l=b[0] r=b[1] if l>r: print(min(se.query(l,n-1),se.query(0,r))) else:print(se.query(l,r)) else: l=b[0] r=b[1] v=b[2] if l>r: se.inc(0,r,v) se.inc(l,n-1,v) else:se.inc(l,r,v) try: #os.system("online_judge.py") sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass solve() ```
581_D. Three Logos
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard. Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules. Input The first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≤ x1, y1, x2, y2, x3, y3 ≤ 100), where xi and yi determine the length and width of the logo of the i-th company respectively. Output If it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes). If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: * the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, * the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, * the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them. See the samples to better understand the statement. Examples Input 5 1 2 5 5 2 Output 5 AAAAA BBBBB BBBBB CCCCC CCCCC Input 4 4 2 6 4 2 Output 6 BBBBBB BBBBBB AAAACC AAAACC AAAACC AAAACC
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect 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=998244353 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) 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 ok(a,b,c): # print(a[0],b,c) n = a[0][-1] ans = [] for i in range(a[0][0]): ans.append([a[1]]*n) l = n r = n - a[0][0] for i in range(2): for j in range(2): l1,r1 = b[0] l2,r2 = c[0] if(i): l1,r1 = r1,l1 if(j): l2,r2 = r2,l2 if(l1 == l): if(l2 != l or r1 + r2 != r): continue for k in range(r1): ans.append([b[1]]*n) for k in range(r2): ans.append([c[1]]*n) return ans if(l1 == r): if(l2 != r or r1 + r2 != l): continue for k in range(r): ans.append( [b[1]]*r1 + [c[1]]*r2) return ans return False l1,r1,l2,r2,l3,r3 = value() a = [sorted((l1,r1)),'A'] b = [sorted((l2,r2)),'B'] c = [sorted((l3,r3)),'C'] A = ok(a,b,c) B = ok(b,a,c) C = ok(c,a,b) if(A): print(len(A)) for i in A: print(*i,sep="") elif(B): print(len(B)) for i in B: print(*i,sep="") elif(C): print(len(C)) for i in C: print(*i,sep="") else: print(-1) ```
603_C. Lieges of Legendre
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either: 1. Remove a single cow from a chosen non-empty pile. 2. Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way. Input The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109). The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game. Output Output the name of the winning player, either "Kevin" or "Nicky" (without quotes). Examples Input 2 1 3 4 Output Kevin Input 1 2 3 Output Nicky Note In the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.
```python def grundy(n, k): if k % 2 == 0: if n <= 2: return n else: return n % 2 == 0 else: if n <= 4: return [0, 1, 0, 1, 2][n] elif n % 2 == 1: return 0 else: return 2 if grundy(n // 2, k) == 1 else 1 if __name__ == "__main__": n, k = map(int, input().split()) xList = map(int, input().split()) res = 0 for x in xList: res ^= grundy(x, k) print("Kevin" if res else "Nicky") ```
626_A. Robot Sequence
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≤ n ≤ 200) — the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' — Calvin's source code. Output Print a single integer — the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
```python import io import sys import time import random start = time.clock() #~ test = '''6 #~ URLLDR''' #~ test = '''7 #~ RLRLRLR''' #~ test = '''200 #~ ''' #~ for i in range(200): #~ test += random.choice("UDLR") #~ print(test) #~ test = '10 15' #~ test = '1 1000000' #28733372 #~ test = '1 11' #55 #~ test = '1 21' #130 #~ sys.stdin = io.StringIO(test) n = int(input()) commands = list(input()) count = 0 def done(steps_dir): for v in steps_dir.values(): if v%4!=0: return False return True dirs = {'U':+1,'D':-1,'L':+1,'R':-1} coords = {'U':0,'D':0,'L':1,'R':1} for i in range(n): # start pos = [0,0] for j in range(i,n): # need minimum 4 steps before getting back c = commands[j] pos[coords[c]] += dirs[c] if pos[0]==pos[1]==0: count += 1 #~ print(steps_dir) print(count) dur = time.clock()-start #~ print("Time:",dur) ```
675_B. Restoring Painting
Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 × 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 × 2 is equal to the sum of integers in the top left square 2 × 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≤ n ≤ 100 000, 1 ≤ a, b, c, d ≤ n) — maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer — the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image>
```python n,a,b,c,d=map(int,input().split()) count=0 for x in range(1,n+1): y=x+b-c z=x+a-d w=y+a-d if (y>=1 and y<=n) and(z>=1 and z<=n) and (w>=1 and w<=n): count+=1 print(count*n) ```
699_C. Vacations
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
```python size = int(input()) days = [int(a) for a in input().split()] daysoff = 0 yesterday = 0 if days[0] == 0: daysoff += 1 yesterday = 0 elif days[0] == 3: yesterday = 0 else: yesterday = days[0] for i in range(1, size): if days[i] == 0: yesterday = 0 daysoff += 1 elif days[i] == yesterday: yesterday = 0 daysoff += 1 elif days[i] == 3 and yesterday == 0: yesterday = 0 elif days[i] == 3 and yesterday == 1: yesterday = 2 elif days[i] == 3 and yesterday == 2: yesterday = 1 else: yesterday = days[i] print(daysoff) ```
71_E. Nuclear Fusion
There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line «YES», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints.
```python numbersDict = { "1": "H", "2": "He", "3": "Li", "4": "Be", "5": "B", "6": "C", "7": "N", "8": "O", "9": "F", "10": "Ne", "11": "Na", "12": "Mg", "13": "Al", "14": "Si", "15": "P", "16": "S", "17": "Cl", "18": "Ar", "19": "K", "20": "Ca", "21": "Sc", "22": "Ti", "23": "V", "24": "Cr", "25": "Mn", "26": "Fe", "27": "Co", "28": "Ni", "29": "Cu", "30": "Zn", "31": "Ga", "32": "Ge", "33": "As", "34": "Se", "35": "Br", "36": "Kr", "37": "Rb", "38": "Sr", "39": "Y", "40": "Zr", "41": "Nb", "42": "Mo", "43": "Tc", "44": "Ru", "45": "Rh", "46": "Pd", "47": "Ag", "48": "Cd", "49": "In", "50": "Sn", "51": "Sb", "52": "Te", "53": "I", "54": "Xe", "55": "Cs", "56": "Ba", "57": "La", "58": "Ce", "59": "Pr", "60": "Nd", "61": "Pm", "62": "Sm", "63": "Eu", "64": "Gd", "65": "Tb", "66": "Dy", "67": "Ho", "68": "Er", "69": "Tm", "70": "Yb", "71": "Lu", "72": "Hf", "73": "Ta", "74": "W", "75": "Re", "76": "Os", "77": "Ir", "78": "Pt", "79": "Au", "80": "Hg", "81": "Tl", "82": "Pb", "83": "Bi", "84": "Po", "85": "At", "86": "Rn", "87": "Fr", "88": "Ra", "89": "Ac", "90": "Th", "91": "Pa", "92": "U", "93": "Np", "94": "Pu", "95": "Am", "96": "Cm", "97": "Bk", "98": "Cf", "99": "Es", "100": "Fm" } lettersDict = { "H": "1", "He": "2", "Li": "3", "Be": "4", "B": "5", "C": "6", "N": "7", "O": "8", "F": "9", "Ne": "10", "Na": "11", "Mg": "12", "Al": "13", "Si": "14", "P": "15", "S": "16", "Cl": "17", "Ar": "18", "K": "19", "Ca": "20", "Sc": "21", "Ti": "22", "V": "23", "Cr": "24", "Mn": "25", "Fe": "26", "Co": "27", "Ni": "28", "Cu": "29", "Zn": "30", "Ga": "31", "Ge": "32", "As": "33", "Se": "34", "Br": "35", "Kr": "36", "Rb": "37", "Sr": "38", "Y": "39", "Zr": "40", "Nb": "41", "Mo": "42", "Tc": "43", "Ru": "44", "Rh": "45", "Pd": "46", "Ag": "47", "Cd": "48", "In": "49", "Sn": "50", "Sb": "51", "Te": "52", "I": "53", "Xe": "54", "Cs": "55", "Ba": "56", "La": "57", "Ce": "58", "Pr": "59", "Nd": "60", "Pm": "61", "Sm": "62", "Eu": "63", "Gd": "64", "Tb": "65", "Dy": "66", "Ho": "67", "Er": "68", "Tm": "69", "Yb": "70", "Lu": "71", "Hf": "72", "Ta": "73", "W": "74", "Re": "75", "Os": "76", "Ir": "77", "Pt": "78", "Au": "79", "Hg": "80", "Tl": "81", "Pb": "82", "Bi": "83", "Po": "84", "At": "85", "Rn": "86", "Fr": "87", "Ra": "88", "Ac": "89", "Th": "90", "Pa": "91", "U": "92", "Np": "93", "Pu": "94", "Am": "95", "Cm": "96", "Bk": "97", "Cf": "98", "Es": "99", "Fm": "100" } _ = input() # Supposed to be n, k but we do not need them atoms = input().split(" ") outAtoms = input().split(" ") atoms = sorted(list(map(lambda x: int(lettersDict[x]), atoms))) outAtoms = sorted(list(map(lambda x: int(lettersDict[x]), outAtoms))) sumAtoms = 0 def testIfPossible(): atomsx = atoms.copy() outAtomsx = outAtoms.copy() for i in range(len(atoms) - 1, -1, -1): if atomsx[i] > outAtomsx[-1]: atomsx.pop() if sum(outAtomsx) > sum(atomsx): print("NO") exit() testIfPossible() for at in atoms: sumAtoms += at outAtom = 0 for at in outAtoms: outAtom += at def dfs(i: int, currentSum: int, arr: [int], searchSum: int) -> [[int]]: if i >= len(arr) or currentSum + arr[i] > searchSum: return [] totalRes = [] # we take res = dfs(i + 1, currentSum + arr[i], arr, searchSum) totalRes += [[i] + a for a in res] # we don't take res = dfs(i + 1, currentSum, arr, searchSum) totalRes += [a for a in res] if currentSum + arr[i] == searchSum: totalRes.append([i]) return totalRes allCombos = [[set(x) for x in dfs(0, 0, atoms, out)] for out in outAtoms] currentSet = set() stack = [] resultFound = False def dfs2(i: int): global resultFound global stack global currentSet if i >= len(allCombos): resultFound = True return for set in allCombos[i]: if not set & currentSet: stack.append(set) currentSet = currentSet | set dfs2(i + 1) if resultFound: break stack.pop() currentSet = currentSet - set isAnyEmpty = False for comb in allCombos: if not comb: isAnyEmpty = True if not isAnyEmpty: dfs2(0) if resultFound: print("YES") res = list(map(lambda x: "+".join(list(map(lambda y: numbersDict[f"{atoms[y]}"],list(x)))), stack)) outs = list(map(lambda x: numbersDict[f"{x}"], outAtoms)) tot = list(map(lambda x: x[0] + "->" + x[1], zip(res, outs))) for t in tot: print(t) else: print("NO") ```
741_B. Arpa's weak amphitheater and Mehrdad's valuable Hoses
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≤ n ≤ 1000, <image>, 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
```python n, m, k = map(int, input().split()) a = map(int, input().split()) b = map(int, input().split()) ab = [(0, 0)] + list(zip(a, b)) l = list(range(n + 1)) def f(x): if x == l[x]: return x l[x] = f(l[x]) return l[x] for i in range(m): x, y = map(int, input().split()) x, y = f(x), f(y) if x != y: l[y] = x p = [[] for j in range(n + 1)] for i in range(1, n + 1): p[f(i)].append(i) r = (k+1) * [0] r[0] = 1 for i in p: if len(i) > 1: l = [ab[x] for x in i] x0 = sum(x[0] for x in l) x1 = sum(x[1] for x in l) l.append((x0, x1)) l.sort() for j in range(k, -1, -1): if r[j]: for w, b in l: if j + w > k: break r[j + w] = max(r[j + w], r[j] + b) elif len(i) == 1: w, b = ab[i[0]] for j in range(k - w, -1, -1): if r[j]: r[j + w] = max(r[j + w], r[j] + b) res = max(r) - 1 print(res) ```
765_A. Neverending competitions
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≤ n ≤ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list.
```python import sys,math from collections import deque #input = sys.stdin.buffer.readline def solve(): return; # for _ in range(int(input())): # solve() n = int(input()) h = input() cnt=0 for i in range(n): s = input() if h==s[:3] or h==s[-3:]: cnt+=1 if cnt%2==0: print("home") else: print("contest") ```
788_C. The Great Mixing
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≤ n ≤ 1000, 1 ≤ k ≤ 106) — carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≤ ai ≤ 1000) — carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>.
```python ## ## ## import sys def line(): return sys.stdin.readline() def numbers(): return list(map(int, line().split())) def number(): return int(line()) adjlist = {} n, k = 0, 0 mark = [False]*2010 edges = [False]*1010 # bfs for "ssph" def bfs(s): i = 0 frontier = [s] while frontier: if mark[s]: break; next_frontier = [] for u in frontier: # check next state for v, isState in enumerate(edges): if isState: # check new node state = u + (n - 1000) - v if state >= 0 and state <= 2000 and not mark[state]: mark[state] = True next_frontier.append(state) frontier = next_frontier i += 1 if mark[s]: return i else: return -1 # main program [n, k] = numbers() concentrations = numbers() # reading edges for x in concentrations: edges[x] = True n = n + 1000 ans = bfs(1000) print(ans) # 1496438704903 ```
834_C. The Meaningless Game
<image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≤ n ≤ 350000) is given. Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(a ,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left)/ 2) # Check if middle element is # less than or equal to key if (arr[mid]<=key): count = mid+1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def countGreater( arr,n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ for i in range(int(input())): a,b=map(int,input().split()) #c=a*b l=int((a*b)**(1/3)+0.5) if l**3==a*b and a%l==0 and b%l==0: print("YES") else: print("NO") ```
855_A. Tom Riddle's Diary
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence. He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not. Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes). Input First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100. Output Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower). Examples Input 6 tom lucius ginny harry ginny harry Output NO NO NO NO YES YES Input 3 a a a Output NO YES YES Note In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".
```python l = [] for _ in range(int(input())): s = input() if s not in l: print('NO') l.append(s) else: print('YES') ```
879_D. Teams Formation
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai. Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times). After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city. Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected. Input The first line contains three integers n, k and m (1 ≤ n ≤ 105, 2 ≤ k ≤ 109, 1 ≤ m ≤ 109). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number of city, person from which must take seat i in the bus. Output Output the number of remaining participants in the line. Examples Input 4 2 5 1 2 3 1 Output 12 Input 1 9 10 1 Output 1 Input 3 2 10 1 2 1 Output 0 Note In the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.
```python def main(): _, k, m = [int(x) for x in input().split()] a = [] last = ("-1", 0) a.append(last) for ai in input().split(): if last[0] == ai: last = (ai, last[1]+1) a[-1] = last else: last = (ai, 1) a.append(last) if last[1] == k: a.pop() last = a[-1] a.pop(0) s1 = 0 while len(a) > 0 and a[0][0] == a[-1][0]: if len(a) == 1: s = a[0][1] * m r1 = s % k if r1 == 0: print(s1 % k) else: print(r1 + s1) return join = a[0][1] + a[-1][1] if join < k: break elif join % k == 0: s1 += join a.pop() a.pop(0) else: s1 += (join // k) * k a[0] = (a[0][0], join % k) a.pop() break s = 0 for ai in a: s += ai[1] print(s*m + s1) if __name__ == "__main__": main() ```
903_A. Hungry Student Problem
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount of chicken. Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a small portions and b large ones contain exactly x chunks. Help Ivan to answer this question for several values of x! Input The first line contains one integer n (1 ≤ n ≤ 100) — the number of testcases. The i-th of the following n lines contains one integer xi (1 ≤ xi ≤ 100) — the number of chicken chunks Ivan wants to eat. Output Print n lines, in i-th line output YES if Ivan can buy exactly xi chunks. Otherwise, print NO. Example Input 2 6 5 Output YES NO Note In the first example Ivan can buy two small portions. In the second example Ivan cannot buy exactly 5 chunks, since one small portion is not enough, but two small portions or one large is too much.
```python t = int(input()) for i in range(0,t): flag = 0 x = int(input()) b = 0 temp = x while temp >= 0 : if(temp%3 == 0): flag = 1 break b = b+1 temp = x-7*b if flag == 1 : print("YES") else: print("NO") ```
925_B. Resource Distribution
One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units. In order for production to work, it is needed to deploy two services S_1 and S_2 to process incoming requests using the servers of the department. Processing of incoming requests of service S_i takes x_i resource units. The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service S_i is deployed using k_i servers, then the load is divided equally between these servers and each server requires only x_i / k_i (that may be a fractional number) resource units. Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides. Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services. Input The first line contains three integers n, x_1, x_2 (2 ≤ n ≤ 300 000, 1 ≤ x_1, x_2 ≤ 10^9) — the number of servers that the department may use, and resource units requirements for each of the services. The second line contains n space-separated integers c_1, c_2, …, c_n (1 ≤ c_i ≤ 10^9) — the number of resource units provided by each of the servers. Output If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes). Otherwise print the word "Yes" (without the quotes). In the second line print two integers k_1 and k_2 (1 ≤ k_1, k_2 ≤ n) — the number of servers used for each of the services. In the third line print k_1 integers, the indices of the servers that will be used for the first service. In the fourth line print k_2 integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them. Examples Input 6 8 16 3 5 2 9 8 7 Output Yes 3 2 1 2 6 5 4 Input 4 20 32 21 11 11 12 Output Yes 1 3 1 2 3 4 Input 4 11 32 5 5 16 16 Output No Input 5 12 20 7 8 4 11 9 Output No Note In the first sample test each of the servers 1, 2 and 6 will will provide 8 / 3 = 2.(6) resource units and each of the servers 5, 4 will provide 16 / 2 = 8 resource units. In the second sample test the first server will provide 20 resource units and each of the remaining servers will provide 32 / 3 = 10.(6) resource units.
```python def fin(c, x): return (x + c - 1) // c def ck(x, b): r = (n, n) for i in range(b, n): r = min(r, (i + fin(c[i][0], x), i)) return r def sol(r, l): if r[0] <= n and l[0] <= n and r[1] < n and l[1] < n : print("Yes") print(r[0] - r[1], l[0]- l[1]) print(' '.join([str(x[1]) for x in c[r[1]:r[0]]])) print(' '.join([str(x[1]) for x in c[l[1]:l[0]]])) return True else: return False n, x1, x2 = [int(x) for x in input().split()] c = sorted([(int(x), i + 1) for i, x in enumerate(input().split())]) r1 = ck(x1, 0) l1 = ck(x2, r1[0]) r2 = ck(x2, 0) l2 = ck(x1, r2[0]) if not sol(r1, l1) and not sol(l2, r2): print("No") # 6 8 16 # 3 5 2 9 8 7 ```
954_C. Matrix Walk
There is a matrix A of size x × y filled with integers. For every <image>, <image> Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on. From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: 1. (i + 1, j) — only if i < x; 2. (i, j + 1) — only if j < y; 3. (i - 1, j) — only if i > 1; 4. (i, j - 1) — only if j > 1. Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves? Input The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path. Output If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109. Examples Input 8 1 2 3 6 9 8 5 2 Output YES 3 3 Input 6 1 2 1 2 5 3 Output NO Input 2 1 10 Output YES 4 9 Note The matrix and the path on it in the first test looks like this: <image> Also there exist multiple correct answers for both the first and the third examples.
```python def main(): int(input()) a = list(map(int, input().split())) ds = [i - j for i, j in zip(a[1:], a)] dss = set(abs(x) for x in ds) if 0 in dss: return False try: dss.remove(1) except KeyError: pass if len(dss) > 1: return False if not dss: return 1e9, 1e9 y = next(iter(dss)) for d, c in zip(ds, a): j = (c - 1) % y if d == 1 and j == y - 1: return False if d == -1 and j == 0: return False return 1e9, y ans = main() if ans: print('YES') print('%d %d' % ans) else: print('NO') ```
980_B. Marlin
The city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon pond at (1, n). The mayor of Fishtopia wants to place k hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells. A person can move from one cell to another if those cells are not occupied by hotels and share a side. Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond? Input The first line of input contain two integers, n and k (3 ≤ n ≤ 99, 0 ≤ k ≤ 2×(n-2)), n is odd, the width of the city, and the number of hotels to be placed, respectively. Output Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO". If it is possible, print an extra 4 lines that describe the city, each line should have n characters, each of which is "#" if that cell has a hotel on it, or "." if not. Examples Input 7 2 Output YES ....... .#..... .#..... ....... Input 5 3 Output YES ..... .###. ..... .....
```python EMPTY = "." HOTEL = "#" def main(): n, k = map(int, input().split()) print("YES") print(EMPTY * n) if k % 2 == 0: m = k // 2 s = EMPTY + HOTEL * m + EMPTY * (n - m - 1) print(s) print(s) elif k < n - 1: s = (HOTEL * k).center(n, EMPTY) print(s) print(EMPTY * n) else: print(EMPTY + HOTEL * (n - 2) + EMPTY) print(EMPTY + HOTEL * (k - n + 1) + EMPTY * (2 * n - k - 4) + HOTEL + EMPTY) print(EMPTY * n) main() ```
9_B. Running Student
And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x. Poor Student knows the following: * during one run the minibus makes n stops, the i-th stop is in point (xi, 0) * coordinates of all the stops are different * the minibus drives at a constant speed, equal to vb * it can be assumed the passengers get on and off the minibus at a bus stop momentarily * Student can get off the minibus only at a bus stop * Student will have to get off the minibus at a terminal stop, if he does not get off earlier * the University, where the exam will be held, is in point (xu, yu) * Student can run from a bus stop to the University at a constant speed vs as long as needed * a distance between two points can be calculated according to the following formula: <image> * Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University. Input The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value. Output In the only line output the answer to the problem — index of the optimum bus stop. Examples Input 4 5 2 0 2 4 6 4 1 Output 3 Input 2 1 1 0 100000 100000 100000 Output 2 Note As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.
```python # -*- coding: utf - 8 -*- """"""""""""""""""""""""""""""""""""""""""""" | author: mr.math - Hakimov Rahimjon | | e-mail: [email protected] | | created: 27.01.2018 9:50 | """"""""""""""""""""""""""""""""""""""""""""" # inp = open("input.txt", "r"); input = inp.readline; out = open("output.txt", "w"); print = out.write TN = 1 # =========================================== def solution(): import math n, v_b, v_s = map(int, input().split()) x = list(map(int, input().split())) x_u, y_u = map(int, input().split()) a_s = 111111111000000000000000000000000 ans = 0 for i in range(1, n): if x[i] / v_b + math.sqrt((x_u-x[i])**2+y_u**2)/v_s <= a_s: a_s = x[i] / v_b + math.sqrt((x_u-x[i])**2+y_u**2)/v_s ans = i+1 print(ans) # =========================================== while TN != 0: solution() TN -= 1 # =========================================== # inp.close() # out.close() ```
p02545 ACL Contest 1 - Center Rearranging
Given are integer sequences A and B of length 3N. Each of these two sequences contains three copies of each of 1, 2, \dots, N. In other words, A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N). Tak can perform the following operation to the sequence A arbitrarily many times: * Pick a value from 1, 2, \dots, N and call it x. A contains exactly three copies of x. Remove the middle element of these three. After that, append x to the beginning or the end of A. Check if he can turn A into B. If he can, print the minimum required number of operations to achieve that. Constraints * 1 \leq N \leq 33 * A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N). * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_{3N} B_1 B_2 ... B_{3N} Output If Tak can turn A into B, print the minimum required number of operations to achieve that. Otherwise, print -1. Examples Input 3 2 3 1 1 3 2 2 1 3 1 2 2 3 1 2 3 1 3 Output 4 Input 3 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 Output 0 Input 3 2 3 3 1 1 1 2 2 3 3 2 2 1 1 1 3 3 2 Output -1 Input 8 3 6 7 5 4 8 4 1 1 3 8 7 3 8 2 4 7 5 2 2 6 5 6 1 7 5 8 1 3 6 7 5 4 8 1 3 3 8 2 4 2 6 5 6 1 4 7 2 Output 7
```python import sys readline = sys.stdin.buffer.readline class E: def __init__(self,to,nx): self.to=to self.nx=nx class Graph: def __init__(self,n): self.n=n self.head=[None]*n def ae(self,a,b): head=self.head head[a]=E(b,head[a]) #head[b]=E(a,head[b]) return head[a] def scc(g): n=g.n cur=g.head last=[None]*n order=[-1]*n low=[-1]*n bl=[-1]*n idx=[] st=[] num=0 for i in range(n): if order[i]!=-1: continue rec=[i] while rec: v=rec[-1] if last[v] is None: #first in v order[v]=low[v]=num num+=1 st.append(v) else: #process last edge low[v]=min(low[v],low[last[v].to]) found=False while cur[v] is not None: #process next edge e=cur[v] cur[v]=e.nx to=e.to if order[to]==-1: #visit another node rec.append(to) last[v]=e found=True break elif bl[to]==-1: low[v]=min(low[v],order[to]) if not found: #last out v rec.pop() if order[v]==low[v]: c=len(idx) tmp=[] while True: a=st.pop() bl[a]=c tmp.append(a) if v==a: break idx.append(tmp) s=len(idx) for i in range(n): bl[i]=s-1-bl[i] idx.reverse() return (s,bl,idx) class twosat: def __init__(self,n): self.n=n self.g=Graph(2*n) def add(self,x,y): self.g.ae(x^1,y) self.g.ae(y^1,x) def solve(self): s,bl,idx=scc(self.g) for i in range(self.n): if bl[i*2]==bl[i*2+1]: return False return True n=int(readline()) N=n*3 a=list(map(int,readline().split())) b=list(map(int,readline().split())) for i in range(N): a[i]-=1 b[i]-=1 apos=[[] for i in range(n)] for i in range(N): apos[a[i]].append(i) bpos=[[] for i in range(n)] for i in range(N): bpos[b[i]].append(i) def feasible(l,r): t=[False]*N def issubseq(): head=l for i in range(N): if t[i]: while head<r and a[i]!=b[head]: head+=1 if head==r: return False head+=1 return True l2r=[] r2l=[] w=[] for val in range(n): z=[] for x in bpos[val]: if x<l: z.append(0) elif x<r: z.append(1) else: z.append(2) if z==[0,0,0]: return False elif z==[0,0,1]: t[apos[val][2]]=1 elif z==[0,0,2]: x=l-bpos[val][0] y=bpos[val][2]-r r2l.append((x,y)) elif z==[0,1,1]: t[apos[val][0]]=1 t[apos[val][2]]=1 elif z==[0,1,2]: x=l-bpos[val][0] y=bpos[val][2]-r w.append((apos[val][0],apos[val][2],x,y)) elif z==[0,2,2]: x=l-bpos[val][0] y=bpos[val][2]-r l2r.append((x,y)) elif z==[1,1,1]: t[apos[val][0]]=1 t[apos[val][1]]=1 t[apos[val][2]]=1 elif z==[1,1,2]: t[apos[val][0]]=1 t[apos[val][2]]=1 elif z==[1,2,2]: t[apos[val][0]]=1 elif z==[2,2,2]: return False else: assert False if not issubseq(): return False def conflict(xa,xb,ya,yb): return ya<=xa and xb<=yb for xa,xb in l2r: for ya,yb in r2l: if conflict(xa,xb,ya,yb): return False s=len(w) ts=twosat(s) for i in range(s): pa,pb,qa,qb=w[i] #left is ok? ok=True t[pa]=1 if not issubseq(): ok=False t[pa]=0; if ok: for xa,xb in l2r: if conflict(xa,xb,qa,qb): ok=False if not ok: ts.add(i*2+1,i*2+1) #right is ok? ok=True t[pb]=1; if not issubseq(): ok=False t[pb]=0; if ok: for ya,yb in r2l: if conflict(qa,qb,ya,yb): ok=False if not ok: ts.add(i*2,i*2) for i in range(s): for j in range(i+1,s): p0a,p0b,q0a,q0b=w[i] p1a,p1b,q1a,q1b=w[j] t0=bpos[a[p0a]][1] t1=bpos[a[p1a]][1] #left-left is ok? ok=True if (p0a<p1a)!=(t0<t1): ok=False if not ok: ts.add(i*2+1,j*2+1) #left-right is ok? ok=True if (p0a<p1b)!=(t0<t1): ok=False if conflict(q1a,q1b,q0a,q0b): ok=False if not ok: ts.add(i*2+1,j*2) #right-left is ok? ok=True if (p0b<p1a)!=(t0<t1): ok=False; if conflict(q0a,q0b,q1a,q1b): ok=False if not ok: ts.add(i*2,j*2+1) #right-right is ok? ok=True if (p0b<p1b)!=(t0<t1): ok=False if not ok: ts.add(i*2,j*2); return ts.solve(); ans=10**18 for i in range(N): for j in range(i,N+1): if feasible(i,j): ans=min(ans,N-(j-i)) if ans==10**18: ans=-1 print(ans) ```
p02676 AtCoder Beginner Contest 168 - ... (Triple Dots)
We have a string S consisting of lowercase English letters. If the length of S is at most K, print S without change. If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result. Constraints * K is an integer between 1 and 100 (inclusive). * S is a string consisting of lowercase English letters. * The length of S is between 1 and 100 (inclusive). Input Input is given from Standard Input in the following format: K S Output Print a string as stated in Problem Statement. Examples Input 7 nikoandsolstice Output nikoand... Input 40 ferelibenterhominesidquodvoluntcredunt Output ferelibenterhominesidquodvoluntcredunt
```python K = int(input()) S = input() print(S[:K] + "...") if len(S) > K else print(S) ```
p02804 AtCoder Beginner Contest 151 - Max-Min Sums
For a finite set of integers X, let f(X)=\max X - \min X. Given are N integers A_1,...,A_N. We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways. Since the answer can be enormous, print it \bmod (10^9+7). Constraints * 1 \leq N \leq 10^5 * 1 \leq K \leq N * |A_i| \leq 10^9 Input Input is given from Standard Input in the following format: N K A_1 ... A_N Output Print the answer \bmod (10^9+7). Examples Input 4 2 1 1 3 4 Output 11 Input 6 3 10 10 10 -10 -10 -10 Output 360 Input 3 1 1 1 1 Output 0 Input 10 6 1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0 Output 999998537
```python N,K = map(int,input().split()) A = list(map(int,input().split())) mod = 10**9+7 A = sorted(A) bikkuri = [1] for i in range(1,N+1): bikkuri.append((bikkuri[-1]*i)%mod) bikkuri2 = [1] for i in range(1,N+1): bikkuri2.append(pow(bikkuri[i],mod-2,mod)) def comb(n,r): if n<r: return 0 else: return (bikkuri[n]*bikkuri2[n-r]*bikkuri2[r])%mod ans = 0 for i in range(N): ans += A[i]*(comb(i,K-1)-comb(N-i-1,K-1)) ans %= mod print(ans) ```
p02940 AtCoder Grand Contest 037 - RGB Balls
We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls. Takahashi will distribute these 3N balls to N people so that each person gets one red ball, one blue ball, and one green ball. The people want balls with IDs close to each other, so he will additionally satisfy the following condition: * Let a_j < b_j < c_j be the IDs of the balls received by the j-th person in ascending order. * Then, \sum_j (c_j-a_j) should be as small as possible. Find the number of ways in which Takahashi can distribute the balls. Since the answer can be enormous, compute it modulo 998244353. We consider two ways to distribute the balls different if and only if there is a person who receives different sets of balls. Constraints * 1 \leq N \leq 10^5 * |S|=3N * S consists of `R`, `G`, and `B`, and each of these characters occurs N times in S. Input Input is given from Standard Input in the following format: N S Output Print the number of ways in which Takahashi can distribute the balls, modulo 998244353. Examples Input 3 RRRGGGBBB Output 216 Input 5 BBRGRRGRGGRBBGB Output 960
```python MOD = 998244353 N = int(input()) Ss = input() convs = {'R': 0, 'G': 1, 'B': 2} num0 = N num1s = [0] * 3 num2s = [0] * 3 ans = 1 for S in Ss: c = convs[S] if num2s[c]: ans *= num2s[c] num2s[c] -= 1 else: for i in range(3): if i == c: continue if num1s[i]: ans *= num1s[i] num1s[i] -= 1 num2s[3-i-c] += 1 break else: ans *= num0 num0 -= 1 num1s[c] += 1 ans %= MOD print(ans) ```
p03077 AtCoder Beginner Contest 123 - Five Transportations
In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)! There are five means of transport in this empire: * Train: travels from City 1 to 2 in one minute. A train can occupy at most A people. * Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people. * Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people. * Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people. * Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people. For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...). There is a group of N people at City 1, and they all want to go to City 6. At least how long does it take for all of them to reach there? You can ignore the time needed to transfer. Constraints * 1 \leq N, A, B, C, D, E \leq 10^{15} * All values in input are integers. Input Input is given from Standard Input in the following format: N A B C D E Output Print the minimum time required for all of the people to reach City 6, in minutes. Examples Input 5 3 2 4 3 5 Output 7 Input 10 123 123 123 123 123 Output 5 Input 10000000007 2 3 5 7 11 Output 5000000008
```python n = int(input()) l = [int(input()) for _ in range(5)] print(-(-n//min(l))+4) ```
p03219 AtCoder Beginner Contest 113 - Discount Fare
There is a train going from Station A to Station B that costs X yen (the currency of Japan). Also, there is a bus going from Station B to Station C that costs Y yen. Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus. How much does it cost to travel from Station A to Station C if she uses this ticket? Constraints * 1 \leq X,Y \leq 100 * Y is an even number. * All values in input are integers. Input Input is given from Standard Input in the following format: X Y Output If it costs x yen to travel from Station A to Station C, print x. Examples Input 81 58 Output 110 Input 4 54 Output 31
```python L = list(map(int,input().split())) print(L[0]+L[1]//2) ```
p03691 AtCoder Grand Contest 016 - Poor Turkeys
There are N turkeys. We number them from 1 through N. M men will visit here one by one. The i-th man to visit will take the following action: * If both turkeys x_i and y_i are alive: selects one of them with equal probability, then eats it. * If either turkey x_i or y_i is alive (but not both): eats the alive one. * If neither turkey x_i nor y_i is alive: does nothing. Find the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the following condition is held: * The probability of both turkeys i and j being alive after all the men took actions, is greater than 0. Constraints * 2 ≤ N ≤ 400 * 1 ≤ M ≤ 10^5 * 1 ≤ x_i < y_i ≤ N Input Input is given from Standard Input in the following format: N M x_1 y_1 x_2 y_2 : x_M y_M Output Print the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the condition is held. Examples Input 3 1 1 2 Output 2 Input 4 3 1 2 3 4 2 3 Output 1 Input 3 2 1 2 1 2 Output 0 Input 10 10 8 9 2 8 4 6 4 9 7 8 2 8 1 8 3 4 3 4 2 7 Output 5
```python import sys from itertools import combinations def solve(n, pairs): survivors = {v: {v} for v in range(1, n + 1)} for x, y in reversed(pairs): for v, srv in survivors.copy().items(): if x in srv: if y in srv: del survivors[v] else: srv.add(y) elif y in srv: srv.add(x) return sum(su.isdisjoint(sv) for su, sv in combinations(survivors.values(), 2)) n, m = map(int, input().split()) pairs = [tuple(map(int, line.split())) for line in sys.stdin.readlines()] print(solve(n, pairs)) ```
p03844 AtCoder Beginner Contest 050 - Addition and Subtraction Easy
Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either `+` or `-`. Your task is to evaluate the formula instead of her. Constraints * 1≦A,B≦10^9 * op is either `+` or `-`. Input The input is given from Standard Input in the following format: A op B Output Evaluate the formula and print the result. Examples Input 1 + 2 Output 3 Input 5 - 7 Output -2
```python a,b,c=input().split();print(int(a)+int(c)if b=='+'else int(a)-int(c)) ```
p04011 AtCoder Beginner Contest 044 - Tak and Hotels (ABC Edit)
There is a hotel with the following accommodation fee: * X yen (the currency of Japan) per night, for the first K nights * Y yen per night, for the (K+1)-th and subsequent nights Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee. Constraints * 1 \leq N, K \leq 10000 * 1 \leq Y < X \leq 10000 * N,\,K,\,X,\,Y are integers. Input The input is given from Standard Input in the following format: N K X Y Output Print Tak's total accommodation fee. Examples Input 5 3 10000 9000 Output 48000 Input 2 3 10000 9000 Output 20000
```python a,b,c,d=[int(input()) for i in range(4)] if a<=b: print(a*c) else: print(b*c+(a-b)*d) ```
p00097 Sum of Integers II
Write a program that extracts n different numbers from the numbers 0 to 100 and outputs the number of combinations that add up to s. Each n number is from 0 to 100, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is 1 + 2 + 3 = 6 0 + 1 + 5 = 6 0 + 2 + 4 = 6 There are three ways. Input Given multiple datasets. For each dataset, n (1 ≤ n ≤ 9) and s (0 ≤ s ≤ 1000) are given on one line, separated by a space. When both n and s are 0, it is the end of the input. The number of datasets does not exceed 50. Output For each dataset, output the number of combinations in which the sum of n integers is s on one line. No input is given with more than 1010 combinations. Example Input 3 6 3 1 0 0 Output 3 0
```python dp = [[0 for _ in range(1001)] for _ in range(10)] dp[1][0] = dp[0][0] = 1 for now in range(1, 101): for used in range(9, 0, -1): dpu = dp[used] dpu_1 = dp[used - 1] for s in range(now, 1001): dpu[s] = dpu_1[s - now] + dpu[s] while True: n, s = map(int, input().split()) if not n: break print(dp[n][s]) ```
p00229 Big Hit !
Ataru Oafoot of Aizu Gakuen University High School decided to play with a slot machine. When you insert a medal on this machine, three reels will start spinning and each reel will stop automatically. In a normal game (normal game), 3 medals are inserted, and when the symbols are aligned, the following medals are obtained according to the symbols. <image> A special service will be started depending on how the patterns are aligned. A big bonus starts when you have 3 of 7 symbols, and you can play 5 bonus games. Also, when you have 3 BAR symbols, the regular bonus will start and you can play 3 bonus games. If you have 3 star symbols, the free game will start and you will not be able to get medals, but you can start the next game without inserting medals. During the bonus game, if you insert 2 medals per game, you will automatically get 3 grape patterns and 15 medals. Oafoot started playing on the machine with 100 medals. After playing for a while, it ended in a normal game. How many medals did you have left? Create a program that inputs play information and outputs the number of medals left at hand. The play information is given as the number of big bonuses b, the number of regular bonuses r, the number of grapes aligned during a normal game g, the number of cherries aligned c, the number of stars aligned s, and the total number of games t. Note that t includes the number of bonus games. Also, medals will not disappear in the middle of the game. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a zero line. Each dataset is given in the following format: b r g c s t b, r, g, c, and s are integers greater than or equal to 0 and less than 200, and t is an integer less than or equal to 1000. The number of datasets does not exceed 120. Output For each input dataset, the number of medals remaining at hand is output on one line. Example Input 3 2 30 3 26 226 9 0 18 3 20 118 5 5 12 2 15 203 7 4 19 2 22 197 7 4 24 4 17 209 0 0 0 0 0 0 Output 127 793 414 629 617
```python while 1: b, r, g, c, s, t = map(int, input().split()) if t == 0: break ans = 100 ans += (15 - 2) * (5*b) + (15 - 3) * b t -= 6*b ans += (15 - 2) * (3*r) + (15 - 3) * r t -= 4*r ans += (7 - 3) * g t -= g ans += (2 - 3) * c t -= c t -= s ans += (0 - 3) * t print(ans) ```
p00391 Treasure Map
Mr. Kobou found a bundle of old paper when he was cleaning his family home. On each paper, two series of numbers are written. Strange as it appeared to him, Mr. Kobou further went through the storehouse and found out a note his ancestor left. According to it, the bundle of paper is a treasure map, in which the two sequences of numbers seem to give a clue to the whereabouts of the treasure the ancestor buried. Mr. Kobou’s ancestor divided the area where he buried his treasure in a reticular pattern and used only some of the grid sections. The two series of numbers indicate the locations: the $i$-th member of the first series indicates the number of locations in the $i$-th column (form left) of the grid sections where a part of the treasure is buried, and the $j$-th member of the second indicates the same information regarding the $j$-th row from the top. No more than one piece of treasure is buried in one grid section. An example of a 5 × 4 case is shown below. If the pieces of treasure are buried in the grid sections noted as "#" the two series of numbers become "0,2,2,1,1" and "1,1,1,3". | 0| 2| 2| 1| 1 ---|---|---|---|---|--- 1| | | #| | 1| | #| | | 1| | | | | # 3| | #| #| #| Mr. Kobou’s ancestor seems to be a very careful person. He slipped some pieces of paper with completely irrelevant information into the bundle. For example, a set of number series "3,2,3,0,0" and "4,2,0,0,2" does not match any combination of 5 × 5 matrixes. So, Mr. Kobou has first to exclude these pieces of garbage information. Given the set of information written on the pieces of paper, make a program to judge if the information is relevant. Input The input is given in the following format. $W$ $H$ $a_1$ $a_2$ $...$ $a_W$ $b_1$ $b_2$ $...$ $b_H$ The first line provides the number of horizontal partitions $W$ ($1 \leq W \leq 1000$) and vertical partitions $H$ ($1 \leq H \leq 1000$). The second line provides the $i$-th member of the first number series $a_i$ ($0 \leq a_i \leq H$) written on the paper, and the third line the $j$-th member of the second series $b_j$ ($0 \leq b_j \leq W$). Output Output "1" if the information written on the paper is relevant, or "0" otherwise. Examples Input 5 4 0 2 2 1 1 1 1 1 3 Output 1 Input 5 5 3 2 3 0 0 4 2 0 0 2 Output 0
```python import sys,heapq _,a,q=[[-int(e) for e in sys.stdin.readline().split() if e!='0'] for _ in[0]*3] heapq.heapify(q) for e in a: t=[] for _ in [0]*-e: if not q:print(0);exit() if q[0]!=-1:heapq.heappush(t,q[0]+1) heapq.heappop(q) while t:heapq.heappush(q,t[0]);heapq.heappop(t) print(int(not q)) ```
p00607 Emacs-like Editor
Emacs is a text editor which is widely used by many programmers. The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed without the mouse. Your task is to write a program which simulates key operations in the Emacs-like editor. The program should read a text and print the corresponding edited text. The text consists of several lines and each line consists of zero or more alphabets and space characters. A line, which does not have any character, is a blank line. The editor has a cursor which can point out a character or the end-of-line in the corresponding line. The cursor can also point out the end-of-line in a blank line. In addition, the editor has a buffer which can hold either a string (a sequence of characters) or a linefeed. The editor accepts the following set of commands (If the corresponding line is a blank line, the word "the first character" should be "the end-of-line"): * a Move the cursor to the first character of the current line. * e Move the cursor to the end-of-line of the current line. * p Move the cursor to the first character of the next upper line, if it exists. If there is no line above the current line, move the cursor to the first character of the current line. * n Move the cursor to the first character of the next lower line, if it exists. If there is no line below the current line, move the cursor to the first character of the current line. * f Move the cursor by one character to the right, unless the cursor points out the end-of-line. If the cursor points out the end-of-line and there is a line below the current line, move the cursor to the first character of the next lower line. Otherwise, do nothing. * b Move the cursor by one character to the left, unless the cursor points out the first character. If the cursor points out the first character and there is a line above the current line, move the cursor to the end-of-line of the next upper line. Otherwise, do nothing. * d If the cursor points out a character, delete the character (Characters and end-of-line next to the deleted character are shifted to the left). If the cursor points out the end-of-line and there is a line below, the next lower line is appended to the end-of-line of the current line (Lines below the current line are shifted to the upper). Otherwise, do nothing. * k If the cursor points out the end-of-line and there is a line below the current line, perform the command d mentioned above, and record a linefeed on the buffer. If the cursor does not point out the end-of-line, cut characters between the cursor (inclusive) and the end-of-line, and record them on the buffer. After this operation, the cursor indicates the end-of-line of the current line. * y If the buffer is empty, do nothing. If the buffer is holding a linefeed, insert the linefeed at the cursor. The cursor moves to the first character of the new line. If the buffer is holding characters, insert the characters at the cursor. The cursor moves to the character or end-of-line which is originally pointed by the cursor. The cursor position just after reading the text is the beginning of the first line, and the initial buffer is empty. Constraints * The number of lines in the text given as input ≤ 10 * The number of characters in a line given as input ≤ 20 * The number of commands ≤ 300 * The maximum possible number of lines in the text during operations ≤ 100 * The maximum possible number of characters in a line during operations ≤ 1000 Input The input consists of only one data-set which includes two parts. The first part gives a text consisting of several lines. The end of the text is indicated by a line (without quotes): "END_OF_TEXT" This line should not be included in the text. Next part gives a series of commands. Each command is given in a line. The end of the commands is indicated by a character '-'. Output For the input text, print the text edited by the commands. Example Input hyo ni END_OF_TEXT f d f f k p p e y a k y y n y - Output honihoni honi
```python class Editer: def __init__(self, text): # カーソルの位置 self.row = 0 #行 self.col = 0 #列 # 編集中のテキスト self.text = [list(t) + ['\n'] for t in text] # バッファー self.buffer = [] def row_head(self): return 0 def row_tail(self): return len(self.text) - 1 def col_head(self): return 0 def col_tail(self): return len(self.text[self.row]) - 1 def __repr__(self): return ''.join(''.join(t) for t in self.text) def command_a(self): # カーソルを現在の行の先頭文字に移動 self.col = self.col_head() def command_e(self): # カーソルを現在の行の行末に移動 self.col = self.col_tail() def command_p(self): # 上に行があれば、カーソルを上の行に if self.row != self.row_head() : self.row -= 1 # カーソルを先頭に self.col = self.col_head() def command_n(self): # 下に行があれば if self.row != self.row_tail(): # カーソルを下の行に移動 self.row += 1 # カーソルを先頭文字に移動 self.col = self.col_head() def command_b(self): # カーソルが行末にない場合 if self.col != self.col_head(): # カーソルを1つ左に移動 self.col -= 1 # カーソルが行末にあり、上に行がある場合 elif self.row != self.row_head(): # カーソルを前の行の先頭に self.row -= 1 self.col = self.col_tail() def command_f(self): # カーソルが行末にない場合 if self.col != self.col_tail(): # カーソルを1つ右に移動 self.col += 1 # カーソルが行末にあり、下に行がある場合 elif self.row != self.row_tail(): # カーソルを次の行の先頭に self.row += 1 self.col = self.col_head() def command_d(self): # カーソルが行末にない場合 if self.col != self.col_tail(): # カーソルの文字を削除 self.text[self.row].pop(self.col) # カーソルが行末を指し、下に行がある場合 elif self.row != self.row_tail(): # 下の行をそのままカーソルの位置に繋げ、以下の行は上にシフト self.text[self.row].pop(self.col_tail()) self.text[self.row] += self.text.pop(self.row+1) def command_k(self): # カーソルが行末にない場合 if self.col != self.col_tail(): # カーソルが指す文字を含めた右側すべての文字を切り取りそれをバッファに記録する。 self.buffer = self.text[self.row][self.col:-1] self.text[self.row] = self.text[self.row][:self.col] + ['\n'] # カーソルは元の行の行末を指すようになる self.col = self.col_tail() # カーソルが行末にあり、下に行がある場合 elif self.row != self.row_tail(): # バッファに改行を記録する。 self.buffer = ['\n'] # 下の行をそのままカーソルの位置に繋げる。以下の行は上にシフトされる。 self.text[self.row].pop(self.col_tail()) self.text[self.row] += self.text.pop(self.row+1) def command_y(self): ''' カーソルが指す文字の直前にバッファを挿入 カーソルの位置はもともと指していた文字へ移動 バッファの内容が改行なら ''' if self.buffer != ['\n']: self.text[self.row][self.col:self.col] = self.buffer self.col += len(self.buffer) else: self.text.insert(self.row+1, self.text[self.row][self.col:]) self.text[self.row] = self.text[self.row][:self.col] + ['\n'] self.row += 1 self.col = self.col_head() def main(): # input text text = [] while True: str = input() if str == 'END_OF_TEXT': break text.append(str) editer = Editer(text) # input command while True: command = input() if command == 'a' : editer.command_a() elif command == 'e' : editer.command_e() elif command == 'p' : editer.command_p() elif command == 'n' : editer.command_n() elif command == 'f' : editer.command_f() elif command == 'b' : editer.command_b() elif command == 'd' : editer.command_d() elif command == 'y' : editer.command_y() elif command == 'k' : editer.command_k() elif command == '-' : break print(editer, end='') if __name__ == '__main__': main() ```
p00744 Cards
There are many blue cards and red cards on the table. For each card, an integer number greater than 1 is printed on its face. The same number may be printed on several cards. A blue card and a red card can be paired when both of the numbers printed on them have a common divisor greater than 1. There may be more than one red card that can be paired with one blue card. Also, there may be more than one blue card that can be paired with one red card. When a blue card and a red card are chosen and paired, these two cards are removed from the whole cards on the table. <image> Figure E-1: Four blue cards and three red cards For example, in Figure E-1, there are four blue cards and three red cards. Numbers 2, 6, 6 and 15 are printed on the faces of the four blue cards, and 2, 3 and 35 are printed on those of the three red cards. Here, you can make pairs of blue cards and red cards as follows. First, the blue card with number 2 on it and the red card with 2 are paired and removed. Second, one of the two blue cards with 6 and the red card with 3 are paired and removed. Finally, the blue card with 15 and the red card with 35 are paired and removed. Thus the number of removed pairs is three. Note that the total number of the pairs depends on the way of choosing cards to be paired. The blue card with 15 and the red card with 3 might be paired and removed at the beginning. In this case, there are only one more pair that can be removed and the total number of the removed pairs is two. Your job is to find the largest number of pairs that can be removed from the given set of cards on the table. Input The input is a sequence of datasets. The number of the datasets is less than or equal to 100. Each dataset is formatted as follows. > m n > b1 ... bk ... bm > r1 ... rk ... rn > The integers m and n are the number of blue cards and that of red cards, respectively. You may assume 1 ≤ m ≤ 500 and 1≤ n ≤ 500. bk (1 ≤ k ≤ m) and rk (1 ≤ k ≤ n) are numbers printed on the blue cards and the red cards respectively, that are integers greater than or equal to 2 and less than 10000000 (=107). The input integers are separated by a space or a newline. Each of bm and rn is followed by a newline. There are no other characters in the dataset. The end of the input is indicated by a line containing two zeros separated by a space. Output For each dataset, output a line containing an integer that indicates the maximum of the number of the pairs. Sample Input 4 3 2 6 6 15 2 3 5 2 3 4 9 8 16 32 4 2 4 9 11 13 5 7 5 5 2 3 5 1001 1001 7 11 13 30 30 10 10 2 3 5 7 9 11 13 15 17 29 4 6 10 14 18 22 26 30 34 38 20 20 195 144 903 63 137 513 44 626 75 473 876 421 568 519 755 840 374 368 570 872 363 650 155 265 64 26 426 391 15 421 373 984 564 54 823 477 565 866 879 638 100 100 195 144 903 63 137 513 44 626 75 473 876 421 568 519 755 840 374 368 570 872 363 650 155 265 64 26 426 391 15 421 373 984 564 54 823 477 565 866 879 638 117 755 835 683 52 369 302 424 513 870 75 874 299 228 140 361 30 342 750 819 761 123 804 325 952 405 578 517 49 457 932 941 988 767 624 41 912 702 241 426 351 92 300 648 318 216 785 347 556 535 166 318 434 746 419 386 928 996 680 975 231 390 916 220 933 319 37 846 797 54 272 924 145 348 350 239 563 135 362 119 446 305 213 879 51 631 43 755 405 499 509 412 887 203 408 821 298 443 445 96 274 715 796 417 839 147 654 402 280 17 298 725 98 287 382 923 694 201 679 99 699 188 288 364 389 694 185 464 138 406 558 188 897 354 603 737 277 35 139 556 826 213 59 922 499 217 846 193 416 525 69 115 489 355 256 654 49 439 118 961 0 0 Output for the Sample Input 3 1 0 4 9 18 85 Example Input 4 3 2 6 6 15 2 3 5 2 3 4 9 8 16 32 4 2 4 9 11 13 5 7 5 5 2 3 5 1001 1001 7 11 13 30 30 10 10 2 3 5 7 9 11 13 15 17 29 4 6 10 14 18 22 26 30 34 38 20 20 195 144 903 63 137 513 44 626 75 473 876 421 568 519 755 840 374 368 570 872 363 650 155 265 64 26 426 391 15 421 373 984 564 54 823 477 565 866 879 638 100 100 195 144 903 63 137 513 44 626 75 473 876 421 568 519 755 840 374 368 570 872 363 650 155 265 64 26 426 391 15 421 373 984 564 54 823 477 565 866 879 638 117 755 835 683 52 369 302 424 513 870 75 874 299 228 140 361 30 342 750 819 761 123 804 325 952 405 578 517 49 457 932 941 988 767 624 41 912 702 241 426 351 92 300 648 318 216 785 347 556 535 166 318 434 746 419 386 928 996 680 975 231 390 916 220 933 319 37 846 797 54 272 924 145 348 350 239 563 135 362 119 446 305 213 879 51 631 43 755 405 499 509 412 887 203 408 821 298 443 445 96 274 715 796 417 839 147 654 402 280 17 298 725 98 287 382 923 694 201 679 99 699 188 288 364 389 694 185 464 138 406 558 188 897 354 603 737 277 35 139 556 826 213 59 922 499 217 846 193 416 525 69 115 489 355 256 654 49 439 118 961 0 0 Output 3 1 0 4 9 18 85
```python import collections import math class Dinic: """Dinic Algorithm: find max-flow complexity: O(EV^2) used in GRL6A(AOJ) """ class edge: def __init__(self, to, cap, rev): self.to, self.cap, self.rev = to, cap, rev def __init__(self, V, E, source, sink): """ V: the number of vertexes E: adjacency list source: start point sink: goal point """ self.V = V self.E = [[] for _ in range(V)] for fr in range(V): for to, cap in E[fr]: self.E[fr].append(self.edge(to, cap, len(self.E[to]))) self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1)) self.maxflow = self.dinic(source, sink) def dinic(self, source, sink): """find max-flow""" INF = float('inf') maxflow = 0 while True: self.bfs(source) if self.level[sink] < 0: return maxflow self.itr = [0] * self.V while True: flow = self.dfs(source, sink, INF) if flow > 0: maxflow += flow else: break def dfs(self, vertex, sink, flow): """find augmenting path""" if vertex == sink: return flow for i in range(self.itr[vertex], len(self.E[vertex])): self.itr[vertex] = i e = self.E[vertex][i] if e.cap > 0 and self.level[vertex] < self.level[e.to]: d = self.dfs(e.to, sink, min(flow, e.cap)) if d > 0: e.cap -= d self.E[e.to][e.rev].cap += d return d return 0 def bfs(self, start): """find shortest path from start""" que = collections.deque() self.level = [-1] * self.V que.append(start) self.level[start] = 0 while que: fr = que.popleft() for e in self.E[fr]: if e.cap > 0 and self.level[e.to] < 0: self.level[e.to] = self.level[fr] + 1 que.append(e.to) while True: M, N = map(int, input().split()) if M == 0 and N == 0: break blue, red = [], [] while True: for x in input().split(): blue.append(int(x)) if len(blue) == M: break while True: for x in input().split(): red.append(int(x)) if len(red) == N: break V = M + N + 2 edge = [set() for _ in range(V)] for i, b in enumerate(blue): if b != 1: for j, r in enumerate(red): if r % b == 0: edge[i].add((M+j, 1)) for j in range(2, int(math.sqrt(b)) + 1): if b % j == 0: for k, r in enumerate(red): if r % j == 0 or r % (b // j) == 0: edge[i].add((M+k, 1)) for i in range(M): edge[M+N].add((i, 1)) for j in range(N): edge[M+j].add((M+N+1, 1)) d = Dinic(V, edge, M+N, M+N+1) print(d.maxflow) ```
p00883 Infected Land
The earth is under an attack of a deadly virus. Luckily, prompt actions of the Ministry of Health against this emergency successfully confined the spread of the infection within a square grid of areas. Recently, public health specialists found an interesting pattern with regard to the transition of infected areas. At each step in time, every area in the grid changes its infection state according to infection states of its directly (horizontally, vertically, and diagonally) adjacent areas. * An infected area continues to be infected if it has two or three adjacent infected areas. * An uninfected area becomes infected if it has exactly three adjacent infected areas. * An area becomes free of the virus, otherwise. Your mission is to fight against the virus and disinfect all the areas. The Ministry of Health lets an anti-virus vehicle prototype under your command. The functionality of the vehicle is summarized as follows. * At the beginning of each time step, you move the vehicle to one of the eight adjacent areas. The vehicle is not allowed to move to an infected area (to protect its operators from the virus). It is not allowed to stay in the same area. * Following vehicle motion, all the areas, except for the area where the vehicle is in, change their infection states according to the transition rules described above. Special functionality of the vehicle protects its area from virus infection even if the area is adjacent to exactly three infected areas. Unfortunately, this virus-protection capability of the vehicle does not last. Once the vehicle leaves the area, depending on the infection states of the adjacent areas, the area can be infected. The area where the vehicle is in, which is uninfected, has the same effect to its adjacent areas as an infected area as far as the transition rules are concerned. The following series of figures illustrate a sample scenario that successfully achieves the goal. Initially, your vehicle denoted by @ is found at (1, 5) in a 5 × 5-grid of areas, and you see some infected areas which are denoted by #'s. <image> Firstly, at the beginning of time step 1, you move your vehicle diagonally to the southwest, that is, to the area (2, 4). Note that this vehicle motion was possible because this area was not infected at the start of time step 1. Following this vehicle motion, infection state of each area changes according to the transition rules. The column "1-end" of the figure illustrates the result of such changes at the end of time step 1. Note that the area (3, 3) becomes infected because there were two adjacent infected areas and the vehicle was also in an adjacent area, three areas in total. In time step 2, you move your vehicle to the west and position it at (2, 3). Then infection states of other areas change. Note that even if your vehicle had exactly three infected adjacent areas (west, southwest, and south), the area that is being visited by the vehicle is not infected. The result of such changes at the end of time step 2 is as depicted in "2-end". Finally, in time step 3, you move your vehicle to the east. After the change of the infection states, you see that all the areas have become virus free! This completely disinfected situation is the goal. In the scenario we have seen, you have successfully disinfected all the areas in three time steps by commanding the vehicle to move (1) southwest, (2) west, and (3) east. Your mission is to find the length of the shortest sequence(s) of vehicle motion commands that can successfully disinfect all the areas. Input The input is a sequence of datasets. The end of the input is indicated by a line containing a single zero. Each dataset is formatted as follows. n a11 a12 ... a1n a21 a22 ... a2n ... an1 an2 ... ann Here, n is the size of the grid. That means that the grid is comprised of n × n areas. You may assume 1 ≤ n ≤ 5. The rest of the dataset consists of n lines of n letters. Each letter aij specifies the state of the area at the beginning: '#' for infection, '.' for free of virus, and '@' for the initial location of the vehicle. The only character that can appear in a line is '#', '.', or '@'. Among n × n areas, there exists exactly one area which has '@'. Output For each dataset, output the minimum number of time steps that is required to disinfect all the areas. If there exists no motion command sequence that leads to complete disinfection, output -1. The output should not contain any other extra character. Examples Input 3 ... .@. ... 3 .## .#. @## 3 ##. #.. @.. 5 ....@ ##... #.... ...#. ##.## 5 #...# ...#. #.... ...## ..@.. 5 #.... ..... ..... ..... ..@.. 5 #..#. #.#.# .#.#. ....# .#@## 5 ..##. ..#.. #.... #.... .#@.. 0 Output 0 10 -1 3 2 1 6 4 Input 3 ... .@. ... 3 .## .#. @## 3 . .. @.. 5 ....@ ... .... ...#. .## 5 ...# ...#. .... ...## ..@.. 5 .... ..... ..... ..... ..@.. 5 ..#. .#.# .#.#. ....# .#@## 5 ..##. ..#.. .... .... .#@.. 0 Output 0 10 -1 3 2 1 6 4
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write dd0 = ((-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)) DD = [] for k in range(6): ddk = [] for y in range(k): for x in range(k): v = 0 for dx, dy in dd0: nx = x + dx; ny = y + dy if not 0 <= nx < k or not 0 <= ny < k: continue v |= 1 << (ny*k + nx) ddk.append(v) DD.append(ddk) L = (1 << 16) bc = [0]*L for v in range(1, L): bc[v] = bc[v ^ (v & -v)] + 1 def solve(): N = int(readline()) if N == 0: return False dd = dd0 dk = DD[N] state = 0 for i in range(N): s = readline().strip() for j, c in enumerate(s): if c == '#': state |= 1 << (N*i + j) elif c == '@': sx = j; sy = i U = {(state, sx, sy): 0} que = deque([(state, sx, sy)]) while que: state, x, y = key = que.popleft() d = U[key] if state == 0: write("%d\n" % d) break for dx, dy in dd: nx = x + dx; ny = y + dy if not 0 <= nx < N or not 0 <= ny < N: continue b = 1 << (ny*N + nx) if state & b: continue state ^= b n_state = 0 for k in range(N*N): v = state & dk[k] if state & (1 << k): if v and 2 <= bc[v // (v & -v)] <= 3: n_state |= (1 << k) else: if v and bc[v // (v & -v)] == 3: n_state |= (1 << k) if n_state & b: n_state ^= b n_key = (n_state, nx, ny) if n_key not in U: U[n_key] = d+1 que.append(n_key) state ^= b else: write("-1\n") return True while solve(): ... ```
p01285 Find the Point
We understand that reading English is a great pain to many of you. So we’ll keep this problem statememt simple. Write a program that reports the point equally distant from a set of lines given as the input. In case of no solutions or multiple solutions, your program should report as such. Input The input consists of multiple datasets. Each dataset is given in the following format: n x1,1 y1,1 x1,2 y1,2 x2,1 y2,1 x2,2 y2,2 ... xn,1 yn,1 xn,2 yn,2 n is the number of lines (1 ≤ n ≤ 100); (xi,1, yi,1) and (xi,2, yi,2) denote the different points the i-th line passes through. The lines do not coincide each other. The coordinates are all integers between -10000 and 10000. The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed. Output For each dataset, print a line as follows. If there is exactly one point equally distant from all the given lines, print the x- and y-coordinates in this order with a single space between them. If there is more than one such point, just print "Many" (without quotes). If there is none, just print "None" (without quotes). The coordinates may be printed with any number of digits after the decimal point, but should be accurate to 10-4. Example Input 2 -35 -35 100 100 -49 49 2000 -2000 4 0 0 0 3 0 0 3 0 0 3 3 3 3 0 3 3 4 0 3 -4 6 3 0 6 -4 2 3 6 6 -1 2 -4 6 0 Output Many 1.5000 1.5000 1.000 1.000
```python import sys readline = sys.stdin.readline write = sys.stdout.write EPS = 1e-9 def line_cross_point(P1, P2, Q1, Q2): x0, y0 = P1; x1, y1 = P2 x2, y2 = Q1; x3, y3 = Q2 dx0 = x1 - x0; dy0 = y1 - y0 dx1 = x3 - x2; dy1 = y3 - y2 s = (y0-y2)*dx1 - (x0-x2)*dy1 sm = dx0*dy1 - dy0*dx1 if -EPS < sm < EPS: return None return x0 + s*dx0/sm, y0 + s*dy0/sm def bisector(P1, P2, Q1, Q2): x0, y0 = P1; x1, y1 = P2 x2, y2 = Q1; x3, y3 = Q2 dx0 = x1 - x0; dy0 = y1 - y0 dx1 = x3 - x2; dy1 = y3 - y2 cp = line_cross_point(P1, P2, Q1, Q2) if cp is None: return None cx, cy = cp d0 = (dx0**2 + dy0**2)**.5 d1 = (dx1**2 + dy1**2)**.5 return [ ((cx, cy), (cx + (dx0*d1 + dx1*d0), cy + (dy0*d1 + dy1*d0))), ((cx, cy), (cx + (dx0*d1 - dx1*d0), cy + (dy0*d1 - dy1*d0))), ] def line_point_dist2(p1, p2, q): x, y = q x1, y1 = p1; x2, y2 = p2 dx = x2 - x1; dy = y2 - y1 dd = dx**2 + dy**2 sv = (x - x1) * dy - (y - y1) * dx return abs(sv / dd**.5) def check(LS, q): ds = [line_point_dist2(p1, p2, q) for p1, p2 in LS] return all(abs(ds[0] - e) < EPS for e in ds) def solve(): N = int(readline()) if N == 0: return False P = [] for i in range(N): x1, y1, x2, y2 = map(int, readline().split()) P.append(((x1, y1), (x2, y2))) if N <= 2: write("Many\n") return True s = [] for i in range(N): p1, p2 = P[i] for j in range(i): q1, q2 = P[j] bs = bisector(p1, p2, q1, q2) if bs is None: continue s.append(bs) if len(s) > 1: break else: continue break if len(s) < 2: write("None\n") return True ans = [] b1, b2 = s for p1, p2 in b1: for q1, q2 in b2: cp = line_cross_point(p1, p2, q1, q2) if cp is None: continue if check(P, cp): cx, cy = cp for ax, ay in ans: if abs(cx - ax) < EPS and abs(cy - ay) < EPS: break else: ans.append(cp) if len(ans) == 0: write("None\n") elif len(ans) > 1: write("Many\n") else: write("%.16f %.16f\n" % ans[0]) return True while solve(): ... ```
p01767 RUPC
Problem statement A programming contest will be held in the Russian Federation. The contest has N questions and has M participants. Question i has a score a_i, and it is known that participant j's ability is b_j. For problem i and participant j, participant j can always solve problem i if a_i ≤ b_j and only then. The score of a participant through the contest is the sum of the scores of the problems that the person was able to solve. Participant j also sets a target score c_j for this contest. Determine if each participant can score more than the target score. input The input is given in the following format. N a_ {0} a_ {1} a_ {2}… a_ {N−1} M b_ {0} b_ {1} b_ {2}… b_ {M−1} c_ {0} c_ {1} c_ {2}… c_ {M−1} Constraint * All inputs are integers * 1 \ ≤ N \ ≤ 300 \,000 * 1 \ ≤ M \ ≤ 300 \,000 * 0 \ ≤ a_ {i} \ ≤ 1 \, 000 \,000 * 0 \ ≤ b_ {i} \ ≤ 1 \, 000 \,000 * 0 \ ≤ c_ {i} \ ≤ ∑a_k output Print the answer on line M. On the i-line, output `Yes` if the participant i-1 can get more points than the target score, and` No` if not. sample Sample input 1 6 1 2 1 3 4 5 7 1 3 4 5 3 1 0 2 4 5 3 4 5 3 Sample output 1 Yes Yes Yes Yes Yes No No The points obtained by each participant are as follows. * Participant 0: 1 + 1 = 2 * Participant 1: 1 + 2 + 1 + 3 = 7 * Participant 2: 1 + 2 + 1 + 3 + 4 = 11 * Participant 3: 1 + 2 + 1 + 3 + 4 + 5 = 16 * Participant 4: 1 + 2 + 1 + 3 = 7 * Participant 5: 1 + 1 = 2 * Participants 6: 0 Sample input 2 8 1 1 2 3 3 4 6 100 Four 1 3 4 99 1 10 15 120 Sample output 2 Yes Yes No No Example Input 6 1 2 1 3 4 5 7 1 3 4 5 3 1 0 2 4 5 3 4 5 3 Output Yes Yes Yes Yes Yes No No
```python import bisect n=int(input()) a=sorted(list(map(int,input().split()))) d=[0]*(n+1) for i in range(1,n+1):d[i]=d[i-1]+a[i-1] m=int(input()) b,c=[list(map(int,input().split())) for _ in [0,0]] for i in range(m): p=bisect.bisect_right(a,b[i]) print(['Yes','No'][d[p]<c[i]]) ```
p01901 Suntan
D: Sunburn-Suntan- story Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. Cute like an angel. Aizu Nyan is planning to participate in this summer festival, so I made a schedule for the band to go to listen to. I'm worried about sunburn here. All live performances are held outdoors, but Aizu Nyan has a constitution that makes it easy to get sunburned, so if you are exposed to too much ultraviolet rays outdoors for a long time, you will get sunburned immediately. I plan to avoid UV rays as much as possible by evacuating indoors while there is no live performance, but during the live performance, it will inevitably hit the sun. Therefore, Aizu Nyan thought about taking measures against ultraviolet rays by applying sunscreen. problem If you apply sunscreen, you can get the effect for T minutes from the time you apply it. Sunscreen can only be applied once, so I want to use it effectively. Aizu Nyan is outdoors from the start time to the end time of the live, and is indoors at other times. You'll be given a live schedule that Aizu Nyan will listen to, so find the maximum amount of time you can get the sunscreen effect while you're outdoors. Input format The input can be given in the following format. T N s_1 t_1 ... s_N t_N The first line is given an integer T that represents the time it takes to get the sunscreen effect. The second line is given an integer N that represents the number of live concerts Aizu Nyan listens to. The following N lines are given the integer s_i, which represents the start time of the live that Aizu Nyan listens to thi, and the integer t_i, which represents the end time, separated by spaces. Constraint * 1 ≤ T ≤ 10 ^ {15} * 1 ≤ N ≤ 10 ^ 5 * 0 ≤ s_i <t_i ≤ 10 ^ {15} (1 ≤ i ≤ N) * The start time of the (i + 1) th live is the same as or later than the end time of the i-th live. That is, t_i ≤ s_ {i + 1} (1 ≤ i <N) output Print one line for the maximum amount of time you can get the sunscreen effect while you're outdoors. Input example 1 20 1 0 10 Output example 1 Ten Input example 2 20 1 0 100 Output example 2 20 Input example 3 9 3 1 5 9 11 13 20 Output example 3 7 Input example 4 twenty five Five 9 12 15 20 21 25 28 40 45 60 Output example 4 twenty one Example Input 20 1 0 10 Output 10
```python # AOJ 2801: Suntan # Python3 2018.7.11 bal4u from bisect import bisect_left T, N = int(input()), int(input()) a, s, t = [0], [0], [0] for i in range(N): _s, _t = map(int, input().split()) s.append(_s) t.append(_t) a.append(a[-1]+_t-_s) s.append(1<<62) t.append(1<<62) ans = 0 k = bisect_left(t, T, 0)-1 for i in range(1, N+1): x = s[i]+T k = bisect_left(t, x, k)-1 y = a[k]-a[i-1] if x > s[k+1]: y += x-s[k+1] if y > ans: ans = y; if ans == T: break print(ans) ```
p02038 Tanuki and Fox
problem There is a mysterious device $ M $, and if you put Tanuki and Fox in this device, one animal will come out from the device (hereinafter, Tanuki will be $ T $ and Fox will be $ F $). $ M (x, y) $ represents an animal that came out by putting animals in the device $ M $ in the order of $ x, y $. As a result of various trials, the following was found. $ M (T, T) = T $ $ M (T, F) = F $ $ M (F, T) = T $ $ M (F, F) = T $ You put the animals in a row $ P_1, P_2, ..., P_N $ into the device as follows. $ M (.... M (M (P_1, P_2), P_3) ...., P_N) $ Answer the last animal that appears. output Output the last animal character $ T $ or $ F $, and also a newline at the end. Example Input 3 F T T Output T
```python from functools import reduce def M(x, y): if x == 'T' and y == 'T': return 'T' elif x == 'T' and y == 'F': return 'F' elif x == 'F' and y == 'T': return 'T' else: return 'T' _ = input() P = input().split() print(reduce(M, P)) ```
p02182 Spot The Difference
A: Find the difference problem Given rectangular boards A and B with N squares vertically and M squares horizontally. For each board, each square is painted white or black. The color of the square in the i-th row and j-th column of the board X is written as C (i, j, X). Count how many pairs of integers (i, j) meet the following conditions: * 1 \ leq i \ leq N * 1 \ leq j \ leq M * C (i, j, A) \ neq C (i, j, B) Input format N M A_1_1 ... A_N B_1_1 ... B_N When the jth character of A_i (1 \ leq i \ leq N) is `#`, C (i, j, A) is black, and when it is `.`, C (i, j, A) is white. Represents that. The same is true for B. Constraint * 1 \ leq N, M \ leq 2,000 * | A_i | = | B_i | = M * A_i and B_i are strings consisting only of `#` and `.` Output format Print the answer on one line. Input example 1 twenty three .. # .. .## .. Output example 1 2 Input example 2 7 28 ............................ ... # ..... ### ... #### .... ### .. .. #. # ... # ... # ... # ... # .... # ... #. . # ... # ... # ...... #### ... # ..... . ##### .. # ... # .. # ...... # ... #. . # ... # ... ### ... # ....... ### .. ............................ ............................ .. ### .... ### ..... ## .... ### .. . # ... # ... # ... # ... #. # ... # ... #. ...##...#...# ..... # .... ####. .. # ..... # ... # ..... # ....... #. . ##### ... ### .... #### ... ### .. ............................ Output example 2 40 Example Input 2 3 ..# ##. .## #.. Output 2
```python N, M = map(int, input().split()) table1 = '' table2 = '' for i in range(2 * N): if i < N: table1 += input() else: table2 += input() count = 0 for i, j in zip(table1, table2): if i != j: count+=1 print(count) ```
p02324 Chinese Postman Problem
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * The graph is connected Input |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge). Note that there can be multiple edges between a pair of vertices. Output Print the shortest distance in a line. Examples Input 4 4 0 1 1 0 2 2 1 3 3 2 3 4 Output 10 Input 4 5 0 1 1 0 2 2 1 3 3 2 3 4 1 2 5 Output 18 Input 2 3 0 1 1 0 1 2 0 1 3 Output 7
```python import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) # adjacency matrix no_edge = float("inf") adj = [[no_edge] * V for i in range(V)] for i in range(V): adj[i][i] = 0 odd_b = 0 # bit DP to record odd vertex ans = 0 # acceptance of input for l_i in f_i: s, t, d = map(int, l_i.split()) t_d = min(d, adj[s][t]) adj[s][t] = t_d adj[t][s] = t_d odd_b ^= 1 << s odd_b ^= 1 << t ans += d if odd_b: # Warshall???Floyd Algorithm for k in range(V): for i in range(V): for j in range(V): adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]) # Minimum weighted matching mw = [no_edge] * (odd_b + 1) mw[0] = 0 digits = len(bin(odd_b)) - 2 for b in range(odd_b): for i in range(0, digits): if not (b & (1 << i)) and odd_b & (1 << i): for j in range(i + 1, digits): if not (b & (1 << j)) and odd_b & (1 << j): t_b = b + (1 << i) + (1 << j) if t_b == t_b & odd_b: t_w = mw[t_b] mw[t_b] = min(t_w, mw[b] + adj[i][j]) # Output ans += mw[odd_b] print(ans) else: print(ans) ```
p02469 Least Common Multiple
Find the least common multiple (LCM) of given n integers. Constraints * 2 ≤ n ≤ 10 * 1 ≤ ai ≤ 1000 * Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1 Input n a1 a2 ... an n is given in the first line. Then, n integers are given in the second line. Output Print the least common multiple of the given integers in a line. Examples Input 3 3 4 6 Output 12 Input 4 1 2 3 5 Output 30
```python from functools import reduce import math n = int(input()) def lcm_base(x, y): return (x * y) // math.gcd(x, y) def lcm_list(numbers): return reduce(lcm_base, numbers, 1) numlis = [int(a) for a in input().split()] print(lcm_list(numlis)) ```
1033_C. Permutation Game
After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell i to cell j only if the following two conditions are satisfied: * the number in the new cell j must be strictly larger than the number in the old cell i (i.e. a_j > a_i), and * the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. |i-j|mod a_i = 0). Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players. Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of numbers. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Furthermore, there are no pair of indices i ≠ j such that a_i = a_j. Output Print s — a string of n characters, where the i-th character represents the outcome of the game if the token is initially placed in the cell i. If Alice wins, then s_i has to be equal to "A"; otherwise, s_i has to be equal to "B". Examples Input 8 3 6 5 4 2 7 1 8 Output BAAAABAB Input 15 3 11 2 5 10 9 7 13 15 8 4 12 6 1 14 Output ABAAAABBBAABAAB Note In the first sample, if Bob puts the token on the number (not position): * 1: Alice can move to any number. She can win by picking 7, from which Bob has no move. * 2: Alice can move to 3 and 5. Upon moving to 5, Bob can win by moving to 8. If she chooses 3 instead, she wins, as Bob has only a move to 4, from which Alice can move to 8. * 3: Alice can only move to 4, after which Bob wins by moving to 8. * 4, 5, or 6: Alice wins by moving to 8. * 7, 8: Alice has no move, and hence she loses immediately.
```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") # ------------------------------ from math import factorial from collections import Counter, defaultdict from heapq import heapify, heappop, heappush def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) mod = 1000000007 INF = float('inf') # ------------------------------ def main(): n = N() arr = RLL() dic = {v: i for i, v in enumerate(arr)} dp = [1]*n for i in range(n-1, 0, -1): for p in range(dic[i]%i, n, i): if arr[p]>i and dp[dic[arr[p]]]==1: dp[dic[i]] = 0 break print("".join(['B' if i == 1 else 'A' for i in dp])) if __name__ == "__main__": main() ```
1056_A. Determine Line
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in. During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in? Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of stops Arkady saw. The next n lines describe the stops. Each of them starts with a single integer r (1 ≤ r ≤ 100) — the number of tram lines that stop there. r distinct integers follow, each one between 1 and 100, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take. Output Print all tram lines that Arkady could be in, in arbitrary order. Examples Input 3 3 1 4 6 2 1 4 5 10 5 6 4 1 Output 1 4 Input 5 1 1 10 10 9 8 7 100 5 4 3 99 1 5 1 2 3 4 5 5 4 1 3 2 5 4 10 1 5 3 Output 1 Note Consider the first example. Arkady woke up three times. The first time he saw a stop with lines 1, 4, 6. The second time he saw a stop with lines 1, 4. The third time he saw a stop with lines 10, 5, 6, 4 and 1. He can be in a tram of one of two lines: 1 or 4.
```python n = int(input()) def intersect(a, b): x = [] for i in a: if i in b: x.append(i) return x things = [input().split()[1:] for i in range(n)] ans = things[0] for i in range(1, n): ans = intersect(ans, things[i]) print(" ".join(ans)) ```
1078_B. The Unbearable Lightness of Weights
You have a set of n weights. You know that their masses are a_1, a_2, ..., a_n grams, but you don't know which of them has which mass. You can't distinguish the weights. However, your friend does know the mass of each weight. You can ask your friend to give you exactly k weights with the total mass m (both parameters k and m are chosen by you), and your friend will point to any valid subset of weights, if it is possible. You are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query. Input The first line contains a single integer n (1 ≤ n ≤ 100) — the number of weights. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100) — the masses of the weights. Output Print the maximum number of weights you can learn the masses for after making a single query. Examples Input 4 1 4 2 2 Output 2 Input 6 1 2 4 4 4 9 Output 2 Note In the first example we can ask for a subset of two weights with total mass being equal to 4, and the only option is to get \{2, 2\}. Another way to obtain the same result is to ask for a subset of two weights with the total mass of 5 and get \{1, 4\}. It is easy to see that the two remaining weights have mass of 2 grams each. In the second example we can ask for a subset of two weights with total mass being 8, and the only answer is \{4, 4\}. We can prove it is not possible to learn masses for three weights in one query, but we won't put the proof here.
```python from collections import defaultdict def calcBinomials(N): global binom N += 1 binom = [[0]*N for _ in range(N)] for n in range(N): binom[n][0] = binom[n][n] = 1 for k in range(1, n): binom[n][k] = binom[n-1][k] + binom[n-1][k-1] n = int(input()) a = list(map(int, input().split())) S, res = sum(a), 0 dp = [defaultdict(lambda: 0) for _ in range(S+1)] dp[0][0] = 1 cnt = {_:a.count(_) for _ in a} for x in a: for i in range(len(dp)-1-x, -1, -1): for k, v in dp[i].items(): dp[i+x][k+1] += v calcBinomials(n) for x, c in cnt.items(): for i in range(1, c+1): if dp[x*i][i] == binom[c][i] or dp[S - x*i][n-i] == binom[c][c-i]: res = max(res, i) if len(cnt) <= 2: res = n print(res) ```
1099_B. Squares and Segments
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with vertices at integer points. In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends (x, y) and (x, y+1). Then Sofia looks if there is already a drawn segment with the coordinates of the ends (x', y) and (x', y+1) for some x'. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates x, x+1 and the differing coordinate y. For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler: <image> After that, she can draw the remaining two segments, using the first two as a guide: <image> If Sofia needs to draw two squares, she will have to draw three segments using a ruler: <image> After that, she can draw the remaining four segments, using the first three as a guide: <image> Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number. Input The only line of input contains a single integer n (1 ≤ n ≤ 10^{9}), the number of squares that Sofia wants to draw. Output Print single integer, the minimum number of segments that Sofia will have to draw with a ruler without a guide in order to draw n squares in the manner described above. Examples Input 1 Output 2 Input 2 Output 3 Input 4 Output 4
```python # cook your dish here t=int(input()) l=int(t**(0.5)) if l==(t**(0.5)): print(2*l) else: if abs((l**2)-t) < ((l+1)**2)-t: print(2*l+1) else: print(2*(l+1)) ```
111_A. Petya and Inequiations
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: * a12 + a22 + ... + an2 ≥ x * a1 + a2 + ... + an ≤ y Input The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use cin, cout streams or the %I64d specificator. Output Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them. Examples Input 5 15 15 Output 4 4 1 1 2 Input 2 3 2 Output -1 Input 1 99 11 Output 11
```python from math import sqrt, ceil n, x, y = map(int, input().split()) t = 1 if x < n else ceil(sqrt(x - n + 1)) if t + n - 1 > y: print(-1) else: print(str(t), '\n1' * (n - 1)) ```
1167_F. Scalar Queries
You are given an array a_1, a_2, ..., a_n. All a_i are pairwise distinct. Let's define function f(l, r) as follows: * let's define array b_1, b_2, ..., b_{r - l + 1}, where b_i = a_{l - 1 + i}; * sort array b in increasing order; * result of the function f(l, r) is ∑_{i = 1}^{r - l + 1}{b_i ⋅ i}. Calculate \left(∑_{1 ≤ l ≤ r ≤ n}{f(l, r)}\right) mod (10^9+7), i.e. total sum of f for all subsegments of a modulo 10^9+7. Input The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of array a. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9, a_i ≠ a_j for i ≠ j) — array a. Output Print one integer — the total sum of f for all subsegments of a modulo 10^9+7 Examples Input 4 5 2 4 7 Output 167 Input 3 123456789 214365879 987654321 Output 582491518 Note Description of the first example: * f(1, 1) = 5 ⋅ 1 = 5; * f(1, 2) = 2 ⋅ 1 + 5 ⋅ 2 = 12; * f(1, 3) = 2 ⋅ 1 + 4 ⋅ 2 + 5 ⋅ 3 = 25; * f(1, 4) = 2 ⋅ 1 + 4 ⋅ 2 + 5 ⋅ 3 + 7 ⋅ 4 = 53; * f(2, 2) = 2 ⋅ 1 = 2; * f(2, 3) = 2 ⋅ 1 + 4 ⋅ 2 = 10; * f(2, 4) = 2 ⋅ 1 + 4 ⋅ 2 + 7 ⋅ 3 = 31; * f(3, 3) = 4 ⋅ 1 = 4; * f(3, 4) = 4 ⋅ 1 + 7 ⋅ 2 = 18; * f(4, 4) = 7 ⋅ 1 = 7;
```python import sys MOD = (int)(1e9+7) def add(a, b): a += b if a >= MOD: a -= MOD return a def mul(a, b): return (a * b) % MOD class fenwickTree: def __init__(self, max_val): self.max_val = max_val + 5 self.tree = [0] * self.max_val def update(self, idx, value): idx += 1 while idx < self.max_val: self.tree[idx] = add(self.tree[idx], value) idx += (idx & (-idx)) def read(self, idx): idx += 1 res = 0 while idx > 0: res = add(res, self.tree[idx]) idx -= (idx & (-idx)) return res inp = [int(x) for x in sys.stdin.read().split()] n = inp[0] a = [] for i in range(1, n + 1): a.append(inp[i]) sorted_array = sorted(a) dict = {} for i in range(n): dict[sorted_array[i]] = i factor = [0] * n for i in range(0, n): factor[i] = mul(i + 1, n - i) left_tree = fenwickTree(n) for i in range(0, n): element_idx = dict[a[i]] factor[i] = add(factor[i], mul(n - i, left_tree.read(element_idx))) left_tree.update(element_idx, i + 1) right_tree = fenwickTree(n) for i in range(n - 1, -1, -1): element_idx = dict[a[i]] factor[i] = add(factor[i], mul(i + 1, right_tree.read(element_idx))) right_tree.update(element_idx, n - i) ans = 0 for i in range(n): ans = add(ans, mul(a[i], factor[i])) print(ans) ```
1186_A. Vus the Cossack and a Contest
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at least one pen and at least one notebook. Input The first line contains three integers n, m, and k (1 ≤ n, m, k ≤ 100) — the number of participants, the number of pens, and the number of notebooks respectively. Output Print "Yes" if it possible to reward all the participants. Otherwise, print "No". You can print each letter in any case (upper or lower). Examples Input 5 8 6 Output Yes Input 3 9 3 Output Yes Input 8 5 20 Output No Note In the first example, there are 5 participants. The Cossack has 8 pens and 6 notebooks. Therefore, he has enough pens and notebooks. In the second example, there are 3 participants. The Cossack has 9 pens and 3 notebooks. He has more than enough pens but only the minimum needed number of notebooks. In the third example, there are 8 participants but only 5 pens. Since the Cossack does not have enough pens, the answer is "No".
```python def solve(n, m, k): if min(m,k) >= n: return "Yes" else: return "No" def main(): n, m, k = list(map(int, input().split())) print(solve(n, m, k)) if __name__ == '__main__': main() ```
1205_A. Almost Equal
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more than by 1. For example, choose n = 3. On the left you can see an example of a valid arrangement: 1 + 4 + 5 = 10, 4 + 5 + 2 = 11, 5 + 2 + 3 = 10, 2 + 3 + 6 = 11, 3 + 6 + 1 = 10, 6 + 1 + 4 = 11, any two numbers differ by at most 1. On the right you can see an invalid arrangement: for example, 5 + 1 + 6 = 12, and 3 + 2 + 4 = 9, 9 and 12 differ more than by 1. <image> Input The first and the only line contain one integer n (1 ≤ n ≤ 10^5). Output If there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output 2n numbers — numbers from 1 to 2n in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them. Examples Input 3 Output YES 1 4 5 2 3 6 Input 4 Output NO Note Example from the statement is shown for the first example. It can be proved that there is no solution in the second example.
```python n = int(input()) if n%2 == 0: print("NO") exit(0) arr = [] for i in range(1, n+1): if i%2 == 1: arr.append(2*i-1) else: arr.append(2*i) for i in range(n): if arr[i] % 2 == 1: arr.append(arr[i]+1) else: arr.append(arr[i]-1) print("YES") print(*arr) ```
1221_E. Game With String
Alice and Bob play a game. Initially they have a string s_1, s_2, ..., s_n, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length a, and Bob must select a substring of length b. It is guaranteed that a > b. For example, if s = ...X.. and a = 3, b = 2, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string s = ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX. Whoever is unable to make a move, loses. You have to determine who wins if they both play optimally. You have to answer q independent queries. Input The first line contains one integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries. The first line of each query contains two integers a and b (1 ≤ b < a ≤ 3 ⋅ 10^5). The second line of each query contains the string s (1 ≤ |s| ≤ 3 ⋅ 10^5), consisting of only characters . and X. It is guaranteed that sum of all |s| over all queries not exceed 3 ⋅ 10^5. Output For each test case print YES if Alice can win and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). Example Input 3 3 2 XX......XX...X 4 2 X...X.X..X 5 3 .......X..X Output YES NO YES Note In the first query Alice can select substring s_3 ... s_5. After that s turns into XXXXX...XX...X. After that, no matter what move Bob makes, Alice can make the move (this will be her second move), but Bob can't make his second move. In the second query Alice can not win because she cannot even make one move. In the third query Alice can choose substring s_2 ... s_6. After that s turns into .XXXXX.X..X, and Bob can't make a move after that.
```python q = int(input()) for i in range(q): a, b = [int(item) for item in input().split()] s = input().rstrip() + "#" cnt = 0 bob_world = 0 alice_world = 0 length = 0 bob_winning = False for ch in s: if ch == ".": cnt += 1 else: if cnt < b: pass elif b <= cnt < a: bob_winning = True break elif a <= cnt < b * 2: alice_world += 1 elif cnt >= b * 2: length = cnt bob_world += 1 if bob_world >= 2: bob_winning = True break cnt = 0 if bob_winning: print("No") else: if length == 0: if alice_world % 2 == 1: print("Yes") else: print("No") continue possibility = set() for i in range(length - a + 1): l = i; r = length - a - i if b <= l < a or b <= r < a: continue if l >= b * 2 or r >= b * 2: continue val = 0 if a <= l < b * 2: val += 1 if a <= r < b * 2: val += 1 possibility.add(val + 1) alice_win = False for item in possibility: if (alice_world + item) % 2 == 1: alice_win = True if alice_win: print("Yes") else: print("No") ```
1248_B. Grow The Tree
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point (0, 0). While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to OX or OY axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification. Alexey wants to make a polyline in such a way that its end is as far as possible from (0, 0). Please help him to grow the tree this way. Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches. Input The first line contains an integer n (1 ≤ n ≤ 100 000) — the number of sticks Alexey got as a present. The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10 000) — the lengths of the sticks. Output Print one integer — the square of the largest possible distance from (0, 0) to the tree end. Examples Input 3 1 2 3 Output 26 Input 4 1 1 2 2 Output 20 Note The following pictures show optimal trees for example tests. The squared distance in the first example equals 5 ⋅ 5 + 1 ⋅ 1 = 26, and in the second example 4 ⋅ 4 + 2 ⋅ 2 = 20. <image> <image>
```python a=int(input());b=sorted(list(map(int,input().split())),reverse=True);from math import ceil as c;print(sum(b[:c(len(b)/2)])**2+sum(b[c(len(b)/2):])**2) ```
1288_A. Deadline
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days optimizing the program, he will make the program run in \left⌈ (d)/(x + 1) \right⌉ days (\left⌈ a \right⌉ is the ceiling function: \left⌈ 2.4 \right⌉ = 3, \left⌈ 2 \right⌉ = 2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x + \left⌈ (d)/(x + 1) \right⌉. Will Adilbek be able to provide the generated results in no more than n days? Input The first line contains a single integer T (1 ≤ T ≤ 50) — the number of test cases. The next T lines contain test cases – one per line. Each line contains two integers n and d (1 ≤ n ≤ 10^9, 1 ≤ d ≤ 10^9) — the number of days before the deadline and the number of days the program runs. Output Print T answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in n days or NO (case insensitive) otherwise. Example Input 3 1 1 4 5 5 11 Output YES YES NO Note In the first test case, Adilbek decides not to optimize the program at all, since d ≤ n. In the second test case, Adilbek can spend 1 day optimizing the program and it will run \left⌈ 5/2 \right⌉ = 3 days. In total, he will spend 4 days and will fit in the limit. In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 2 days, it'll still work \left⌈ (11)/(2+1) \right⌉ = 4 days.
```python import math for _ in range(int(input())): n,d = map(int,input().split()) if ((1-n)**2) - (4*(d-n)) >= 0: print('YES') else: print('NO') ```
1331_D. Again?
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A144045 Output 1
```python value = input() print(int(value, 16)%2) ```
1351_B. Square?
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given in two lines. The first line contains two integers a_1 and b_1 (1 ≤ a_1, b_1 ≤ 100) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers a_2 and b_2 (1 ≤ a_2, b_2 ≤ 100) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). Output Print t answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). Example Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No
```python for t in range(int(input())): a, b = map(int, input().split()) c, d = map(int, input().split()) a, b = min(a, b), max(a, b) c, d = min(c, d), max(c, d) if a + c == b == d: print("YES") else: print("NO") ```
1371_D. Grid-00100
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the grid is equal to k. Let's define: * A_{i,j} as the integer in the i-th row and the j-th column. * R_i = A_{i,1}+A_{i,2}+...+A_{i,n} (for all 1 ≤ i ≤ n). * C_j = A_{1,j}+A_{2,j}+...+A_{n,j} (for all 1 ≤ j ≤ n). * In other words, R_i are row sums and C_j are column sums of the grid A. * For the grid A let's define the value f(A) = (max(R)-min(R))^2 + (max(C)-min(C))^2 (here for an integer sequence X we define max(X) as the maximum value in X and min(X) as the minimum value in X). Find any grid A, which satisfies the following condition. Among such grids find any, for which the value f(A) is the minimum possible. Among such tables, you can find any. Input The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines contain descriptions of test cases. For each test case the only line contains two integers n, k (1 ≤ n ≤ 300, 0 ≤ k ≤ n^2). It is guaranteed that the sum of n^2 for all test cases does not exceed 10^5. Output For each test case, firstly print the minimum possible value of f(A) among all tables, for which the condition is satisfied. After that, print n lines contain n characters each. The j-th character in the i-th line should be equal to A_{i,j}. If there are multiple answers you can print any. Example Input 4 2 2 3 8 1 0 4 16 Output 0 10 01 2 111 111 101 0 0 0 1111 1111 1111 1111 Note In the first test case, the sum of all elements in the grid is equal to 2, so the condition is satisfied. R_1 = 1, R_2 = 1 and C_1 = 1, C_2 = 1. Then, f(A) = (1-1)^2 + (1-1)^2 = 0, which is the minimum possible value of f(A). In the second test case, the sum of all elements in the grid is equal to 8, so the condition is satisfied. R_1 = 3, R_2 = 3, R_3 = 2 and C_1 = 3, C_2 = 2, C_3 = 3. Then, f(A) = (3-2)^2 + (3-2)^2 = 2. It can be proven, that it is the minimum possible value of f(A).
```python 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") ####################################### t=int(input()) for i in range(t): n,k=map(int,input().split()) a=k//n b=k%n l=[[0 for j in range(n)] for p in range(n)] x=0 c=n-b if k!=0: for j in range(n): if c>0: for p in range(x,x+a): l[j][p%n]=1 c-=1 else: for p in range(x,x+a+1): l[j][p%n]=1 x+=1 x%=n if k%n: ans=2 else: ans=0 else: ans=0 print(ans) for j in l: print(*j,sep='') ```
1394_A. Boboniu Chats with Du
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu with fun factor a_i. But after that, he may be muzzled depending on Boboniu's mood. * Otherwise, Du won't do anything. Boboniu's mood is a constant m. On the i-th day: * If Du can speak and a_i>m, then Boboniu will be angry and muzzle him for d days, which means that Du won't be able to speak on the i+1, i+2, ⋅⋅⋅, min(i+d,n)-th days. * Otherwise, Boboniu won't do anything. The total fun factor is the sum of the fun factors on the days when Du can speak. Du asked you to find the maximum total fun factor among all possible permutations of a. Input The first line contains three integers n, d and m (1≤ d≤ n≤ 10^5,0≤ m≤ 10^9). The next line contains n integers a_1, a_2, …,a_n (0≤ a_i≤ 10^9). Output Print one integer: the maximum total fun factor among all permutations of a. Examples Input 5 2 11 8 10 15 23 5 Output 48 Input 20 2 16 20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7 Output 195 Note In the first example, you can set a'=[15, 5, 8, 10, 23]. Then Du's chatting record will be: 1. Make fun of Boboniu with fun factor 15. 2. Be muzzled. 3. Be muzzled. 4. Make fun of Boboniu with fun factor 10. 5. Make fun of Boboniu with fun factor 23. Thus the total fun factor is 48.
```python #! /usr/bin/python3 n, d, m = [int(inp) for inp in input().split()] aArr = sorted([int(inp) for inp in input().split()], reverse = True) i = sum([j > m for j in aArr]) aU = aArr[:i] aL = aArr[i:] aUS = aU for i in range(1, len(aU)): aUS[i] += aUS[i - 1] aUS = [0] + aUS aLS = aL for i in range(1, len(aL)): aLS[i] += aLS[i - 1] aLS = [0] + aLS fromU = min(1 + (n - 1)//(d + 1), len(aU)) maxFun = aUS[0] + aLS[-1] for j in range(1, fromU + 1): newFun = aUS[j] + aLS[min(max(0, n - 1 - (j - 1)*(d + 1)), len(aL))] if newFun > maxFun: maxFun = newFun print(maxFun) ```
1436_E. Complicated Computations
In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers. An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself. Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays! Input The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — the elements of the array. Output Print a single integer — the MEX of MEXes of all subarrays. Examples Input 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6
```python class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.range = [(-1,n)] * 2 * self.num # 配列の値を葉にセット for i in range(n): self.tree[self.num + i] = init_val[i] self.range[self.num + i] = (i,i) # 構築していく for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) self.range[i] = (self.range[2 * i][0],self.range[2 * i + 1][1]) def update(self, k, x): k += self.num self.tree[k] = x while k > 1: self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1]) k >>= 1 def query(self, l, r): res = self.ide_ele l += self.num r += self.num while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: res = self.segfunc(res, self.tree[r - 1]) l >>= 1 r >>= 1 return res def bisect_l(self,l,r,x): l += self.num r += self.num Lmin = -1 Rmin = -1 while l<r: if l & 1: if self.tree[l] <= x and Lmin==-1: Lmin = l l += 1 if r & 1: if self.tree[r-1] <=x: Rmin = r-1 l >>= 1 r >>= 1 if Lmin != -1: pos = Lmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num elif Rmin != -1: pos = Rmin while pos<self.num: if self.tree[2 * pos] <=x: pos = 2 * pos else: pos = 2 * pos +1 return pos-self.num else: return -1 n = int(input()) p = list(map(int,input().split())) pos = [[] for i in range(n+2)] for i in range(n): pos[p[i]].append(i) query = [[] for i in range(n)] for i in range(1,n+2): for j in range(len(pos[i])-1): L = pos[i][j] + 1 R = pos[i][j+1] - 1 if L<=R: query[R].append((L,i)) if pos[i]: if pos[i][0]!=0: query[pos[i][0]-1].append((0,i)) if pos[i][-1]!=n-1: query[n-1].append((pos[i][-1]+1,i)) else: query[n-1].append((0,i)) #print(query) flag = [False for i in range(n+3)] init = [-1]*(n+2) init[0] = n lastappeared = SegmentTree(init,min,-1) for i in range(n): lastappeared.update(p[i],i) for l,val in query[i]: check = lastappeared.bisect_l(0,n+2,l-1) #print(l,i,val,check) #pp = [lastappeared.tree[j+lastappeared.num] for j in range(n)] if check>=val or check==-1: flag[val] = True for i in range(1,n+3): if not flag[i]: print(i) break ```
1461_C. Random Events
Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). <image> Ron's permutation is subjected to m experiments of the following type: (r_i, p_i). This means that elements in range [1, r_i] (in other words, the prefix of length r_i) have to be sorted in ascending order with the probability of p_i. All experiments are performed in the same order in which they are specified in the input data. As an example, let's take a look at a permutation [4, 2, 1, 5, 3] and an experiment (3, 0.6). After such an experiment with the probability of 60\% the permutation will assume the form [1, 2, 4, 5, 3] and with a 40\% probability it will remain unchanged. You have to determine the probability of the permutation becoming completely sorted in ascending order after m experiments. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of the permutation and the number of experiments, respectively. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n) — contents of the permutation. The following m lines of each test case each contain an integer r_i and a real number p_i (1 ≤ r_i ≤ n, 0 ≤ p_i ≤ 1) — the length of the prefix and the probability of it being sorted. All probabilities are given with at most 6 decimal places. It is guaranteed that the sum of n and the sum of m does not exceed 10^5 (∑ n, ∑ m ≤ 10^5). Output For each test case, print a single number — the probability that after all experiments the permutation becomes sorted in ascending order. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}. Example Input 4 4 3 4 3 2 1 1 0.3 3 1 4 0.6 5 3 4 2 1 3 5 3 0.8 4 0.6 5 0.3 6 5 1 3 2 4 5 6 4 0.9 5 0.3 2 0.4 6 0.7 3 0.5 4 2 1 2 3 4 2 0.5 4 0.1 Output 0.600000 0.720000 0.989500 1.000000 Note Explanation of the first test case: It can be demonstrated that whether the final permutation is sorted or not depends solely on sorting being performed in the (4, 0.6) experiment.
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n,m = map(int,input().split()) a = list(map(int,input().split())) j = n-1 while j != -1 and a[j] == j+1: j -= 1 if j == -1: for _ in range(m): x = input() print(1) continue ans = 0 fac = 1 for _ in range(m): r,p = map(float,input().split()) r = int(r) if r >= j+1: ans += fac*p fac *= (1-p) print(ans) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main() ```
1486_D. Max Median
You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2, median([2, 1, 2, 1]) = 1. Subarray a[l..r] is a contiguous part of the array a, i. e. the array a_l,a_{l+1},…,a_r for some 1 ≤ l ≤ r ≤ n, its length is r - l + 1. Input The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5). The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Output Output one integer m — the maximum median you can get. Examples Input 5 3 1 2 3 2 1 Output 2 Input 4 2 1 2 3 4 Output 3 Note In the first example all the possible subarrays are [1..3], [1..4], [1..5], [2..4], [2..5] and [3..5] and the median for all of them is 2, so the maximum possible median is 2 too. In the second example median([3..4]) = 3.
```python import collections def solveTestCase(): n, k = [int(i) for i in input().split()] a = [int(i) for i in input().split()] r = n + 1 l = 1 while r - l > 1: m = (r+l)//2 b = [1 if i >= m else -1 for i in a] for i in range(1, len(b)): b[i] += b[i - 1] ans = False if b[k-1] > 0: ans = True mm = 0 for i in range(k, n): mm = min(mm, b[i-k]) if b[i] - mm > 0: ans = True break if ans: l = m else: r = m print(l) if __name__ == "__main__": t = 1 while t > 0: t -= 1 solveTestCase() ```
1510_D. Digits
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her. Input The first line contains the integers n and d (1≤ n≤ 10^5, 0≤ d≤ 9). The second line contains n integers a_i (1≤ a_i≤ 1000). Output On the first line, print the number of chosen cards k (1≤ k≤ n). On the next line, print the numbers written on the chosen cards in any order. If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1. Examples Input 6 4 4 11 8 2 1 13 Output 5 1 2 4 11 13 Input 3 1 2 4 6 Output -1 Input 5 7 1 3 1 5 3 Output -1 Input 6 3 8 9 4 17 11 5 Output 3 9 11 17 Input 5 6 2 2 2 2 2 Output 4 2 2 2 2 Note In the first example, 1 × 2 × 4 × 11 × 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144. In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1. In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7. In the fourth example, 9 × 11 × 17 = 1683, which ends with the digit 3. In the fifth example, 2 × 2 × 2 × 2 = 16, which ends with the digit 6.
```python import math;n, d = map(int, input().split());a = [int(_) for _ in input().split()];dp = [[-1e10] * 10 for _ in range(n + 1)] come = [[(0, 0, 0) for i in range(10)] for j in range(n + 1)];dp[0][1] = 0 for i in range(n): for j in range(10): val = dp[i][j] + math.log(a[i]) if dp[i + 1][(j * a[i]) % 10] <= val: dp[i + 1][(j * a[i]) % 10] = val; come[i + 1][(j * a[i]) % 10] = (i, j, 1) val = dp[i][j] if dp[i + 1][j] <= val: dp[i + 1][j] = val; come[i + 1][j] = (i, j, 0) now = n;prod = 1;dig = d;soln = [] while now > 0: if come[now][dig][2] == 1: soln.append(a[now - 1]) now, dig = come[now][dig][:2] for i in soln: prod = (prod * i) % 10 if prod == d and len(soln) > 0: print(len(soln)); print(' '.join(map(str, soln))) else: print(-1) ```
1536_F. Omkar and Akmar
Omkar and Akmar are playing a game on a circular board with n (2 ≤ n ≤ 10^6) cells. The cells are numbered from 1 to n so that for each i (1 ≤ i ≤ n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty. Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves. Output the number of possible distinct games where both players play optimally modulo 10^9+7. Note that we only consider games where some player has lost and there are no more valid moves. Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different. A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move. Input The only line will contain an integer n (2 ≤ n ≤ 10^6) — the number of cells on the board. Output Output a single integer — the number of possible distinct games where both players play optimally modulo 10^9+7. Examples Input 2 Output 4 Input 69420 Output 629909355 Input 42069 Output 675837193 Note For the first sample case, the first player has 4 possible moves. No matter what the first player plays, the second player only has 1 possible move, so there are 4 possible games.
```python import sys input = sys.stdin.readline n = int(input()) mod = 10 ** 9 + 7 F = [0] * (n + 1) F[0] = 1 for i in range(1, n + 1): F[i] = i * F[i - 1] % mod iF = [0] * (n + 1) iF[-1] = pow(F[-1], mod - 2, mod) for i in range(n - 1, -1, -1): iF[i] = iF[i + 1] * (i + 1) % mod def C(n, k): if k > n: return 0 return F[n] * iF[n - k] * iF[k] % mod ans = 0 for x in range((n + 1) // 2, n + 1): if x % 2: continue if x < n: cur = (C(x, n - x) + C(x - 1, n - x - 1)) % mod else: cur = 1 cur = (cur * 2 * F[x]) % mod ans = (ans + cur) % mod print(ans) ```
185_A. Plant
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process. <image> Help the dwarfs find out how many triangle plants that point "upwards" will be in n years. Input The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7). Examples Input 1 Output 3 Input 2 Output 10 Note The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.
```python n=int(input()) e=10**9+7 print(1if n==0else(pow(2,n-1,e)+pow(2,n*2-1,e))%e) # Made By Mostafa_Khaled ```
231_B. Magic, Wizardry and Wonders
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones. This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left. Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1. Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them. It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d. Help Vasya to recover the initial set of cards with numbers. Input The single line contains three space-separated integers: n (2 ≤ n ≤ 100) — the initial number of cards on the table, d (|d| ≤ 104) — the number on the card that was left on the table after all the magical actions, and l (1 ≤ l ≤ 100) — the limits for the initial integers. Output If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them. Examples Input 3 3 2 Output 2 1 2 Input 5 -4 3 Output -1 Input 5 -4 4 Output 2 4 1 4 1
```python n, d, L = map(int, input().split()) sp = [] for _ in range(n - 1): if d <= 0: sp.append(1) d = 1 - d else: sp.append(L) d = L - d if 1 <= d <= L: sp.append(d) print(*sp) else: print(-1) ```
257_A. Sockets
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets. Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filter to any other supply-line filter. The device (or the supply-line filter) is considered plugged to electricity if it is either plugged to one of k electrical sockets, or if it is plugged to some supply-line filter that is in turn plugged to electricity. What minimum number of supply-line filters from the given set will Vasya need to plug all the devices he has to electricity? Note that all devices and supply-line filters take one socket for plugging and that he can use one socket to plug either one device or one supply-line filter. Input The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 50) — the number of supply-line filters, the number of devices and the number of sockets that he can plug to directly, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 50) — number ai stands for the number of sockets on the i-th supply-line filter. Output Print a single number — the minimum number of supply-line filters that is needed to plug all the devices to electricity. If it is impossible to plug all the devices even using all the supply-line filters, print -1. Examples Input 3 5 3 3 1 2 Output 1 Input 4 7 2 3 3 2 4 Output 2 Input 5 5 1 1 3 1 2 1 Output -1 Note In the first test case he can plug the first supply-line filter directly to electricity. After he plug it, he get 5 (3 on the supply-line filter and 2 remaining sockets for direct plugging) available sockets to plug. Thus, one filter is enough to plug 5 devices. One of the optimal ways in the second test sample is to plug the second supply-line filter directly and plug the fourth supply-line filter to one of the sockets in the second supply-line filter. Thus, he gets exactly 7 sockets, available to plug: one to plug to the electricity directly, 2 on the second supply-line filter, 4 on the fourth supply-line filter. There's no way he can plug 7 devices if he use one supply-line filter.
```python n,m,k=map(int,input().split(" ")) li=list(map(int,input().split(" ",n)[:n])) li.sort(reverse=True) fl=0 a,s=0,0 if m<=k: print(0) else: while fl==0 and a<n: s+=li[a] a+=1 if a!=1: s-=1 if s+k-1>=m and a!=0: fl=1 break if fl!=1: print(-1) else: print(a) ```
280_A. Rectangle Puzzle
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α. <image> Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture. Input The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees. Output In a single line print a real number — the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6. Examples Input 1 1 45 Output 0.828427125 Input 6 4 30 Output 19.668384925 Note The second sample has been drawn on the picture above.
```python from math import radians, cos, sin, atan2 def rotate(point, alpha): x = point[0] y = point[1] return (x * cos(alpha) - y * sin(alpha), x * sin(alpha) + y * cos(alpha)) def crs(a, b): return a[0] * b[1] - a[1] * b[0] def m(end, start): return (end[0] - start[0], end[1] - start[1]) def area(poly): ret = 0 n = len(poly) for i in range(n): j = (i + 1) % n ret += crs(poly[i], poly[j]) return abs(ret) / 2.0 def intersect(a, b, c, d): r = crs(m(c, d), m(a, d)) * crs(m(c, d), m(b, d)) <= 0 r &= crs(m(b, a), m(c, a)) * crs(m(b, a), m(d, a)) <= 0 if not r: return None x1 = a[0] y1 = a[1] x2 = c[0] y2 = c[1] dx1 = b[0] - a[0] dx2 = d[0] - c[0] dy1 = b[1] - a[1] dy2 = d[1] - c[1] if dx2 * dy1 == dx1 * dy2: return None t = ((x1 - x2) * dy2 + (y2 - y1) * dx2) / (dx2 * dy1 - dx1 * dy2) return (x1 + t * dx1, y1 + t * dy1) w, h, alpha = map(int, input().split()) if alpha == 0 or alpha == 180: print(w * h) else: alpha = radians(alpha) pnt = [] pnt.append((w / 2, h / 2)) pnt.append((-w / 2, h / 2)) pnt.append((-w / 2, -h / 2)) pnt.append((w / 2, -h / 2)) pnt2 = [] for p in pnt: pnt2.append(rotate(p, alpha)) pnt2.append(pnt2[0]) pnt.append(pnt[0]) points_total = [] for st in range(4): for en in range(4): t = intersect(pnt[st], pnt[st + 1], pnt2[en], pnt2[en + 1]) if t != None: points_total.append(t) points_total = sorted(points_total, key=lambda x: atan2(x[1], x[0])) print(area(points_total)) ```
32_A. Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment. Ways (1, 2) and (2, 1) should be regarded as different. Input The first line contains two integers n and d (1 ≤ n ≤ 1000, 1 ≤ d ≤ 109) — amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers — heights of all the soldiers in Bob's detachment. These numbers don't exceed 109. Output Output one number — amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d. Examples Input 5 10 10 20 50 60 65 Output 6 Input 5 1 55 30 29 31 55 Output 6
```python n, d = [int(i) for i in input().split()] S = sorted([int(i) for i in input().split()]) k = 0 for i in range(n): for j in range(i+1, n): if(S[j]-S[i]<=d): k += 1 else: break print(k*2) ```
397_B. On Corruption and Numbers
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate. The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — ni berubleys. He cannot pay more than ni, because then the difference between the paid amount and ni can be regarded as a bribe! Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than ri. The rector also does not carry coins of denomination less than li in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where li ≤ x ≤ ri (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater. Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type. In other words, you are given t requests, each of them contains numbers ni, li, ri. For each query you need to answer, whether it is possible to gather the sum of exactly ni berubleys using only coins with an integer denomination from li to ri berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times. Input The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: ni, li, ri (1 ≤ ni, li, ri ≤ 109; li ≤ ri). Output For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise. Examples Input 2 5 2 3 6 4 5 Output Yes No Note You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
```python t = int(input()) for _ in range(t): n, l, r = map(int, input().split()) print("No" if n // l * r < n else "Yes") ```
41_C. Email address
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([email protected]). It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots. You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result. Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at. Input The first line contains the email address description. It is guaranteed that that is a proper email address with all the dots replaced by dot an the at signs replaced by at. The line is not empty and its length does not exceed 100 symbols. Output Print the shortest email address, from which the given line could be made by the described above replacements. If there are several solutions to that problem, print the lexicographically minimal one (the lexicographical comparison of the lines are implemented with an operator < in modern programming languages). In the ASCII table the symbols go in this order: . @ ab...z Examples Input vasyaatgmaildotcom Output [email protected] Input dotdotdotatdotdotat Output [email protected] Input aatt Output a@t
```python a = input() b = '' if a[0] + a[1] + a[2] == 'dot': b += 'dot' i = 3 elif a[0] + a[1] == 'at': b += 'at' i = 2 else: i = 0 at = 0 while i < len(a) - 3: if a[i] == 'd' and a[i + 1] == 'o' and a[i + 2] == 't': b += '.' i += 3 elif a[i] == 'a' and a[i + 1] == 't' and at == 0: b += '@' at = 1 i += 2 else: b += a[i] i += 1 if a[i] + a[-1] == 'at' and at == 0: b += '@' b += a[i + 2] else: for j in range(i, len(a)): b += a[j] print(b) ```
446_A. DZY Loves Sequences
DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing. You only need to output the length of the subsegment you find. Input The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). Output In a single line print the answer to the problem — the maximum length of the required subsegment. Examples Input 6 7 2 3 1 5 6 Output 5 Note You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.
```python def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().split()) def msi(): return map(str,input().split()) def li(): return list(mi()) n=ii() a=li() pre,suf = [1]*n,[1]*n for i in range(1,n): if a[i]>a[i-1]: pre[i]+=pre[i-1] for i in range(n-2,-1,-1): if a[i]<a[i+1]: suf[i]+=suf[i+1] ans=max(pre) if ans<n: ans+=1 for i in range(1,n-1): if a[i+1]>a[i-1]+1: ans=max(ans,pre[i-1]+suf[i+1]+1) print(ans) ```
468_B. Two Sets
Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible. Input The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109). Output If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes). Examples Input 4 5 9 2 3 4 5 Output YES 0 0 1 1 Input 3 3 4 1 2 4 Output NO Note It's OK if all the numbers are in the same set, and the other one is empty.
```python import sys import queue sys.setrecursionlimit(100000) # global constant INF = int(1e7+1) MAX = 100005 # For testing #sys.stdin = open("INP.txt", 'r') #sys.stdout = open("OUT.txt", 'w') # global variables parents = [] ranks = [] size = [] n = 0 # classes class Pair: def __init__(self, a, b): self.first = a self.second = b # functions def init(): global parents, ranks, size parents = [i for i in range(n+2)] ranks = [0 for i in range(n+2)] size = [1 for i in range(n+2)] def findSet(u): if(parents[u] != u): parents[u] = findSet(parents[u]) return parents[u] def unionSet(u, v): up = findSet(u) vp = findSet(v) if up == vp: return if ranks[up] < ranks[vp]: parents[up] = vp elif ranks[vp] < ranks[up]: parents[vp] = up else: ranks[vp] += 1 parents[up] = vp # main function def main(): global n n, a, b = map(int, input().split()) init() M = {} l = list(map(int, input().split())) Max = -1 l.insert(0, -1) l.append(-1) for i in range(1, n+1): M[l[i]] = i parents[i] = i Max = max(Max, l[i]) if Max >= a and Max >= b: print("NO") return for i in range(1, n+1): # print(l[i], a-l[i], b-l[i], (a-l[i] in M), (b-l[i]) in M) if (a-l[i]) in M: unionSet(M[a - l[i]], i) else: unionSet(i, n+1) if(b-l[i]) in M: unionSet(M[b-l[i]], i) else: unionSet(i, 0) A = findSet(0) B = findSet(n+1) """ for parent in parents: print(parent, end = ' ') print() print(A, B) """ if(A == B): print("NO") return print("YES") for i in range(1, n+1): # print(l[i], findSet(l[i])) if (findSet(i) == A): print("%d" % (0), end=' ') else: print("%d" % (1), end=' ') main() ```
490_B. Queue
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working. Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1). After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task. Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue. Input The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue. Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist. The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order. Output Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one. Examples Input 4 92 31 0 7 31 0 7 141 Output 92 7 31 141 Note The picture illustrates the queue for the first sample. <image>
```python import math from collections import deque class Empty(Exception): pass class _DoublyLinkedBase: """A base class providing a doubly linked list representation.""" #-------------------------- nested _Node class -------------------------- # nested _Node class class _Node: """Lightweight, nonpublic class for storing a doubly linked node.""" __slots__ = '_element', '_prev', '_next' # streamline memory def __init__(self, element, prev, next): # initialize node's fields self._element = element # user's element self._prev = prev # previous node reference self._next = next # next node reference #-------------------------- list constructor -------------------------- def __init__(self): """Create an empty list.""" self._header = self._Node(None, None, None) self._trailer = self._Node(None, None, None) self._header._next = self._trailer # trailer is after header self._trailer._prev = self._header # header is before trailer self._size = 0 # number of elements #-------------------------- public accessors -------------------------- def __len__(self): """Return the number of elements in the list.""" return self._size def is_empty(self): """Return True if list is empty.""" return self._size == 0 #-------------------------- nonpublic utilities -------------------------- def _insert_between(self, e, predecessor, successor): """Add element e between two existing nodes and return new node.""" newest = self._Node(e, predecessor, successor) # linked to neighbors predecessor._next = newest successor._prev = newest self._size += 1 return newest def _delete_node(self, node): """Delete nonsentinel node from the list and return its element.""" predecessor = node._prev successor = node._next predecessor._next = successor successor._prev = predecessor self._size -= 1 element = node._element # record deleted element node._prev = node._next = node._element = None # deprecate node return element # return deleted element class LinkedDeque(_DoublyLinkedBase): # note the use of inheritance """Double-ended queue implementation based on a doubly linked list.""" def first(self): """Return (but do not remove) the element at the front of the deque. Raise Empty exception if the deque is empty. """ if self.is_empty(): raise Empty("Deque is empty") return self._header._next._element # real item just after header def last(self): """Return (but do not remove) the element at the back of the deque. Raise Empty exception if the deque is empty. """ if self.is_empty(): raise Empty("Deque is empty") return self._trailer._prev._element # real item just before trailer def insert_first(self, e): """Add an element to the front of the deque.""" self._insert_between(e, self._header, self._header._next) # after header def insert_last(self, e): """Add an element to the back of the deque.""" self._insert_between(e, self._trailer._prev, self._trailer) # before trailer def delete_first(self): """Remove and return the element from the front of the deque. Raise Empty exception if the deque is empty. """ if self.is_empty(): raise Empty("Deque is empty") return self._delete_node(self._header._next) # use inherited method def delete_last(self): """Remove and return the element from the back of the deque. Raise Empty exception if the deque is empty. """ if self.is_empty(): raise Empty("Deque is empty") return self._delete_node(self._trailer._prev) # use inherited method class PositionalList(_DoublyLinkedBase): """A sequential container of elements allowing positional access.""" #-------------------------- nested Position class -------------------------- class Position: """An abstraction representing the location of a single element. Note that two position instaces may represent the same inherent location in the list. Therefore, users should always rely on syntax 'p == q' rather than 'p is q' when testing equivalence of positions. """ def __init__(self, container, node): """Constructor should not be invoked by user.""" self._container = container self._node = node def element(self): """Return the element stored at this Position.""" return self._node._element def __eq__(self, other): """Return True if other is a Position representing the same location.""" return type(other) is type(self) and other._node is self._node def __ne__(self, other): """Return True if other does not represent the same location.""" return not (self == other) # opposite of __eq__ #------------------------------- utility methods ------------------------------- def _validate(self, p): """Return position's node, or raise appropriate error if invalid.""" if not isinstance(p, self.Position): raise TypeError('p must be proper Position type') if p._container is not self: raise ValueError('p does not belong to this container') if p._node._next is None: # convention for deprecated nodes raise ValueError('p is no longer valid') return p._node def _make_position(self, node): """Return Position instance for given node (or None if sentinel).""" if node is self._header or node is self._trailer: return None # boundary violation else: return self.Position(self, node) # legitimate position #------------------------------- accessors ------------------------------- def first(self): """Return the first Position in the list (or None if list is empty).""" return self._make_position(self._header._next) def last(self): """Return the last Position in the list (or None if list is empty).""" return self._make_position(self._trailer._prev) def before(self, p): """Return the Position just before Position p (or None if p is first).""" node = self._validate(p) return self._make_position(node._prev) def after(self, p): """Return the Position just after Position p (or None if p is last).""" node = self._validate(p) return self._make_position(node._next) def __iter__(self): """Generate a forward iteration of the elements of the list.""" cursor = self.first() while cursor is not None: yield cursor.element() cursor = self.after(cursor) #------------------------------- mutators ------------------------------- # override inherited version to return Position, rather than Node def _insert_between(self, e, predecessor, successor): """Add element between existing nodes and return new Position.""" node = super()._insert_between(e, predecessor, successor) return self._make_position(node) def add_first(self, e): """Insert element e at the front of the list and return new Position.""" return self._insert_between(e, self._header, self._header._next) def add_last(self, e): """Insert element e at the back of the list and return new Position.""" return self._insert_between(e, self._trailer._prev, self._trailer) def add_before(self, p, e): """Insert element e into list before Position p and return new Position.""" original = self._validate(p) return self._insert_between(e, original._prev, original) def add_after(self, p, e): """Insert element e into list after Position p and return new Position.""" original = self._validate(p) return self._insert_between(e, original, original._next) def delete(self, p): """Remove and return the element at Position p.""" original = self._validate(p) return self._delete_node(original) # inherited method returns element def replace(self, p, e): """Replace the element at Position p with e. Return the element formerly at Position p. """ original = self._validate(p) old_value = original._element # temporarily store old element original._element = e # replace with new element return old_value # return the old element value L1=LinkedDeque() L2=LinkedDeque() dic={} dic2={} n=int(input()) for i in range(n): a,b=(int(i) for i in input().split()) dic[a]=b dic2[b]=a forw=0 while (forw in dic) : L1.insert_last(dic[forw]) t=dic[forw] dic.pop(forw) forw=t if L1.last()==0 : L1.delete_last() if n%2==0 : backw=0 while (backw in dic2) : L2.insert_first(dic2[backw]) t=dic2[backw] dic2.pop(backw) backw=t else: tk,tv=0,0 for (k, v) in dic.items(): tk=k tv=v forw=tk while (forw in dic) : L2.insert_last(dic[forw]) t=dic[forw] dic.pop(forw) forw=t backw=tv while (backw in dic2) : L2.insert_first(dic2[backw]) t=dic2[backw] dic2.pop(backw) backw=t outList=[] while L1.is_empty()==False : outList.append(str(L2.first())) outList.append(str(L1.first())) L1.delete_first() L2.delete_first() if L2.is_empty()==False : outList.append(str(L2.first())) pass print(" ".join(outList)) ```
514_B. Han Solo and Lazer Gun
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0). Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers. The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. Input The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000, - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point. Output Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers. Examples Input 4 0 0 1 1 2 2 2 0 -1 -1 Output 2 Input 2 1 2 1 1 1 0 Output 1 Note Explanation to the first and second samples from the statement, respectively: <image>
```python n, x0, y0 = map(int, input().split()) slopes = {} # key: (num, den), val: count for i in range(n): x, y = map(int, input().split()) num = y - y0 den = x - x0 # print(num, den) if den == 0 and "inf" in slopes: slopes["inf"] += 1 elif den == 0: slopes["inf"] = 1 else: found = False for s in slopes: # print(isinstance(s, tuple)) if isinstance(s, tuple) and num * s[1] == den * s[0]: slopes[s] += 1 found = True if found == False: slopes[(num, den)] = 1 print(slopes.__len__()) ```
540_C. Ice Cave
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice. The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked. Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c). You are staying in the cell (r1, c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2, c2) since the exit to the next level is there. Can you do this? Input The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description. Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice). The next line contains two integers, r1 and c1 (1 ≤ r1 ≤ n, 1 ≤ c1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1, c1), that is, the ice on the starting cell is initially cracked. The next line contains two integers r2 and c2 (1 ≤ r2 ≤ n, 1 ≤ c2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one. Output If you can reach the destination, print 'YES', otherwise print 'NO'. Examples Input 4 6 X...XX ...XX. .X..X. ...... 1 6 2 2 Output YES Input 5 4 .X.. ...X X.X. .... .XX. 5 3 1 1 Output NO Input 4 7 ..X.XX. .XX..X. X...X.. X...... 2 2 1 6 Output YES Note In the first sample test one possible path is: <image> After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.
```python import queue MAX = 500 dr = [0,0,1,-1] dc = [1,-1,0,0] def isValid(r, c): return r in range(m) and c in range(n) def BFS(sr, sc, fr, fc): q = [0] * (MAX * MAX) left = right = 0 q[0] = (sr, sc) while left <= right: ur, uc = q[left] left += 1 for i in range(4): vr = ur + dr[i] vc = uc + dc[i] if isValid(vr, vc): if maze[vr][vc] == '.': maze[vr][vc] = 'X' right += 1 q[right] = (vr, vc) else: if(vr == fr) and (vc==fc): return True return False if __name__ == '__main__': maze = [] m, n = map(int, input().split()) for i in range(m): temp = list(input()) maze.append(temp) start, start2 = map(int, input().split()) # s1 = Cell(start-1,start2-1) end1, end2 = map(int, input().split()) # e = Cell(end1-1,end2-1) if(BFS(start - 1, start2 - 1, end1 - 1, end2 - 1)): print('YES') else: print('NO') ```
58_B. Coins
In Berland a money reform is being prepared. New coins are being introduced. After long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. Also the following restriction has been introduced for comfort: the denomination of each coin should be divisible by the denomination of any cheaper coin. It is known that among all the possible variants the variant with the largest number of new coins will be chosen. Find this variant. Print in the order of decreasing of the coins' denominations. Input The first and only line contains an integer n (1 ≤ n ≤ 106) which represents the denomination of the most expensive coin. Output Print the denominations of all the coins in the order of decreasing. The number of coins must be the largest possible (with the given denomination n of the most expensive coin). Also, the denomination of every coin must be divisible by the denomination of any cheaper coin. Naturally, the denominations of all the coins should be different. If there are several solutins to that problem, print any of them. Examples Input 10 Output 10 5 1 Input 4 Output 4 2 1 Input 3 Output 3 1
```python def O(x): l=[] if x==1: return 1 for i in range(1,x//2+1): if x%i==0: l.append(i) print(x) return O(l[len(l)-1]) x=int(input()) O(x) print(1) ```
631_A. Interview
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ..., xr, where xi is the i-th element of the array x. You are given two arrays a and b of length n. You need to determine the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. <image> Input The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the length of the arrays. The second line contains n integers ai (0 ≤ ai ≤ 109). The third line contains n integers bi (0 ≤ bi ≤ 109). Output Print a single integer — the maximum value of sum f(a, l, r) + f(b, l, r) among all possible 1 ≤ l ≤ r ≤ n. Examples Input 5 1 2 4 3 2 2 3 3 12 1 Output 22 Input 10 13 2 7 11 8 4 9 8 5 1 5 7 18 9 2 3 0 11 8 6 Output 46 Note Bitwise OR of two non-negative integers a and b is the number c = a OR b, such that each of its digits in binary notation is 1 if and only if at least one of a or b have 1 in the corresponding position in binary notation. In the first sample, one of the optimal answers is l = 2 and r = 4, because f(a, 2, 4) + f(b, 2, 4) = (2 OR 4 OR 3) + (3 OR 3 OR 12) = 7 + 15 = 22. Other ways to get maximum value is to choose l = 1 and r = 4, l = 1 and r = 5, l = 2 and r = 4, l = 2 and r = 5, l = 3 and r = 4, or l = 3 and r = 5. In the second sample, the maximum value is obtained for l = 1 and r = 9.
```python read = lambda: map(int, input().split()) n = int(input()) a = list(read()) b = list(read()) f1 = f2 = 0 for i in a: f1 |= i for i in b: f2 |= i print(f1 + f2) ```
706_B. Interesting drink
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola". Input The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day. Output Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day. Example Input 5 3 10 8 6 11 4 1 10 3 11 Output 0 4 1 5 Note On the first day, Vasiliy won't be able to buy a drink in any of the shops. On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4. On the third day, Vasiliy can buy a drink only in the shop number 1. Finally, on the last day Vasiliy can buy a drink in any shop.
```python def binary(t,s): fir=0 last=len(t)-1 mid=0 while(fir<=last): mid=(fir+last)//2 if t[mid]>s: last=mid-1 else: fir=mid+1 return last+1 n=int(input()) t=list(map(int,input().split())) m=int(input()) p=0 t.sort() for i in range(m): s=int(input()) print(binary(t,s)) ```
729_D. Sea Battle
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss"). Galya has already made k shots, all of them were misses. Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. It is guaranteed that there is at least one valid ships placement. Input The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string. Output In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them. Examples Input 5 1 2 1 00100 Output 2 4 2 Input 13 3 2 3 1000000010001 Output 2 7 11 Note There is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.
```python n,a,b,k = map(int, input().split()) open = 0 must = 0 must_arr = [] for i,c in enumerate(input()): if c == '1': open = 0 else: open += 1 if open == b: open = 0 must += 1 if must >= a: must_arr.append(i+1) must -= a - 1 print(must) print(*must_arr) ```
749_E. Inversions After Shuffle
You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable. 2. Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable. 3. This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above. Input The first line contains a single integer n (1 ≤ n ≤ 100 000) — the length of the permutation. The second line contains n distinct integers from 1 to n — elements of the permutation. Output Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>. Example Input 3 2 3 1 Output 1.916666666666666666666666666667
```python # Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates a node in Binary Index Tree (BITree) # at given index in BITree. The given value # 'val' is added to BITree[i] and all of its # ancestors in tree. def updateBIT(BITree, n, index, val): # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent # in update View index += index & (-index) # Returns count of inversions of size three def getInvCount(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], 1) return invcount def getInvCountAdv(arr, n): invcount = 0 # Initialize result # Find maximum element in arrays maxElement = max(arr) # Create a BIT with size equal to # maxElement+1 (Extra one is used # so that elements can be directly # be used as index) BIT = [0] * (maxElement + 1) for i in range(1, maxElement + 1): BIT[i] = 0 for i in range(n - 1, -1, -1): invcount += (i + 1) * getSum(BIT, arr[i] - 1) updateBIT(BIT, maxElement, arr[i], n-i) return invcount # Driver code n = int(input()) a = list(map(int,input().split())) InvCount = getInvCount(a, n) InvCountAdv = getInvCountAdv(a,n) thirdSum = 0 for i in range(1,n+1): thirdSum += i * (i - 1) * (n- i + 1) / 2 print(InvCount - InvCountAdv / (n * (n + 1)) * 2 + thirdSum / (n * (n + 1))) # Some part of this code is contributed by # Shubham Singh(SHUBHAMSINGH10) ```
797_D. Broken BST
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: 1. Set pointer to the root of a tree. 2. Return success if the value in the current vertex is equal to the number you are looking for 3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for 4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for 5. Return fail if you try to go to the vertex that doesn't exist Here is the pseudo-code of the described algorithm: bool find(TreeNode t, int x) { if (t == null) return false; if (t.value == x) return true; if (x < t.value) return find(t.left, x); else return find(t.right, x); } find(root, x); The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree. Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree. If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately. Input First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree. Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values. Output Print number of times when search algorithm will fail. Examples Input 3 15 -1 -1 10 1 3 5 -1 -1 Output 2 Input 8 6 2 3 3 4 5 12 6 7 1 -1 8 4 -1 -1 5 -1 -1 14 -1 -1 2 -1 -1 Output 1 Note In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
```python from collections import deque nodes = [] parents = [] values = [] broken = [] upperBound = [] lowerBound = [] n = int(input()) for _ in range(n): v, l, r = map(int, input().split()) nodes.append((v, l - 1, r - 1)) parents.append(-1) values.append(v) broken.append(False) upperBound.append(10 ** 9) lowerBound.append(-10 ** 9) for i, (v, l, r) in enumerate(nodes): if l > -1: parents[l] = i if r > -1: parents[r] = i root = -1 for i in range(n): if parents[i] == -1: root = i proc = deque([root]) while len(proc) > 0: node = proc.popleft() v, l, r = nodes[node] if l > -1: proc.append(l) upperBound[l] = min(upperBound[node], v) lowerBound[l] = lowerBound[node] if not (lowerBound[l] <= nodes[l][0] <= upperBound[l]): broken[l] = True if r > -1: proc.append(r) upperBound[r] = upperBound[node] lowerBound[r] = max(lowerBound[node], v) if not (lowerBound[r] <= nodes[r][0] <= upperBound[r]): broken[r] = True s = set([]) for v, b in zip(values, broken): if not b: s.add(v) ans = 0 for v in values: if v not in s: ans += 1 print(ans) ```
843_A. Sorting by Subsequences
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing.
```python n = int(input()) d = list(map(int, input().split())) temp = d[:] d.sort() from bisect import bisect_left A = [bisect_left(d,i) for i in temp] del d,temp f = [False]*len(A) result = [] for i in range(n): if not f[i]: L = [i+1] f[i] = True j = A[i] while j != i: L.append(j+1) f[j] = True j = A[j] result.append(L) print(len(result)) for L in result: print(len(L),' '.join(map(str,L))) ```
863_F. Almost Permutation
Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less than 1 and not greater than n. Also he remembers q facts about the array. There are two types of facts that Ivan remembers: * 1 li ri vi — for each x such that li ≤ x ≤ ri ax ≥ vi; * 2 li ri vi — for each x such that li ≤ x ≤ ri ax ≤ vi. Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the q facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the cost of array as follows: <image>, where cnt(i) is the number of occurences of i in the array. Help Ivan to determine minimum possible cost of the array that corresponds to the facts! Input The first line contains two integer numbers n and q (1 ≤ n ≤ 50, 0 ≤ q ≤ 100). Then q lines follow, each representing a fact about the array. i-th line contains the numbers ti, li, ri and vi for i-th fact (1 ≤ ti ≤ 2, 1 ≤ li ≤ ri ≤ n, 1 ≤ vi ≤ n, ti denotes the type of the fact). Output If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible cost of the array. Examples Input 3 0 Output 3 Input 3 1 1 1 3 2 Output 5 Input 3 2 1 1 3 2 2 1 3 2 Output 9 Input 3 2 1 1 3 2 2 1 3 1 Output -1
```python import sys def is_feasible(cnt,L,R): n = len(R) inter = [(L[i],R[i]) for i in range(n)] AUX = [] feasible = True for x in range(n): for p in inter: if p[0] == x: AUX.append(p[1]) while AUX and min(AUX) < x: AUX.remove(min(AUX)) for quantity in range(cnt[x]): if AUX: AUX.remove(min(AUX)) else: feasible = False return feasible n,q = map(int,sys.stdin.readline().split()) L = [0 for i in range(n)] R = [n-1 for i in range(n)] for restriction in range(q): t,l,r,v = map(int,sys.stdin.readline().split()) if t == 1: for k in range(l-1,r): L[k] = max(L[k],v-1) else: for k in range(l-1,r): R[k] = min(R[k],v-1) is_possible = all(map(lambda x,y : x <= y,L,R)) if not is_possible: print(-1) else: cnt = {x:L.count(x) for x in range(n)} had_pair = True while had_pair: had_pair = False for x in range(n-1,-1,-1): for y in range(n-1,-1,-1): if cnt[x] > cnt[y]+1: cnt[x] -= 1 cnt[y] += 1 has_pair = True if not is_feasible(cnt,L,R): cnt[x] += 1 cnt[y] -= 1 has_pair = False had_pair = had_pair or has_pair ans = sum([cnt[x]*cnt[x] for x in range(n)]) print(ans) ```
912_A. Tricky Alchemy
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, green — one yellow and one blue, and for a blue ball, three blue crystals are enough. Right now there are A yellow and B blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls. Input The first line features two integers A and B (0 ≤ A, B ≤ 109), denoting the number of yellow and blue crystals respectively at Grisha's disposal. The next line contains three integers x, y and z (0 ≤ x, y, z ≤ 109) — the respective amounts of yellow, green and blue balls to be obtained. Output Print a single integer — the minimum number of crystals that Grisha should acquire in addition. Examples Input 4 3 2 1 1 Output 2 Input 3 9 1 1 3 Output 1 Input 12345678 87654321 43043751 1000000000 53798715 Output 2147483648 Note In the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue.
```python y,b=input().split(' ') ay,ag,ab=input().split(' ') y=int(y) b=int(b) ay=int(ay) ag=int(ag) ab=int(ab) b=b-(ab*3) y=y-(ay*2) b=b-ag y=y-ag br=0 if(y<0): br=br-y if(b<0): br=br-b print(br) ```
934_A. A Compatible Pair
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1, a2, ..., an, and Banban's have brightness b1, b2, ..., bm respectively. Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns. Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible. You are asked to find the brightness of the chosen pair if both of them choose optimally. Input The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50). The second line contains n space-separated integers a1, a2, ..., an. The third line contains m space-separated integers b1, b2, ..., bm. All the integers range from - 109 to 109. Output Print a single integer — the brightness of the chosen pair. Examples Input 2 2 20 18 2 14 Output 252 Input 5 3 -1 0 1 2 3 -1 0 1 Output 2 Note In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself. In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.
```python n, m = [int(x) for x in input().split()] lstT = [int(x) for x in input().split()] lstB = [int(x) for x in input().split()] z=-9999999999999999999999999999 T=0 B=0 for i in range(n): for j in range(m): if z<lstT[i]*lstB[j]: T=i B=j z=lstT[i]*lstB[j] lol = -99999999999999999999 for i in range(n): for j in range(m): if T!=i: lol = max(lol, lstT[i]*lstB[j]) print(lol) ```
960_C. Subsequence Counting
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ d Pikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1. Input The only line of input consists of two space separated integers X and d (1 ≤ X, d ≤ 109). Output Output should consist of two lines. First line should contain a single integer n (1 ≤ n ≤ 10 000)— the number of integers in the final array. Second line should consist of n space separated integers — a1, a2, ... , an (1 ≤ ai < 1018). If there is no answer, print a single integer -1. If there are multiple answers, print any of them. Examples Input 10 5 Output 6 5 50 7 15 6 100 Input 4 2 Output 4 10 100 1000 10000 Note In the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid. Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid.
```python X, d = map(int, input().split()) x = X ans = list() ln = 0 last = 1 while x > 0: if last >= 10 ** 18: print(-1) exit() i = 0 while 2 ** (i + 1) - 1 <= x: i += 1 t = 2 ** i - 1 x -= t if ln + i > 10000: print(-1) exit() for _ in range(i): ans.append(last) ln += 1 last += d print(len(ans)) print(' '.join(map(str, ans))) ```
p02592 AtCoder Grand Contest 047 - Product Simulation
This is an output-only problem. You shouldn't read anything from the input. In short, your task is to simulate multiplication by using only comparison (x < y) and addition (x + y). There is no input in this problem, you just print a sequence of operations. Imagine that there is a big array a[0], a[1], ..., a[N-1] of length N. The first two values are initially two non-negative integers A and B (which are unknown to you), the other elements are zeros. Your goal is to get the product A \cdot B in a[2] at the end. You are allowed operations of two types, with the following format (where 0 \leq i, j, k < N): * `+ i j k` — applies operation a[k] = a[i] + a[j]. * `< i j k` — applies operation a[k] = a[i] < a[j]. That is, if a[i] < a[j] then a[k] becomes 1, otherwise it becomes 0. You can use at most Q operations. Elements of a can't exceed V. Indices (i, j, k) don't have to be distinct. It's allowed to modify any element of the array (including the first two). The actual checker simulates the process for multiple pairs (A, B) within a single test. Each time, the checker chooses values A and B, creates the array a = [A, B, 0, 0, \ldots, 0], applies all your operations and ensures that a[2] = A \cdot B. Constraints * 0 \leq A, B \leq 10^9 * N = Q = 200\,000 * V = 10^{19} = 10\,000\,000\,000\,000\,000\,000 Input The Standard Input is empty. Output In the first line, print the number of operations. Each operation should then be printed in a single line of format `+ i j k` or `< i j k`. Example Input Output
```python n=97 p=print r=range def a(i,j,k,l=0):p(chr(43+l*17),i,j,k) def b(i):a(i,i,i+1) def d(x,i,j): for t in r(30): b(j+t-1);a(j+t,n,j+t) for s in r(j+t,j+29):b(s) a(j+29,x,i+t,1);b(j+t-1);a(j+t,i+t,j+t) p(3933) a(0,1,n) a(2,n,n,1) a(0,n,3) a(1,n,4) d(3,5,36) d(4,36,67) for t in r(59): a(2,2,2) for s in r(t+1): if t-30<s<30:a(5+t-s,36+s,98);a(n,98,99,1);a(2,99,2) ```