name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1419_B. Stairs
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases. A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has n stairs, then it is made of n columns, the first column is 1 cell high, the second column is 2 cells high, …, the n-th column if n cells high. The lowest cells of all stairs must be in the same row. A staircase with n stairs is called nice, if it may be covered by n disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with 7 stairs looks like: <image> Find out the maximal number of different nice staircases, that can be built, using no more than x cells, in total. No cell can be used more than once. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The description of each test case contains a single integer x (1 ≤ x ≤ 10^{18}) — the number of cells for building staircases. Output For each test case output a single integer — the number of different nice staircases, that can be built, using not more than x cells, in total. Example Input 4 1 8 6 1000000000000000000 Output 1 2 1 30 Note In the first test case, it is possible to build only one staircase, that consists of 1 stair. It's nice. That's why the answer is 1. In the second test case, it is possible to build two different nice staircases: one consists of 1 stair, and another consists of 3 stairs. This will cost 7 cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is 2. In the third test case, it is possible to build only one of two nice staircases: with 1 stair or with 3 stairs. In the first case, there will be 5 cells left, that may be used only to build a staircase with 2 stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is 1. If Jett builds a staircase with 3 stairs, then there are no more cells left, so the answer is 1 again.
```python ty=[1] p=2 while(True): p=p*2 ty.append(p-1) if(p>10**18): break t=int(input()) for j in range(0,t): x=int(input()) s=0 c=0 for o in ty: s=s+((o)*(o+1))//2 if(s<=x): c=c+1 else: break print(c) ```
1437_B. Reverse Binary Strings
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's. String s has exactly n/2 zeroes and n/2 ones (n is even). In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string. What is the minimum number of operations you need to make string s alternating? A string is alternating if s_i ≠ s_{i + 1} for all i. There are two types of alternating strings in general: 01010101... or 10101010... Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5; n is even) — the length of string s. The second line of each test case contains a binary string s of length n (s_i ∈ {0, 1}). String s has exactly n/2 zeroes and n/2 ones. It's guaranteed that the total sum of n over test cases doesn't exceed 10^5. Output For each test case, print the minimum number of operations to make s alternating. Example Input 3 2 10 4 0110 8 11101000 Output 0 1 2 Note In the first test case, string 10 is already alternating. In the second test case, we can, for example, reverse the last two elements of s and get: 0110 → 0101. In the third test case, we can, for example, make the following two operations: 1. 11101000 → 10101100; 2. 10101100 → 10101010.
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase #New Imports def solution(): n = int(input()) s = input() val = s.count('10') a1 = n//2 - val val = s.count('01') a2 = n//2 - val print(min(a1,a2)) return def main(): testcases = 1 testcases = int(input()) for _ in range(testcases): solution() # 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") # endregion if __name__ == "__main__": main() ```
1461_F. Mathematical Expression
Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information. <image> It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression! Input The first line of the input contains a single integer n (1 ≤ n ≤ 10^5) — the amount of numbers on the paper. The second line of the input contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 9), where a_i is the i-th element of a. The third line of the input contains the string s (1 ≤ |s| ≤ 3) — symbols allowed in the expression. It is guaranteed that the string may only consist of symbols "-", "+" and "*". It is also guaranteed that all symbols in the string are distinct. Output Print n numbers separated by n - 1 symbols — a mathematical expression with the greatest result. If there are multiple equally valid results — output any one of them. Examples Input 3 2 2 0 +-* Output 2*2-0 Input 4 2 1 1 2 +* Output 2+1+1+2 Note The following answers also fit the first example: "2+2+0", "2+2-0", "2*2+0".
```python import sys input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) ops = input().strip() if len(ops) == 1: print(ops.join(map(str, a))) elif '+' in ops and '*' in ops: seqs = [[a[0]]] output = [] # split into seqs of all 0's or non 0's # every seq in seqs is a list of all 0's or non 0's for i in range(1,n): if a[i] == 0: if seqs[-1][-1] == 0: seqs[-1].append(a[i]) else: seqs.append([a[i]]) else: if seqs[-1][-1] == 0: seqs.append([a[i]]) else: seqs[-1].append(a[i]) for seq in seqs: if seq[0] == 0: # all 0 output.append('+'.join(map(str,seq))) else: # if prod >= 2*n, using addition is never optimal prod = 1 for i in seq: prod *= i if prod >= 2 * n: break if prod >= 2 * n: new_seq = '' l = 0 r = len(seq) - 1 for i in range(len(seq)): if seq[i] != 1: l = i break for i in range(len(seq)-1,-1,-1): if seq[i] != 1: r = i break if l != 0: new_seq += '+'.join('1'*l) + '+' new_seq += '*'.join(map(str,seq[l:r+1])) if r != len(seq)-1: new_seq += '+' + '+'.join('1' * (len(seq) - 1 - r)) output.append(new_seq) continue # prod < 2*n so max length of seq after combining 1's is 2*log(2*n) # use dp to find optimal operations b = [] lst = -1 for i in seq: if i == 1: if lst != 1: b.append([-1,1]) else: b[-1][-1] += 1 else: b.append([0,i]) lst = i # + -> 0 | * -> 1 last_state = [[None]*2 for i in range(len(b)+1)] dp = [[-10**9]*2 for i in range(len(b)+1)] dp[0][0] = 0 dp[0][1] = 0 for i in range(len(b)): # find state with mx val with i-1 elements used mx = None state = None if dp[i][0] > dp[i][1]: mx = dp[i][0] state = [i,0] else: mx = dp[i][1] state = [i,1] # add if mx + b[i][1] > dp[i+1][0]: dp[i+1][0] = mx + b[i][1] last_state[i+1][0] = ['+', state] # multiply prod = 1 for j in range(i,len(b)): if b[j][0] == 0: prod *= b[j][1] if mx + prod > dp[j+1][1]: dp[j+1][1] = mx + prod last_state[j+1][1] = ['*', state] # go in reverse to reconstruct sequence solved_seq = [] state = None if dp[len(b)][1] > dp[len(b)][0]: state = [len(b),1] else: state = [len(b),0] while state[0] != 0: next_state = last_state[state[0]][state[1]][1] operation = last_state[state[0]][state[1]][0] for i in range(state[0] - 1, next_state[0]-1,-1): # will add extra operation at end of output, but we can remove it later if b[i][0] == -1: solved_seq.append(operation.join('1' * b[i][1]) + operation) else: solved_seq.append(str(b[i][1]) + operation) if operation == '*': solved_seq[-1] = solved_seq[-1][:-1] + '+' state = next_state # remove extra operation at beg(was at end but we reversed) output.append(''.join(solved_seq)[-2::-1]) print('+'.join(output)) elif '+' in ops: print('+'.join(map(str,a))) elif '*' in ops: if 0 in a: output = [] all_mult = 0 for i in range(n-1): if a[i+1] == 0 and not all_mult: output.extend([a[i],'-']) all_mult = 0 else: output.extend([a[i],'*']) output.append(a[-1]) print(*output,sep='') else: print('*'.join(map(str, a))) ```
1487_A. Arena
n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i. Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute). When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by 1. The winner of the tournament is the first hero that wins in at least 100^{500} fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament. Calculate the number of possible winners among n heroes. Input The first line contains one integer t (1 ≤ t ≤ 500) — the number of test cases. Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 100) — the number of heroes. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100), where a_i is the initial level of the i-th hero. Output For each test case, print one integer — the number of possible winners among the given n heroes. Example Input 3 3 3 2 2 2 5 5 4 1 3 3 7 Output 1 0 3 Note In the first test case of the example, the only possible winner is the first hero. In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner.
```python tests = int(input()) for t in range(tests): n = int(input()) heroes = list(map(int, input().split(' '))) m = min(heroes) print(sum([1 for x in heroes if x > m])) ```
1538_C. Number of Pairs
You are given an array a of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r). For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable: * i=1 and j=2 (4 ≤ 5 + 1 ≤ 7); * i=1 and j=3 (4 ≤ 5 + 2 ≤ 7). Input The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow. The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9). It is guaranteed that the sum of n overall test cases does not exceed 2 ⋅ 10^5. Output For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r. Example Input 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 Output 2 7 0 1
```python # Author: Javier Bórquez import os import sys import bisect def main(): fastReadInt = sys.stdin.buffer.readline def fastReadStr(): return sys.stdin.buffer.readline().decode('utf-8').strip() def fastWrite(ans): return sys.stdout.buffer.write(str(str(ans) + "\n").encode('utf-8')) def fastWriteList(ans): return sys.stdout.buffer.write(str(" ".join(map(str, ans)) + "\n").encode('utf-8')) DEBUG = 'DEBUG' in os.environ def debug(*args): if DEBUG: print(">", *args) def find_le(a, x): 'Find rightmost value less than or equal to x' i = bisect.bisect_right(a, x) if i: return i - 1 return -1 def find_ge(a, x): 'Find leftmost item greater than or equal to x' i = bisect.bisect_left(a, x) if i != len(a): return i return -1 def solution(n, l, r, value): debug("") value.sort() debug(n, l, r, value) res = 0 for ni in range(0, len(value)): n = value[ni] upper = find_le(value, r - n) lower = find_ge(value, l - n) if upper != -1 and lower != -1: debug(ni, [lower, upper]) res += upper - lower + 1 if ni >= lower and ni <= upper: res -= 1 fastWrite(res // 2) # N lines, then N int for t in range(int(fastReadInt())): nlr = list(map(int, fastReadInt().split())) n = nlr[0] l = nlr[1] r = nlr[2] solution(n, l, r, list(map(int, fastReadInt().split()))) main() ```
231_E. Cactus
A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle. A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1, and also exists an edge between vertices v1 and vt. A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1, v2, ..., vt (t > 0), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1 and furthermore each edge occurs no more than once. We'll say that a simple path v1, v2, ..., vt starts at vertex v1 and ends at vertex vt. You've got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you've got a list of k pairs of interesting vertices xi, yi, for which you want to know the following information — the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct. For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109 + 7). Input The first line contains two space-separated integers n, m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105) — the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the indexes of the vertices connected by the i-th edge. The next line contains a single integer k (1 ≤ k ≤ 105) — the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the indexes of interesting vertices in the i-th pair. It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n. Output Print k lines: in the i-th line print a single integer — the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109 + 7). Examples Input 10 11 1 2 2 3 3 4 1 4 3 5 5 6 8 6 8 7 7 6 7 9 9 10 6 1 2 3 5 6 9 9 2 9 3 9 10 Output 2 2 2 4 4 1
```python from collections import defaultdict 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") sys.setrecursionlimit(3*10**4) 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 dfs1(cur,prev,v): depth[cur] = depth[prev] + 1 parent[cur][0] = prev blacks[cur]=v if val[cur]: blacks[cur]+=1 for i in tree[cur]: if (i != prev): yield dfs1(i, cur,blacks[cur]) yield def precomputeSparseMatrix(n): for i in range(1,level): for node in range(1,n+1): if (parent[node][i-1] != -1): parent[node][i] =parent[parent[node][i-1]][i-1] def lca(u,v): if (depth[v] < depth[u]): u,v=v,u diff = depth[v] - depth[u] for i in range(level): if ((diff >> i) & 1): v = parent[v][i] if (u == v): return u i=level-1 while(i>=0): if (parent[u][i] != parent[v][i]): u = parent[u][i] v = parent[v][i] i+=-1 return parent[u][0] @bootstrap def dfs(u,p): global curr for j in adj[u]: if j!=p: if id[j]==0: id[j]=id[u]+1 yield dfs(j,u) elif id[u]>id[j]: up[u]=curr down[j]=curr curr+=1 yield @bootstrap def dfs2(u,p): vis[u]=1 for j in adj[u]: if not vis[j]: yield dfs2(j,u) if up[u]: id[u]=up[u] else: id[u]=u for j in adj[u]: if j!=p: if id[j]!=j and down[j]==0: id[u]=id[j] yield n,m=map(int,input().split()) adj=[[] for i in range(n+1)] edges=[] for j in range(m): u,v=map(int,input().split()) edges.append([u,v]) adj[u].append(v) adj[v].append(u) up=defaultdict(lambda:0) down=defaultdict(lambda:0) curr=n+1 id=[] vis=[] val=[] tree=[] depth=[] for j in range(n+1): id.append(0) vis.append(0) val.append(0) tree.append([]) depth.append(0) id[1]=1 dfs(1,0) dfs2(1,0) res=sorted(list(set(id[1:]))) up=defaultdict(lambda:0) l=len(res) for j in range(l): up[res[j]]=j+1 d=defaultdict(lambda:0) for j in range(1,n+1): id[j]=up[id[j]] d[id[j]]+=1 if d[id[j]]>1: val[id[j]]=1 level=17 parent=[[0 for i in range(level)] for j in range(l+1)] blacks=[0]*(l+1) d=defaultdict(lambda:0) for j in edges: u,v=j[0],j[1] p,q=id[u],id[v] if not d[p,q] and p!=q: tree[p].append(q) tree[q].append(p) d[p,q]=1 d[q,p]=1 dfs1(1,0,0) precomputeSparseMatrix(l) k=int(input()) mod=10**9+7 value=[1] for j in range(1,l+1): value.append((2*value[-1])%(mod)) for j in range(k): a,b=map(int,input().split()) u1,v1=id[a],id[b] lc=lca(u1,v1) res=value[blacks[u1]+blacks[v1]-2*blacks[lc]] if val[lc]: res*=2 print(res%mod) ```
257_D. Sum
Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n). Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists. Input The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array. It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n). Output In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them. Examples Input 4 1 2 3 5 Output +++- Input 3 3 3 5 Output ++-
```python #!/usr/bin/python3 n = int(input()) a = list(map(int, input().split())) s = a[-1] ans = ['+'] for v in reversed(a[:-1]): if s > 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = -a[-1] ans = ['-'] for v in reversed(a[:-1]): if s > 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = a[-1] ans = ['+'] for v in reversed(a[:-1]): if s >= 0: s -= v ans.append('-') else: s += v ans.append('+') if 0 <= s <= a[-1]: print(''.join(reversed(ans))) else: s = -a[-1] ans = ['-'] for v in reversed(a[:-1]): if s >= 0: s -= v ans.append('-') else: s += v ans.append('+') print(''.join(reversed(ans))) ```
32_D. Constellation
A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: * the 2nd is on the same vertical line as the 1st, but x squares up * the 3rd is on the same vertical line as the 1st, but x squares down * the 4th is on the same horizontal line as the 1st, but x squares left * the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one. Your task is to find the constellation with index k by the given Berland's star map. Input The first line contains three integers n, m and k (1 ≤ n, m ≤ 300, 1 ≤ k ≤ 3·107) — height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right — (n, m). Then there follow n lines, m characters each — description of the map. j-th character in i-th line is «*», if there is a star in the corresponding square, and «.» if this square is empty. Output If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each — coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right. Examples Input 5 6 1 ....*. ...*** ....*. ..*... .***.. Output 2 5 1 5 3 5 2 4 2 6 Input 5 6 2 ....*. ...*** ....*. ..*... .***.. Output -1 Input 7 7 2 ...*... ....... ...*... *.***.* ...*... ....... ...*... Output 4 4 1 4 7 4 4 1 4 7
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)] cnt = [0] * 400 for i in range(1, n - 1): for j in range(1, m - 1): if not a[i][j]: continue for rad, ui, di, lj, rj in zip(range(1, 400), range(i - 1, -1, -1), range(i + 1, n), range(j - 1, -1, -1), range(j + 1, m)): if all((a[ui][j], a[di][j], a[i][lj], a[i][rj])): cnt[rad] += 1 rad = -1 for i in range(300): cnt[i + 1] += cnt[i] if cnt[i] >= k: rad = i k -= cnt[i - 1] break else: print(-1) exit() for i in range(rad, n - rad): for j in range(rad, m - rad): if all((a[i][j], a[i - rad][j], a[i + rad][j], a[i][j - rad], a[i][j + rad])): k -= 1 if k == 0: print(f'{i+1} {j+1}\n{i-rad+1} {j+1}\n{i+rad+1} {j+1}\n{i+1} {j-rad+1}\n{i+1} {j+rad+1}') exit() ```
351_B. Jeff and Furik
Jeff has become friends with Furik. Now these two are going to play one quite amusing game. At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order. Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well. You can consider that the coin shows the heads (or tails) with the probability of 50 percent. Input The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation p. The numbers are separated by spaces. Output In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. Examples Input 2 1 2 Output 0.000000 Input 5 3 5 2 4 1 Output 13.000000 Note In the first test the sequence is already sorted, so the answer is 0.
```python from sys import * n=int(stdin.readline().strip()) s1=stdin.readline().strip() a=list(map(int,s1.split())) if n==1: print('0') else: x=0 n0=1 while n0<n: n0=n0*2 b=[0]*(2*n0+10) '''for i in range (n-1): for j in range (i+1,n): if a[i]>a[j]: x+=1''' for i in range (n): t=a[i] u=0 k=1 j=1 while t>0: if (t>>j)<<j!=t: u=u+b[(n0+t-1)>>(j-1)] t=t-k k=k<<1 j=j+1 x=x+u j=n0+a[i]-1 while j>0: b[j]+=1 j=j>>1 x=((n*(n-1))//2)-x '''n=x//2 print(x,n,' !!!') r=x i=1 bi=n eps=0.0000001 if x>0: while (x+2*i)*bi*((0.5)**i)>eps: r=r+(x+2*i)*bi*((0.5)**i) #print(r) bi=(bi*(n+i))//(i+1) i=i+1 #print(bi,i) else: r=0 r=r*((0.5)**n) print("%.7f"%r)''' if x%2 ==1: print(2*x-1) else: print(2*x) ```
420_A. Start Up
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. Input The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font: <image> Output Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). Examples Input AHA Output YES Input Z Output NO Input XO Output NO
```python '''input XO ''' s = input() if all(s[x] == s[~x] for x in range(len(s)//2)): if any(y not in "AHIMOTUVWXY" for y in s[:len(s)//2+1]): print("NO") else: print("YES") else: print("NO") ```
490_E. Restoring Increasing Sequence
Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit. Restore the the original sequence knowing digits remaining on the board. Input The first line of the input contains integer n (1 ≤ n ≤ 105) — the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive. Output If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers — a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them. If there is no answer, print a single line "NO" (without the quotes). Examples Input 3 ? 18 1? Output YES 1 18 19 Input 2 ?? ? Output NO Input 5 12224 12??5 12226 ?0000 ?00000 Output YES 12224 12225 12226 20000 100000
```python def solve(s, t, i, l): if i == l: return False if s[i] == "?": if solve(s, t, i + 1, l): s[i] = t[i] return True elif t[i] == "9": return False s[i] = nxt[t[i]] for j in range(i, l): if s[j] == "?": s[j] = "0" return True elif s[i] > t[i]: for j in range(i, l): if s[j] == "?": s[j] = "0" return True elif s[i] < t[i]: return False else: return solve(s, t, i + 1, l) n = int(input()) a = [list(input()) for _ in range(n)] p = ["0"] nxt = {str(x): str(x + 1) for x in range(9)} for i, ai in enumerate(a): if len(p) > len(ai): print("NO") break if len(p) < len(ai): if a[i][0] == "?": a[i][0] = "1" for j in range(len(ai)): if a[i][j] == "?": a[i][j] = "0" elif not solve(a[i], p, 0, len(ai)): print("NO") break p = a[i] else: print("YES") print("\n".join("".join(line) for line in a)) ```
514_E. Darth Vader and Tree
When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes. But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' — you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7. Input The first line contains two space-separated integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 109) — the number of children of each node and the distance from the root within the range of which you need to count the nodes. The next line contains n space-separated integers di (1 ≤ di ≤ 100) — the length of the edge that connects each node with its i-th child. Output Print a single number — the number of vertexes in the tree at distance from the root equal to at most x. Examples Input 3 3 1 2 3 Output 8 Note Pictures to the sample (the yellow color marks the nodes the distance to which is at most three) <image>
```python # fast io from sys import stdin _data = iter(stdin.read().split('\n')) input = lambda: next(_data) N = 101 MOD = 1000000007 def mul_vec_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD return c def mul_vec_sparse_mat(v, a): c = [0] * N for i in range(N): c[i] = sum(x * v[j] % MOD for j, x in a[i]) % MOD return c _, x = [int(v) for v in input().split()] a = [[0] * N for i in range(N)] a[0][0] = 1 a[N - 1][0] = 1 for i in range(1, N - 1): a[i][i + 1] = 1 for d in map(int, input().split()): a[N - 1][N - d] += 1 sa = [[] for i in range(N)] for i in range(N): for j in range(N): if a[i][j] != 0: sa[j].append((i, a[i][j])) r = [[1 if i == j else 0 for j in range(N)] for i in range(N)] while x > 0: if x & 1: r[0] = mul_vec_mat(r[0], a) r[1] = mul_vec_mat(r[1], a) aa = [[0] * N for i in range(N)] aa[0] = mul_vec_mat(a[0], a) aa[1] = mul_vec_mat(a[1], a) for i in range(2, N): aa[i] = mul_vec_sparse_mat(aa[i - 1], sa) a = aa x >>= 1 for i in range(2, N): r[i] = mul_vec_sparse_mat(r[i - 1], sa) b = [0] * N b[0] = 1 b[N - 1] = 1 print(sum(r[N - 1][i] * b[i] % MOD for i in range(N)) % MOD) ```
569_B. Inventory
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything. During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering. You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal. Input The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items. Output Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them. Examples Input 3 1 3 2 Output 1 3 2 Input 4 2 2 3 3 Output 2 1 3 4 Input 1 2 Output 1 Note In the first test the numeration is already a permutation, so there is no need to change anything. In the second test there are two pairs of equal numbers, in each pair you need to replace one number. In the third test you need to replace 2 by 1, as the numbering should start from one.
```python n = int(input()) fix = list() factors = set(range(1, n + 1)) for i in map(int, input().split()): if i in factors: factors.remove(i) fix.append(i) else: fix.append(None) print(' '.join(str(factors.pop()) if i is None else str(i) for i in fix)) ```
631_D. Messenger
Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve. All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>. Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t. Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>... Input The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of blocks in the strings t and s, respectively. The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≤ li ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter. The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≤ li ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter. Output Print a single integer — the number of occurrences of s in t. Examples Input 5 3 3-a 2-b 4-c 3-a 2-c 2-a 2-b 1-c Output 1 Input 6 1 3-a 6-b 7-a 4-c 8-e 2-a 3-a Output 6 Input 5 5 1-h 1-e 1-l 1-l 1-o 1-w 1-o 1-r 1-l 1-d Output 0 Note In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2. In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14.
```python def ziped(a): p = [] for i in a: x = int(i.split('-')[0]) y = i.split('-')[1] if len(p) > 0 and p[-1][1] == y: p[-1][0] += x else: p.append([x, y]) return p def solve(a, b , c): ans = 0 if len(b) == 1: for token in a: #print("token",token) if c(token, b[0]): ans += token[0] - b[0][0] + 1 return ans if len(b) == 2: for i in range(len(a) - 1): if c(a[i], b[0]) and c(a[i + 1], b[-1]): ans += 1 return ans v = b[1 : -1] + [[100500, '#']] + a p = [0] * len(v) for i in range(1, len(v)): j = p[i - 1] while j > 0 and v[i] != v[j]: j = p[j - 1] if v[i] == v[j]: j += 1 p[i] = j for i in range(len(v) - 1): if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]): ans += 1 return ans n, m = map(int, input().split()) a = ziped(input().split()) b = ziped(input().split()) print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0])) ```
660_B. Seating On Bus
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n. Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below: 1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat. After occupying all the window seats (for m > 2n) the non-window seats are occupied: 1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat. All the passengers go to a single final destination. In the final destination, the passengers get off in the given order. 1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. <image> The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus. Input The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers. Output Print m distinct integers from 1 to m — the order in which the passengers will get off the bus. Examples Input 2 7 Output 5 1 6 2 7 3 4 Input 9 36 Output 19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18
```python n,m = map(int,input().split()) for k in range(1,2*n +1): num = 2 *n +k if num <= m: print(num, end=" ") num = k if num <= m: print(num, end=" ") ```
74_C. Chessboard Billiard
Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving. More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed. <image> It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located. You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size. Input The first line contains two integers n and m (2 ≤ n, m ≤ 106). Output Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator). Examples Input 3 4 Output 2 Input 3 3 Output 3
```python import math n,m=map(int,input().split()) print(math.gcd(n-1,m-1)+1) ```
773_B. Dynamic Problem Scoring
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round. <image> Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500. If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem. There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem. With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing. Unfortunately, Vasya is a cheater. He has registered 109 + 7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved. Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts. Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal. Input The first line contains a single integer n (2 ≤ n ≤ 120) — the number of round participants, including Vasya and Petya. Each of the next n lines contains five integers ai, 1, ai, 2..., ai, 5 ( - 1 ≤ ai, j ≤ 119) — the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j. It is guaranteed that each participant has made at least one successful submission. Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order. Output Output a single integer — the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal. Examples Input 2 5 15 40 70 115 50 45 40 30 15 Output 2 Input 3 55 80 10 -1 -1 15 -1 79 60 -1 42 -1 13 -1 -1 Output 3 Input 5 119 119 119 119 119 0 0 0 0 -1 20 65 12 73 77 78 112 22 23 11 1 78 60 111 62 Output 27 Input 4 -1 20 40 77 119 30 10 73 50 107 21 29 -1 64 98 117 65 -1 -1 -1 Output -1 Note In the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980 + 940 + 420 + 360 + 270 = 2970 points, while Petya will score just 800 + 820 + 420 + 440 + 470 = 2950 points. In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points. In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one.
```python import sys inf = 10**9 + 7 def solve(): n = int(sys.stdin.readline()) v = [int(vi) for vi in sys.stdin.readline().split()] # Vesya p = [int(pi) for pi in sys.stdin.readline().split()] # Petya cnt = [0]*5 for i in range(5): if v[i] != -1: cnt[i] += 1 if p[i] != -1: cnt[i] += 1 for i in range(n - 2): a = [int(ai) for ai in sys.stdin.readline().split()] for j in range(5): if a[j] != -1: cnt[j] += 1 for i in range(4000): if check(n, v, p, cnt, i): print(i) return print(-1) def check(n, v, p, cnt, m): tot = n + m solved = cnt[:] dif = 0 for i in range(5): if p[i] != -1 and v[i] > p[i]: solved[i] += m for i in range(5): if solved[i]*2 > tot: max_score = 500 elif solved[i]*4 > tot: max_score = 1000 elif solved[i]*8 > tot: max_score = 1500 elif solved[i]*16 > tot: max_score = 2000 elif solved[i]*32 > tot: max_score = 2500 else: max_score = 3000 if v[i] == p[i] == -1: pass elif v[i] == -1: dif -= max_score * (250 - p[i]) // 250 elif p[i] == -1: dif += max_score * (250 - v[i]) // 250 else: dif += max_score * (p[i] - v[i]) // 250 return dif > 0 if __name__ == '__main__': solve() ```
798_A. Mike and palindrome
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not. Input The first and single line contains string s (1 ≤ |s| ≤ 15). Output Print "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise. Examples Input abccaa Output YES Input abbcca Output NO Input abcda Output YES
```python import sys import math import itertools import collections def getdict(n): d = {} if type(n) is list or type(n) is str: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() if t in d: d[t] += 1 else: d[t] = 1 return d def divs(n, start=1): r = [] for i in range(start, int(math.sqrt(n) + 1)): if (n % i == 0): if (n / i == i): r.append(i) else: r.extend([i, n // i]) return r def cdiv(n, k): return n // k + (n % k != 0) def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return list(map(int, input().split())) def lcm(a, b): return abs(a*b) // math.gcd(a, b) def wr(arr): return ''.join(map(str, arr)) def revn(n): return int(str(n)[::-1]) def prime(n): if n == 2: return True if n % 2 == 0 or n <= 1: return False sqr = int(math.sqrt(n)) + 1 for d in range(3, sqr, 2): if n % d == 0: return False return True def convn(number, base=3): newnumber = '' while number > 0: newnumber = str(number % base) + newnumber number //= base return newnumber s = input() t = 0 for i in range(len(s) // 2): if s[i] != s[-i -1]: t += 1 if len(s) % 2 == 1 and t < 2 or len(s) % 2 == 0 and t == 1: print('YES') else: print('NO') ```
818_C. Sofa Thief
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss? Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same! The storehouse is represented as matrix n × m. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells. Sofa A is standing to the left of sofa B if there exist two such cells a and b that xa < xb, a is covered by A and b is covered by B. Sofa A is standing to the top of sofa B if there exist two such cells a and b that ya < yb, a is covered by A and b is covered by B. Right and bottom conditions are declared the same way. Note that in all conditions A ≠ B. Also some sofa A can be both to the top of another sofa B and to the bottom of it. The same is for left and right conditions. The note also stated that there are cntl sofas to the left of Grandpa Maks's sofa, cntr — to the right, cntt — to the top and cntb — to the bottom. Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions. Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1. Input The first line contains one integer number d (1 ≤ d ≤ 105) — the number of sofas in the storehouse. The second line contains two integer numbers n, m (1 ≤ n, m ≤ 105) — the size of the storehouse. Next d lines contains four integer numbers x1, y1, x2, y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — coordinates of the i-th sofa. It is guaranteed that cells (x1, y1) and (x2, y2) have common side, (x1, y1) ≠ (x2, y2) and no cell is covered by more than one sofa. The last line contains four integer numbers cntl, cntr, cntt, cntb (0 ≤ cntl, cntr, cntt, cntb ≤ d - 1). Output Print the number of the sofa for which all the conditions are met. Sofas are numbered 1 through d as given in input. If there is no such sofa then print -1. Examples Input 2 3 2 3 1 3 2 1 2 2 2 1 0 0 1 Output 1 Input 3 10 10 1 2 1 1 5 5 6 5 6 4 5 4 2 1 2 0 Output 2 Input 2 2 2 2 1 1 1 1 2 2 2 1 0 0 0 Output -1 Note Let's consider the second example. * The first sofa has 0 to its left, 2 sofas to its right ((1, 1) is to the left of both (5, 5) and (5, 4)), 0 to its top and 2 to its bottom (both 2nd and 3rd sofas are below). * The second sofa has cntl = 2, cntr = 1, cntt = 2 and cntb = 0. * The third sofa has cntl = 2, cntr = 1, cntt = 1 and cntb = 1. So the second one corresponds to the given conditions. In the third example * The first sofa has cntl = 1, cntr = 1, cntt = 0 and cntb = 1. * The second sofa has cntl = 1, cntr = 1, cntt = 1 and cntb = 0. And there is no sofa with the set (1, 0, 0, 0) so the answer is -1.
```python import sys from collections import defaultdict as dd from collections import deque pl=1 from math import * import copy #sys.setrecursionlimit(10**6) if pl: input=sys.stdin.readline def li(): return [int(xxx) for xxx in input().split()] def fi(): return int(input()) def si(): return list(input().rstrip()) def mi(): return map(int,input().split()) d=[] from bisect import * from itertools import permutations from bisect import * f=[0 for i in range(100)] for i in range(1,100): if i==1: f[i]=1 else: f[i]=2*f[i-1]+1 #print(f[:15]) def rec(n,k): s=[] while n!=0: n,r=n//k,n%k #print(n,r) if r<0: r-=k n+=1 #print(s,n,r) s.append(r) return s n=fi() p,q=mi() pp=[] l=[];r=[];u=[];d=[] for i in range(n): x1,y1,x2,y2=mi() x1,x2=min(x1,x2),max(x1,x2) y1,y2=min(y1,y2),max(y1,y2) l.append(x1) r.append(-x2) u.append(y1) d.append(-y2) pp.append([x1,x2,y1,y2]) l.sort() r.sort() u.sort() d.sort() #print(l,r,u,d) f=[[0,0,0,0] for i in range(n+1)] for i in range(n): f[i][0]=bisect_left(l,pp[i][1]) if pp[i][0]<pp[i][1]: f[i][0]-=1 f[i][1]=bisect_left(r,-pp[i][0]) if pp[i][0]<pp[i][1]: f[i][1]-=1 f[i][2]=bisect_left(u,pp[i][3]) if pp[i][2]<pp[i][3]: f[i][2]-=1 f[i][3]=bisect_left(d,-pp[i][2]) if pp[i][2]<pp[i][3]: f[i][3]-=1 #f[l[i][1]][0]=bisect_left(l,) co=li() #print(f) for i in range(n): if co==f[i]: print(i+1) exit(0) print(-1) ```
864_B. Polycarp and Letters
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters. Let A be a set of positions in the string. Let's call it pretty if following conditions are met: * letters on positions from A in the string are all distinct and lowercase; * there are no uppercase letters in the string which are situated between positions from A (i.e. there is no such j that s[j] is an uppercase letter, and a1 < j < a2 for some a1 and a2 from A). Write a program that will determine the maximum number of elements in a pretty set of positions. Input The first line contains a single integer n (1 ≤ n ≤ 200) — length of string s. The second line contains a string s consisting of lowercase and uppercase Latin letters. Output Print maximum number of elements in pretty set of positions for string s. Examples Input 11 aaaaBaabAbA Output 2 Input 12 zACaAbbaazzC Output 3 Input 3 ABC Output 0 Note In the first example the desired positions might be 6 and 8 or 7 and 8. Positions 6 and 7 contain letters 'a', position 8 contains letter 'b'. The pair of positions 1 and 8 is not suitable because there is an uppercase letter 'B' between these position. In the second example desired positions can be 7, 8 and 11. There are other ways to choose pretty set consisting of three elements. In the third example the given string s does not contain any lowercase letters, so the answer is 0.
```python import re input() print(max(map(lambda s: len(set(s)), re.split('[A-Z]', input())))) ```
88_A. Chord
Vasya studies music. He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitones Vasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads — major and minor. Let's define a major triad. Let the triad consist of notes X, Y and Z. If we can order the notes so as the distance along the musical scale between X and Y equals 4 semitones and the distance between Y and Z is 3 semitones, then the triad is major. The distance between X and Z, accordingly, equals 7 semitones. A minor triad is different in that the distance between X and Y should be 3 semitones and between Y and Z — 4 semitones. For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F — 4 semitones. Help Vasya classify the triad the teacher has given to him. Input The only line contains 3 space-separated notes in the above-given notation. Output Print "major" if the chord is major, "minor" if it is minor, and "strange" if the teacher gave Vasya some weird chord which is neither major nor minor. Vasya promises you that the answer will always be unambiguous. That is, there are no chords that are both major and minor simultaneously. Examples Input C E G Output major Input C# B F Output minor Input A B H Output strange
```python # Problem: 88A # Time Created: August 10(Monday) 2020 || 11:37:58 #>-------------------------<# import sys input = sys.stdin.readline #>-------------------------<# from itertools import permutations # Helper Functions. -> Don't cluster your code. def check_chord(tup): notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H'] notes += notes x, y, z = tup x_y = 0 y_z = 0 for i in range(notes.index(x), len(notes)): if notes[i] == y: break else: x_y += 1 for i in range(notes.index(y), len(notes)): if notes[i] == z: break else: y_z += 1 if x_y == 4 and y_z == 3: return "major" elif x_y == 3 and y_z == 4: return "minor" else: return "strange" # IO Functions. -> Input output def io(): x, y, z = map(str, input().split()) perms = permutations([x,y,z]) return list(perms) # Main functions. -> Write the main solution here def solve(): perms = io() ans = 'strange' for perm in perms: chord = check_chord(perm) if chord != 'strange': ans = chord break print(ans) # Multiple test cases. -> When you have T test cases. solve() ```
912_D. Fishes
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!). The gift bundle also includes a square scoop of size r × r, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x, y), all fishes inside the square (x, y)...(x + r - 1, y + r - 1) get caught. Note that the scoop-net should lie completely inside the pond when used. Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (n - r + 1)·(m - r + 1) possible positions, the average number of caught fishes is as high as possible. Input The only line contains four integers n, m, r, k (1 ≤ n, m ≤ 105, 1 ≤ r ≤ min(n, m), 1 ≤ k ≤ min(n·m, 105)). Output Print a single number — the maximum possible expected number of caught fishes. You answer is considered correct, is its absolute or relative error does not exceed 10 - 9. Namely, let your answer be a, and the jury's answer be b. Your answer is considered correct, if <image>. Examples Input 3 3 2 3 Output 2.0000000000 Input 12 17 9 40 Output 32.8333333333 Note In the first example you can put the fishes in cells (2, 1), (2, 2), (2, 3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value. <image>
```python n, m, r, k = map(int, input().split()) def count(y, x): minx = max(0, x-(r-1)) maxx = min(m-1-(r-1), x) miny = max(0, y-(r-1)) maxy = min(n-1-(r-1), y) res = (maxy-miny+1)*(maxx-minx+1) return res #X = [[0]*m for i in range(n)] #for i in range(n): #for j in range(m): #X[i][j] = count(i, j) #print(i, j, count(i, j)) #for i in range(n): #print(*X[i]) sy, sx = n//2, m//2 c = count(sy, sx) cnt = 0 import heapq q = [(-c, sy, sx)] heapq.heapify(q) visit = set() visit.add((sy, sx)) E = 0 while q: c, y, x = heapq.heappop(q) c = -c E += c cnt += 1 if cnt == k: break for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1): ny, nx = y+dy, x+dx if 0 <= ny < n and 0 <= nx < m: if (ny, nx) in visit: continue c = count(ny, nx) heapq.heappush(q, (-c, ny, nx)) visit.add((ny, nx)) ans = E/((n-r+1)*(m-r+1)) print(ans) ```
934_D. A Determined Cleanup
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients). Input The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 1018, 2 ≤ k ≤ 2 000). Output If the polynomial does not exist, print a single integer -1, or output two lines otherwise. In the first line print a non-negative integer d — the number of coefficients in the polynomial. In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial <image> fulfilling the given requirements. Your output should satisfy 0 ≤ ai < k for all 0 ≤ i ≤ d - 1, and ad - 1 ≠ 0. If there are many possible solutions, print any of them. Examples Input 46 2 Output 7 0 1 0 0 1 1 1 Input 2018 214 Output 3 92 205 1 Note In the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)·(x + 2) + 46. In the second example, f(x) = x2 + 205x + 92 = (x - 9)·(x + 214) + 2018.
```python p, k = input().split() p, k = int(p), int(k) s = k - 1 ls = [0] while s < p: ls.append(0) ls.append(0) s = s * k * k + k - 1 n = len(ls) for i in range(n): if (i & 1) == 0: ls[i] = k - 1 res = s - p for i in range(n): t = res % k if i & 1: ls[i] += t else: ls[i] -= t res //= k print(n) print(" ".join(str(x) for x in ls)) ```
988_C. Equal Sums
You are given k sequences of integers. The length of the i-th sequence equals to n_i. You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the changed sequence j (its length will be equal to n_j - 1). Note that it's required to remove exactly one element in each of the two chosen sequences. Assume that the sum of the empty (of the length equals 0) sequence is 0. Input The first line contains an integer k (2 ≤ k ≤ 2 ⋅ 10^5) — the number of sequences. Then k pairs of lines follow, each pair containing a sequence. The first line in the i-th pair contains one integer n_i (1 ≤ n_i < 2 ⋅ 10^5) — the length of the i-th sequence. The second line of the i-th pair contains a sequence of n_i integers a_{i, 1}, a_{i, 2}, ..., a_{i, n_i}. The elements of sequences are integer numbers from -10^4 to 10^4. The sum of lengths of all given sequences don't exceed 2 ⋅ 10^5, i.e. n_1 + n_2 + ... + n_k ≤ 2 ⋅ 10^5. Output If it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers i, x (1 ≤ i ≤ k, 1 ≤ x ≤ n_i), in the third line — two integers j, y (1 ≤ j ≤ k, 1 ≤ y ≤ n_j). It means that the sum of the elements of the i-th sequence without the element with index x equals to the sum of the elements of the j-th sequence without the element with index y. Two chosen sequences must be distinct, i.e. i ≠ j. You can print them in any order. If there are multiple possible answers, print any of them. Examples Input 2 5 2 3 1 3 2 6 1 1 2 2 2 1 Output YES 2 6 1 2 Input 3 1 5 5 1 1 1 1 1 2 2 3 Output NO Input 4 6 2 2 2 2 2 2 5 2 2 2 2 2 3 2 2 2 5 2 2 2 2 2 Output YES 2 2 4 1 Note In the first example there are two sequences [2, 3, 1, 3, 2] and [1, 1, 2, 2, 2, 1]. You can remove the second element from the first sequence to get [2, 1, 3, 2] and you can remove the sixth element from the second sequence to get [1, 1, 2, 2, 2]. The sums of the both resulting sequences equal to 8, i.e. the sums are equal.
```python k = int(input()) arr = [] for _ in range(k): n = int(input()) arr.append(list(map(int,input().split()))) d = {} for i in range(k): s = sum(arr[i]) used = set() for j,c in enumerate(arr[i]): if c in used: continue used.add(c) if s-c in d: print("YES") print(*d[s-c]) print(i+1,j+1) exit() else: d[s-c] = [i+1,j+1] print("NO") ```
p02595 AtCoder Beginner Contest 174 - Distance
We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i). Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there? We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}. Constraints * 1 \leq N \leq 2\times 10^5 * 0 \leq D \leq 2\times 10^5 * |X_i|,|Y_i| \leq 2\times 10^5 * All values in input are integers. Input Input is given from Standard Input in the following format: N D X_1 Y_1 \vdots X_N Y_N Output Print an integer representing the number of points such that the distance from the origin is at most D. Examples Input 4 5 0 5 -2 4 3 4 4 -4 Output 3 Input 12 3 1 1 1 1 1 1 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Output 7 Input 20 100000 14309 -32939 -56855 100340 151364 25430 103789 -113141 147404 -136977 -37006 -30929 188810 -49557 13419 70401 -88280 165170 -196399 137941 -176527 -61904 46659 115261 -153551 114185 98784 -6820 94111 -86268 -30401 61477 -55056 7872 5901 -163796 138819 -185986 -69848 -96669 Output 6
```python N, D = map(int, input().split()) P = [tuple(map(int, input().split())) for i in range(N)] print(sum([p * p + q * q <= D * D for p, q in P])) ```
p02726 AtCoder Beginner Contest 160 - Line++
We have an undirected graph G with N vertices numbered 1 to N and N edges as follows: * For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1. * There is an edge between Vertex X and Vertex Y. For each k=1,2,...,N-1, solve the problem below: * Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k. Constraints * 3 \leq N \leq 2 \times 10^3 * 1 \leq X,Y \leq N * X+1 < Y * All values in input are integers. Input Input is given from Standard Input in the following format: N X Y Output For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem. Examples Input 5 2 4 Output 5 4 1 0 Input 3 1 3 Output 3 0 Input 7 3 7 Output 7 8 4 2 0 0 Input 10 4 8 Output 10 12 10 8 4 1 0 0 0
```python n,x,y = map(int, input().split()) x = x-1 y = y-1 k=[0]*n for i in range(n-1): for j in range(i+1,n): m = min(j-i,abs(x-i)+1+abs(y-j)) k[m] += 1 for i in range(1,n): print(k[i]) ```
p02993 AtCoder Beginner Contest 131 - Security
The door of Snuke's laboratory is locked with a security code. The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same. You are given the current security code S. If S is hard to enter, print `Bad`; otherwise, print `Good`. Constraints * S is a 4-character string consisting of digits. Input Input is given from Standard Input in the following format: S Output If S is hard to enter, print `Bad`; otherwise, print `Good`. Examples Input 3776 Output Bad Input 8080 Output Good Input 1333 Output Bad Input 0024 Output Bad
```python S=input() for i in range(3): if S[i]==S[i+1]: print('Bad') exit(0) print('Good') ```
p03134 Yahoo Programming Contest 2019 - Pass
There are N Snukes lining up in a row. You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is `0`; one red ball and one blue ball if the i-th character in S is `1`; two blue balls if the i-th character in S is `2`. Takahashi has a sequence that is initially empty. Find the number of the possible sequences he may have after repeating the following procedure 2N times, modulo 998244353: * Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row. * Takahashi receives the ball and put it to the end of his sequence. Constraints * 1 \leq |S| \leq 2000 * S consists of `0`,`1` and `2`. Note that the integer N is not directly given in input; it is given indirectly as the length of the string S. Input Input is given from Standard Input in the following format: S Output Print the number of the possible sequences Takahashi may have after repeating the procedure 2N times, modulo 998244353. Examples Input 02 Output 3 Input 1210 Output 55 Input 12001021211100201020 Output 543589959
```python s = input() n = len(s) red = [0] blue = [0] mod = 998244353 red = [-1]*(2*n) blue = [-1]*(2*n) cntr = 0 cntb = 0 for i in range(n): cntr = max(cntr,i) cntb = max(cntb,i) if s[i] == "0": red[cntr] = 1 red[cntr+1] = 1 cntr += 2 if s[i] == "1": red[cntr] = 1 cntr += 1 blue[cntb] = 1 cntb += 1 if s[i] == "2": blue[cntb] = 1 blue[cntb+1] = 1 cntb += 2 for i in range(1,2*n): red[i] += red[i-1] blue[i] += blue[i-1] dp = [[0]*(4*n+5) for i in range(2*n+1)] dp[0][0] = 1 for i in range(1,2*n+1): for j in range(-blue[i-1],red[i-1]+1,1): dp[i][j] = (dp[i-1][j+1]+dp[i-1][j-1])%mod print(dp[-1][red[-1]]) ```
p03279 AtCoder Regular Contest 101 - Robots and Exits
There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j. Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously: * Increment the coordinates of all the robots on the number line by 1. * Decrement the coordinates of all the robots on the number line by 1. Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit. Snuke will continue performing operations until all the robots disappear. When all the robots disappear, how many combinations of exits can be used by the robots? Find the count modulo 10^9 + 7. Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations. Constraints * 1 \leq N, M \leq 10^5 * 1 \leq x_1 < x_2 < ... < x_N \leq 10^9 * 1 \leq y_1 < y_2 < ... < y_M \leq 10^9 * All given coordinates are integers. * All given coordinates are distinct. Input Input is given from Standard Input in the following format: N M x_1 x_2 ... x_N y_1 y_2 ... y_M Output Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7. Examples Input 2 2 2 3 1 4 Output 3 Input 3 4 2 5 10 1 3 7 13 Output 8 Input 4 1 1 2 4 5 3 Output 1 Input 4 5 2 5 7 11 1 3 6 9 13 Output 6 Input 10 10 4 13 15 18 19 20 21 22 25 27 1 5 11 12 14 16 23 26 29 30 Output 22
```python from bisect import bisect from collections import defaultdict class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) self.depth = n.bit_length() def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i <= self.size: self.tree[i] += x i += i & -i def debug_print(self): for i in range(1, self.size + 1): j = (i & -i).bit_length() print(' ' * j, self.tree[i]) def lower_bound(self, x): sum_ = 0 pos = 0 for i in range(self.depth, -1, -1): k = pos + (1 << i) if k <= self.size and sum_ + self.tree[k] < x: sum_ += self.tree[k] pos += 1 << i return pos + 1, sum_ n, m = map(int, input().split()) xxx = list(map(int, input().split())) yyy = list(map(int, input().split())) ab = defaultdict(set) coordinates = set() for x in xxx: if x < yyy[0] or yyy[-1] < x: continue i = bisect(yyy, x) a = x - yyy[i - 1] b = yyy[i] - x ab[a].add(b) coordinates.add(b) # Bitのindexは1から始まるように作っているが、"0"を取れるようにするため、全体を1ずらす cor_dict = {b: i for i, b in enumerate(sorted(coordinates), start=2)} cdg = cor_dict.get bit = Bit(len(coordinates) + 1) bit.add(1, 1) for a in sorted(ab): bbb = sorted(map(cdg, ab[a]), reverse=True) for b in bbb: bit.add(b, bit.sum(b - 1)) print(bit.sum(bit.size) % (10 ** 9 + 7)) ```
p03434 AtCoder Beginner Contest 088 - Card Game for Two
We have N cards. A number a_i is written on the i-th card. Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first. The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score. Constraints * N is an integer between 1 and 100 (inclusive). * a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive). Input Input is given from Standard Input in the following format: N a_1 a_2 a_3 ... a_N Output Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores. Examples Input 2 3 1 Output 2 Input 3 2 7 4 Output 5 Input 4 20 18 2 18 Output 18
```python input() card=sorted(map(int,input().split()))[::-1] print(sum(card[::2])-sum(card[1::2])) ```
p03593 CODE FESTIVAL 2017 qual A - Palindromic Matrix
We have an H-by-W matrix. Let a_{ij} be the element at the i-th row from the top and j-th column from the left. In this matrix, each a_{ij} is a lowercase English letter. Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A. Here, he wants to satisfy the following condition: * Every row and column in A' can be read as a palindrome. Determine whether he can create a matrix satisfying the condition. Constraints * 1 ≤ H, W ≤ 100 * a_{ij} is a lowercase English letter. Input Input is given from Standard Input in the following format: H W a_{11}a_{12}...a_{1W} : a_{H1}a_{H2}...a_{HW} Output If Snuke can create a matrix satisfying the condition, print `Yes`; otherwise, print `No`. Examples Input 3 4 aabb aabb aacc Output Yes Input 2 2 aa bb Output No Input 5 1 t w e e t Output Yes Input 2 5 abxba abyba Output No Input 1 1 z Output Yes
```python from collections import Counter H, W = map(int, input().split()) cntA = Counter() for _ in range(H): cntA += Counter(list(input())) four = (H // 2) * (W // 2) for a, c in cntA.items(): if four <= 0: break while c >= 4 and four > 0: c -= 4 four -= 1 cntA[a] = c if four > 0: print('No') exit() if H % 2 == W % 2 == 1: for a, c in cntA.items(): if c % 2 == 1: cntA[a] -= 1 break else: print('No') exit() print('Yes' if all(c % 2 == 0 for c in cntA.values()) else 'No') ```
p03914 CODE FESTIVAL 2016 Final - Road of the King
There are N towns in Takahashi Kingdom. They are conveniently numbered 1 through N. Takahashi the king is planning to go on a tour of inspection for M days. He will determine a sequence of towns c, and visit town c_i on the i-th day. That is, on the i-th day, he will travel from his current location to town c_i. If he is already at town c_i, he will stay at that town. His location just before the beginning of the tour is town 1, the capital. The tour ends at town c_M, without getting back to the capital. The problem is that there is no paved road in this kingdom. He decided to resolve this issue by paving the road himself while traveling. When he travels from town a to town b, there will be a newly paved one-way road from town a to town b. Since he cares for his people, he wants the following condition to be satisfied after his tour is over: "it is possible to travel from any town to any other town by traversing roads paved by him". How many sequences of towns c satisfy this condition? Constraints * 2≦N≦300 * 1≦M≦300 Input The input is given from Standard Input in the following format: N M Output Print the number of sequences of towns satisfying the condition, modulo 1000000007 (=10^9+7). Examples Input 3 3 Output 2 Input 150 300 Output 734286322 Input 300 150 Output 0
```python mod=10**9+7 N,M=map(int,input().split()) dp=[[0 for i in range(N+1)] for j in range(N+1)] dp[N][N]=1 for i in range(M-1,-1,-1): for k in range(1,N+1): for j in range(k,N+1): if j==k: if j<N: dp[j][k]=(j*dp[j][k]+(N-j)*dp[j+1][k])%mod else: dp[j][k]=(N*dp[j][k])%mod else: if j<N: dp[j][k]=(k*dp[j][j]+(N-j)*dp[j+1][k]+(j-k)*dp[j][k])%mod else: dp[j][k]=(k*dp[j][j]+(N-k)*dp[j][k])%mod print(dp[1][1]) ```
p00016 Treasure Hunt
When a boy was cleaning up after his grand father passing, he found an old paper: <image> In addition, other side of the paper says that "go ahead a number of steps equivalent to the first integer, and turn clockwise by degrees equivalent to the second integer". His grand mother says that Sanbonmatsu was standing at the center of town. However, now buildings are crammed side by side and people can not walk along exactly what the paper says in. Your task is to write a program which hunts for the treature on the paper. For simplicity, 1 step is equivalent to 1 meter. Input consists of several pairs of two integers d (the first integer) and t (the second integer) separated by a comma. Input ends with "0, 0". Your program should print the coordinate (x, y) of the end point. There is the treature where x meters to the east and y meters to the north from the center of town. You can assume that d ≤ 100 and -180 ≤ t ≤ 180. Input A sequence of pairs of integers d and t which end with "0,0". Output Print the integer portion of x and y in a line respectively. Example Input 56,65 97,54 64,-4 55,76 42,-27 43,80 87,-86 55,-6 89,34 95,5 0,0 Output 171 -302
```python import math def calc(x, y, r, d, nd): x = x + r * math.cos(math.radians(d)) y = y + r * math.sin(math.radians(d)) d -= nd return x, y, d x = y = 0 d = 90 while True: r, nd = map(int, input().split(",")) if r == nd == 0: break x, y, d = calc(x, y, r, d, nd) print(int(x)) print(int(y)) ```
p00148 Candy and Class Flag
In Group C of the 3rd year, we decided to use the "class flag" used at the sports festival on November 10, 2007 at future class reunions. So, in order to decide which students to keep the "class flag", I decided to play the following game using a large amount of candy that the teacher gave me the other day. * Each student will take one candy in the order of student number. * If candy remains after one round, continue to take candy in order from the person with the first student number. * The person who picks up the last candy will be the student who keeps the "class flag". There are 39 students in the 3rd grade C class. Their student numbers are 3C01 to 3C39. For example, if you have 50 candies and everyone in the class finishes taking the first candy, you will have 11 candies left. If you take it again in student number order, the last one will be taken by the 3C11 student. That is, the 3C11 student is the student who keeps the "class flag". Create a program that takes the number of candies as input and outputs the student number of the student who stores the "class flag". Input Multiple test cases are given. Each test case is given in the following format. For each test case, an integer a (1 ≤ a ≤ 10000) representing the number of candies is given on one line. Process until the end of input (EOF). The number of datasets does not exceed 20. Output For each test case, output the student number (half-width alphanumeric characters) of the student who stores the "class flag" on one line. Example Input 50 5576 5577 5578 Output 3C11 3C38 3C39 3C01
```python while True: try: n = int(input()) except: break ans = n % 39 if ans == 0: ans = "39" else: ans = "{0:02d}".format(ans) print("3C"+ans) ```
p00469 Lining up the cards
problem Hanako is playing with n (4 ≤ n ≤ 10) cards side by side. Each card has one integer between 1 and 99. Hanako chose k cards (2 ≤ k ≤ 4) from these cards and arranged them in a horizontal row to make an integer. How many kinds of integers can Hanako make in total? For example, consider that you are given five cards of 1, 2, 3, 13, 21 and choose three of them to make an integer. By arranging 2, 1, and 13 in this order, we can make an integer 2113. Also, by arranging 21, 1, and 3 in this order, the same integer 2113 can be created. In this way, the same integer may be created from a combination of different cards. Given the integers written on n cards, create a program to find the number of integers that can be created by selecting k cards from them and arranging them in a horizontal row. input The input consists of multiple datasets. Each dataset is given in the following format. Each dataset consists of 2 + n rows. The number of cards n (4 ≤ n ≤ 10) is written on the first line, and the number of cards to be selected k (2 ≤ k ≤ 4) is written on the second line. On the 2 + i line (1 ≤ i ≤ n), the integer from 1 to 99 written on the i-th card is written. When both n and k are 0, it indicates the end of input. The number of data sets does not exceed 5. output For each data set, the number of integers that Hanako can create is output on one line. Examples Input 4 2 1 2 12 1 6 3 72 2 12 7 2 1 0 0 Output 7 68 Input None Output None
```python import itertools while(True): n = int(input()) k = int(input()) if (n,k) == (0,0): break num_lis = [] for _ in range(n): num_lis.append(input()) word_list = [] for item in list(itertools.permutations(num_lis,k)): word_list.append("".join(item)) print(len(set(word_list))) ```
p00661 Time Manipulation
She is an apprentice wizard. She first learned the magic of manipulating time. And she decided to open a liquor store to earn a living. It has to do with the fact that all the inhabitants of the country where she lives love alcohol. Residents especially like sake that has been aged for many years, and its value increases proportionally with the number of years it has been aged. It's easy to imagine that 100-year-old liquor is more valuable than 50-year-old liquor. And it's also difficult to get. She used her magic to instantly make a long-aged liquor and sell it to earn money. She priced the sake according to the number of years it was aged. For example, if you need 5 years of aging, you will have to pay 5 emers, and if you have 100 years of aging, you will have to pay 100 emers. For her, making either one uses the same magic, so there is no difference. A long-term aging order is better for her. Since she is still immature, there are two restrictions on the magic that can be used now. She can't age sake for more than n years now. Also, there are m integers, and it is impossible for her to age sake for those and multiple years. She is worried if she can live only by running a liquor store. She cannot predict how much income she will earn. So I decided to decide if I needed to do another job based on my expected daily income. Fortunately, she can grow vegetables, take care of pets, cook, sew, carpentry, and so on, so even if she has a small income at a liquor store, she doesn't seem to be in trouble. It's your job to calculate the expected value of her daily income. The following three may be assumed when calculating the expected value. Only one order can be accepted per day. Residents do not order liquor for years that she cannot make. The number of years of inhabitants' orders is evenly distributed. Input The input consists of multiple cases. Each case is given in the following format. n m p0 ... pm-1 Residents request liquor that has been aged for the number of years with an integer value between 1 and n. However, no one asks for m integer pi and its multiples. The end of the input is given with n = 0 and m = 0. Each value meets the following conditions 2 ≤ n ≤ 2,000,000,000 1 ≤ m ≤ 20 Also, pi is guaranteed to be divisible by n. The number of test cases does not exceed 200. Output Output the expected value of her daily income. If there is no possible number of years for the resident's order, output 0 as the expected value of the answer. The correct answer prepared by the judge and an error of 1e-5 or less are allowed as the correct answer. Example Input 12 3 2 3 6 12 4 1 2 3 6 0 0 Output 6.0000000000 0.0000000000
```python # AOJ 1076 Time Manipulation # Python3 2018.7.10 bal4u while True: n, m = map(int, input().split()) if n == 0: break p = list(map(int, input().split())) if 1 in p: n = 0 print(n/2) ```
p00935 Decimal Sequences
Example Input 3 3 0 1 Output 2
```python j=''.join u=input n=int(u()) d=j(j(u().split())for i in[0]*(n//19+(n%19>0))) i=0 while 1: if d.find(str(i))<0: print(i) exit() i+=1 ```
p01676 Tree Reconstruction
J - Tree Reconstruction Problem Statement You have a directed graph. Some non-negative value is assigned on each edge of the graph. You know that the value of the graph satisfies the flow conservation law That is, for every node v, the sum of values on edges incoming to v equals to the sum of values of edges outgoing from v. For example, the following directed graph satisfies the flow conservation law. <image> Suppose that you choose a subset of edges in the graph, denoted by E', and then you erase all the values on edges other than E'. Now you want to recover the erased values by seeing only remaining information. Due to the flow conservation law, it may be possible to recover all the erased values. Your task is to calculate the smallest possible size for such E'. For example, the smallest subset E' for the above graph will be green edges in the following figure. By the flow conservation law, we can recover values on gray edges. <image> Input The input consists of multiple test cases. The format of each test case is as follows. N M s_1 t_1 ... s_M t_M The first line contains two integers N (1 \leq N \leq 500) and M (0 \leq M \leq 3,000) that indicate the number of nodes and edges, respectively. Each of the following M lines consists of two integers s_i and t_i (1 \leq s_i, t_i \leq N). This means that there is an edge from s_i to t_i in the graph. You may assume that the given graph is simple: * There are no self-loops: s_i \neq t_i. * There are no multi-edges: for all i < j, \\{s_i, t_i\\} \neq \\{s_j, t_j\\}. Also, it is guaranteed that each component of the given graph is strongly connected. That is, for every pair of nodes v and u, if there exist a path from v to u, then there exists a path from u to v. Note that you are NOT given information of values on edges because it does not effect the answer. Output For each test case, print an answer in one line. Sample Input 1 9 13 1 2 1 3 2 9 3 4 3 5 3 6 4 9 5 7 6 7 6 8 7 9 8 9 9 1 Output for the Sample Input 1 5 Sample Input 2 7 9 1 2 1 3 2 4 3 4 4 5 4 6 5 7 6 7 7 1 Output for the Sample Input 2 3 Sample Input 3 4 4 1 2 2 1 3 4 4 3 Output for the Sample Input 3 2 Example Input 9 13 1 2 1 3 2 9 3 4 3 5 3 6 4 9 5 7 6 7 6 8 7 9 8 9 9 1 Output 5
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M = map(int, readline().split()) G = [[] for i in range(N)] for i in range(M): s, t = map(int, readline().split()) G[s-1].append(t-1) used = [0]*N cnt = 0 ans = 0 for i in range(N): if used[i]: continue que = deque([i]) used[i] = 1 while que: v = que.popleft() ans += len(G[v])-1 for w in G[v]: if used[w]: continue used[w] = 1 que.append(w) ans += 1 write("%d\n" % ans) solve() ```
p02240 Connected Components
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network. Constraints * $2 \leq n \leq 100,000$ * $0 \leq m \leq 100,000$ * $1 \leq q \leq 10,000$ Input In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$. In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other). In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character. Output For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise. Example Input 10 9 0 1 0 2 3 4 5 7 5 6 6 7 6 8 7 8 8 9 3 0 1 5 9 1 3 Output yes yes no
```python # -*- coding: utf-8 -*- import sys sys.setrecursionlimit(10**6) class LinkedList: def __init__(self, n): self.n = n self.ll = [[] for _ in range(self.n)] def link(self, u, v, direction=False): self.ll[u].append(v) if not direction: self.ll[v].append(u) def dfs(self): self.cc = [None] * self.n color = 1 for u in range(self.n): if not self.cc[u]: self.dfs_visit(u, color) color += 1 def dfs_visit(self, u, color): self.cc[u] = color for v in self.ll[u]: if not self.cc[v]: self.dfs_visit(v, color) def check(self, u, v): if self.cc[u] == self.cc[v]: print('yes') else: print('no') if __name__ == '__main__': n, m = map(int, input().split()) ll = LinkedList(n) for _ in range(m): u, v = map(int, input().split()) ll.link(u, v) ll.dfs() q = int(input()) for _ in range(q): u, v = map(int, input().split()) ll.check(u, v) ```
p02386 Dice IV
Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III. Constraints * $2 \leq n \leq 100$ * $0 \leq $ the integer assigned to a face $ \leq 100$ Input In the first line, the number of dices $n$ is given. In the following $n$ lines, six integers assigned to the dice faces are given respectively in the same way as Dice III. Output Print "Yes" if given dices are all different, otherwise "No" in a line. Examples Input 3 1 2 3 4 5 6 6 2 4 3 5 1 6 5 4 3 2 1 Output No Input 3 1 2 3 4 5 6 6 5 4 3 2 1 5 4 3 2 1 6 Output Yes
```python ptn=[ [1,2,3,4,5,6], [2,6,3,4,1,5], [3,6,5,2,1,4], [4,6,2,5,1,3], [5,6,4,3,1,2], [6,2,4,3,5,1] ] def diffDice(orgDice, newDice): flg = False # diff tmpDice = [0,0,0,0,0,0] for i in range(6): #newDiceをptn1で並べ替え for idx, j in enumerate(ptn[i]): tmpDice[idx] = newDice[j-1] if orgDice[0] != tmpDice[0] and orgDice[5] != tmpDice[5]: continue if ((orgDice[0] == tmpDice[0] and orgDice[5] != tmpDice[5]) or (orgDice[0] != tmpDice[0] and orgDice[5] == tmpDice[5])): continue if ( (orgDice[1:5] == [tmpDice[1],tmpDice[2],tmpDice[3],tmpDice[4]]) or (orgDice[1:5] == [tmpDice[3],tmpDice[1],tmpDice[4],tmpDice[2]]) or (orgDice[1:5] == [tmpDice[2],tmpDice[4],tmpDice[1],tmpDice[3]]) or (orgDice[1:5] == [tmpDice[4],tmpDice[3],tmpDice[2],tmpDice[1]])): flg = True break return flg n = int(input()) dice1 = list(input().split(" ")) flg=False for i in range(1,n): dice2 = list(input().split(" ")) flg = diffDice(dice1,dice2) if flg == True: break if flg: print("No") else: print("Yes") ```
1077_E. Thematic Contests
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide. Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the problems. It is possible that there are no contests for some topics. Polycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that: * number of problems in each contest is exactly twice as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems; * the total number of problems in all the contests should be maximized. Your task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests. Input The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of problems Polycarp has prepared. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) where a_i is the topic of the i-th problem. Output Print one integer — the maximum number of problems in the set of thematic contests. Examples Input 18 2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10 Output 14 Input 10 6 6 6 3 6 1000000000 3 3 6 6 Output 9 Input 3 1337 1337 1337 Output 3 Note In the first example the optimal sequence of contests is: 2 problems of the topic 1, 4 problems of the topic 2, 8 problems of the topic 10. In the second example the optimal sequence of contests is: 3 problems of the topic 3, 6 problems of the topic 6. In the third example you can take all the problems with the topic 1337 (the number of such problems is 3 so the answer is 3) and host a single contest.
```python # from collections import Counter as C # n, k_ = map(int, input().split()) # l = [*map(int, input().split())] # c = C(l) # d = {} # for k, v in c.items(): # d[v] = d.get(v, []) + [str(k)] # ld = sorted([(k, v) for k, v in d.items()], reverse = True) # res = [] # # print(ld) # for e in ld: # res += [e[1]] # if e[0] * len(res) >= k_: # i = 0 # while k_ > e[0] * len(res[i]): # print((' '.join(res[i]) + ' ') * e[0]) # i += 1 # k_ -= e[0] * len(res[i]) # # if k_: # # print((res[i] + ' ') * k_) # exit(0) from bisect import bisect_left, bisect_right from collections import Counter as C n_ = int(input()) l = sorted(C(map(int, input().split())).values()) n = len(l) i = res = 0 # print(l) def f(x): i = 0 for m in range(33): t = x << m i = bisect_left(l, t, i) if i == n: return t - x i += 1 res = 0 for x in range(1, n_ + 1): res = max(res, f(x)) print(res) ```
1119_E. Pavel and Triangles
Pavel has several sticks with lengths equal to powers of two. He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle. It is forbidden to break sticks, and each triangle should consist of exactly three sticks. Find the maximum possible number of triangles. Input The first line contains a single integer n (1 ≤ n ≤ 300 000) — the number of different lengths of sticks. The second line contains n integers a_0, a_1, ..., a_{n-1} (1 ≤ a_i ≤ 10^9), where a_i is the number of sticks with the length equal to 2^i. Output Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make. Examples Input 5 1 2 2 2 2 Output 3 Input 3 1 1 1 Output 0 Input 3 3 3 3 Output 3 Note In the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): (2^0, 2^4, 2^4), (2^1, 2^3, 2^3), (2^1, 2^2, 2^2). In the second example, Pavel cannot make a single triangle. In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): (2^0, 2^0, 2^0), (2^1, 2^1, 2^1), (2^2, 2^2, 2^2).
```python n = int(input()) a = list(map(int, input().split())) ans = 0 last = 0 for q in range(len(a)): while last > 0 and a[q] >= 2: ans += 1 a[q] -= 2 last -= 1 ans += a[q]//3 last += a[q] % 3 print(ans) ```
1146_B. Hate "A"
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string t. Your task is to find some s that Bob could have used to generate t. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string t (1 ≤ |t| ≤ 10^5) consisting of lowercase English letters. Output Print a string s that could have generated t. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have s = "aaaaa", and s' = "". In the second example, no such s can work that will generate the given t. In the third example, we have s = "ababacac", and s' = "bbcc", and t = s + s' = "ababacacbbcc".
```python s = input() s1 = "" a = 0 for i in s: if i == 'a': a -= -1 else: s1 += i if len(s1) % 2: print(":(") exit() t = len(s1) // 2 ch = 1 x = len(s) - 1 for i in range(t - 1, -1, -1): if s1[i] != s[x]: ch = 0 break x += -1 if ch: for i in range(len(s) - t): print(s[i], end = "") else: print(":(") ```
1167_B. Lost Numbers
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>. The jury guessed some array a consisting of 6 integers. There are 6 special numbers — 4, 8, 15, 16, 23, 42 — and each of these numbers occurs in a exactly once (so, a is some permutation of these numbers). You don't know anything about their order, but you are allowed to ask up to 4 queries. In each query, you may choose two indices i and j (1 ≤ i, j ≤ 6, i and j are not necessarily distinct), and you will get the value of a_i ⋅ a_j in return. Can you guess the array a? The array a is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries. Interaction Before submitting the answer, you may ask up to 4 queries. To ask a query, print one line in the following format: ? i j, where i and j should be two integers such that 1 ≤ i, j ≤ 6. The line should be ended with a line break character. After submitting a query, flush the output and read the answer to your query — one line containing one integer a_i ⋅ a_j. If you submit an incorrect query (or ask more than 4 queries), the answer to it will be one string 0. After receiving such an answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer". To give the answer, your program should print one line ! a_1 a_2 a_3 a_4 a_5 a_6 with a line break in the end. After that, it should flush the output and terminate gracefully. Example Input 16 64 345 672 Output ? 1 1 ? 2 2 ? 3 5 ? 4 6 ! 4 8 15 16 23 42 Note If you want to submit a hack for this problem, your test should contain exactly six space-separated integers a_1, a_2, ..., a_6. Each of 6 special numbers should occur exactly once in the test. The test should be ended with a line break character.
```python # -*- coding: utf-8 -*- """ Created on Mon Apr 15 18:26:08 2019 @author: Hamadeh """ class LLNode: def __init__(self, data): self.data = data self.next = None self.prev = None # Class to create a Doubly Linked List class LL: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Given a reference to the head of a list and an # integer, inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = LLNode(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node # Given a node as prev_node, insert a new node after # the given node def insertAfter(self, prev_node, new_data): # 1. Check if the given prev_node is None if prev_node is None: print ("the given previous node cannot be NULL") return # 2. allocate new node # 3. put in the data new_node = LLNode(new_data) # 4. Make net of new node as next of prev node new_node.next = prev_node.next # 5. Make prev_node as previous of new_node prev_node.next = new_node # 6. Make prev_node ass previous of new_node new_node.prev = prev_node # 7. Change previous of new_nodes's next node if new_node.next is not None: new_node.next.prev = new_node return new_node # Given a reference to the head of DLL and integer, # appends a new node at the end def append(self, new_data): # 1. Allocates node # 2. Put in the data new_node = LLNode(new_data) # 3. This new node is going to be the last node, # so make next of it as None new_node.next = None # 4. If the Linked List is empty, then make the # new node as head if self.head is None: new_node.prev = None self.head = new_node return # 5. Else traverse till the last node last = self.head while(last.next is not None): last = last.next # 6. Change the next of last node last.next = new_node # 7. Make last node as previous of new node new_node.prev = last return new_node # This function prints contents of linked list # starting from the given node def printList(self, node): print ("\nTraversal in forward direction") while(node is not None): print (" % d" ,(node.data),) last = node node = node.next print ("\nTraversal in reverse direction") while(last is not None): print (" % d" ,(last.data),) last = last.prev class cinn: def __init__(self): self.x=[] def cin(self,t=int): if(len(self.x)==0): a=input() self.x=a.split() self.x.reverse() return self.get(t) def get(self,t): return t(self.x.pop()) def clist(self,n,t=int): #n is number of inputs, t is type to be casted l=[0]*n for i in range(n): l[i]=self.cin(t) return l def clist2(self,n,t1=int,t2=int,t3=int,tn=2): l=[0]*n for i in range(n): if(tn==2): a1=self.cin(t1) a2=self.cin(t2) l[i]=(a1,a2) elif (tn==3): a1=self.cin(t1) a2=self.cin(t2) a3=self.cin(t3) l[i]=(a1,a2,a3) return l def clist3(self,n,t1=int,t2=int,t3=int): return self.clist2(self,n,t1,t2,t3,3) def cout(self,i,ans=''): if(ans==''): print("Case #"+str(i+1)+":", end=' ') else: print("Case #"+str(i+1)+":",ans) def printf(self,thing): print(thing,end='') def countlist(self,l,s=0,e=None): if(e==None): e=len(l) dic={} for el in range(s,e): if l[el] not in dic: dic[l[el]]=1 else: dic[l[el]]+=1 return dic def talk (self,x): print(x,flush=True) def dp1(self,k): L=[-1]*(k) return L def dp2(self,k,kk): L=[-1]*(k) for i in range(k): L[i]=[-1]*kk return L c=cinn(); L=[4,8,15,16,23,42] Lans=[] c.talk("? 1 2") p1=c.cin() c.talk("? 3 4") p2=c.cin() c.talk("? 1 5") p3=c.cin() c.talk("? 3 6") p4=c.cin() a1=0; a2=0; a3=0; a4=0 a5=0 a6=0 for x in L: #print(p1//x, p2//x, p3//x,p4//x) if p1//x in L and p3//x in L and p1%x==0 and p3%x==0 and x!=p3**0.5 and x!=p1**0.5: a1=x a2=p1//x a5=p3//x if(p2//x in L and p4//x in L and p2%x==0 and p4%x==0 and x!=p2**0.5 and x!=p4**0.5): a3=x a4=p2//x a6=p4//x print("!",a1,a2,a3,a4,a5,a6) ```
1185_E. Polycarp and Snakes
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells. Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26. Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 × l or l × 1, where l is snake's length. Note that snakes can't bend. When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell. Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases to solve. Then t test cases follow. The first line of the test case description contains two integers n, m (1 ≤ n,m ≤ 2000) — length and width of the checkered sheet of paper respectively. Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed 4⋅10^6. Output Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 ≤ k ≤ 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 ≤ r_{1,i}, r_{2,i} ≤ n, 1 ≤ c_{1,i}, c_{2,i} ≤ m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper. Examples Input 1 5 6 ...a.. ..bbb. ...a.. .cccc. ...a.. Output YES 3 1 4 5 4 2 3 2 5 4 2 4 5 Input 3 3 3 ... ... ... 4 4 ..c. adda bbcb .... 3 5 ..b.. aaaaa ..b.. Output YES 0 YES 4 2 1 2 4 3 1 3 4 1 3 3 3 2 2 2 3 NO Input 2 3 3 ... .a. ... 2 2 bb cc Output YES 1 2 2 2 2 YES 3 1 1 1 2 1 1 1 2 2 1 2 2
```python def naiveSolve(): return from collections import defaultdict def charToInt(c): #'a'->0 if c=='.': return -1 return ord(c)-ord('a') def main(): t=int(input()) allans=[] for _ in range(t): n,m=readIntArr() grid=[] # convert all chars to int for __ in range(n): row=list(input()) grid.append([charToInt(c) for c in row]) start=[None]*26 end=[None]*26 for i in range(n): for j in range(m): if grid[i][j]!=-1: if start[grid[i][j]]==None: start[grid[i][j]]=[i,j] end[grid[i][j]]=[i,j] while start and start[-1]==None: start.pop() end.pop() if len(start)==0: allans.append(['YES']) allans.append([0]) continue ok=True N=len(start) dr,dc=end[N-1] # dummy row and cols for unused chars ans=[[dr,dc,dr,dc] for __ in range(N)] for i in range(N): if start[i]==None: # unused char continue if start[i][0]!=end[i][0] and start[i][1]!=end[i][1]: ok=False break ans[i]=[*start[i],*end[i]] if ok==False: allans.append(['NO']) continue reconstruct=[[-1 for _z in range(m)] for __ in range(n)] for i in range(N): r1,c1,r2,c2=ans[i] if r1==r2: for col in range(c1,c2+1): reconstruct[r1][col]=i else: assert c1==c2 for row in range(r1,r2+1): reconstruct[row][c1]=i # check for i in range(n): for j in range(m): if grid[i][j]!=reconstruct[i][j]: ok=False if ok==False: allans.append(['NO']) continue allans.append(['YES']) allans.append([N]) for a in ans: for j in range(4): a[j]+=1 # 1-index allans.extend(ans) multiLineArrayOfArraysPrint(allans) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(l,r): print('? {} {}'.format(l,r)) sys.stdout.flush() return int(input()) def answerInteractive(x): print('! {}'.format(x)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 MOD=998244353 from math import gcd,floor,ceil # from math import floor,ceil # for Python2 for _abc in range(1): main() ```
1204_C. Anna, Svyatoslav and Maps
The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v_k of k vertexes as good, if v is a subsequence of p, v_1 = p_1, v_k = p_m, and p is one of the shortest paths passing through the vertexes v_1, …, v_k in that order. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. It is obvious that the sequence p is good but your task is to find the shortest good subsequence. If there are multiple shortest good subsequences, output any of them. Input The first line contains a single integer n (2 ≤ n ≤ 100) — the number of vertexes in a graph. The next n lines define the graph by an adjacency matrix: the j-th character in the i-st line is equal to 1 if there is an arc from vertex i to the vertex j else it is equal to 0. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer m (2 ≤ m ≤ 10^6) — the number of vertexes in the path. The next line contains m integers p_1, p_2, …, p_m (1 ≤ p_i ≤ n) — the sequence of vertexes in the path. It is guaranteed that for any 1 ≤ i < m there is an arc from p_i to p_{i+1}. Output In the first line output a single integer k (2 ≤ k ≤ m) — the length of the shortest good subsequence. In the second line output k integers v_1, …, v_k (1 ≤ v_i ≤ n) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct. Examples Input 4 0110 0010 0001 1000 4 1 2 3 4 Output 3 1 2 4 Input 4 0110 0010 1001 1000 20 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Output 11 1 2 4 2 4 2 4 2 4 2 4 Input 3 011 101 110 7 1 2 3 1 3 2 1 Output 7 1 2 3 1 3 2 1 Input 4 0110 0001 0001 1000 3 1 2 4 Output 2 1 4 Note Below you can see the graph from the first example: <image> The given path is passing through vertexes 1, 2, 3, 4. The sequence 1-2-4 is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes 1, 2 and 4 in that order is 1-2-3-4. Note that subsequences 1-4 and 1-3-4 aren't good because in both cases the shortest path passing through the vertexes of these sequences is 1-3-4. In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes. In the fourth example, the paths 1-2-4 and 1-3-4 are the shortest paths passing through the vertexes 1 and 4.
```python from collections import deque n = int(input()) graph = [list(map(lambda bit: bit == '1', list(input()))) for _ in range(n)] m = int(input()) way = list(map(lambda i: int(i) - 1, input().split())) #print(graph) def dfs(start): queue = deque([start]) d = [-1] * n d[start] = 0 while len(queue) != 0: u = queue[0] queue.popleft() for v in range(n): if graph[u][v] and d[v] == -1: d[v] = d[u] + 1 queue.append(v) return d minpath = list(map(dfs, range(n))) good = [way[0]] checkp = way[0] for i in range(1, m): prev = way[i - 1] if minpath[checkp][way[i]] != minpath[checkp][prev] + 1: good.append(prev) checkp = prev #print(minpath) good.append(way[-1]) print(len(good)) print(' '.join([str(p + 1) for p in good])) ```
1221_A. 2048 Game
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number equal to their sum into s. For example, if s = \{1, 2, 1, 1, 4, 2, 2\} and you choose integers 2 and 2, then the multiset becomes \{1, 1, 1, 4, 4, 2\}. You win if the number 2048 belongs to your multiset. For example, if s = \{1024, 512, 512, 4\} you can win as follows: choose 512 and 512, your multiset turns into \{1024, 1024, 4\}. Then choose 1024 and 1024, your multiset turns into \{2048, 4\} and you win. You have to determine if you can win this game. You have to answer q independent queries. Input The first line contains one integer q (1 ≤ q ≤ 100) – the number of queries. The first line of each query contains one integer n (1 ≤ n ≤ 100) — the number of elements in multiset. The second line of each query contains n integers s_1, s_2, ..., s_n (1 ≤ s_i ≤ 2^{29}) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two. Output For each query print YES if it is possible to obtain the number 2048 in your multiset, 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 6 4 1024 512 64 512 1 2048 3 64 512 2 2 4096 4 7 2048 2 2048 2048 2048 2048 2048 2 2048 4096 Output YES YES NO NO YES YES Note In the first query you can win as follows: choose 512 and 512, and s turns into \{1024, 64, 1024\}. Then choose 1024 and 1024, and s turns into \{2048, 64\} and you win. In the second query s contains 2048 initially.
```python q=int(input()) for i in range(q): n=int(input()) lst2=[] lst1=list(map(int,input().split())) for i in range(len(lst1)): if lst1[i]<=2048: lst2.append(lst1[i]) sum1=sum(lst2) if sum1>=2048: print("YES") else: print("NO") ```
1266_B. Dice Tower
Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5. <image> The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total. Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob. The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers. Output For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity). Example Input 4 29 34 19 38 Output YES YES YES NO Note The first example is mentioned in the problem statement. In the second example, one can build the tower by flipping the top dice from the previous tower. In the third example, one can use a single die that has 5 on top. The fourth example is impossible.
```python # -*- coding: utf-8 -*- """ Created on Wed Mar 18 14:08:47 2020 @author: Varun """ from sys import stdin, stdout stdin.readline() numbers = map(int, stdin.readline().split()) def check(n): if n < 15: return False m = n%14 return 1 <= m <= 6 for el in numbers: if check(el): stdout.write("YES") else: stdout.write("NO") stdout.write("\n") ```
1287_D. Numbers on Tree
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices. Help him to restore initial integers! Input The first line contains an integer n (1 ≤ n ≤ 2000) — the number of vertices in the tree. The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 ≤ p_i ≤ n; 0 ≤ c_i ≤ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i. It is guaranteed that the values of p_i describe a rooted tree with n vertices. Output If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 ≤ a_i ≤ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9. If there are no solutions, print "NO". Examples Input 3 2 0 0 2 2 0 Output YES 1 2 1 Input 5 0 1 1 3 2 1 3 0 2 0 Output YES 2 3 2 1 2
```python import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n = int(input()) cs = [0] * (n + 1) ps = [0] * (n + 1) children = [[] for _ in range(n+1)] for i in range(1, n+1): p, c = map(int, input().split()) ps[i] = p children[p].append(i) cs[i] = c def sortDescendants(v): result = [] pos = cs[v] for child in children[v]: result += sortDescendants(child) if len(result) < pos: print('NO') sys.exit() result.insert(pos, v) return result root = children[0][0] order = sortDescendants(root) a = [0] * n for i, v in enumerate(order): a[v - 1] = i + 1 print('YES') print(*a) # inf.close() ```
1307_D. Cow and Fields
Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day. The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them. After the road is added, Bessie will return home on the shortest path from field 1 to field n. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him! Input The first line contains integers n, m, and k (2 ≤ n ≤ 2 ⋅ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5, 2 ≤ k ≤ n) — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains k integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n) — the special fields. All a_i are distinct. The i-th of the following m lines contains integers x_i and y_i (1 ≤ x_i, y_i ≤ n, x_i ≠ y_i), representing a bidirectional road between fields x_i and y_i. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them. Output Output one integer, the maximum possible length of the shortest path from field 1 to n after Farmer John installs one road optimally. Examples Input 5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 Output 3 Input 5 4 2 2 4 1 2 2 3 3 4 4 5 Output 3 Note The graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 3 and 5, and the resulting shortest path from 1 to 5 is length 3. <image> The graph for the second example is shown below. Farmer John must add a road between fields 2 and 4, and the resulting shortest path from 1 to 5 is length 3. <image>
```python import sys from collections import deque reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ # v(G), e(G), special v n, m, k = map(int, input().split()) a = list(map(int, input().split())) # adjacency lists g = [[] for _ in range(n + 1)] for _ in range(m): v, to = map(int, input().split()) g[v].append(to) g[to].append(v) dist_1 = [float('inf')] * (n + 1) s = 1 # start vertex dist_1[s] = 0 queue = deque([s]) while queue: v = queue.pop() for to in g[v]: if dist_1[to] > dist_1[v] + 1: dist_1[to] = dist_1[v] + 1 queue.appendleft(to) dist_n = [float('inf')] * (n + 1) s = n # start vertex dist_n[s] = 0 queue = deque([s]) while queue: v = queue.pop() for to in g[v]: if dist_n[to] > dist_n[v] + 1: dist_n[to] = dist_n[v] + 1 queue.appendleft(to) a.sort(key=dist_1.__getitem__) # print(dist_1) # print(a) # print(dist_n) class SegmTree(): def __init__(self, size): N = 1 while N < size: N <<= 1 self.N = N self.tree = [-float('inf')] * (2*self.N) def modify(self, i, value): i += self.N self.tree[i] = value while i > 1: self.tree[i>>1] = max(self.tree[i], self.tree[i^1]) i >>= 1 def query_range(self, l, r): l += self.N r += self.N result = -float('inf') while l < r: if l & 1: result = max(result, self.tree[l]) l += 1 if r & 1: r -= 1 result = max(result, self.tree[r]) l >>= 1 r >>= 1 return result st = SegmTree(n + 1) for v in a: st.modify(v, dist_n[v]) longestPossible = 0 for v in a: st.modify(v, -float('inf')) dist = dist_1[v] + 1 + st.query_range(0, n + 1) longestPossible = max(longestPossible, dist) shortDist = min(dist_1[n], longestPossible) print(shortDist) ```
1330_D. Dreamoon Likes Sequences
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0
```python t = int(input()) for _ in range(t): d, m = map(int, input().split()) a = [] i = 0 while d > (1<<(i+1))-1: a.append(1<<i) i += 1 a.append((1<<i) - (1<<(i+1)) + d + 1) #print(a) ans = 1 for x in a: ans *= x+1 ans %= m print((ans-1)%m) ```
1350_D. Orac and Medians
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to the ⌊ (|s|+1)/(2)⌋-th smallest number in it. For example, the median of \{1,4,4,6,5\} is 4, and the median of \{1,7,5,8\} is 5. Slime wants Orac to make a_1 = a_2 = … = a_n = k using these operations. Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times. Input The first line of the input is a single integer t: the number of queries. The first line of each query contains two integers n\ (1≤ n≤ 100 000) and k\ (1≤ k≤ 10^9), the second line contains n positive integers a_1,a_2,...,a_n\ (1≤ a_i≤ 10^9) The total sum of n is at most 100 000. Output The output should contain t lines. The i-th line should be equal to 'yes' if it is possible to make all integers k in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase. Example Input 5 5 3 1 5 2 6 1 1 6 6 3 2 1 2 3 4 3 3 1 2 3 10 3 1 2 3 4 5 6 7 8 9 10 Output no yes yes no yes Note In the first query, Orac can't turn all elements into 3. In the second query, a_1=6 is already satisfied. In the third query, Orac can select the complete array and turn all elements into 2. In the fourth query, Orac can't turn all elements into 3. In the fifth query, Orac can select [1,6] at first and then select [2,10].
```python # Template 1.0 import sys, re, math from collections import deque, defaultdict, Counter, OrderedDict from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd from heapq import heappush, heappop, heapify, nlargest, nsmallest def STR(): return list(input()) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) def list2d(a, b, c): return [[c] * b for i in range(a)] def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx])) def sortDictWithVal(passedDic): temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0])) toret = {} for tup in temp: toret[tup[0]] = tup[1] return toret def sortDictWithKey(passedDic): return dict(OrderedDict(sorted(passedDic.items()))) sys.setrecursionlimit(10 ** 9) INF = float('inf') mod = 10 ** 9 + 7 def check(idx): up = down = 0 a1,a2,a3 = sorted(a[idx:idx+3]) return (a1<=a2<=a3 and a2>=k) t = INT() while(t!=0): n,k = MAP() a = LIST() if(k in a): flag = 1 else: flag = 0 if(flag==1): for patchStart in range(n-2): if(check(patchStart)): flag = 1 break else: flag=0 continue if(n==2): foo = 0 for el in a: if(el>=k): foo+=1 if(foo==2): print("yes") else: print("no") else: if (flag == 0): print("no") else: print("yes") else: print("no") t-=1 ```
1393_C. Pinkie Pie Eats Patty-cakes
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling. Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them. Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating! Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags! Input The first line contains a single integer T (1 ≤ T ≤ 100): the number of bags for which you need to solve the problem. The first line of each bag description contains a single integer n (2 ≤ n ≤ 10^5): the number of patty-cakes in it. The second line of the bag description contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling. It is guaranteed that the sum of n over all bags does not exceed 10^5. Output For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag. Example Input 4 7 1 7 1 6 4 4 6 8 1 1 4 6 4 6 4 7 3 3 3 3 6 2 5 2 3 1 4 Output 3 2 0 4 Note For the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 6, 4, 7, 1, 6, 4 (in this way, the minimum distance is equal to 3). For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 4, 6, 7, 4, 1, 6, 4 (in this way, the minimum distance is equal to 2).
```python def solve(n,ar): freq = [0] * 200000 for i in range(n): freq[ar[i]] += 1 maxi = 0 max_freq = 0 for i in range(len(freq)): if maxi < freq[i]: maxi = max(maxi,freq[i]) max_freq = 1 elif freq[i] == maxi: max_freq += 1 print((n-max_freq)//(maxi-1) -1) if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) ar = list(map(int,input().split())) solve(n,ar) ```
1418_B. Negative Prefixes
You are given an array a, consisting of n integers. Each position i (1 ≤ i ≤ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were. For example, let a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}], the underlined positions are locked. You can obtain the following arrays: * [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]; * [-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]; * [1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]; * [1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]; * and some others. Let p be a sequence of prefix sums of the array a after the rearrangement. So p_1 = a_1, p_2 = a_1 + a_2, p_3 = a_1 + a_2 + a_3, ..., p_n = a_1 + a_2 + ... + a_n. Let k be the maximum j (1 ≤ j ≤ n) such that p_j < 0. If there are no j such that p_j < 0, then k = 0. Your goal is to rearrange the values in such a way that k is minimum possible. Output the array a after the rearrangement such that the value k for it is minimum possible. If there are multiple answers then print any of them. Input The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. Then t testcases follow. The first line of each testcase contains a single integer n (1 ≤ n ≤ 100) — the number of elements in the array a. The second line of each testcase contains n integers a_1, a_2, ..., a_n (-10^5 ≤ a_i ≤ 10^5) — the initial array a. The third line of each testcase contains n integers l_1, l_2, ..., l_n (0 ≤ l_i ≤ 1), where l_i = 0 means that the position i is unlocked and l_i = 1 means that the position i is locked. Output Print n integers — the array a after the rearrangement. Value k (the maximum j such that p_j < 0 (or 0 if there are no such j)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones. If there are multiple answers then print any of them. Example Input 5 3 1 3 2 0 0 0 4 2 -3 4 -1 1 1 1 1 7 -8 4 -2 -6 4 7 1 1 0 0 0 1 1 0 5 0 1 -4 6 3 0 0 0 1 1 6 -1 7 10 4 -8 -1 1 0 0 0 0 1 Output 1 2 3 2 -3 4 -1 -8 -6 1 4 4 7 -2 -4 0 1 6 3 -1 4 7 -8 10 -1 Note In the first testcase you can rearrange all values however you want but any arrangement will result in k = 0. For example, for an arrangement [1, 2, 3], p=[1, 3, 6], so there are no j such that p_j < 0. Thus, k = 0. In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one. In the third testcase the prefix sums for the printed array are p = [-8, -14, -13, -9, -5, 2, 0]. The maximum j is 5, thus k = 5. There are no arrangements such that k < 5. In the fourth testcase p = [-4, -4, -3, 3, 6]. In the fifth testcase p = [-1, 3, 10, 2, 12, 11].
```python import sys from sys import stdin import math import fractions #Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1)) def iinput(): return int(input()) def minput(): return map(int,input().split()) def linput(): return list(map(int,input().split())) def fiinput(): return int(stdin.readline()) def fminput(): return map(int,stdin.readline().strip().split()) def flinput(): return list(map(int,stdin.readline().strip().split())) for _ in range(iinput()): n=iinput() list1=linput() list2=linput() list3=[] for i in range(n): if(list2[i]==0): list3.append(list1[i]) list3.sort() for i in range(n): if(list2[i]==0): list1[i]=list3.pop() print(*list1) ```
1436_A. Reorder
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, 5/2=2.5. Input The first line contains a single integer t — the number of test cases (1 ≤ t ≤ 100). The test cases follow, each in two lines. The first line of a test case contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 10^6). The second line contains integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^6) — the elements of the array. Output For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise. Example Input 2 3 8 2 5 1 4 4 0 1 2 3 Output YES NO Note In the first test case one of the reorders could be [1, 2, 5]. The sum is equal to (1/1 + 2/2 + 5/3) + (2/2 + 5/3) + (5/3) = 8. The brackets denote the inner sum ∑_{j=i}^{n}{(a_j)/(j)}, while the summation of brackets corresponds to the sum over i.
```python #import numpy as np #import collections #import sys # ============================================================================= #def get_primeFactor(n): # res=[1] # x=2 # while x*x<=n: # while n%x==0: # res.append(x) # n//=x # x+=1 # if n>1:res.append(n) # return res # #def getFactor(n): # res={1,n} # x=2 # while x*x<=n: # if n%x==0: # res.add(x) # res.add(n//x) # x+=1 # return res #for _ in range(int(input())): # r,b,g,w=tuple(map(int,input().split())) # f=tuple(filter(lambda x:x%2!=0,(r,b,g,w))) # if len(f)<=1 or len(f)==4:print("Yes") # elif len(f)==2:print("No") # else: # if w%2==0:print("Yes") # elif all(t!=0 for t in (r,b,g) ):print("Yes") # else :print("No") # for _ in range(int(input())): n,m=map(int,input().split()) ar=map(int,input().split()) total=sum(ar) if total != m:print("NO") else: print("YES") ```
1485_F. Copy or Prefix Sum
You are given an array of integers b_1, b_2, …, b_n. An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≤ i ≤ n) at least one of these conditions is true: * b_i = a_i, or * b_i = ∑_{j=1}^{i} a_j. Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should print the answer modulo 10^9 + 7. Input The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. The first line of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5). The second line of each test case contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9). It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5. Output For each test case, print a single integer: the number of hybrid arrays a_1, a_2, …, a_n modulo 10^9 + 7. Example Input 4 3 1 -1 1 4 1 2 3 4 10 2 -1 1 -2 2 3 -5 0 2 -1 4 0 0 0 1 Output 3 8 223 1 Note In the first test case, the hybrid arrays are [1, -2, 1], [1, -2, 2], [1, -1, 1]. In the second test case, the hybrid arrays are [1, 1, 1, 1], [1, 1, 1, 4], [1, 1, 3, -1], [1, 1, 3, 4], [1, 2, 0, 1], [1, 2, 0, 4], [1, 2, 3, -2], [1, 2, 3, 4]. In the fourth test case, the only hybrid array is [0, 0, 0, 1].
```python for s in[*open(0)][2::2]: C=[0];N=0;D={0:1};S=1 for n in map(int,s.split()):C+=C[-1]+n,;N+=1 for i in range(1,N):D[C[i]],S=S,(2*S-D.get(C[i],0))%(10**9+7) print(S) ```
1536_B. Prinzessin der Verurteilung
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me. It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying? You are given a string of n lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX. A string a is lexicographically smaller than a string b if and only if one of the following holds: * a is a prefix of b, but a ≠ b; * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. Find out what the MEX of the string is! Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000). Description of the test cases follows. The first line of each test case contains an integer n (1 ≤ n ≤ 1000) — the length of the word. The second line for each test case contains a single string of n lowercase Latin letters. The sum of n over all test cases will not exceed 1000. Output For each test case, output the MEX of the string on a new line. Example Input 3 28 qaabzwsxedcrfvtgbyhnujmiklop 13 cleanairactbd 10 aannttoonn Output ac f b
```python # abc = 'abcdefghijklmnopqrstuvwxy' # test1_previous = [x + y for x in abc for y in abc if x!='m'] def nextchr(c): return chr(ord(c)+1) def next(s): if s == '': ans = '.' elif s[-1] == 'z': ans = next(s[:-1]) + 'a' else: ans = s[:-1] + nextchr(s[-1]) return ans t = int(input()) for _ in range(t): # n = len(test_1) # a = test_1 # print(n,a) n = int(input()) a = input() one = [] two = [] three = [] for i in range(n): one.append(a[i:i+1]) if i <= n-2: two.append(a[i:i+2]) if i <= n-3: three.append(a[i:i+3]) one.sort() two.sort() three.sort() current_1 = 'a' current_2 = 'aa' current_3 = 'aaa' for x in one: if current_1 == x: current_1 = next(current_1) ans = current_1 if current_1[0] == '.': for x in two: if current_2 == x: current_2 = next(current_2) ans = current_2 if current_2[0] == '.': for x in three: if current_3 == x: current_3 = next(current_3) ans = current_3 print(ans) ```
163_A. Substring and Subsequence
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences. The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|. A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different. Input The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters. Output Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7). Examples Input aa aa Output 5 Input codeforces forceofcode Output 60 Note Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
```python from sys import stdin s=[ord(i)-97 for i in stdin.readline().strip()] s1=[ord(i)-97 for i in stdin.readline().strip()] n=len(s) m=len(s1) mod=1000000007 dp=[[0 for i in range(n)] for j in range(26)] for i in range(m): arr=[0 for j in range(n)] for j in range(n): if s1[i]==s[j] : arr[j]=1 if j>0 : arr[j]=(arr[j]+dp[s[j-1]][j-1])%mod for j in range(n): dp[s1[i]][j]=(arr[j] +dp[s1[i]][j]) %mod x=0 for i in dp: for j in i: x=(x+j)%mod print(x) ```
183_B. Zoo
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move. In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line. Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum. Input The first line contains two space-separated integers n and m (1 ≤ n ≤ 106, 1 ≤ m ≤ 250), denoting the number of binoculars and the number of flamingos, respectively. Then m lines follow, the i-th line will contain two space-separated integers xi and yi (1 ≤ xi, yi ≤ 109), which means that the i-th flamingo is located at point (xi, yi). All flamingos will be located at distinct points. Output Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars. Examples Input 5 5 2 1 4 1 3 2 4 3 4 4 Output 11 Note This picture shows the answer to the example test case. <image>
```python def gcd(a,b): if b == 0: return a return gcd(b, a % b) def normalize_rational(num,den): #associate the -ve with the num or cancel -ve sign when both are -ve if num ^ den < 0 and num > 0 or num ^ den > 0 and num < 0: num = -num; den = -den #put it in its simplest form g = gcd(abs(num),abs(den)) num //= g; den //=g return (num,den) from sys import * l = stdin.readline() (n,m) = (int(tkn) for tkn in l.split()) xs = [0] * m; ys = [0] * m #maxhits = [set() for i in range(n+1)] maxhits = [1] * (n + 1) maxhits[0] = 0 for i in range(m): l = stdin.readline() (x,y) = (int(tkn) for tkn in l.split()) xs[i] = x; ys[i] = y line_to_points = {} for i in range(m): for j in range(m): #m = dy/dx; y = (dy/dx)x + c ==> y.dx = x.dy + c.dx #y.dx = x.dy + c' #c' = y.dx - x.dy #c' = ys[i]*dx - xs[i]*dy #Now, at y = 0, x = -c' / dy dy = ys[i] - ys[j]; dx = xs[i] - xs[j] if dy == 0: continue #not a special case anymore # if dx == 0: # if xs[i] > n: # continue # else: # count_seen_from_x = len([x for x in xs if x == xs[i]]) # maxhits[xs[i]] = max(count_seen_from_x, maxhits[xs[i]]) else: slope = normalize_rational(dy,dx) c_prime = ys[i]*dx - xs[i]*dy x_intercept = -c_prime / dy line = (slope,x_intercept) if line in line_to_points: #print("line: ", line) #print("now: ", points) points = line_to_points[line] points.add(i); points.add(j) #print("after addition: ", points) continue #if (i == 1 and j == 2): # print(c_prime, x_intercept, dy, dx) if int(x_intercept) == x_intercept and x_intercept <= n and x_intercept > 0: points = set([i,j]) line_to_points[line] = points #maxhits[int(x_intercept)] = points # count_on_line = 2 # for k in range(m): # if k != i and k != j and ys[k] * dx == xs[k]*dy + c_prime: # count_on_line += 1 # maxhits[int(x_intercept)] = max(count_on_line, maxhits[int(x_intercept)]) for line,points in line_to_points.items(): x_intercept = int(line[1]) maxhits[x_intercept] = max(maxhits[x_intercept],len(points)) #print(maxhits) #print(sum([max(len(points),1) for points in maxhits]) - 1) print(sum(maxhits)) ```
230_C. Shifts
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100". Determine the minimum number of moves needed to make some table column consist only of numbers 1. Input The first line contains two space-separated integers: n (1 ≤ n ≤ 100) — the number of rows in the table and m (1 ≤ m ≤ 104) — the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1". Output Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1. Examples Input 3 6 101010 000100 100000 Output 3 Input 2 3 111 000 Output -1 Note In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s. In the second sample one can't shift the rows to get a column containing only 1s.
```python def solve(rows): all_dists = [0 for _ in range(len(rows[0]))] for r in rows: dists = [len(r) for _ in r] if '1' not in r: return -1 start = r.index('1') for i in range(len(r)): right = (i+start)%len(r) # going right left = (start+2*len(r)-i)%len(r) # going left dists[right] = 0 if r[right]=='1' else min(dists[right],dists[(i+start-1)%len(r)]+1) dists[left] = 0 if r[left]=='1' else min(dists[left],dists[(start+2*len(r)-i+1)%len(r)]+1) for i,c in enumerate(r): all_dists[i] += dists[i] return min(all_dists) if __name__ == "__main__": n,m = (int(i) for i in input().split()) rows = [input() for _ in range(n)] print(solve(rows)) ```
256_B. Mr. Bender and Square
Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy. We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on. For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1). In how many seconds will Mr. Bender get happy? Input The first line contains four space-separated integers n, x, y, c (1 ≤ n, c ≤ 109; 1 ≤ x, y ≤ n; c ≤ n2). Output In a single line print a single integer — the answer to the problem. Examples Input 6 4 3 1 Output 0 Input 9 3 8 10 Output 2 Note Initially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. <image>.
```python x, y, n, c = 0, 0, 0, 0 def suma_impares(m): return m * m def suma_n(m): return m * (m - 1) // 2 def cnt(t): u, d, l, r = x + t, x - t, y - t, y + t suma = t ** 2 + (t + 1) ** 2 if u > n: suma -= suma_impares(u - n) if d < 1: suma -= suma_impares(1 - d) if l < 1: suma -= suma_impares(1 - l) if r > n: suma -= suma_impares(r - n) if 1 - l > x - 1 and 1 - d > y - 1: suma += suma_n(2 - l - x) if r - n > x - 1 and 1 - d > n - y: suma += suma_n(r - n - x + 1) if 1 - l > n - x and u - n > y - 1: suma += suma_n(1 - l - n + x) if u - n > n - y and r - n > n - x: suma += suma_n(u - n - n + y) return suma n, x, y, c = input().split() n, x, y, c = int(n), int(x), int(y), int(c) #for i in range(10): # print(i, cnt(i)) ini, fin = 0, int(1e9) cont = int(1e9) while cont > 0: m = ini paso = cont // 2 m += paso if cnt(m) < c: ini = m + 1 cont -= paso + 1 else: cont = paso print(ini) ```
27_B. Tournament
The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a match with each other participant. The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «xi yi», where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws. Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value pj — the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life. It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game. Input The first line contains one integer n (3 ≤ n ≤ 50) — the number of participants. The following n·(n - 1) / 2 - 1 lines contain the results of the games. Each game is described in a single line by two integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi и yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n - 1 games, one game with each other participant. Output Output two integers x and y — the missing record. If there are several solutions, output any of them. Examples Input 4 4 2 4 1 2 3 2 1 3 1 Output 4 3
```python a = int(input()) d = {} f = {} for i in range(a*(a-1)//2-1): v, c = map(int, input().split()) if v not in f: f[v] = [] f[v].append(c) if v in d: d[v] += 1 else: d[v] = 1 if c in d: d[c] += 1 else: d[c] = 1 s = [] m = 0 for i in range(1, a + 1): if d[i] > m: m = d[i] for i in range(1, a + 1): if d[i] < m: s.append(i) m = 0 for i in range(1, a + 1): if i not in s: if s[0] in f and i in f and s[1] in f: if i in f[s[1]] and s[0] in f[i]: m = 1 s.reverse() break print(*s) ```
302_A. Eugeny and Array
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: * Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). * The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries. Input The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n). Output Print m integers — the responses to Eugene's queries in the order they occur in the input. Examples Input 2 3 1 -1 1 1 1 2 2 2 Output 0 1 0 Input 5 5 -1 1 1 1 -1 1 1 2 3 3 5 2 5 1 5 Output 0 1 0 1 0
```python from collections import Counter num, cases = map(int, input().split()) arr = list(map(int, input().split())) count = Counter(arr) minus = count[-1] plus = count[1] mn = min(plus, minus) ans = [] while cases: cases -= 1 a, b = map(int, input().split()) if (b - a + 1) % 2 != 0: ans.append(0) elif (b - a + 1) // 2 <= mn: ans.append(1) else: ans.append(0) print(*ans) ```
34_E. Collisions
On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored. The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds will be: <image>. Your task is to find out, where each ball will be t seconds after. Input The first line contains two integers n and t (1 ≤ n ≤ 10, 0 ≤ t ≤ 100) — amount of balls and duration of the process. Then follow n lines, each containing three integers: xi, vi, mi (1 ≤ |vi|, mi ≤ 100, |xi| ≤ 100) — coordinate, speed and weight of the ball with index i at time moment 0. It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;t]). Output Output n numbers — coordinates of the balls t seconds after. Output the numbers accurate to at least 4 digits after the decimal point. Examples Input 2 9 3 4 5 0 7 8 Output 68.538461538 44.538461538 Input 3 10 1 2 3 4 -5 6 7 -8 9 Output -93.666666667 -74.666666667 -15.666666667
```python class Ball: def __init__(self, x, v, m): self.v = v self.x = x self.m = m def move(self, time): self.x += self.v * time def collisionTime(self, other): if self.v == other.v: return float("inf") t = - (self.x - other.x) / (self.v - other.v) if t < 1e-9: return float("inf") return t def __str__(self): return "Ball(x={:.2f} v={:.2f} m={:.2f})".format(self.x, self.v, self.m) def findFirst(): global nBalls, balls minTime = float("inf") minPairs = [] for i in range(nBalls): for j in range(i + 1, nBalls): time = balls[i].collisionTime(balls[j]) if time < minTime: minTime = time minPairs = [(i, j)] elif abs(time - minTime) < 1e-9: minPairs.append((i, j)) return minTime, minPairs def collidePair(i, j): global balls v1 = balls[i].v v2 = balls[j].v m1 = balls[i].m m2 = balls[j].m balls[i].v = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2) balls[j].v = ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2) nBalls, maxTime = map(int, input().split()) balls = [] for i in range(nBalls): x, v, m = map(int, input().split()) balls.append(Ball(x, v, m)) while True: time, pairs = findFirst() if time > maxTime: break for i in range(nBalls): balls[i].move(time) # print(time, maxTime) for i, j in pairs: collidePair(i, j) # print(i, balls[i], j, balls[j]) # print() maxTime -= time for ball in balls: ball.move(maxTime) print("{:.6f}".format(ball.x)) ```
374_A. Inna and Pink Pony
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b. Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types: * move the candy from position (x, y) on the board to position (x - a, y - b); * move the candy from position (x, y) on the board to position (x + a, y - b); * move the candy from position (x, y) on the board to position (x - a, y + b); * move the candy from position (x, y) on the board to position (x + a, y + b). Naturally, Dima doesn't allow to move the candy beyond the chessboard borders. Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task! Input The first line of the input contains six integers n, m, i, j, a, b (1 ≤ n, m ≤ 106; 1 ≤ i ≤ n; 1 ≤ j ≤ m; 1 ≤ a, b ≤ 106). You can assume that the chessboard rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. Position (i, j) in the statement is a chessboard cell on the intersection of the i-th row and the j-th column. You can consider that the corners are: (1, m), (n, 1), (n, m), (1, 1). Output In a single line print a single integer — the minimum number of moves needed to get the candy. If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes. Examples Input 5 7 1 3 2 2 Output 2 Input 5 5 2 3 1 1 Output Poor Inna and pony! Note Note to sample 1: Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two.
```python n, m, i, j, a, b = map(int, input().split()) corners = [(1, 1), (1, m), (n, 1), (n, m)] result = False ans = -1 for cnt in corners: if (abs(cnt[0] - i) % a == 0) and (abs(cnt[1] - j) % b == 0): result = True t1, t2 = abs(cnt[0] - i) // a, abs(cnt[1] - j) // b if (t1 + t2) % 2 == 0: if ans == -1: ans = max(abs(cnt[0] - i) // a, abs(cnt[1] - j) // b) else: ans = min(max(abs(cnt[0] - i) // a, abs(cnt[1] - j) // b), ans) if ans == 0: print(ans) elif not result or (i+a > n and i-a < 1) or (j+b > m and j-b < 1) or ans == -1: print("Poor Inna and pony!") else: print(ans) ```
445_B. DZY Loves Chemistry
DZY loves chemistry, and he enjoys mixing chemicals. DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is. Find the maximum possible danger after pouring all the chemicals one by one in optimal order. Input The first line contains two space-separated integers n and m <image>. Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order. Output Print a single integer — the maximum possible danger. Examples Input 1 0 Output 1 Input 2 1 1 2 Output 2 Input 3 2 1 2 2 3 Output 4 Note In the first sample, there's only one way to pour, and the danger won't increase. In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2. In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).
```python def iterative_dfs(graph, start, path=[]): visited = {} for i in graph: visited[i] = [] q=[start] while q: v=q.pop(0) if not visited[v]: visited[v] = True path=path+[v] q=graph[v]+q return path nodes, edges = map(int, input().split(' ')) graph = {} for i in range(nodes): graph[i] = [] for i in range(edges): a, b = map(int, input().split(' ')) graph[a-1].append(b-1) graph[b-1].append(a-1) marked = [False] * nodes num = 0 for i in range(nodes): if not marked[i]: for j in iterative_dfs(graph, i): marked[j] = True num += 1 print(2**(nodes-num)) ```
467_C. George and Job
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work. Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum <image> is maximal possible. Help George to cope with the task. Input The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). Output Print an integer in a single line — the maximum possible value of sum. Examples Input 5 2 1 1 2 3 4 5 Output 9 Input 7 1 3 2 10 7 18 5 33 0 Output 61
```python n, m, k = list(map(int, input().split())) a = list(map(int, input().split())) p_a = [0 for _ in range(n)] p_a[0] = a[0] for i in range(1, n): p_a[i] = p_a[i - 1] + a[i] INF = -1e10 # print(p_a) dp = {} from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def solve(i, k, m): if (i, k, m) in dp: yield dp[(i, k, m)] if k == 0: dp[(i, k, m)] = 0 yield 0 if i + m == n: if k == 1: # print(p_a[n - 1] - p_a[i - 1]) if i==0: dp[(i, k, m)]=p_a[n - 1] else: dp[(i, k, m)] = p_a[n - 1] - p_a[i - 1] yield dp[(i, k, m)] if k > 1: dp[(i, k, m)] = INF yield INF if i + m > n - 1: dp[(i, k, m)] = INF yield INF if k == 0: dp[(i, k, m)] = 0 yield 0 if i == 0: a=yield solve(i + 1, k, m) b=yield solve(i + m, k - 1, m) dp[(i, k, m)] = max(a ,b+ p_a[i + m - 1]) yield dp[(i, k, m)] else: a = yield solve(i + 1, k, m) b=yield solve(i + m, k - 1, m) dp[(i, k, m)] = max(a, b+ p_a[i + m - 1] - p_a[i - 1]) yield dp[(i, k, m)] if m==1:print(sum(sorted(a)[n-k:])) else: print(solve(0, k, m)) ```
513_G1. Inversions problem
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. Input The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold. * In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold. * In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold. Output Output the answer with absolute or relative error no more than 1e - 9. Examples Input 3 1 1 2 3 Output 0.833333333333333 Input 3 4 1 3 2 Output 1.458333333333334 Note Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
```python n, k = map(int, input().split()) p = list(map(int, input().split())) def count_invs(a): ans = 0 for i in range(n-1): for j in range(i + 1, n): if a[i] > a[j]: ans += 1 return ans def inv_in_perms(a, count): if count > 0: ans = 0 for l in range(n): for r in range(l, n): a[l: r + 1] = a[l: r + 1][::-1] ans += inv_in_perms(a, count - 1) a[l: r + 1] = a[l: r + 1][::-1] return(ans) else: return(count_invs(a)) total = (n * (n + 1) // 2) ** k perms = 0 print(inv_in_perms(p, k) / total) ```
53_D. Physical Education
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves. Input The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets. Output In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1. Examples Input 4 1 2 3 2 3 2 1 2 Output 4 2 3 1 2 3 4 2 3 Input 2 1 100500 1 100500 Output 0
```python import sys n = int(sys.stdin.readline ()) a= [int (x) for x in sys.stdin.readline ().split ()] assert len(a) == n b = [int (x) for x in sys.stdin.readline ().split ()] assert len(b) == n ans = [] for i in range (n): j = i; while b[j] != a[i] : j += 1 while j > i: ans += [(j, j + 1)] b[j - 1], b[j] = b[j], b[j - 1] j -= 1 print (len(ans)) for p, q in ans: print (p, + q) ```
567_F. Mausoleum
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital. The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters. The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement: * [1, 2, 2, 3, 4, 4, 3, 1]; * [1, 1]; * [2, 2, 1, 1]; * [1, 2, 3, 3, 2, 1]. Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi. Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met. Input The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements. Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs. Output Print the sought number of ways. Examples Input 3 0 Output 9 Input 3 1 2 &gt; 3 Output 1 Input 4 1 3 = 6 Output 3
```python n,k = map(int,input().split()) n*=2 n+=2 l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n ok = 1 for i in range(k): a,c,b = input().split() a,b = int(a), int(b) if c=="=": if a==b: continue if (e[a] and e[a]!=b) or (e[b] and e[b]!=a): ok = 0 e[a], e[b] = b,a if c=="<": a,b,c = b,a,">" if c==">": l[a].append(b) if c=="<=": a,b,c = b,a,">=" if c==">=": le[a].append(b) def check(i, j, a, b): if e[a] and e[a]!=a and e[a]!=b: return 0 for x in l[a]: if x>i and x<j: return 0 for x in le[a]: if x>i and x<j and x!=a and x!=b: return 0 return 1 dp = [[0]*n for i in range(n)] dp[0][n-1] = 1 ans = 0 for i in range(n): for j in range(n-1,i,-1): if i+1==j: ans+=dp[i][j] elif ((i+j)%2)==1: if check(i,j,i+1,i+2) and check(i,j,i+2,i+1): dp[i+2][j]+=dp[i][j] if i+3<j and check(i,j,j-2,j-1) and check(i,j,j-1,j-2): dp[i][j-2]+=dp[i][j] if i+3<j and check(i,j,i+1,j-1) and check(i,j,j-1,i+1): dp[i+1][j-1]+=dp[i][j] print(ans if ok else 0) ```
630_O. Arrow
Petya has recently started working as a programmer in the IT city company that develops computer games. Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen. A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c. The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector. Enumerate the arrow points coordinates in counter-clockwise order starting from the tip. <image> Input The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx2 + vy2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c). Output Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9. Examples Input 8 8 0 2 8 3 4 5 Output 8.000000000000 11.000000000000 4.000000000000 8.000000000000 6.000000000000 8.000000000000 6.000000000000 3.000000000000 10.000000000000 3.000000000000 10.000000000000 8.000000000000 12.000000000000 8.000000000000
```python from math import atan2, pi EPS = 0.00000001 def eq(a, b): return abs(a - b) < EPS class Vector: def __init__(self, x2, y2, x1=0, y1=0): self.x = (x2 - x1) self.y = y2 - y1 self.s = (self.x ** 2 + self.y ** 2) ** 0.5 def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def mul_k(self, k): self.x *= k self.y *= k def mul_kk(self, k): return Vector(self.x * k, self.y * k) def rotate(self): return Vector(-self.y, self.x) def rotate2(self): return self.rotate().rotate().rotate() def reverseee(self): return Vector(-self.x, -self.y) def __mul__(self, other): return self.x * other.x + self.y * other.y def vectormul(self, other): return self.x * other.y - self.y * other.x def get_angle(self, other): return atan2(self.vectormul(other), self * other) def norm(self): if self.s == 0: return Vector(self.x, self.y) return Vector(self.x / self.s, self.y / self.s) def __str__(self): return f'{self.x} {self.y}' def middle(self, point): return Vector((self.x + point.x) / 2, (self.y + point.y) / 2) class Line: def __init__(self, point=None, vector=None, point2=None, a=None, b=None, c=None): if a is not None: self.v = Vector(a, b).rotate() self.p = Vector(a, b) self.p.mul_k(-c / (a ** 2 + b ** 2)) self.A = a self.B = b self.C = c return if vector is None: vector = point2 - point self.p = point self.v = vector self.A = self.v.y self.B = -self.v.x self.C = - self.A * self.p.x - self.p.y * self.B def get_abc(self): return self.A, self.B, self.C def __str__(self): return str(self.A) + ' ' + str(self.B) + ' ' + str(self.C) def check(self, point): return eq(- point.x * self.A - self.B * point.y, self.C) def get_s_from_point(self, point): v = self.v.norm() v2 = point - self.p a = v * v2 v.mul_k(a) v3 = v + self.p s = v3 - point return s.s def get_bisect(self, line): return Line(point=self.get_peresech(line)[1], vector=self.v.norm() + line.v.norm()) def get_proection(self, point): v = self.v.norm() v2 = point - self.p a = v * v2 v.mul_k(a) v3 = v + self.p return v3 def get_paral_line(self, le): v = self.v.norm().rotate() v.mul_k(le) return Line(point=self.p + v, vector=self.v) def get_peresech(self, lin): u = lin.v.rotate() a = self.v * u if eq(a, 0): if eq(self.get_s_from_point(lin.p), 0): return (2,) return (0,) t = ((lin.p - self.p) * u) / (self.v * u) v = Vector(self.v.x, self.v.y) v.mul_k(t) return (1, self.p + v) def get_mirror(self, point): v = self.v.norm() v2 = point - self.p a = v * v2 v.mul_k(a) v3 = v + self.p s = v3 - point return s + v3 def is_on_line(v1, v2): return eq(v1.vectormul(v2), 0) def is_on_luch(v1, v2): return eq(v1.get_angle(v2), 0) def is_on_otr(v1, v2, v3, v4): return eq(v1.get_angle(v2), 0) and eq(v3.get_angle(v4), 0) def get_s_from_luch(xp, yp, x1, y1, x2, y2): v = Vector(x2, y2, x1, y1).norm() v2 = Vector(xp, yp, x1, y1) a = v * v2 v1 = Vector(x2, y2, x1, y1) v.mul_k(a) v3 = v + Vector(x1, y1) xh, yh = v3.x, v3.y v4 = Vector(xh, yh, x1, y1) b = v1.get_angle(v4) if eq(b, 0): se = v3 - Vector(xp, yp) return se.s else: return (Vector(x1, y1) - Vector(xp, yp)).s def get_s_from_otr(xp, yp, x1, y1, x2, y2): return max(get_s_from_luch(xp, yp, x1, y1, x2, y2), get_s_from_luch(xp, yp, x2, y2, x1, y1)) def get_s_from_line(xp, yp, x1, y1, x2, y2): v = Vector(x2, y2, x1, y1).norm() v2 = Vector(xp, yp, x1, y1) a = v * v2 return a def peresec_otr(x1, y1, x2, y2, x3, y3, x4, y4): AB = Vector(x2, y2, x1, y1) CD = Vector(x4, y4, x3, y3) AC = Vector(x3, y3, x1, y1) AD = Vector(x4, y4, x1, y1) CA = Vector(x1, y1, x3, y3) CB = Vector(x2, y2, x3, y3) yg1 = AB.get_angle(AD) yg2 = AB.get_angle(AC) yg3 = CD.get_angle(CA) yg4 = CD.get_angle(CB) flag = False if (yg1 < 0 and yg2 < 0) or (yg1 > 0 and yg2 > 0): flag = True if (yg3 < 0 and yg4 < 0) or (yg3 > 0 and yg4 > 0): flag = True if max(min(x1, x2), min(x3, x4)) > min(max(x1, x2), max(x3, x4)): flag = True if max(min(y1, y2), min(y3, y4)) > min(max(y1, y2), max(y3, y4)): flag = True return not flag def get_s_from_otr_to_otr(x1, y1, x2, y2, x3, y3, x4, y4): if peresec_otr(x1, y1, x2, y2, x3, y3, x4, y4): return 0 return min(get_s_from_otr(x1, y1, x3, y3, x4, y4), get_s_from_otr(x2, y2, x3, y3, x4, y4), get_s_from_otr(x3, y3, x1, y1, x2, y2), get_s_from_otr(x4, y4, x1, y1, x2, y2)) def main(): px, py, vx, vy, a, b, c, d = map(int, input().split()) P = Vector(px, py) V = Vector(vx, vy).norm() A = V.mul_kk(b) + P B = V.mul_kk(a/2).rotate() + P C = V.mul_kk(c/2).rotate() + P D = C + V.rotate().rotate().mul_kk(d) E = D + V.rotate2().mul_kk(c) F = P + V.rotate2().mul_kk(c/2) G = P + V.rotate2().mul_kk(a/2) print(A, B, C, D, E, F, G, sep='\n') main() ```
659_G. Fence Divercity
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi. Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence). You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary. As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7). Input The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence. The second line contains n space-separated numbers h1, h2, ..., hn (1 ≤ hi ≤ 109), where hi equals the height of the i-th board to the left. Output Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good. Examples Input 2 1 1 Output 0 Input 3 3 4 2 Output 13 Note From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good. All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part): <image>
```python mod = 10 ** 9 + 7 n = int(input()) h = list(map(lambda x: int(x) - 1, input().split())) ans = x = 0 for i in range(n): ans += h[i] + min(h[i], h[i - 1]) * x if i < n - 1: x *= min(h[i - 1], h[i], h[i + 1]) x += min(h[i], h[i + 1]) ans %= mod x %= mod print(ans) ```
682_D. Alyona and Strings
After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants. Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions: * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty); * sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence. A substring of a string is a subsequence of consecutive characters of the string. Input In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters. Output In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists. Examples Input 3 2 2 abc ab Output 2 Input 9 12 4 bbaaababb abbbabbaaaba Output 7 Note The following image describes the answer for the second sample case: <image>
```python n, m, k = map(int, input().split()) s, t = input(), input() n += 1 m += 1 p = [i for i in range(n * m - n) if (i + 1) % n] r = p[::-1] d = [0] * n * m for i in p: if s[i % n] == t[i // n]: d[i] = d[i - n - 1] + 1 f = d[:] for y in range(k - 1): for i in p: f[i] = max(f[i], f[i - 1], f[i - n]) for i in r: f[i] = f[i - d[i] * (n + 1)] + d[i] print(max(f)) ```
705_C. Thor
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are about to happen (in chronological order). They are of three types: 1. Application x generates a notification (this new notification is unread). 2. Thor reads all notifications generated so far by application x (he may re-read some notifications). 3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone. Input The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typei — type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 ≤ typei ≤ 3, 1 ≤ xi ≤ n, 1 ≤ ti ≤ q). Output Print the number of unread notifications after each event. Examples Input 3 4 1 3 1 1 1 2 2 3 Output 1 2 3 2 Input 4 6 1 2 1 4 1 2 3 3 1 3 1 3 Output 1 2 3 0 1 2 Note In the first sample: 1. Application 3 generates a notification (there is 1 unread notification). 2. Application 1 generates a notification (there are 2 unread notifications). 3. Application 2 generates a notification (there are 3 unread notifications). 4. Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: 1. Application 2 generates a notification (there is 1 unread notification). 2. Application 4 generates a notification (there are 2 unread notifications). 3. Application 2 generates a notification (there are 3 unread notifications). 4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. 5. Application 3 generates a notification (there is 1 unread notification). 6. Application 3 generates a notification (there are 2 unread notifications).
```python import collections import copy n, q = map(int, input().split()) Q = collections.deque() A = n * [0] B = copy.copy(A) L = [] s = n = 0 for _ in range(q): y, x = map(int, input().split()) if 2 > y: x -= 1 Q.append(x) B[x] += 1 A[x] += 1 s += 1 elif 3 > y: x -= 1 s -= A[x] A[x] = 0 else: while x > n: n += 1 y = Q.popleft() B[y] -= 1 if B[y] < A[y]: A[y] -= 1 s -= 1 L.append(str(s)) print('\n'.join(L)) ```
749_A. Bachgold Problem
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k. Input The only line of the input contains a single integer n (2 ≤ n ≤ 100 000). Output The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them. Examples Input 5 Output 2 2 3 Input 6 Output 3 2 2 2
```python n=int(input()) c=0 if(n%2==1): n-=3 l=[2]*(n//2) l.append(3) print(len(l)) print(*l) else: l=[2]*(n//2) print(len(l)) print(*l) ```
817_B. Makes And The Product
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it! Input The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array. Output Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible. Examples Input 4 1 1 1 1 Output 4 Input 5 1 3 2 3 4 Output 2 Input 6 1 3 3 1 3 2 Output 1 Note In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4. In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2. In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
```python n=int(input()) a=list(map(int,(input().split(' ')))) a=sorted(a) a.append(0) ans=1 t=0 while a[3+t]==a[2]:t=t+1 if a[3]==a[0]:ans=(t+3)*(t+2)*(t+1)/6 elif a[3]==a[1]:ans=(t+2)*(t+1)/2 elif a[3]==a[2]:ans=t+1 print(int(ans)) ```
842_B. Gleb And Pizza
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi). Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust. Input First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage. Output Output the number of pieces of sausage that lay on the crust. Examples Input 8 4 7 7 8 1 -7 3 2 0 2 1 0 -2 2 -3 -3 1 0 6 2 5 3 1 Output 2 Input 10 8 4 0 0 9 0 0 10 1 0 1 1 0 2 Output 0 Note Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust. <image>
```python '''input 8 4 7 7 8 1 -7 3 2 0 2 1 0 -2 2 -3 -3 1 0 6 2 5 3 1 ''' r, d = map(int, input().split()) n = int(input()) c = 0 for _ in range(n): x, y, r1 = map(int, input().split()) s = (x**2 + y**2)**0.5 if r-d <= s-r1 and s+r1 <= r: c += 1 print(c) ```
863_B. Kayaking
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash. Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks. Help the party to determine minimum possible total instability! Input The first line contains one number n (2 ≤ n ≤ 50). The second line contains 2·n integer numbers w1, w2, ..., w2n, where wi is weight of person i (1 ≤ wi ≤ 1000). Output Print minimum possible total instability. Examples Input 2 1 2 3 4 Output 1 Input 4 1 3 4 6 3 4 100 200 Output 5
```python n = int(input()) n = 2*n w = [int(i) for i in input().split()] w.sort() import math res = math.inf for x in range(n): for y in range(x+1, n): wc = w[:] wc.pop(y); wc.pop(x) # print(wc) s = 0 for i in range(0, n-3, 2): s += wc[i+1]-wc[i] res = min(s, res) print(res) ```
888_F. Connecting Vertices
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly). But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid). How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 109 + 7. Input The first line contains one number n (3 ≤ n ≤ 500) — the number of marked points. Then n lines follow, each containing n elements. ai, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise ai, j = 0). It is guaranteed that for any pair of points ai, j = aj, i, and for any point ai, i = 0. Output Print the number of ways to connect points modulo 109 + 7. Examples Input 3 0 0 1 0 0 1 1 1 0 Output 1 Input 4 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 Output 12 Input 3 0 0 0 0 0 1 0 1 0 Output 0
```python import sys from array import array n = int(input()) edge = [list(map(int, input().split())) for _ in range(n)] mod = 10**9 + 7 dp_f = [array('i', [-1])*n for _ in range(n)] dp_g = [array('i', [-1])*n for _ in range(n)] for i in range(n): dp_f[i][i] = dp_g[i][i] = 1 for i in range(n-1): dp_f[i][i+1] = dp_g[i][i+1] = 1 if edge[i][i+1] else 0 def f(l, r): if dp_f[l][r] != -1: return dp_f[l][r] dp_f[l][r] = g(l, r) if edge[l][r] else 0 for m in range(l+1, r): if edge[l][m]: dp_f[l][r] = (dp_f[l][r] + g(l, m) * f(m, r)) % mod return dp_f[l][r] def g(l, r): if dp_g[l][r] != -1: return dp_g[l][r] dp_g[l][r] = f(l+1, r) for m in range(l+1, r): dp_g[l][r] = (dp_g[l][r] + f(l, m) * f(m+1, r)) % mod return dp_g[l][r] print(f(0, n-1)) ```
911_D. Inversion Counting
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3). You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2]. After each query you have to determine whether the number of inversions is odd or even. Input The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct. The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process. Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another. Output Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise. Examples Input 3 1 2 3 2 1 2 2 3 Output odd even Input 4 1 2 4 3 4 1 1 1 4 1 4 2 3 Output odd odd odd even Note The first example: 1. after the first query a = [2, 1, 3], inversion: (2, 1); 2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2). The second example: 1. a = [1, 2, 4, 3], inversion: (4, 3); 2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3); 3. a = [1, 2, 4, 3], inversion: (4, 3); 4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2).
```python def solve(): n=int(input()) a=list(map(int,input().split())) cl=['odd','even'] m=int(input()) ans=True b=[] ap=b.append for i in range(n): for j in range(i): if a[j]>a[i]: ans=not ans for i in range(m): left,right=map(int,input().split()) if ((right-left+1)//2)%2 == 1: ans=not ans ap(cl[ans]) print('\n'.join(b)) solve() ```
933_B. A Determined Cleanup
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients). Input The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 1018, 2 ≤ k ≤ 2 000). Output If the polynomial does not exist, print a single integer -1, or output two lines otherwise. In the first line print a non-negative integer d — the number of coefficients in the polynomial. In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial <image> fulfilling the given requirements. Your output should satisfy 0 ≤ ai < k for all 0 ≤ i ≤ d - 1, and ad - 1 ≠ 0. If there are many possible solutions, print any of them. Examples Input 46 2 Output 7 0 1 0 0 1 1 1 Input 2018 214 Output 3 92 205 1 Note In the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)·(x + 2) + 46. In the second example, f(x) = x2 + 205x + 92 = (x - 9)·(x + 214) + 2018.
```python s = input() # s = '46 2' p, k = list(map(int, s.split())) res = [] f = True while p != 0: if f: n = p % k m = (p - n) // k f = False else: n = (-p) % k m = (p + n) // k f = True res.append(n) p = m print(len(res)) print(' '.join(list(map(str, res)))) ```
987_B. High School: Become Human
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≤ x, y ≤ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 = 390625, and 8^5 = 8 ⋅ 8 ⋅ 8 ⋅ 8 ⋅ 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
```python import math x,y=map(lambda x:math.log(int(x))/int(x),input().split()) print('<=>'[(x>=y)+(x>y)]) ```
p02588 AtCoder Grand Contest 047 - Integer Product
You are given N real values A_1, A_2, \ldots, A_N. Compute the number of pairs of indices (i, j) such that i < j and the product A_i \cdot A_j is integer. Constraints * 2 \leq N \leq 200\,000 * 0 < A_i < 10^4 * A_i is given with at most 9 digits after the decimal. Input Input is given from Standard Input in the following format. N A_1 A_2 \vdots A_N Output Print the number of pairs with integer product A_i \cdot A_j (and i < j). Examples Input 5 7.5 2.4 17.000000001 17 16.000000000 Output 3 Input 11 0.9 1 1 1.25 2.30000 5 70 0.000000001 9999.999999999 0.999999999 1.000000001 Output 8
```python import collections N=int(input()) A=[] PRECISION_DIGITS=9 cnt=collections.defaultdict(int) for n in range(N): tmpA = float(input()) tmpA = round(tmpA*10**PRECISION_DIGITS) #print(tmpA) five = 0 two = 0 while (tmpA % 2) == 0: two += 1 tmpA //= 2 while (tmpA % 5) == 0: five += 1 tmpA //= 5 # (10**9) -> (two,five)=(9,9) two -= PRECISION_DIGITS five -= PRECISION_DIGITS cnt[(two,five)]+=1 # print(cnt) ans = 0 for t1, cnt1 in cnt.items(): for t2, cnt2 in cnt.items(): # 2**a(a>=0) and 5**b(b>=0) => integer if 0 <= t1[0]+t2[0] and 0 <= t1[1]+t2[1]: if t1 < t2: ans += int(cnt1*cnt2) elif t1 == t2: # same entry # Total number of combinations choose 2 items # nC2 = n*(n-1)/2 ans += int((cnt1*(cnt2-1))/2) print(ans) ```
p02719 AtCoder Beginner Contest 161 - Replacing Integer
Given any integer x, Aoki can do the operation below. Operation: Replace x with the absolute difference of x and K. You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times. Constraints * 0 ≤ N ≤ 10^{18} * 1 ≤ K ≤ 10^{18} * All values in input are integers. Input Input is given from Standard Input in the following format: N K Output Print the minimum possible value taken by N after Aoki does the operation zero or more times. Examples Input 7 4 Output 1 Input 2 6 Output 2 Input 1000000000000000000 1 Output 0
```python n,k= map(int,input().split()) a=n%k b=abs(k-a) print(min(a,b)) ```
p02848 AtCoder Beginner Contest 146 - ROT N
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given. Shift each character of S by N in alphabetical order (see below), and print the resulting string. We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` by 3 results in `B` (`Y` \to `Z` \to `A` \to `B`). Constraints * 0 \leq N \leq 26 * 1 \leq |S| \leq 10^4 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: N S Output Print the string resulting from shifting each character of S by N in alphabetical order. Examples Input 2 ABCXYZ Output CDEZAB Input 0 ABCXYZ Output ABCXYZ Input 13 ABCDEFGHIJKLMNOPQRSTUVWXYZ Output NOPQRSTUVWXYZABCDEFGHIJKLM
```python N = int(input()) S = input() print(''.join(chr((ord(c) - ord('A') + N) % 26 + ord('A')) for c in S)) ```
p02986 AtCoder Beginner Contest 133 - Colorful Tree
There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors. Answer the following Q queries: * Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.) Constraints * 2 \leq N \leq 10^5 * 1 \leq Q \leq 10^5 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq N-1 * 1 \leq d_i \leq 10^4 * 1 \leq x_j \leq N-1 * 1 \leq y_j \leq 10^4 * 1 \leq u_j < v_j \leq N * The given graph is a tree. * All values in input are integers. Input Input is given from Standard Input in the following format: N Q a_1 b_1 c_1 d_1 : a_{N-1} b_{N-1} c_{N-1} d_{N-1} x_1 y_1 u_1 v_1 : x_Q y_Q u_Q v_Q Output Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j. Example Input 5 3 1 2 1 10 1 3 2 20 2 4 4 30 5 2 1 40 1 100 1 4 1 100 1 5 3 1000 3 4 Output 130 200 60
```python import sys input=sys.stdin.readline sys.setrecursionlimit(10**9) class LCA: def __init__(self,V,edges,depth,parent,root=0): self.edges=edges self.maxLog=18 self.parent=[[-1]*V for _ in range(self.maxLog+1)] self.parent[0]=parent self.depth=depth for i in range(self.maxLog): for j in range(V): if self.parent[i][j]!=-1: self.parent[i+1][j]=self.parent[i][self.parent[i][j]] def lca(self,a,b): if self.depth[a]>self.depth[b]: a,b=b,a for i in range(self.maxLog): if (self.depth[b]-self.depth[a])&(1<<i): b=self.parent[i][b] if a==b: return b for i in reversed(range(self.maxLog-1)): if self.parent[i][a]!=self.parent[i][b]: a=self.parent[i][a] b=self.parent[i][b] return self.parent[0][a] from collections import deque def Eulertour(Edges,n,root=0): Euler=[] Depth=[-1]*n Depth[root]=0 Parent=[-1]*n que=deque([root]) que2=deque() Visited=[False]*n while que: fr=que.pop() Euler.append((Depth[fr],fr)) if Visited[fr]: continue for to in Edges[fr]: if Visited[to]: que.append(to) else: Depth[to]=Depth[fr]+1 Parent[to]=fr que2.append(to) que.extend(que2) que2=deque() Visited[fr]=True return Euler,Depth,Parent n,q=map(int,input().split()) Edgedict=[dict() for _ in range(n)] for _ in range(n-1): a,b,c,d=map(int,input().split()) a-=1; b-=1 Edgedict[a][b]=(c,d) Edgedict[b][a]=(c,d) Queries=[tuple(map(int,input().split())) for _ in range(q)] Euler,Depth,Parent=Eulertour(Edgedict,n) lca=LCA(n,Edgedict,Depth,Parent) Q=[[] for _ in range(n)] for i,(x,y,u,v) in enumerate(Queries): u-=1; v-=1 Q[u].append([i,x,y,True]) Q[v].append([i,x,y,True]) Q[lca.lca(u,v)].append([i,x,y,False]) Ans=[0]*q dist=0 C_len=[0]*n C_cnt=[0]*n for i in range(1,len(Euler)): idx=Euler[i][1] c,l=Edgedict[Euler[i-1][1]][idx] if Euler[i-1][0]<Euler[i][0]: dist+=l C_len[c]+=l C_cnt[c]+=1 for q_idx,x,y,flag in Q[idx]: if flag: Ans[q_idx]+=dist+C_cnt[x]*y-C_len[x] else: Ans[q_idx]-=(dist+C_cnt[x]*y-C_len[x])*2 else: dist-=l C_len[c]-=l C_cnt[c]-=1 print(*Ans,sep='\n') ```
p03127 AtCoder Beginner Contest 118 - Monsters Battle Royale
There are N monsters, numbered 1, 2, ..., N. Initially, the health of Monster i is A_i. Below, a monster with at least 1 health is called alive. Until there is only one alive monster, the following is repeated: * A random alive monster attacks another random alive monster. * As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking. Find the minimum possible final health of the last monster alive. Constraints * All values in input are integers. * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 Input Input is given from Standard Input in the following format: N A_1 A_2 ... A_N Output Print the minimum possible final health of the last monster alive. Examples Input 4 2 10 8 40 Output 2 Input 4 5 13 8 1000000000 Output 1 Input 3 1000000000 1000000000 1000000000 Output 1000000000
```python from fractions import gcd from functools import reduce n, *A = map(int, open(0).read().split()) print(reduce(gcd, A)) ```
p03270 AtCoder Regular Contest 102 - Stop. Otherwise...
Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable. For each i=2,3,...,2K, find the following value modulo 998244353: * The number of combinations of N sides shown by the dice such that the sum of no two different sides is i. Note that the dice are NOT distinguishable, that is, two combinations are considered different when there exists an integer k such that the number of dice showing k is different in those two. Constraints * 1 \leq K \leq 2000 * 2 \leq N \leq 2000 * K and N are integers. Input Input is given from Standard Input in the following format: K N Output Print 2K-1 integers. The t-th of them (1\leq t\leq 2K-1) should be the answer for i=t+1. Examples Input 3 3 Output 7 7 4 7 7 Input 4 5 Output 36 36 20 20 20 36 36 Input 6 1000 Output 149393349 149393349 668669001 668669001 4000002 4000002 4000002 668669001 668669001 149393349 149393349
```python from sys import exit, setrecursionlimit, stderr from functools import reduce from itertools import * from collections import defaultdict from bisect import bisect def read(): return int(input()) def reads(): return [int(x) for x in input().split()] K, N = reads() MOD = 998244353 MAXN = 4020 fact = [1] * MAXN for i in range(1, MAXN): fact[i] = (fact[i-1] * i) % MOD invfact = [0] * MAXN; invfact[-1] = pow(fact[-1], MOD-2, MOD) for i in range(MAXN-2, -1, -1): invfact[i] = invfact[i+1] * (i+1) % MOD def comb(n, k): return fact[n] * invfact[n-k] * invfact[k] % MOD if 0 <= k <= n else 0 def h(n, k): return comb(n+k-1, n) def solve(n, k, u): ans = 0 for q in range(u+1): ans = (ans + comb(u, q) * pow(2, u-q, MOD) % MOD * h(n-u+q, k-q-u)) % MOD return ans anss = [0] * (2*K+1) for i in range(2, K+2): u = sum(j < i-j <= K for j in range(1, K+1)) if i % 2 == 1: ans = solve(N, K, u) else: ans = (solve(N, K-1, u) + solve(N-1, K-1, u)) % MOD anss[i] = ans print(ans) for j in range(K+2, 2*K+1): print(anss[2*K - j + 2]) ```
p03427 AtCoder Grand Contest 021 - Digit Sum 2
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N. Constraints * 1\leq N \leq 10^{16} * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N. Examples Input 100 Output 18 Input 9995 Output 35 Input 3141592653589793 Output 137
```python N=input() NL=len(N) if N[1:]=='9'*(NL-1): ans=int(N[0])+9*(NL-1) else: ans=int(N[0])+9*(NL-1)-1 print(ans) ```
p03585 Tenka1 Programmer Contest - CARtesian Coodinate
There are N lines in the xy-plane. The i-th line is represented by A_ix+B_iy=C_i. Any two lines among the N+2 lines, the above N lines plus the x-axis and y-axis, cross each other at exactly one point. For each pair 1 \leq i < j \leq N, there is a car at the cross point of the i-th and j-th lines. Even where three or more lines intersect at a point, a car is individually placed for each pair of lines. That is, there will be k(k-1)/2 cars placed at the intersection of k lines. Those cars are already very old, and can only be moved parallel to the x-axis or y-axis. Takahashi will hold an exhibition of antique cars at a place on the xy-plane. In order to avoid damaging the half-broken cars too much, he will select the place of the exhibition so that the total distance covered will be minimized when all the cars are moved to the place. If such a place is not uniquely determined, among the places that satisfy the condition above, the place with the minimum x-coordinate will be selected. If the place is still not uniquely determined, among the places that satisfy the two conditions above, the place with the minimum y-coordinate will be selected. Find the place of the exhibition that will be selected. Constraints * 2 \leq N \leq 4 × 10^4 * 1 \leq |A_i|,|B_i| \leq 10^4(1 \leq i \leq N) * 0 \leq |C_i| \leq 10^4(1 \leq i \leq N) * No two given lines are parallel. * All input values are integers. Inputs Input is given from Standard Input in the following format: N A_1 B_1 C_1 : A_N B_N C_N Outputs Print the x-coordinate and y-coordinate of the place of the exhibition that will be selected, in this order, with a space in between. The output will be judged as correct when the absolute or relative error is at most 10^{-9}. Examples Input 3 1 1 1 2 -1 2 -1 2 2 Output 1.000000000000000 1.000000000000000 Input 4 1 1 2 1 -1 0 3 -1 -2 1 -3 4 Output -1.000000000000000 -1.000000000000000 Input 7 1 7 8 -2 4 9 3 -8 -5 9 2 -14 6 7 5 -8 -9 3 3 8 10 Output -1.722222222222222 1.325000000000000
```python def addbit(i): i += 1 while i <= N: BIT[i] += 1 i += i & (-i) def getsum(i): ret = 0 i += 1 while i != 0: ret += BIT[i] i -= i&(-i) return ret def bit(L): global BIT BIT=[0] * (N+1) re = 0 for l in L: re += getsum(l) addbit(l) return N*(N-1)//2 - re def get_rank(L): D = {x:i for i,x in enumerate(sorted(L))} return [D[x] for x in L] def calc(Z): Z.sort() l, r = -1<<28, 1<<28 while (r - l) / max(abs(l), 1) > 0.000000001: m = (l+r)/2 A = get_rank([s*m+t for s, t in Z]) c = bit(A) if c > N*(N-1)//4: l = m else: r = m return l N = int(input()) X, Y = [], [] for _ in range(N): a, b, c = map(int, input().split()) X.append((-a/b, c/b)) Y.append((-b/a, c/a)) print(calc(X), calc(Y)) ```
p03743 AtCoder Regular Contest 072 - Alice in linear land
Alice lives on a line. Today, she will travel to some place in a mysterious vehicle. Initially, the distance between Alice and her destination is D. When she input a number x to the vehicle, it will travel in the direction of the destination by a distance of x if this move would shorten the distance between the vehicle and the destination, and it will stay at its position otherwise. Note that the vehicle may go past the destination when the distance between the vehicle and the destination is less than x. Alice made a list of N numbers. The i-th number in this list is d_i. She will insert these numbers to the vehicle one by one. However, a mischievous witch appeared. She is thinking of rewriting one number in the list so that Alice will not reach the destination after N moves. She has Q plans to do this, as follows: * Rewrite only the q_i-th number in the list with some integer so that Alice will not reach the destination. Write a program to determine whether each plan is feasible. Constraints * 1≤ N ≤ 5*10^5 * 1≤ Q ≤ 5*10^5 * 1≤ D ≤ 10^9 * 1≤ d_i ≤ 10^9(1≤i≤N) * 1≤ q_i ≤ N(1≤i≤Q) * D and each d_i are integers. Input Input is given from Standard Input in the following format: N D d_1 d_2 ... d_N Q q_1 q_2 ... q_Q Output Print Q lines. The i-th line should contain `YES` if the i-th plan is feasible, and `NO` otherwise. Examples Input 4 10 3 4 3 3 2 4 3 Output NO YES Input 5 9 4 4 2 3 2 5 1 4 2 3 5 Output YES YES YES YES YES Input 6 15 4 3 5 4 2 1 6 1 2 3 4 5 6 Output NO NO YES NO NO YES
```python N, D = map(int, input().split()) d = list(map(int, input().split())) Q = int(input()) q = list(map(lambda x : int(x)-1 , input().split())) dis = [0 for i in range(N+1)] dis[0] = D for i in range(N): dis[i+1] = min(dis[i], abs(dis[i] - d[i])) dp = [0 for i in range(N+1)] dp[N] = 1 for i in range(N-1, -1, -1): if d[i] // 2 >= dp[i+1]: dp[i] = dp[i+1] else: dp[i] = dp[i+1] + d[i] for qi in range(Q): print(["YES", "NO"][dis[q[ qi ]] < dp[q[ qi ] + 1]]) ```
p03903 CODE FESTIVAL 2016 Elimination Tournament Round 1 (Parallel) - Graph
Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i. He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges. For each round, find the minimum possible total weight of the edges chosen by Takahashi. Constraints * 1 ≦ N ≦ 4,000 * 1 ≦ M ≦ 400,000 * 1 ≦ Q ≦ 100,000 * 1 ≦ a_i,b_i,S_i,T_i ≦ N * 1 ≦ c_i ≦ 10^{9} * a_i \neq b_i * S_i \neq T_i * The given graph is connected. Input The input is given from Standard Input in the following format: N M a_1 b_1 c_1 a_2 b_2 c_2 : a_M b_M c_M Q S_1 T_1 S_2 T_2 : S_Q T_Q Output Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi. Examples Input 4 3 1 2 3 2 3 4 3 4 5 2 2 3 1 4 Output 8 7 Input 4 6 1 3 5 4 1 10 2 4 6 3 2 2 3 4 5 2 1 3 1 2 3 Output 8
```python from collections import deque import sys sys.setrecursionlimit(10**5) N, M = map(int, input().split()) E = [] for i in range(M): a, b, c = map(int, input().split()) E.append((c, a-1, b-1)) E.sort() *p, = range(N) def root(x): if x == p[x]: return x p[x] = y = root(p[x]) return y L = 2*N-1 G = [[]] * L C = [0]*L *lb, = range(N) cur = N s = 0 for c, a, b in E: pa = root(a); pb = root(b) if pa == pb: continue s += c chds = [lb[pa], lb[pb]] if pa < pb: p[pb] = pa lb[pa] = cur else: p[pa] = pb lb[pb] = cur C[cur] = c G[cur] = chds cur += 1 H = [0]*L prv = [-1]*L def dfs(v): s = 1; heavy = -1; m = 0 for w in G[v]: prv[w] = v c = dfs(w) if m < c: heavy = w m = c s += c H[v] = heavy return s dfs(L-1) SS = [] D = [] LB = [0]*L I = [0]*L que = deque([(L-1, 0)]) while que: v, d = que.popleft() S = [] k = len(SS) while v != -1: I[v] = len(S) S.append(v) LB[v] = k h = H[v] for w in G[v]: if h == w: continue que.append((w, d+1)) v = h SS.append(S) D.append(d) def query(u, v): lu = LB[u]; lv = LB[v] dd = D[lv] - D[lu] if dd < 0: lu, lv = lv, lu v, u = u, v dd = -dd for _ in range(dd): v = prv[SS[lv][0]] lv = LB[v] while lu != lv: u = prv[SS[lu][0]] lu = LB[u] v = prv[SS[lv][0]] lv = LB[v] return u if I[u] < I[v] else v def gen(): Q = int(input()) for i in range(Q): u, v = map(int, input().split()) w = query(u-1, v-1) yield "%d\n" % (s - C[w]) ans = list(gen()) sys.stdout.writelines(ans) ```
p00009 Prime Number
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7. Input Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line. The number of datasets is less than or equal to 30. Output For each dataset, prints the number of prime numbers. Example Input 10 3 11 Output 4 2 5
```python import sys import math LIMIT = 1000000 p = 2 pList = [True] * (LIMIT + 1) while p ** 2 <= LIMIT: if(pList[p]): for i in range(p * 2, LIMIT + 1 , p): pList[i] = False p += 1 # print(pList) lines = str(sys.stdin.read()).strip().split("\n") for line in lines: line = int(line) count = 0 for i in range(2, line + 1): if pList[i]: count += 1 print(count) ```
p00141 Spiral Pattern
I decided to create a program that displays a "round and round pattern". The "round and round pattern" is as follows. * If the length of one side is n, it is displayed as a character string with n rows and n columns. * A spiral pattern that rotates clockwise with the lower left corner as the base point. * The part with a line is represented by # (half-width sharp), and the blank part is represented by "" (half-width blank). * Leave a space between the lines. Create a program that takes an integer n as an input and outputs a "round and round pattern" with a side length of n. Input The input is given in the following format: d n1 n2 :: nd The number of datasets d (d ≤ 20) is given to the first line, and the side length ni (1 ≤ ni ≤ 100) of the i-th round pattern is given to each of the following d lines. Output Please output a round and round pattern for each data set. Insert a blank line between the datasets. Example Input 2 5 6 Output ##### # # # # # # # # # ### ###### # # # ## # # # # # # # # ####
```python vector = ((0, -1), (1, 0), (0, 1), (-1, 0)) def make_guruguru(d): lst = [["#"] * (d + 4)] for _ in range(d + 2): lst.append(["#"] + [" "] * (d + 2) + ["#"]) lst.append(["#"] * (d + 4)) x, y = 2, d + 1 lst[y][x] = "#" direct = 0 vx, vy = vector[0] cnt = 1 while True: while lst[y + vy * 2][x + vx * 2] == " ": lst[y + vy][x + vx] = "#" y += vy x += vx cnt += 1 if cnt <= 1: break direct = (direct + 1) % 4 vx, vy = vector[direct] cnt = 0 for y in range(2, d + 2): print("".join(lst[y][2:-2])) n = int(input()) make_guruguru(int(input())) for _ in range(n - 1): print() make_guruguru(int(input())) ```
p00274 A Pair of Prizes
Jou and Yae are a good couple. Jou is collecting prizes for capsule toy vending machines (Gachapon), and even when they go out together, when they find Gachapon, they seem to get so hot that they try it several times. Yae was just looking at Jou, who looked happy, but decided to give him a Gachapon prize for his upcoming birthday present. Yae wasn't very interested in Gachapon itself, but hopefully he would like a match with Jou. For Gachapon that Yae wants to try, one prize will be given in one challenge. You can see how many types of prizes there are, including those that are out of stock, and how many of each prize remains. However, I don't know which prize will be given in one challenge. Therefore, regardless of the order in which the prizes are given, create a program that outputs the minimum number of challenges required for Yae to get two of the same prizes. input The input consists of multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: N k1 k2 ... kN Each dataset has two lines, and the first line is given the integer N (1 ≤ N ≤ 10000), which indicates how many types of prizes there are. The next line is given the integer ki (0 ≤ ki ≤ 10000), which indicates how many prizes are left. The number of datasets does not exceed 100. output For each dataset, the minimum number of challenges required to get two identical prizes is output. However, if it is not possible, NA is output. Example Input 2 3 2 3 0 1 1 1 1000 0 Output 3 NA 2
```python # AOJ 0279: A Pair of Prizes # Python3 2018.6.25 bal4u while True: n = int(input()) if n == 0: break k = list(map(int, input().split())) one, many = 0, 0 for i in k: if i == 1: one += 1 elif i > 1: many += 1 print(one+many+1 if many > 0 else "NA") ```
p00462 Pizza
problem JOI Pizza sells pizza home delivery along the d-meter-long ring road that runs through the city center. JOI Pizza has n stores S1, ..., Sn on the loop line. The head office is S1. The distance from S1 to Si when moving the loop line clockwise is set to di meters. D2 , ..., dn is an integer greater than or equal to 1 and less than or equal to d -1. D2, ..., dn are all different. Bake and deliver pizza at the shortest store. The location of the delivery destination is represented by an integer k that is greater than or equal to 0 and less than or equal to d -1. This means that the distance from the head office S1 to the delivery destination in the clockwise direction is k meters. Pizza delivery is done along the loop line and no other road is allowed. However, the loop line may move clockwise or counterclockwise. For example, if the location of the store and the location of the delivery destination are as shown in the figure below (this example corresponds to Example 1 of "I / O example"). <image> The store closest to the delivery destination 1 is S2, so the delivery is from store S2. At this time, the distance traveled from the store is 1. Also, the store closest to delivery destination 2 is S1 (main store), so store S1 (main store). ) To deliver to home. At this time, the distance traveled from the store is 2. Total length of the loop line d, Number of JOI pizza stores n, Number of orders m, N --1 integer representing a location other than the main store d2, ..., dn, Integer k1, .. representing the location of the delivery destination Given ., km, create a program to find the sum of all orders for each order by the distance traveled during delivery (ie, the distance from the nearest store to the delivery destination). input The input consists of multiple datasets. Each dataset is given in the following format. The first line is a positive integer d (2 ≤ d ≤ 1000000000 = 109) that represents the total length of the loop line, the second line is a positive integer n (2 ≤ n ≤ 100000) that represents the number of stores, and the third line is A positive integer m (1 ≤ m ≤ 10000) is written to represent the number of orders. The n --1 lines after the 4th line are integers d2, d3, ..., dn that represent the location of stores other than the main store. (1 ≤ di ≤ d -1) is written in this order, and the integers k1, k2, ..., km (0 ≤ ki ≤ d) representing the delivery destination location are in the m lines after the n + 3rd line. --1) are written in this order. Of the scoring data, for 40% of the points, n ≤ 10000 is satisfied. For 40% of the points, the total distance traveled and the value of d are both 1000000 or less. In the scoring data, the total distance traveled is 1000000000 = 109 or less. When d is 0, it indicates the end of input. The number of data sets does not exceed 10. output For each data set, one integer representing the total distance traveled during delivery is output on one line. Examples Input 8 3 2 3 1 4 6 20 4 4 12 8 16 7 7 11 8 0 Output 3 3 Input None Output None
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0539 AC """ import sys from sys import stdin from bisect import bisect_right input = stdin.readline def main(args): while True: d = int(input()) # ??°??¶???????????? if d == 0: break n = int(input()) # ??¬????????????????????° m = int(input()) # ??¨????????° cw_pos = [int(input()) for _ in range(n-1)] dests = [int(input()) for _ in range(m)] cw_pos.append(0) # ??¬???????????? cw_pos.append(d) # ??°??¶??????1??¨??????????????¬????????????(??????) cw_pos.sort() # ccw_pos = [d-x for x in cw_pos] # ??°??¶?????????????????£???????????????????????? # ccw_pos.sort() total_distance = 0 for t in dests: if t == 0: # ?????????????????????0?????\??£????????????bisect_right?????¨????????????????????§?????? continue i = bisect_right(cw_pos, t) # ????¨?????????§?????????????????? a1 = min(t-cw_pos[i-1], cw_pos[i]-t) # ?????????????????????????????¢ # j = bisect_right(ccw_pos, d-t) # ???????¨?????????§???????????¨????????? # a2 = min(d-t-ccw_pos[j-1], ccw_pos[j]-(d-t)) # ans = min(a1, a2) total_distance += a1 # ?????????????????????????????°OK print(total_distance) if __name__ == '__main__': main(sys.argv[1:]) ```
p00652 Cutting a Chocolate
Turtle Shi-ta and turtle Be-ko decided to divide a chocolate. The shape of the chocolate is rectangle. The corners of the chocolate are put on (0,0), (w,0), (w,h) and (0,h). The chocolate has lines for cutting. They cut the chocolate only along some of these lines. The lines are expressed as follows. There are m points on the line connected between (0,0) and (0,h), and between (w,0) and (w,h). Each i-th point, ordered by y value (i = 0 then y =0), is connected as cutting line. These lines do not share any point where 0 < x < w . They can share points where x = 0 or x = w . However, (0, li ) = (0,lj ) and (w,ri ) = (w,rj ) implies i = j . The following figure shows the example of the chocolate. <image> There are n special almonds, so delicious but high in calories on the chocolate. Almonds are circle but their radius is too small. You can ignore radius of almonds. The position of almond is expressed as (x,y) coordinate. Two turtles are so selfish. Both of them have requirement for cutting. Shi-ta's requirement is that the piece for her is continuous. It is possible for her that she cannot get any chocolate. Assume that the minimum index of the piece is i and the maximum is k . She must have all pieces between i and k . For example, chocolate piece 1,2,3 is continuous but 1,3 or 0,2,4 is not continuous. Be-ko requires that the area of her chocolate is at least S . She is worry about her weight. So she wants the number of almond on her chocolate is as few as possible. They doesn't want to make remainder of the chocolate because the chocolate is expensive. Your task is to compute the minumum number of Beko's almonds if both of their requirment are satisfied. Input Input consists of multiple test cases. Each dataset is given in the following format. n m w h S l0 r0 ... lm-1 rm-1 x0 y0 ... xn-1 yn-1 The last line contains five 0s. n is the number of almonds. m is the number of lines. w is the width of the chocolate. h is the height of the chocolate. S is the area that Be-ko wants to eat. Input is integer except xi yi. Input satisfies following constraints. 1 ≤ n ≤ 30000 1 ≤ m ≤ 30000 1 ≤ w ≤ 200 1 ≤ h ≤ 1000000 0 ≤ S ≤ w*h If i < j then li ≤ lj and ri ≤ rj and then i -th lines and j -th lines share at most 1 point. It is assured that lm-1 and rm-1 are h. xi yi is floating point number with ten digits. It is assured that they are inside of the chocolate. It is assured that the distance between points and any lines is at least 0.00001. Output You should output the minumum number of almonds for Be-ko. Example Input 2 3 10 10 50 3 3 6 6 10 10 4.0000000000 4.0000000000 7.0000000000 7.0000000000 2 3 10 10 70 3 3 6 6 10 10 4.0000000000 4.0000000000 7.0000000000 7.0000000000 2 3 10 10 30 3 3 6 6 10 10 4.0000000000 4.0000000000 7.0000000000 7.0000000000 2 3 10 10 40 3 3 6 6 10 10 4.0000000000 4.0000000000 7.0000000000 7.0000000000 2 3 10 10 100 3 3 6 6 10 10 4.0000000000 4.0000000000 7.0000000000 7.0000000000 0 0 0 0 0 Output 1 1 0 1 2
```python # AOJ 1067 Cutting a Chocolate # Python3 2018.7.10 bal4u from bisect import bisect_left while True: n, m, w, h, S = map(int, input().split()) if n == 0: break m, wh2 = m+1, 2*(w*h) S = wh2-2*S tbl, s = [[0,0,0,0]], [0] for i in range(1, m): l, r = map(int, input().split()) tbl.append([l, r, 0, r-l]) s.append((l+r)*w) p = [] for i in range(n): x, y = map(float, input().split()) p.append((x, y)) p.sort(key=lambda x:(x[1],x[0])) j = 1 for i in range(n): x, y = p[i] while True: y1 = tbl[j-1][3]*x/w + tbl[j-1][0] y2 = tbl[j ][3]*x/w + tbl[j ][0] if y1 < y: if y < y2: break j += 1 else: j -= 1 tbl[j][2] += 1 for i in range(1, m): tbl[i][2] += tbl[i-1][2] if S == 0: print(n) continue elif S == wh2: print(0) continue j = bisect_left(s, S, 0, m) if s[j] != S: j -= 1 ans, i = tbl[j][2], 1 while j+1 < m: j += 1 while s[j]-s[i] > S: i += 1 ans = max(ans, tbl[j][2]-tbl[i][2]) print(n - ans) ```
p00928 Automotive Navigation
Example Input 4 2 1 1 1 1 1 2 2 2 2 1 2 2 1 2 1 1 2 1 9 N Output 1 1 2 2
```python # coding: utf-8 import sys sys.setrecursionlimit(50000000) max_c=101 vec=[(0,2),(2,0),(0,-2),(-2,0)] try: while True: log=[-1 for i in range(10001)] n,x0,y0,t=map(int,input().split()) field=[[0 for i in range(max_c)]for i in range(max_c)] for i in range(n): a,b,c,d=map(lambda x:int(x)*2,input().split()) if b==d: field[b][min(a,c):max(a,c)+1]=[1 for i in range(max(a,c)+1-min(a,c))] else: for p in field[min(b,d):max(b,d)+1]: p[a]=1 a,b=-1,-1 pt=0 for i in range(t): a,b=input().split() a=int(a)+pt pt=a b='NESW'.find(b) log[a]=b end_t=pt end_v=b ans=[] memo=set({}) def check(t,x,y,v): if t>end_t or (log[t]!=-1 and not((v+2)%4!=log[t])) or ((t,x,y,v) in memo): return memo.add((t,x,y,v)) if t==end_t: ex,ey=vec[end_v] if v==end_v or 0<=y+ey//2<=100 and 0<=x+ex//2<=100 and field[y+ey//2][x+ex//2]==1 and (v+2)%4!=end_v: ans.append((x,y)) return if log[t]!=-1 and v==log[t] or log[t]==-1: i=0 for mx,my in vec: if i==(v+2)%4: i+=1 continue nx,ny=x+mx,y+my if 0<=nx<=100 and 0<=ny<=100 and field[ny-my//2][nx-mx//2]==1: check(t+1,nx,ny,i) i+=1 elif log[t]!=-1: i=0 for mx,my in vec: if i!=log[t]: i+=1 continue nx,ny=x+mx,y+my if 0<=nx<=100 and 0<=ny<=100 and field[ny-my//2][nx-mx//2]==1: check(t+1,nx,ny,i) i+=1 for i in range(4): check(0,x0*2,y0*2,i) for q in sorted(set(ans)): print(q[0]//2,q[1]//2) except: pass ```
p01061 Community Integration
Problem There are N villages. Each village is numbered from 1 to N. Due to the recent merger boom, several villages have been merged. Two or more merged villages will become one new city, and villages that are not merged with any village will remain villages. You will be given multiple pieces of information that two villages will be in the same city after the merger. Depending on the combination of the information, three or more villages can become one city. Given information about villages that will be in the same city after the merger, output the absolute value of the difference between the number of cities and the number of villages after the merger. Constraints * 1 ≤ N ≤ 1,000 * 0 ≤ M ≤ 100 * 1 ≤ ai ≤ N * 1 ≤ bi ≤ N Input The input is given in the following format. N M a1 b1 a2 b2 ... ai bi ... aM bM The first line gives the number N of villages and the number M of information about the merger, separated by blanks. From the second line to the M + 1 line, two integers ai and bi representing information about the merger are given, separated by blanks. Each information indicates that the ai and bi villages will be the same city after the merger. However, no input is given that satisfies ai = bi. Output Output the absolute value of the difference between the number of villages and the number of cities on one line. Examples Input 3 1 1 2 Output 0 Input 4 2 1 4 2 3 Output 2 Input 5 0 Output 5 Input 3 3 1 2 2 3 3 1 Output 1 Input 3 2 1 2 2 3 Output 1 Input 5 4 1 2 2 3 3 4 4 5 Output 1 Input 10 5 3 4 1 2 9 6 2 6 2 9 Output 2
```python n, m = map(int, input().split()) q = [] for _ in range(m): a, b = map(int, input().split()) i, j = -1, -1 for k in range(len(q)): if i == -1: if a in q[k]: i = k if j == -1: if b in q[k]: j = k if i >= 0 and j >= 0: break if i >= 0: if j >= 0: if i != j: q[i] |= q[j] q.pop(j) else: q[i].add(b) elif j >= 0: q[j].add(a) else: q.append(set([a, b])) print(abs(n - sum([len(i) for i in q]) - len(q))) ```
p01498 King Slime
There is a grid of size W × H surrounded by walls. Some cells in the grid are occupied by slimes. The slimes want to unite with each other and become a "King Slime". In each move, a slime can move to east, west, south and north direction until it enters a cell occupied by another slime or hit the surrounding wall. If two slimes come together, they unite and become a new slime. Your task is write a program which calculates the minimum number of moves that all the slimes unite and become a King Slime. Suppose slimes move one by one and they never move simultaneously. Input The first line contains three integers N (2 ≤ N ≤ 40,000), W and H (1 ≤ W, H ≤ 100,000), which denote the number of slimes, the width and the height of the grid respectively. The following N lines describe the initial coordinates of the slimes. The i-th line contains two integers xi (1 ≤ xi ≤ W) and yi (1 ≤ yi ≤ H), which indicate the coordinates of the i-th slime . All the coordinates are 1-based. You may assume that each cell is occupied by at most one slime initially. Output Output the minimum number of moves that all the slimes unite and become a King Slime. Examples Input 4 3 3 1 1 1 3 3 1 3 3 Output 3 Input 2 3 3 2 2 3 3 Output 2 Input 2 4 4 2 2 3 3 Output 3 Input 2 4 4 2 2 2 3 Output 1
```python import sys class UnionFind: def __init__(self,sz): self.__ranks = [1] * sz self.__parents = [ i for i in range(sz) ] def find_parent(self, x): if x == self.__parents[x]: return x else: self.__parents[x] = self.find_parent(self.__parents[x]) return self.__parents[x] def same(self, x, y): return self.find_parent(x) == self.find_parent(y) def unite(self, x, y): px = self.find_parent(x) py = self.find_parent(y) if px == py: return if self.__ranks[px] > self.__ranks[py]: self.__parents[py] = px else: self.__parents[px] = py if self.__ranks[px] == self.__ranks[py]: self.__ranks[py] += 1 def main(): n,w,h = map(int, input().split()) uf = UnionFind(n) xd = {} yd = {} is_edges_slime = False for i in range(n): x,y = map(int, sys.stdin.readline().split()) if x == 1 or x == w: is_edges_slime = True if y == 1 or y == h: is_edges_slime = True if x in xd: uf.unite(xd[x], i) else: xd[x] = i if y in yd: uf.unite(yd[y], i) else: yd[y] = i root = set() for i in range(n): root.add( uf.find_parent(i) ) if len(root) == 1: print(n - 1) else: ans = n - len(root) # ????´?????????¨?????? ans += len(root) - (1 if is_edges_slime else 0) # ??????????????? ans += len(root) - 1 # ????????°??????????????? print(ans) if __name__ == '__main__': main() ```