index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
700 | 11 | 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 | 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) | {
"input": [
"10 11\n1 2\n2 3\n3 4\n1 4\n3 5\n5 6\n8 6\n8 7\n7 6\n7 9\n9 10\n6\n1 2\n3 5\n6 9\n9 2\n9 3\n9 10\n"
],
"output": [
"2\n2\n2\n4\n4\n1\n"
]
} |
701 | 10 | 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
++- | def invert(s):
t = ''
for i in s:
if(i =='+'):
t += '-'
else:
t += '+'
#print(s,t)
return t
n = int(input())
if(n==1):
print('+')
exit()
a=list(map(int,input().split()))
cur = a[-1]
s = '+'
for i in range(n-2,0,-1):
if(cur > 0):
cur -= a[i]
s += '-'
else:
cur += a[i]
s += '+'
#print(s[::-1])
if(cur >= a[0]):
s += '-'
elif(abs(cur) <= a[0] and cur <= 0):
s += '+'
elif( 0 < cur < a[0]):
s=invert(s)
s += '+'
else:
s=invert(s)
s += '-'
print(s[::-1])
| {
"input": [
"3\n3 3 5\n",
"4\n1 2 3 5\n"
],
"output": [
"++-\n",
"+--+\n"
]
} |
702 | 10 | 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 | 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()
| {
"input": [
"5 6 1\n....*.\n...***\n....*.\n..*...\n.***..\n",
"7 7 2\n...*...\n.......\n...*...\n*.***.*\n...*...\n.......\n...*...\n",
"5 6 2\n....*.\n...***\n....*.\n..*...\n.***..\n"
],
"output": [
"2 5\n1 5\n3 5\n2 4\n2 6\n",
"4 4\n1 4\n7 4\n4 1\n4 7\n",
"-1\n"
]
} |
703 | 8 | 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. | def count(a):
n = len(a)
cnt = 0
for i in range(n):
for j in range(i+1, n):
if a[i] > a[j]:
cnt+=1
return cnt
n = int(input())
p = list(map(int, input().split()))
num = count(p)
print(num*2 - num%2) | {
"input": [
"5\n3 5 2 4 1\n",
"2\n1 2\n"
],
"output": [
"13",
"0"
]
} |
704 | 7 | 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 | def ic(s):
ss=set('AHIMOTUVWXY')
m=len(s)//2+1
for c in range(m):
if s[c]!=s[-(c+1)] or s[c] not in ss:
return 0
return 1
s='YES' if ic(input()) else 'NO'
print(s) | {
"input": [
"AHA\n",
"Z\n",
"XO\n"
],
"output": [
"YES\n",
"NO\n",
"NO\n"
]
} |
705 | 11 | 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 | 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)) | {
"input": [
"3\n?\n18\n1?\n",
"2\n??\n?\n",
"5\n12224\n12??5\n12226\n?0000\n?00000\n"
],
"output": [
"YES\n1\n18\n19\n",
"NO\n",
"YES\n12224\n12225\n12226\n20000\n100000\n"
]
} |
706 | 11 | 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> | # 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) | {
"input": [
"3 3\n1 2 3\n"
],
"output": [
"8"
]
} |
707 | 8 | 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. | def main():
n = int(input())
a = list(map(int, input().split()))
used = [True] * (n + 1)
X = {i + 1 for i in range(n)}
Y = {i for i in a if i <= n}
A = X ^ Y
for i in a:
if i > n or not used[i]:
print(A.pop(), end = ' ')
else:
used[i] = False
print(i, end = ' ')
main() | {
"input": [
"3\n1 3 2\n",
"4\n2 2 3 3\n",
"1\n2\n"
],
"output": [
"1 3 2 \n",
"2 1 3 4 \n",
"1 \n"
]
} |
708 | 10 | 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. | 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:
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]))
| {
"input": [
"6 1\n3-a 6-b 7-a 4-c 8-e 2-a\n3-a\n",
"5 5\n1-h 1-e 1-l 1-l 1-o\n1-w 1-o 1-r 1-l 1-d\n",
"5 3\n3-a 2-b 4-c 3-a 2-c\n2-a 2-b 1-c\n"
],
"output": [
"6\n",
"0\n",
"1\n"
]
} |
709 | 8 | 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 | def get_ints():
return list(map(int, input().split()))
N,M = get_ints()
for i in range(1,min(2*N, M)+1):
if 2*N+i<=M:
print(2*N+i, end=" ")
print(i,end=" ") | {
"input": [
"2 7\n",
"9 36\n"
],
"output": [
"5 1 6 2 7 3 4\n",
"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\n"
]
} |
710 | 8 | 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. | def f(v, x, n):
if v<0:
return 0
elif x<<1>n:
return int( 500*(1-v/250))
elif x<<2>n:
return int(1000*(1-v/250))
elif x<<3>n:
return int(1500*(1-v/250))
elif x<<4>n:
return int(2000*(1-v/250))
elif x<<5>n:
return int(2500*(1-v/250))
else:
return int(3000*(1-v/250))
n=int(input())
a=[list(map(int, input().split())) for _ in range(n)]
c=[sum(_[i]>=0 for _ in a) for i in range(5)]
ans=-1
for i in range(10000):
p, q=0, 0
for j in range(5):
x, y=c[j], n
if a[0][j]>a[1][j] and a[1][j]>=0:
x+=i
p+=f(a[0][j], x, n+i)
q+=f(a[1][j], x, n+i)
if p>q:
ans=i
break
print(ans)
# Made By Mostafa_Khaled | {
"input": [
"4\n-1 20 40 77 119\n30 10 73 50 107\n21 29 -1 64 98\n117 65 -1 -1 -1\n",
"5\n119 119 119 119 119\n0 0 0 0 -1\n20 65 12 73 77\n78 112 22 23 11\n1 78 60 111 62\n",
"2\n5 15 40 70 115\n50 45 40 30 15\n",
"3\n55 80 10 -1 -1\n15 -1 79 60 -1\n42 -1 13 -1 -1\n"
],
"output": [
"-1\n",
"27\n",
"2\n",
"3\n"
]
} |
711 | 7 | 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 | def fun(ss):
if len(ss)<2: return 0
if ss[0]==ss[-1]: return fun(ss[1:-1])
else: return 1+fun(ss[1:-1])
ss=input()
print(['NO','YES'][[fun(ss)<2,fun(ss)==1][len(ss)%2==0]]) | {
"input": [
"abbcca\n",
"abcda\n",
"abccaa\n"
],
"output": [
"NO\n",
"YES\n",
"YES\n"
]
} |
712 | 9 | 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. | 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) | {
"input": [
"2\n3 2\n3 1 3 2\n1 2 2 2\n1 0 0 1\n",
"2\n2 2\n2 1 1 1\n1 2 2 2\n1 0 0 0\n",
"3\n10 10\n1 2 1 1\n5 5 6 5\n6 4 5 4\n2 1 2 0\n"
],
"output": [
"1\n",
"-1\n",
"2\n"
]
} |
713 | 8 | 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. | import re
def polycarp(string):
parts = re.split("[A-Z]", string)
return max(len(list(set(part))) for part in parts)
n = int(input())
mystring = input()
print(polycarp(mystring))
| {
"input": [
"11\naaaaBaabAbA\n",
"3\nABC\n",
"12\nzACaAbbaazzC\n"
],
"output": [
"2\n",
"0\n",
"3\n"
]
} |
714 | 7 | 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 | def check(A,B,C):
x = a.index(A)
y = a.index(B)
z = a.index(C)
if((y-x)%12 == 4 and (z-y)%12 == 3):
print("major")
exit(0)
elif((y-x)%12 == 3 and (z-y)%12 == 4):
print("minor")
exit(0)
a = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H']
A,B,C = input().split()
check(A,B,C)
check(A,C,B)
check(B,A,C)
check(B,C,A)
check(C,A,B)
check(C,B,A)
print("strange") | {
"input": [
"A B H\n",
"C E G\n",
"C# B F\n"
],
"output": [
"strange\n",
"major\n",
"minor\n"
]
} |
715 | 10 | 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> | from heapq import *
n, m, r, k = map(int, input().split())
u, v = n // 2, m // 2
h = []
g = lambda z, l: min(z + 1, l - z, l - r + 1, r)
def f(x, y):
if 0 <= x < n and 0 <= y < m:
s = g(x, n) * g(y, m)
heappush(h, (-s, x, y))
f(u, v)
t = 0
for i in range(k):
s, x, y = heappop(h)
t -= s
if x <= u: f(x - 1, y)
if x == u and y <= v: f(x, y - 1)
if x >= u: f(x + 1, y)
if x == u and y >= v: f(x, y + 1)
print(t / (n - r + 1) / (m - r + 1)) | {
"input": [
"12 17 9 40\n",
"3 3 2 3\n"
],
"output": [
"32.8333333333",
"2.0000000000"
]
} |
716 | 10 | 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. | def solve(n, k):
if n == 0:
return []
x = n%k
return [x] + solve(-(n-x)//k, k)
n, k = map(int, input().split())
a = solve(n, k)
print(len(a))
print(*a) | {
"input": [
"46 2\n",
"2018 214\n"
],
"output": [
"7\n 0 1 0 0 1 1 1\n",
"3\n 92 205 1\n"
]
} |
717 | 9 | 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. | def sum_without_one(arr):
s = sum(arr)
return [s-x for x in arr]
res = {}
for i in range(int(input())):
input()
for j, x in enumerate(sum_without_one(list(map(int, input().split())))):
if x in res and i+1 != res[x][0]:
print('YES')
print(i+1,j+1)
print(*res[x])
exit(0)
res[x] = (i+1, j+1)
print('NO')
| {
"input": [
"2\n5\n2 3 1 3 2\n6\n1 1 2 2 2 1\n",
"4\n6\n2 2 2 2 2 2\n5\n2 2 2 2 2\n3\n2 2 2\n5\n2 2 2 2 2\n",
"3\n1\n5\n5\n1 1 1 1 1\n2\n2 3\n"
],
"output": [
"YES\n1 4\n2 1\n",
"YES\n2 5\n4 1\n",
"NO\n"
]
} |
718 | 11 | 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. | from collections import *
from math import *
def ch(mx):
if(mx > n):
return 0
m = l[0]//(1<<(mx-1))
for i in range(mx):
m = min(m,l[i]//(1<<(mx-i-1)))
return m*((1<<mx)-1)
n = int(input())
mx = ceil(log(n,2))
a = list(map(int,input().split()))
c = Counter(a)
l = list(c.values())
l.sort(reverse = True)
n = len(l)
ans = 1
for i in range(1,mx+1):
ans = max(ans,ch(i))
print(ans) | {
"input": [
"10\n6 6 6 3 6 1000000000 3 3 6 6\n",
"3\n1337 1337 1337\n",
"18\n2 1 2 10 2 10 10 2 2 1 10 10 10 10 1 1 10 10\n"
],
"output": [
"9",
"3",
"14"
]
} |
719 | 11 | 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). | def li():
return list(map(int, input().split(" ")))
input()
ans = lo = 0
for i in li():
k = min(lo, i//2)
i -= 2*k
lo -= k
ans += k
ans += i//3
lo += (i%3)
print(ans) | {
"input": [
"5\n1 2 2 2 2\n",
"3\n1 1 1\n",
"3\n3 3 3\n"
],
"output": [
"3",
"0",
"3"
]
} |
720 | 8 | 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". | def solution(t):
no_a = t.replace('a', '')
s_ = no_a[:len(no_a) // 2]
if s_ + s_ == no_a and t.endswith(s_):
return t[:-len(s_) or None]
else:
return ':('
print(solution(input())) | {
"input": [
"ababacacbbcc\n",
"aacaababc\n",
"baba\n",
"aaaaa\n"
],
"output": [
"ababacac",
":(",
":(",
"aaaaa"
]
} |
721 | 8 | 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. | # -*- 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)
| {
"input": [
"16\n64\n345\n672"
],
"output": [
"? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 \n? 128 256 384 512 640 768 896 1024 1152 1280 1408 1536 1664 1792 1920 2048 2176 2304 2432 2560 2688 2816 2944 3072 3200 3328 3456 3584 3712 3840 3968 4096 4224 4352 4480 4608 4736 4864 4992 5120 5248 5376 5504 5632 5760 5888 6016 6144 6272 6400 6528 6656 6784 6912 7040 7168 7296 7424 7552 7680 7808 7936 8064 8192 8320 8448 8576 8704 8832 8960 9088 9216 9344 9472 9600 9728 9856 9984 10112 10240 10368 10496 10624 10752 10880 11008 11136 11264 11392 11520 11648 11776 11904 12032 12160 12288 12416 12544 12672 12800 \n! 64"
]
} |
722 | 11 | 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 | import sys
input = iter(sys.stdin.read().splitlines()).__next__
from collections import defaultdict as di
def solve():
n,m = map(int,input().split())
B = [input() for _ in range(n)]
pos = di(list)
for i in range(n):
b = B[i]
for j in range(m):
pos[b[j]].append((i,j))
if '.' in pos:
del pos['.']
C = [list('.'*m) for _ in range(n)]
moves = []
if pos:
mxx = max(pos)
for i in range(97,ord(mxx)+1):
c = chr(i)
if c not in pos:
pos[c] = pos[mxx]
P = pos[c]
if all(p[0] == P[0][0] for p in P):
mn = min(p[1] for p in P)
mx = max(p[1] for p in P)
i = P[0][0]
for j in range(mn,mx+1):
C[i][j] = c
moves.append((i+1,mn+1,i+1,mx+1))
elif all(p[1] == P[0][1] for p in P):
mn = min(p[0] for p in P)
mx = max(p[0] for p in P)
j = P[0][1]
for i in range(mn,mx+1):
C[i][j] = c
moves.append((mn+1,j+1,mx+1,j+1))
if [''.join(s) for s in C] == B:
print('YES')
print(len(moves))
for m in moves:
print(*m)
else:
print('NO')
def main():
t = int(input())
for _ in range(t):
solve()
main() | {
"input": [
"3\n3 3\n...\n...\n...\n4 4\n..c.\nadda\nbbcb\n....\n3 5\n..b..\naaaaa\n..b..\n",
"2\n3 3\n...\n.a.\n...\n2 2\nbb\ncc\n",
"1\n5 6\n...a..\n..bbb.\n...a..\n.cccc.\n...a..\n"
],
"output": [
"YES\n0\nYES\n4\n2 1 2 4\n3 1 3 4\n1 3 3 3\n2 2 2 3\nNO\n",
"YES\n1\n2 2 2 2\nYES\n3\n1 1 1 2\n1 1 1 2\n2 1 2 2\n",
"YES\n3\n1 4 5 4\n2 3 2 5\n4 2 4 5\n"
]
} |
723 | 9 | 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. | def floyd(n, dist):
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
n = int(input())
graph = [[0] * n for _ in range(n)]
for i in range(n):
s = input()
for j in range(n):
graph[i][j] = int(s[j]) if s[j] != '0' or i == j else float('+inf')
m = int(input())
path = [x - 1 for x in list(map(int, input().split()))]
floyd(n, graph)
ans = [path[0]]
last = 0
for i in range(1, m):
if i - last > graph[ans[-1]][path[i]]:
ans.append(path[i - 1])
last = i - 1
ans.append(path[-1])
print(len(ans))
print(*[x + 1 for x in ans])
| {
"input": [
"3\n011\n101\n110\n7\n1 2 3 1 3 2 1\n",
"4\n0110\n0001\n0001\n1000\n3\n1 2 4\n",
"4\n0110\n0010\n1001\n1000\n20\n1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4\n",
"4\n0110\n0010\n0001\n1000\n4\n1 2 3 4\n"
],
"output": [
"7\n1 2 3 1 3 2 1 \n",
"2\n1 4 \n",
"11\n1 2 4 2 4 2 4 2 4 2 4 \n",
"3\n1 2 4 \n"
]
} |
724 | 7 | 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. | def solve():
n = int(input())
a = [x for x in map(int, input().split()) if x <= 2048]
if sum(a) >= 2048:
print('YES')
else:
print('NO')
t = int(input())
for _ in range(t):
solve() | {
"input": [
"6\n4\n1024 512 64 512\n1\n2048\n3\n64 512 2\n2\n4096 4\n7\n2048 2 2048 2048 2048 2048 2048\n2\n2048 4096\n"
],
"output": [
"YES\nYES\nNO\nNO\nYES\nYES\n"
]
} |
725 | 8 | 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. | input()
def f(s):
s = int(s)
return ['NO', 'YES'][s >= 14 and s % 14 in range(1, 7)]
print(*map(f, input().split())) | {
"input": [
"4\n29 34 19 38\n"
],
"output": [
"YES\nYES\nYES\nNO\n"
]
} |
726 | 10 | 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 | from sys import setrecursionlimit
setrecursionlimit(1000000)
n = int(input())
graph = [[] for _ in range(n + 1)]
ci = [0]
def solve(x):
rlt = []
for v in graph[x]:
rlt.extend(solve(v))
if len(rlt) < ci[x]:
raise ValueError
rlt.insert(ci[x], x)
return rlt
for i in range(1, n + 1):
p, c = map(int, input().split())
graph[p].append(i)
ci.append(c)
try:
ans = solve(graph[0][0])
except ValueError:
print("NO")
else:
print("YES")
for i in range(1, n + 1):
print(ans.index(i) + 1, end=' ')
| {
"input": [
"3\n2 0\n0 2\n2 0\n",
"5\n0 1\n1 3\n2 1\n3 0\n2 0\n"
],
"output": [
"YES\n1 3 2 \n",
"YES\n2 5 3 1 4 \n"
]
} |
727 | 10 | 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> | from collections import deque
import sys
def bfs(s):
q = deque()
d = [-1] * n
q.append(s)
d[s] = 0
while len(q) > 0:
u = q.popleft()
for v in adj[u]:
if d[v] == -1:
d[v] = d[u] + 1
q.append(v)
return d
n, m, k = map(int, input().split())
a = list(map(lambda x : x - 1, map(int, input().split())))
inp = sys.stdin.readlines()
adj = [[] for _ in range(n)]
for i in range(m):
x, y = map(int, inp[i].split())
x -= 1; y -= 1
adj[x].append(y)
adj[y].append(x)
ds = bfs(0)
de = bfs(n - 1)
p = sorted([(ds[i], de[i]) for i in a])
mx = p[0][0]
ans = 0
for i in range(1, k):
ans = max(mx + p[i][1] + 1, ans)
mx = max(mx, p[i][0])
print(min(ans, de[0])) | {
"input": [
"5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5\n",
"5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4\n"
],
"output": [
"3\n",
"3\n"
]
} |
728 | 10 | 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 | def msb(x):
return len(bin(x)) - 2
def solve():
d, mod = map(int, input().split())
way = 1
for i in range(msb(d) - 1):
way += way * (1 << i)
way += way * (d + 1 - (1 << (msb(d) - 1)))
print((way - 1) % mod)
for _ in range(int(input())):
solve()
| {
"input": [
"10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1\n"
],
"output": [
"1\n3\n5\n11\n17\n23\n29\n59\n89\n0\n"
]
} |
729 | 10 | 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]. | import sys
input=sys.stdin.readline
def main():
n,k=map(int,input().split())
A=list(map(int,input().split()))
if min(A) == max(A) == k:
print('yes')
return
if k not in A:
print('no')
return
A = [x >= k for x in A] + [0, 0]
print('yes' if max(sum(A[i:i+3]) for i in range(n)) > 1 else 'no')
T=int(input())
for _ in range(T):
main()
| {
"input": [
"5\n5 3\n1 5 2 6 1\n1 6\n6\n3 2\n1 2 3\n4 3\n3 1 2 3\n10 3\n1 2 3 4 5 6 7 8 9 10\n"
],
"output": [
"no\nyes\nyes\nno\nyes\n"
]
} |
730 | 9 | 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). | from collections import Counter
def solve(arr):
n = len(arr)
mp = Counter(arr)
fmax = max(mp.values())
m = sum(1 for f in mp.values() if f==fmax)
h = (n-m*fmax) // (fmax-1)
return h + m - 1
for _ in range(int(input())):
input()
arr = list(map(int,input().split()))
print(solve(arr))
| {
"input": [
"4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4\n"
],
"output": [
"3\n2\n0\n4\n"
]
} |
731 | 8 | 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]. | def mp():return map(int,input().split())
def it():return int(input())
for _ in range(it()):
n=it()
l=list(mp())
k=list(mp())
v=[]
for i in range(n):
if not k[i]:
v.append(l[i])
v.sort()
ans=0
for i in range(n):
if k[i]<1:
l[i]=v.pop()
print(*l)
| {
"input": [
"5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1\n"
],
"output": [
"3 2 1 \n2 -3 4 -1 \n-8 4 1 -2 4 7 -6 \n1 0 -4 6 3 \n-1 10 7 4 -8 -1 \n"
]
} |
732 | 7 | 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. |
def solv():
x, y = map(int, input().split())
s = sum(list(map(int, input().split())))
print('YES' if s == y else 'NO')
for n in range(int(input())):
solv()
| {
"input": [
"2\n3 8\n2 5 1\n4 4\n0 1 2 3\n"
],
"output": [
"YES\nNO\n"
]
} |
733 | 12 | 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]. | import sys, os
#from collections import defaultdict
if os.environ['USERNAME']=='kissz':
inp=open('in.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=sys.stdin.readline
def debug(*args):
pass
# SCRIPT STARTS HERE
for _ in range(int(inp())):
n=int(inp())
offset,*B=map(int,inp().split())
#presum_list=defaultdict(int)
#presum_list[0]=1
presum_list={0:1}
total=1
for b in B:
if -offset not in presum_list.keys(): presum_list[-offset]=0
zeros=presum_list[-offset]
presum_list[-offset]=total
total=(2*total-zeros) % 1000000007
offset+=b
print(total) | {
"input": [
"4\n3\n1 -1 1\n4\n1 2 3 4\n10\n2 -1 1 -2 2 3 -5 0 2 -1\n4\n0 0 0 1\n"
],
"output": [
"\n3\n8\n223\n1\n"
]
} |
734 | 8 | 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 |
def increase(l) :
i = 0
while i < len(l) and l[i] == 'z' :
l[i] = 'a'
i+=1
if i == len(l) :
l.append('a')
else :
l[i] = chr(ord(l[i])+1)
def solve(s) :
l = ['a']
while 1 :
c = ''.join(l[::-1])
if c not in s :
print(c)
return
increase(l)
t = int(input())
for i in range(t) :
n = int(input())
s = input()
solve(s) | {
"input": [
"3\n28\nqaabzwsxedcrfvtgbyhnujmiklop\n13\ncleanairactbd\n10\naannttoonn\n"
],
"output": [
"\nac\nf\nb\n"
]
} |
735 | 7 | 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]". | def f(a,b):
dp=[[0]*(len(b)+1) for i in range(len(a)+1)]
for i in range(len(a)):
for j in range(len(b)):
dp[i+1][j+1]=(dp[i+1][j]+(a[i]==b[j])*(dp[i][j]+1))%(10**9+7)
ans=0
for i in range(0,len(a)):
ans=(ans+dp[i+1][-1])%(10**9+7)
return ans
a=input()
b=input()
print(f(a,b)) | {
"input": [
"codeforces\nforceofcode\n",
"aa\naa\n"
],
"output": [
"60\n",
"5\n"
]
} |
736 | 8 | 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> | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#######################################
n,m = map(int,input().split())
l = []
anss = [1]*(n+1)
for i in range(m):
l.append(list(map(int,input().split())))
for i in range(m-1):
for j in range(i+1,m):
sx = l[i][0] - l[j][0]
sy = l[i][1] - l[j][1]
ans = 2
if sx:
if sy:
x = (l[i][0]*sy - l[i][1]*sx)/sy
if 1<=x<=n and int(x) == x:
for k in range(j+1,m):
if l[k][1]*sx == (sy*(l[k][0]-l[i][0]) + l[i][1]*sx) :
ans+=1
anss[int(x)] = max(ans,anss[int(x)])
else:
if 1<=l[i][0]<=n:
for k in range(j+1,m):
if l[k][0] == l[i][0]:
ans+=1
anss[l[i][0]] = max(anss[l[i][0]],ans)
print(sum(anss[1::]))
| {
"input": [
"5 5\n2 1\n4 1\n3 2\n4 3\n4 4\n"
],
"output": [
"11\n"
]
} |
737 | 9 | 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. | 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)) | {
"input": [
"3 6\n101010\n000100\n100000\n",
"2 3\n111\n000\n"
],
"output": [
"3",
"-1"
]
} |
738 | 8 | 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>. | 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) | {
"input": [
"9 3 8 10\n",
"6 4 3 1\n"
],
"output": [
"2\n",
"0\n"
]
} |
739 | 8 | 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 | def s():
n = int(input())
a = [0]*(n+1)
b = [0]*(n+1)
r = []
for _ in range(n*(n-1)//2-1):
c = list(map(int,input().split()))
a[c[0]] += 1
b[c[1]] += 1
for i in range(1,n+1):
if a[i] + b[i] == n-2:
r.append(i)
r.sort(key = lambda x:-a[x])
print(*r)
s() | {
"input": [
"4\n4 2\n4 1\n2 3\n2 1\n3 1\n"
],
"output": [
"4 3\n"
]
} |
740 | 7 | 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 | def main():
n, m = map(int, input().split())
a = input().count('-')
if a > n - a:
a = n - a
res = []
for _ in range(m):
l, r = map(int, input().split())
r -= l
res.append(('0', '1')[r & 1 and a * 2 >= r + 1])
print('\n'.join(res))
if __name__ == '__main__':
main() | {
"input": [
"5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n",
"2 3\n1 -1\n1 1\n1 2\n2 2\n"
],
"output": [
"0\n1\n0\n1\n0\n",
"0\n1\n0\n"
]
} |
741 | 11 | 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 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, t = map(int, input().split())
t = float(t)
balls = sorted(list(map(float, input().split())) + [i] for i in range(n))
eps = 1e-9
def calc(i, j):
ok, ng = 0.0, t + 1.0
for _ in range(50):
mid = (ok + ng) / 2
if balls[i][0] + balls[i][1] * mid - eps > balls[j][0] + balls[j][1] * mid:
ng = mid
else:
ok = mid
return mid
def adv(i, delta):
balls[i][0] += balls[i][1] * delta
def collide(i, j):
balls[i][1], balls[j][1] = (
((balls[i][2] - balls[j][2]) * balls[i][1] + 2 * balls[j][2] * balls[j][1]) / (balls[i][2] + balls[j][2]),
((balls[j][2] - balls[i][2]) * balls[j][1] + 2 * balls[i][2] * balls[i][1]) / (balls[i][2] + balls[j][2])
)
while t > 0:
x, y, d = 0, 0, t + 1.0
for i in range(n - 1):
res = calc(i, i + 1)
if d > res:
d = res
x, y = i, i + 1
if d >= t:
for i in range(n):
adv(i, t)
break
for i in range(n):
adv(i, d)
collide(x, y)
t -= d
ans = [0.0] * n
for i in range(n):
ans[balls[i][-1]] = balls[i][0]
print(*ans, sep='\n')
| {
"input": [
"2 9\n3 4 5\n0 7 8\n",
"3 10\n1 2 3\n4 -5 6\n7 -8 9\n"
],
"output": [
"68.538461538\n44.538461538\n",
"-93.666666667\n-74.666666667\n-15.666666667\n"
]
} |
742 | 7 | 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. | import sys
input=sys.stdin.readline
n,m,i,j,a,b=map(int,input().split())
MIN=10**18
def calc(u,v):
global MIN
if (u-i)%a==0 and (v-j)%b==0:
x=abs(u-i)//a
y=abs(v-j)//b
if x%2==y%2 and 1+a<=n and 1+b<=m:
MIN=min(MIN,max(x,y))
if x==y==0:
MIN=0
calc(1,1)
calc(1,m)
calc(n,1)
calc(n,m)
if MIN==10**18:
print("Poor Inna and pony!")
else:
print(MIN) | {
"input": [
"5 5 2 3 1 1\n",
"5 7 1 3 2 2\n"
],
"output": [
"Poor Inna and pony!\n",
"2\n"
]
} |
743 | 8 | 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). | def gf(x):
if fa[x] != x:
fa[x] = gf(fa[x])
return fa[x]
n, m = map(int, input().split())
fa = list(range(n + 1))
for _ in range(m):
x, y = map(int, input().split())
fa[gf(x)] = gf(y)
ans = 2 ** n
for i in range(1, n + 1):
if gf(i) == i:
ans //= 2
print(ans)
| {
"input": [
"3 2\n1 2\n2 3\n",
"2 1\n1 2\n",
"1 0\n"
],
"output": [
"4\n",
"2\n",
"1\n"
]
} |
744 | 9 | 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 | from sys import stdin
input = stdin.readline
def put(): return map(int, input().split())
n,m,k = put()
l = list(put())
p = []
summ = 0
for i in range(m):
summ+= l[i]
p.append(summ)
for i in range(m, n):
summ+= l[i]-l[i-m]
p.append(summ)
r = p.copy()
c = len(p)
q = [0]*c
for j in range(k):
for i in range(j,c):
q[i] = max(q[i-1] if i-1>=0 else 0, p[i]+ (r[i-m] if i-m>=0 and j>0 else 0))
r = q.copy()
print(r[-1])
| {
"input": [
"5 2 1\n1 2 3 4 5\n",
"7 1 3\n2 10 7 18 5 33 0\n"
],
"output": [
"9",
"61"
]
} |
745 | 10 | 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 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = []
for i in range(n):
j = b.index(a[i], i)
while i < j:
ans.append(f'{j} {j+1}')
b[j - 1], b[j] = b[j], b[j - 1]
j -= 1
print(len(ans))
print('\n'.join(ans))
| {
"input": [
"2\n1 100500\n1 100500\n",
"4\n1 2 3 2\n3 2 1 2\n"
],
"output": [
"0\n",
"3\n2 3\n1 2\n2 3\n"
]
} |
746 | 12 | 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 > 3
Output
1
Input
4 1
3 = 6
Output
3 | def check(l, r, a, b):
if a < 0 or b >= 2 * N:
return 0
def val(p):
if p in [a, b]: return '0'
if l <= p and p < r: return '1'
return '-1'
for i in range(K):
x, y = val(A[i]), val(C[i])
if A[i] in [a, b] or C[i] in [a, b]:
if not eval(x + B[i] + y):
return 0
return 1
N, K = map(int, input().split())
tmp = [input().split() for i in range(K)]
try: A, B, C = zip(*tmp)
except: A, B, C = [], [], []
A = [int(x) - 1 for x in A]
B = ['==' if x is '=' else x for x in B]
C = [int(x) - 1 for x in C]
dp = []
for i in range(N + 1):
dp.append([0] * (2 * N + 1))
dp[N][0] = 1
for i in range(N, 0, -1):
for j in range(0, 2 * (N - i) + 3):
d, k = 0, j + 2 * i - 2
if check(j, k, j - 2, j - 1): d += dp[i][j - 2]
if check(j, k, j - 1, k): d += dp[i][j - 1]
if check(j, k, k, k + 1): d += dp[i][j]
dp[i - 1][j] = d
print(sum(dp[0]) // 3) | {
"input": [
"3 0\n",
"4 1\n3 = 6\n",
"3 1\n2 > 3\n"
],
"output": [
"9\n",
"3\n",
" 9\n"
]
} |
747 | 9 | 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). | import sys, collections
def inp():
return map(int, input().split())
n, q = inp()
Q = collections.deque()
A = n * [0]
B = A[:]
L = []
s = n = 0
for _ in range(q):
typeq, x = inp()
if typeq == 1:
x -= 1
Q.append(x)
B[x] += 1
A[x] += 1
s += 1
elif typeq == 2:
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(s)
sys.stdout.write('\n'.join(map(str,L))) | {
"input": [
"4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3\n",
"3 4\n1 3\n1 1\n1 2\n2 3\n"
],
"output": [
"1\n2\n3\n0\n1\n2\n",
"1\n2\n3\n2\n"
]
} |
748 | 7 | 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 | def bachgold(n):
print(n//2)
a = [2] * (n//2)
if n%2:
a[-1] += 1
print(*a)
n = int(input())
bachgold(n) | {
"input": [
"6\n",
"5\n"
],
"output": [
"3\n2 2 2 \n",
"2\n2 3\n"
]
} |
749 | 8 | 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. | def C(n,r):
if r>n//2:
r=n-r
ans=1
for i in range(1,r+1):
ans*=(n-r+i)
ans//=i
return ans
n=input()
a=list(map(int,input().split()))
a.sort()
b=set(a[0:3])
m={}
for i in b:
m[i]=0
for i in a[0:3]:
m[i]+=1
ans=1
for i in m:
ans*=C(a.count(i),m[i])
print(ans) | {
"input": [
"5\n1 3 2 3 4\n",
"6\n1 3 3 1 3 2\n",
"4\n1 1 1 1\n"
],
"output": [
"2\n",
"1\n",
"4\n"
]
} |
750 | 8 | 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> | R=lambda:list(map(int,input().split()))
r,d=R()
def ok():
x,y,z=R()
return 1 if (r-d+z)**2<=x*x+y*y<=(r-z)**2 else 0
print(sum(ok() for i in range(int(input()))))
| {
"input": [
"10 8\n4\n0 0 9\n0 0 10\n1 0 1\n1 0 2\n",
"8 4\n7\n7 8 1\n-7 3 2\n0 2 1\n0 -2 2\n-3 -3 1\n0 6 2\n5 3 1\n"
],
"output": [
"0\n",
"2\n"
]
} |
751 | 8 | 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 | n = int(input())
ws = sorted(list(map(int, input().split(' '))))
res = 10 ** 10
def f(vs):
return sum(abs(a - b) for a, b in zip(vs[0::2], vs[1::2]))
for i in range(len(ws)):
for j in range(i + 1, len(ws)):
test = ws[:i] + ws[i+1:j] + ws[j+1:]
res = min(res, f(test))
print(res)
| {
"input": [
"4\n1 3 4 6 3 4 100 200\n",
"2\n1 2 3 4\n"
],
"output": [
"5\n",
"1\n"
]
} |
752 | 12 | 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 | 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)) | {
"input": [
"3\n0 0 1\n0 0 1\n1 1 0\n",
"4\n0 1 1 1\n1 0 1 1\n1 1 0 1\n1 1 1 0\n",
"3\n0 0 0\n0 0 1\n0 1 0\n"
],
"output": [
"1\n",
"12\n",
"0\n"
]
} |
753 | 10 | 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). | 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() | {
"input": [
"4\n1 2 4 3\n4\n1 1\n1 4\n1 4\n2 3\n",
"3\n1 2 3\n2\n1 2\n2 3\n"
],
"output": [
"odd\nodd\nodd\neven\n",
"odd\neven\n"
]
} |
754 | 8 | 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. | def solve(n, k):
if n == 0:
return []
x = n%k
return [x] + solve(-(n-x)//k, k)
n, k = map(int, input().split())
a = solve(n, k)
print(len(a))
print(*a) | {
"input": [
"46 2\n",
"2018 214\n"
],
"output": [
"7\n0 1 0 0 1 1 1 \n",
"3\n92 205 1 \n"
]
} |
755 | 8 | 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
>
Input
10 3
Output
<
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. | import math
x,y=map(int, input().split())
def f(x):
if x: return math.log(x)/x
if f(x)<f(y): print('<')
elif f(y)<f(x): print('>')
elif x==y:print('=')
else: print('=') | {
"input": [
"5 8\n",
"6 6\n",
"10 3\n"
],
"output": [
">\n",
"=\n",
"<\n"
]
} |
756 | 8 | This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 β€ i β€ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.
As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.
You can ask questions of form Β«which number was received by student i?Β», and the goal is to determine whether the desired pair exists in no more than 60 questions.
Input
At the beginning the even integer n (2 β€ n β€ 100 000) is given β the total number of students.
You are allowed to ask no more than 60 questions.
Output
To ask the question about the student i (1 β€ i β€ n), you should print Β«? iΒ». Then from standard output you can read the number ai received by student i ( - 109 β€ ai β€ 109).
When you find the desired pair, you should print Β«! iΒ», where i is any student who belongs to the pair (1 β€ i β€ n). If you determined that such pair doesn't exist, you should output Β«! -1Β». In both cases you should immediately terminate the program.
The query that contains your answer is not counted towards the limit of 60 queries.
Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.
Hacking
Use the following format for hacking:
In the first line, print one even integer n (2 β€ n β€ 100 000) β the total number of students.
In the second line print n integers ai ( - 109 β€ ai β€ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1.
The hacked solution will not have direct access to the sequence ai.
Examples
Input
8
<span class="tex-span"></span>
2
<span class="tex-span"></span>
2
Output
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 8
<span class="tex-span"></span>
! 4
Input
6
<span class="tex-span"></span>
1
<span class="tex-span"></span>
2
<span class="tex-span"></span>
3
<span class="tex-span"></span>
2
<span class="tex-span"></span>
1
<span class="tex-span"></span>
0
Output
<span class="tex-span"></span>
? 1
<span class="tex-span"></span>
? 2
<span class="tex-span"></span>
? 3
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 5
<span class="tex-span"></span>
? 6
<span class="tex-span"></span>
! -1
Note
Input-output in statements illustrates example interaction.
In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2
In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. | import sys
def ask(x):
print('? %d'%x)
sys.stdout.flush()
x=int(input())
return x
n=int(input())
t=n//2
if t&1:
print('! -1')
sys.stdout.flush()
sys.exit()
l=1
r=n
while l<r:
mid=(l+r)>>1
if ask(mid)>=ask((mid+t-1)%n+1):
r=mid
else:
l=mid+1
print('! %d'%l)
sys.stdout.flush()
| {
"input": [
"6\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n3 \n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n0",
"8\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n2\n"
],
"output": [
"! -1\n",
"? 1\n? 5\n! 1\n"
]
} |
757 | 7 | There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k.
Nobody leaves the taken seat during the whole process.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of benches in the park.
The second line contains a single integer m (1 β€ m β€ 10 000) β the number of people additionally coming to the park.
Each of the next n lines contains a single integer a_i (1 β€ a_i β€ 100) β the initial number of people on the i-th bench.
Output
Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park.
Examples
Input
4
6
1
1
1
1
Output
3 7
Input
1
10
5
Output
15 15
Input
3
6
1
6
5
Output
6 12
Input
3
7
1
6
5
Output
7 13
Note
In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining β the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench.
The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it. | def inp():
return list(map(int,input().split()))
n,=inp()
m,=inp()
a = [int(input()) for i in range(n)]
s=sum(a)
mx=max(a)
mi= max([mx, int((s+m+n-1)/n)])
mx= mx + m
print(mi,mx) | {
"input": [
"4\n6\n1\n1\n1\n1\n",
"1\n10\n5\n",
"3\n6\n1\n6\n5\n",
"3\n7\n1\n6\n5\n"
],
"output": [
"3 7\n",
"15 15\n",
"6 12\n",
"7 13\n"
]
} |
758 | 10 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, β¦, a_n is recorded.
Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.
A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds:
* x is a prefix of y, but x β y (this is impossible in this problem as all considered sequences have the same length);
* in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 10^5), denoting the number of nodes and edges, respectively.
The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n), representing the nodes the i-th edge connects.
Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.
Output
Output a line containing the lexicographically smallest sequence a_1, a_2, β¦, a_n Bob can record.
Examples
Input
3 2
1 2
1 3
Output
1 2 3
Input
5 5
1 4
3 4
5 4
3 2
1 5
Output
1 4 3 2 5
Input
10 10
1 4
6 8
2 5
3 7
9 4
5 6
3 4
8 10
8 9
1 10
Output
1 4 3 7 9 8 6 5 2 10
Note
In the first sample, Bob's optimal wandering path could be 1 β 2 β 1 β 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one.
In the second sample, Bob's optimal wandering path could be 1 β 4 β 3 β 2 β 3 β 4 β 1 β 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. | import bisect
def dfs(i,vis,g):
print(i,end=" ")
vis[i]=1
for j in g[i]:
if vis[j]==0:
dfs(j,vis,g)
n,m=map(int,input().split())
g=[[] for i in range(n+1)]
for i in range(m):
u,v=map(int,input().split())
bisect.insort(g[u],v)
bisect.insort(g[v],u)
bfs=[1]
l=1
vis=[0]*(n+1)
vis[1]=1
while l!=0:
i=bfs.pop(0)
print(i,end=" ")
l-=1
for j in g[i]:
if vis[j]==0:
bisect.insort(bfs,j)
vis[j]=1
l+=1
#dfs(1,vis,g)
print()
| {
"input": [
"3 2\n1 2\n1 3\n",
"10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10\n",
"5 5\n1 4\n3 4\n5 4\n3 2\n1 5\n"
],
"output": [
"1 2 3 ",
"1 4 3 7 9 8 6 5 2 10 ",
"1 4 3 2 5 "
]
} |
759 | 11 | You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).
It is possible that some students not be included in any team at all.
Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 5000) β the number of students and the maximum number of teams, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is a programming skill of the i-th student.
Output
Print one integer β the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.
Examples
Input
5 2
1 2 15 15 15
Output
5
Input
6 1
36 4 1 25 9 16
Output
2
Input
4 4
1 10 100 1000
Output
4 | from sys import stdin
input=stdin.readline
from collections import defaultdict
def f(a,n,k):
cnt=[0]*(n)
a=sorted(a)
for i in range(n):
while i+cnt[i]<n and a[i+cnt[i]]-a[i]<=5:
cnt[i]+=1
dp=[[0]*(k+1) for i in range(n+1)]
for i in range(n):
for j in range(k+1):
dp[i+1][j]=max(dp[i+1][j],dp[i][j])
if j+1<=k:
dp[i+cnt[i]][j+1]=max(dp[i+cnt[i]][j+1],dp[i][j]+cnt[i])
# print(dp)
return (dp[n][k])
n,k=map(int,input().strip().split())
print(f([*map(int,input().strip().split())],n,k)) | {
"input": [
"4 4\n1 10 100 1000\n",
"6 1\n36 4 1 25 9 16\n",
"5 2\n1 2 15 15 15\n"
],
"output": [
"4\n",
"2\n",
"5\n"
]
} |
760 | 8 | You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D β₯ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is possible that after an operation the value a_i becomes negative.
Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n).
Print the required D or, if it is impossible to choose such value D, print -1.
For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4].
Input
The first line of the input contains one integer n (1 β€ n β€ 100) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100) β the sequence a.
Output
Print one integer β the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal.
If it is impossible to choose such value D, print -1.
Examples
Input
6
1 4 4 7 4 1
Output
3
Input
5
2 2 5 2 5
Output
3
Input
4
1 3 3 7
Output
-1
Input
2
2 8
Output
3 | input()
s = set(map(int, input().split()))
def no():
print(-1)
exit(0)
n = len(s)
if n > 3:
no()
elif n == 1:
print(0)
else:
a = sorted([x for x in s])
if n == 2:
m = a[1] - a[0]
if m % 2 == 0:
print(m // 2)
else:
print(m)
elif a[0] + a[2] != a[1] + a[1]:
no()
else:
print(a[1] - a[0]) | {
"input": [
"2\n2 8\n",
"4\n1 3 3 7\n",
"5\n2 2 5 2 5\n",
"6\n1 4 4 7 4 1\n"
],
"output": [
"3\n",
"-1\n",
"3\n",
"3\n"
]
} |
761 | 12 | Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming.
Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).
Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent.
After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E β the expected number of crosswords he will be able to solve completely. Can you calculate it?
Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values β in this problem it means that the expected value of the number of solved crosswords can be calculated as E = β _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords.
We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P β
Q^{-1} mod (10^9 + 7).
Input
The first line contains two integers n and T (1 β€ n β€ 2 β
10^5, 1 β€ T β€ 2 β
10^{14}) β the number of crosswords and the time Adilbek has to spend, respectively.
The second line contains n integers t_1, t_2, ..., t_n (1 β€ t_i β€ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword.
Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
Output
Print one integer β the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P β
Q^{-1} mod (10^9 + 7).
Examples
Input
3 5
2 2 2
Output
750000007
Input
3 5
2 1 2
Output
125000003
Note
The answer for the first sample is equal to 14/8.
The answer for the second sample is equal to 17/8. | mod = 10 ** 9 + 7
MAX = 2 * 10 ** 5+2
r = [1] * MAX
factorial = [1] * MAX
rfactorial = [1] * MAX
rp = [1] * MAX
for i in range(2, MAX):
factorial[i] = i * factorial[i - 1] % mod
r[i] = mod - (mod // i) * r[mod%i] % mod
rfactorial[i] = rfactorial[i-1] * r[i] % mod
for i in range(1, MAX):
rp[i] = rp[i - 1] * (mod + 1) // 2 % mod
n, T = list(map(int, input().split()))
t = list(map(int, input().split()))
t.append(10**10+1)
def Combination(n,k):
return factorial[n]*rfactorial[k]*rfactorial[n-k]
S=0
EX=0
for i in range(len(t)):
cof = rp[1]
for add in range(2):
l_, r_ = max(0, T-S-t[i] + add), min(i, T-S)
for x in range(l_, r_+1):
EX = ( EX + i * Combination(i,x) * rp[i+1]) % mod
S += t[i]
print(EX)
| {
"input": [
"3 5\n2 2 2\n",
"3 5\n2 1 2\n"
],
"output": [
"750000007\n",
"125000003\n"
]
} |
762 | 8 | The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0).
Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.
You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 β€ id_i β€ 10^9).
If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.
Otherwise (i.e. if there is no conversation with id_i on the screen):
* Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen.
* Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen.
* The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.
Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages.
Input
The first line of the input contains two integers n and k (1 β€ n, k β€ 200) β the number of messages and the number of conversations your smartphone can show.
The second line of the input contains n integers id_1, id_2, ..., id_n (1 β€ id_i β€ 10^9), where id_i is the ID of the friend which sends you the i-th message.
Output
In the first line of the output print one integer m (1 β€ m β€ min(n, k)) β the number of conversations shown after receiving all n messages.
In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages.
Examples
Input
7 2
1 2 3 2 1 3 2
Output
2
2 1
Input
10 4
2 3 3 1 1 2 1 2 3 3
Output
3
1 3 2
Note
In the first example the list of conversations will change in the following way (in order from the first to last message):
* [];
* [1];
* [2, 1];
* [3, 2];
* [3, 2];
* [1, 3];
* [1, 3];
* [2, 1].
In the second example the list of conversations will change in the following way:
* [];
* [2];
* [3, 2];
* [3, 2];
* [1, 3, 2];
* and then the list will not change till the end. | from collections import deque
def solve(k, ids):
mes = deque(maxlen=k)
for i in ids:
if i not in mes:
mes.appendleft(i)
return len(mes), mes
n, k = map(int, input().split())
ids = input().split()
m, ids = solve(k, ids)
print(m)
print(' '.join(ids)) | {
"input": [
"10 4\n2 3 3 1 1 2 1 2 3 3\n",
"7 2\n1 2 3 2 1 3 2\n"
],
"output": [
"3\n1 3 2\n",
"2\n2 1\n"
]
} |
763 | 11 | There are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each position (that is, if a coordinate x appears k times among numbers b_1, β¦, b_4, there should be exactly k stones at x in the end).
We are allowed to move stones with the following operation: choose two stones at distinct positions x and y with at least one stone each, and move one stone from x to 2y - x. In other words, the operation moves a stone to a symmetric position relative to some other stone. At any moment it is allowed to have any number of stones at the same position.
Find any sequence of operations that achieves the goal, or determine that it is impossible. The sequence does not have to be shortest, but it may contain at most 1000 operations.
Input
The first line contains four integers a_1, β¦, a_4 (-10^9 β€ a_i β€ 10^9) β initial coordinates of the stones. There may be multiple stones sharing the same coordinate.
The second line contains four integers b_1, β¦, b_4 (-10^9 β€ b_i β€ 10^9) β target coordinates of the stones. There may be multiple targets sharing the same coordinate.
Output
If there is no sequence of operations that achieves the goal, print a single integer -1. Otherwise, on the first line print a single integer k (0 β€ k β€ 1000) β the number of operations in your sequence. On the next k lines, describe the operations. The i-th of these lines should contain two integers x_i and y_i (x_i β y_i) β coordinates of the moved stone and the center of symmetry stone for the i-th operation.
For each operation i, there should at least one stone in each of the coordinates x_i and y_i, and the resulting coordinate 2y_i - x_i must not exceed 10^{18} by absolute value.
If there are multiple suitable sequences, print any of them. It is guaranteed that if there is a suitable sequence of operations, then there is also a suitable sequence that satisfies all the additional requirement.
Examples
Input
0 1 2 3
3 5 6 8
Output
3
1 3
2 5
0 3
Input
0 0 0 0
1 1 1 1
Output
-1
Input
0 0 0 1
0 1 0 1
Output
-1 | def gcd(a, b):
while a and b:
a %= b
if a: b %= a
return a + b
def gcd2(A):
r = A[1] - A[0]
for i in (2, 3):
r = gcd(r, A[i] - A[0])
return r
def Mir(x, c): return c * 2 - x
def Solve(A):
A[0].sort()
A[1].sort()
gcds = [gcd2(A[0]), gcd2(A[1])]
I0, I1 = 0, 1
if A[0][-1] - A[0][0] > A[1][-1] - A[1][0]: I0, I1 = I1, I0
if A[I1][-1] == A[I1][0]:
if A[I1][0] == A[I0][0]: return []
return None
elif A[I0][-1] == A[I0][0]:
return None
if gcds[0] != gcds[1]: return None
if (A[0][0] - A[1][0]) % gcds[0] != 0: return None
ops = [[], []]
def Op(I, J1, JC):
ops[I].append((A[I0][J1], A[I0][JC]))
A[I0][J1] = Mir(A[I0][J1], A[I0][JC])
while True:
for a in A: a.sort()
if max(A[0][-1], A[1][-1]) - min(A[0][0], A[1][0]) <= gcds[0]: break
#print('====now', A)
gapL = abs(A[0][0] - A[1][0])
gapR = abs(A[0][-1] - A[1][-1])
if gapL > gapR:
I0, I1 = (0, 1) if A[0][0] < A[1][0] else (1, 0)
view = lambda x: x
else:
I0, I1 = (0, 1) if A[0][-1] > A[1][-1] else (1, 0)
view = lambda x: 3 - x
for a in A: a.sort(key=view)
lim = max(view(A[I0][-1]), view(A[I1][-1]))
B = [view(x) for x in A[I0]]
actioned = False
for J in (3, 2):
if Mir(B[0], B[J]) <= lim:
Op(I0, (0), (J))
actioned = True
break
if actioned: continue
if Mir(B[0], B[1]) > lim:
Op(I0, (3), (1))
continue
if (B[1] - B[0]) * 8 >= lim - B[0]:
Op(I0, (0), (1))
continue
if (B[3] - B[2]) * 8 >= lim - B[0]:
Op(I0, (0), (2))
Op(I0, (0), (3))
continue
if B[1] - B[0] < B[3] - B[2]:
Op(I0, (1), (2))
Op(I0, (1), (3))
else:
Op(I0, (2), (1))
Op(I0, (2), (0))
Op(I0, (0), (1))
if A[0] != A[1]: return None
return ops[0] + [(Mir(x, c), c) for x, c in reversed(ops[1])]
def Output(ops):
if ops is None:
print(-1)
return
print(len(ops))
for x, c in ops: print(x, c)
import sys
A = [list(map(int, sys.stdin.readline().split())) for _ in range(2)]
Output(Solve(A))
| {
"input": [
"0 1 2 3\n3 5 6 8\n",
"0 0 0 1\n0 1 0 1\n",
"0 0 0 0\n1 1 1 1\n"
],
"output": [
"\n3\n1 3\n2 5\n0 3\n",
"-1\n",
"-1\n"
]
} |
764 | 11 | This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in s).
After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.
The goal is to make the string sorted, i.e. all characters should be in alphabetical order.
Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the length of s.
The second line of the input contains the string s consisting of exactly n lowercase Latin letters.
Output
In the first line print one integer res (1 β€ res β€ n) β the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.
In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array c of length n, where 1 β€ c_i β€ res and c_i means the color of the i-th character.
Examples
Input
9
abacbecfd
Output
2
1 1 2 1 2 1 2 1 2
Input
8
aaabbcbb
Output
2
1 2 1 2 1 2 1 1
Input
7
abcdedc
Output
3
1 1 1 1 1 2 3
Input
5
abcde
Output
1
1 1 1 1 1 | def main():
n = int(input())
s = input()
lst = ['a']*n
ans=[]
m=0
for i in range(n):
for j in range(n):
if lst[j]<=s[i]:
lst[j] = s[i]
ans.append(j+1)
m = max(m, j+1)
break
print (m)
print (*ans)
main()
| {
"input": [
"8\naaabbcbb\n",
"5\nabcde\n",
"7\nabcdedc\n",
"9\nabacbecfd\n"
],
"output": [
"2\n1 1 1 1 1 1 2 2 \n",
"1\n1 1 1 1 1 \n",
"3\n1 1 1 1 1 2 3 \n",
"2\n1 1 2 1 2 1 2 1 2 \n"
]
} |
765 | 9 | You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{x-1} for j = 1, 2, β¦, k. Note that you are allowed to not select any indices at all.
You have to make a nondecreasing as fast as possible. Find the smallest number T such that you can make the array nondecreasing after at most T seconds.
Array a is nondecreasing if and only if a_{1} β€ a_{2} β€ β¦ β€ a_{n}.
You have to answer t independent test cases.
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 single integer n (1 β€ n β€ 10^{5}) β the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.
The second line of each test case contains n integers a_{1}, a_{2}, β¦, a_{n} (-10^{9} β€ a_{i} β€ 10^{9}).
Output
For each test case, print the minimum number of seconds in which you can make a nondecreasing.
Example
Input
3
4
1 7 6 5
5
1 2 3 4 5
2
0 -4
Output
2
0
3
Note
In the first test case, if you select indices 3, 4 at the 1-st second and 4 at the 2-nd second, then a will become [1, 7, 7, 8]. There are some other possible ways to make a nondecreasing in 2 seconds, but you can't do it faster.
In the second test case, a is already nondecreasing, so answer is 0.
In the third test case, if you do nothing at first 2 seconds and select index 2 at the 3-rd second, a will become [0, 0]. | t=int(input())
def f(x):
i=0
for _ in range(t):
n=int(input())
a=(list(map(int,input().split())))
k=0
for i in range(1,n):
if a[i-1]>a[i]:
d= a[i-1] - a[i]
a[i] = a[i-1]
k=max(k, len(bin(d))-2)
print(k)
| {
"input": [
"3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n"
],
"output": [
"2\n0\n3\n"
]
} |
766 | 7 | This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an operation, you select a prefix of a, and simultaneously invert the bits in the prefix (0 changes to 1 and 1 changes to 0) and reverse the order of the bits in the prefix.
For example, if a=001011 and you select the prefix of length 3, it becomes 011011. Then if you select the entire string, it becomes 001001.
Your task is to transform the string a into b in at most 3n operations. It can be proved that it is always possible.
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 3t lines contain descriptions of test cases.
The first line of each test case contains a single integer n (1β€ nβ€ 1000) β the length of the binary strings.
The next two lines contain two binary strings a and b of length n.
It is guaranteed that the sum of n across all test cases does not exceed 1000.
Output
For each test case, output an integer k (0β€ kβ€ 3n), followed by k integers p_1,β¦,p_k (1β€ p_iβ€ n). Here k is the number of operations you use and p_i is the length of the prefix you flip in the i-th operation.
Example
Input
5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1
Output
3 1 2 1
6 5 2 5 3 1 2
0
9 4 1 2 10 4 1 2 1 5
1 1
Note
In the first test case, we have 01β 11β 00β 10.
In the second test case, we have 01011β 00101β 11101β 01000β 10100β 00100β 11100.
In the third test case, the strings are already the same. Another solution is to flip the prefix of length 2, which will leave a unchanged. | def solve():
# put code here
n = int(input())
a=input()
b=input()
ans=[]
for i in range(n):
if a[i]!=b[i]:
ans.extend([i+1, 1, i+1])
print(len(ans), ' '.join(str(v) for v in ans))
t = int(input())
for _ in range(t):
solve()
| {
"input": [
"5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n"
],
"output": [
"3 1 2 1\n3 1 5 2\n0\n7 1 10 8 7 1 2 1\n1 1\n"
]
} |
767 | 7 | We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist?
Input
The first line contains one integer t (1 β€ t β€ 6000) β the number of test cases.
The only line of each test case contains two integers n and k (0 β€ n, k β€ 10^6) β the initial position of point A and desirable absolute difference.
Output
For each test case, print the minimum number of steps to make point B exist.
Example
Input
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
Output
0
3
1000000
0
1
0
Note
In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0.
In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3.
<image> | def func(n,k):
print(0+(n%2!=k%2))if n>=k else print(abs(n-k))
t=int(input())
for i in range(t):
n,k=map(int,input().split())
func(n,k)
| {
"input": [
"6\n4 0\n5 8\n0 1000000\n0 0\n1 0\n1000000 1000000\n"
],
"output": [
"0\n3\n1000000\n0\n1\n0\n"
]
} |
768 | 10 | You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p). | def res(n):
nu=s=1
for i in range(n):
nu=(nu*(2*n-i))%m
s=(s*(i+1))%m
return((nu*pow(s,m-2,m))%m)
m=998244353
n=int(input())
fg=sorted(list(map(int,input().split())))
f=abs((sum(fg[:n])-sum(fg[n:])))
print((f*res(n))%m)
#print(f) | {
"input": [
"5\n13 8 35 94 9284 34 54 69 123 846\n",
"2\n2 1 2 1\n",
"3\n2 2 2 2 2 2\n",
"1\n1 4\n"
],
"output": [
"2588544",
"12",
"0",
"6"
]
} |
769 | 10 | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1 | a1,a2,a3,a4=map(int,input().split())
L=[]
def Solve(a1,a2,a3,a4):
if(a3-a4<-1 or a3-a4>1 or a1<a3 or a1<a4 or a2<a3 or a2<a4):
return -1
elif(a3-a4==0):
Ans="47"*a3
Ans+="4"
if(a1-a3==0 and a2-a4==0):
return -1
elif(a1-a3==0):
return "74"*a3+"7"*(a2-a4)
return "4"*(a1-a3-1)+Ans[:len(Ans)-1]+"7"*(a2-a4)+"4"
elif(a3-a4==1):
if(a2==a4):
return -1
Ans="47"*a3
Ans="4"*(a1-a3)+Ans+"7"*(a2-a4-1)
return Ans
else:
if(a3==a1):
return -1
Ans="74"*a4
Ans="7"+"4"*(a1-a3-1)+Ans[1:len(Ans)-1]+"7"*(a2-a4)+"4"
return Ans
print(Solve(a1,a2,a3,a4))
# Made By Mostafa_Khaled | {
"input": [
"2 2 1 1\n",
"4 7 3 1\n"
],
"output": [
"4774\n",
"-1\n"
]
} |
770 | 9 | Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3]; | from collections import defaultdict
def mkprefix(a):
b = []
sm = 0
for i in range(len(a)):
sm+= a[i]
b.append(sm)
return b
R = lambda : list(map(int,input().split()))
for _ in range(int(input())):
n = int(input())
u = R()
s = R()
d = defaultdict(lambda : list())
for i in range(n):
d[u[i]].append(s[i])
for key in d.keys():
d[key].sort(reverse=True)
d[key] = mkprefix(d[key])
ans = [0]*n
for u in d.keys():
l = len(d[u])
for i in range(l):
idx = l-(l%(i+1)) -1
ans[i]+=d[u][idx]
print(*ans)
| {
"input": [
"4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n3083\n"
],
"output": [
"\n29 28 26 19 0 0 0 \n24907 20705 22805 9514 0 0 0 0 0 0 \n43 43 43 32 38 43 \n3083 \n"
]
} |
771 | 9 | AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right. | import sys
input = sys.stdin.readline
def main():
n=int(input())
a=list(map(int,input().split()))
if sorted(a)[::2]==sorted(a[::2]):
print("YES")
else:
print("NO")
for _ in range(int(input())):
main()
| {
"input": [
"3\n4\n4 3 2 5\n4\n3 3 2 2\n5\n1 2 3 5 4\n"
],
"output": [
"YES\nYES\nNO\n"
]
} |
772 | 11 | John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14 |
n,m,l,f,L=10000,15000,int(10**13),int(input()),[]
def F(i):
if i==0:
return (0,1)
x,y=F(i>>1)
x,y=((2*x*y-x*x)%n,(y*y+x*x)%n)
if i&1:
x,y=(y%n,(x+y)%n)
return (x,y)
for i in range(m):
if F(i)[0]==f%n:
L.append(i)
while n<l:
n*=10;
T=[]
for i in L:
for j in range(10):
if F(i+j*m)[0]==f%n:
T.append(i+j*m)
L=T;m*=10
if L==[]:
break
if L==[]:
print(-1)
else:
L.sort()
print(L[0]) | {
"input": [
"13\n",
"377\n"
],
"output": [
"7\n",
"14\n"
]
} |
773 | 9 | You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0 |
def find_all(s, c):
index = s.index(c)
while True:
yield index
try:
index = s.index(c, index + 1)
except ValueError:
break
n = int(input())
row, col, actions = [], [], []
available = list(range(1, n + 1))
for _ in range(n - 1):
(r, c) = map(int, input().split(' '))
row.append(r)
col.append(c)
for cur in range(n, 1, -1):
if not row:
break
# for column
if cur in col:
indices = list(find_all(col, cur))
zero = list(set(available) - set(col))[0]
actions.append([2, cur, zero])
for i in indices:
col[i] = zero
# row
try:
idx = row.index(cur)
indices = list(find_all(row, cur))
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
continue
except ValueError:
val = row[0]
indices = list(find_all(row, val))
actions.append([1, row[0], cur])
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
if not actions:
print(0)
else:
print(len(actions))
for move in actions:
print(*move)
| {
"input": [
"3\n3 1\n1 3\n",
"2\n1 2\n",
"3\n2 1\n3 2\n"
],
"output": [
"3\n2 2 3\n1 1 3\n1 1 2\n",
"2\n2 1 2\n1 1 2\n",
"0\n"
]
} |
774 | 9 | There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 50) β the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 β€ ai β€ 50). ai means the amount of wash basins in the i-th room.
Output
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
Examples
Input
1 1
2
Output
1.00000000000000000000
Input
2 2
1 1
Output
1.50000000000000000000
Input
2 3
1 1 1
Output
1.33333333333333350000
Input
7 5
1 1 2 3 1
Output
2.50216960000000070000 | from sys import stdin
input = stdin.buffer.readline
def c(n, k):
if k > n:
return 0
a = b = 1
for i in range(n - k + 1, n + 1):
a *= i
for i in range(1, k + 1):
b *= i
return a // b
n, m = map(int, input().split())
*a, = map(int, input().split())
dp = [[[0 for k in range(n + 1)] for j in range(m + 1)] for i in range(n + 1)]
p = [[[0 for x in range(n + 1)] for j in range(m + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
for x in range(i + 1):
p[i][j][x] = c(i, x) * (1 / j) ** x * ((j - 1) / j) ** (i - x)
for i in range(n + 1):
for j in range(1, m + 1):
for k in range(n + 1):
if i == 0:
dp[i][j][k] = k
continue
if j == 1:
dp[i][j][k] = max(k, (i + a[0] - 1) // a[0])
continue
if j == 0:
continue
for x in range(i + 1):
dp[i][j][k] += p[i][j][x] * (dp[i - x][j - 1][max(k, (x + a[j - 1] - 1) // a[j - 1])])
print(dp[n][m][0])
# print(dp[0], dp[1], dp[2], sep='\n')
| {
"input": [
"2 2\n1 1\n",
"2 3\n1 1 1\n",
"7 5\n1 1 2 3 1\n",
"1 1\n2\n"
],
"output": [
"1.500000000000000\n",
"1.333333333333333\n",
"2.502169600000002\n",
"1.000000000000000\n"
]
} |
775 | 9 | During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4. | from sys import stdin,stdout
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
def fn(a):
print('a',a)
n=len(a)
pos1=[0]
for i in range(1,n):
pos1+=[pos1[-1]+a[i]*i]
print('pos1',pos1)
neg=[]
for i in range(n):
neg+=[i*(n-i-1)*a[i]]
print('neg',neg)
d=[]
for i in range(1,n+1):
sm=0
for j in range(1,i):
sm+=a[j-1]*(j-1)-(n-i)*a[i-1]
d+=[sm]
print('d',d);
print('================================')
p=-1
for i in range(1,n):
if pos1[i-1]-neg[i]<k:
p=i
break
if p==-1:return
a.pop(p)
fn(a)
for _ in range(1):#nmbr()):
n,k=lst()
a=lst()
# fn(a)
# exit(0)
pos = [0]
for i in range(1, n):
pos += [pos[-1] + a[i] * i]
removed=0
positive_term=0
for i in range(1,n):
negative_term=(i-removed)*a[i]*(n-i-1)
# print(positive_term,positive_term-negative_term)
if (positive_term-negative_term)<k:
removed+=1
stdout.write(str(i+1)+'\n')
else:positive_term += (i - removed) * a[i]
| {
"input": [
"5 0\n5 3 4 1 2\n",
"10 -10\n5 5 1 7 5 1 2 4 9 2\n"
],
"output": [
"2\n3\n4\n",
"2\n4\n5\n7\n8\n9\n"
]
} |
776 | 8 | One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an β an, a1, a2, ..., an - 1.
Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
Input
The first line contains an integer n (2 β€ n β€ 105). The second line contains n integer numbers a1, a2, ..., an (1 β€ ai β€ 105).
Output
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
Examples
Input
2
2 1
Output
1
Input
3
1 3 2
Output
-1
Input
2
1 2
Output
0 | def min_moves(n,l):
m,k=0,0
for i in range(n-1):
if l[i+1]<l[i]:
return (-1,n-i-1)[sorted(l)==l[i+1:]+l[:i+1]]
break
else:
return 0
n=int(input())
l=list(map(int,input().split()))
print(min_moves(n,l)) | {
"input": [
"3\n1 3 2\n",
"2\n1 2\n",
"2\n2 1\n"
],
"output": [
"-1\n",
"0\n",
"1\n"
]
} |
777 | 7 | One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
Input
The first (and the only) input line contains integer number w (1 β€ w β€ 100) β the weight of the watermelon bought by the boys.
Output
Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.
Examples
Input
8
Output
YES
Note
For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant β two parts of 4 and 4 kilos). | def a(n):
return "YES" if n%2==0 and n!=2 else "NO"
print(a(int(input()))) | {
"input": [
"8\n"
],
"output": [
"YES\n"
]
} |
778 | 7 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.
Examples
Input
ABA
Output
NO
Input
BACFAB
Output
YES
Input
AXBYBXA
Output
NO
Note
In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".
In the second sample test there are the following occurrences of the substrings: BACFAB.
In the third sample test there is no substring "AB" nor substring "BA". | def f(inp, ab, ba):
i = inp.find(ab)
return i != -1 and inp.find(ba, i + 2) != -1
inp = input()
if (f(inp, "AB", "BA") or f(inp, "BA", "AB")):
print ("YES")
else:
print ("NO")
| {
"input": [
"ABA\n",
"AXBYBXA\n",
"BACFAB\n"
],
"output": [
"NO\n",
"NO\n",
"YES\n"
]
} |
779 | 8 | You are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 β€ n β€ 106, 2 β€ m β€ 103) β the size of the original sequence and the number such that sum should be divisible by it.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 109).
Output
In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.
Examples
Input
3 5
1 2 3
Output
YES
Input
1 6
5
Output
NO
Input
4 6
3 1 1 3
Output
YES
Input
6 6
5 5 5 5 5 5
Output
YES
Note
In the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.
In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.
In the third sample test you need to choose two numbers 3 on the ends.
In the fourth sample test you can take the whole subsequence. | def solve():
n, m = map(int, input().split())
a = list(map(int, input().split()))
if n >= m:
return "YES"
s = set()
for i in a:
w = set()
for j in s:
w.add((i+j)%m)
s.update(w)
s.add(i%m)
if 0 in s:
return "YES"
return "NO"
print(solve())
| {
"input": [
"4 6\n3 1 1 3\n",
"1 6\n5\n",
"6 6\n5 5 5 5 5 5\n",
"3 5\n1 2 3\n"
],
"output": [
"YES\n",
"NO\n",
"YES\n",
"YES\n"
]
} |
780 | 7 | Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer n?"
Petya knows only 5 integer types:
1) byte occupies 1 byte and allows you to store numbers from - 128 to 127
2) short occupies 2 bytes and allows you to store numbers from - 32768 to 32767
3) int occupies 4 bytes and allows you to store numbers from - 2147483648 to 2147483647
4) long occupies 8 bytes and allows you to store numbers from - 9223372036854775808 to 9223372036854775807
5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer n. Since BigInteger works much slower, Peter regards it last. Help him.
Input
The first line contains a positive number n. It consists of no more than 100 digits and doesn't contain any leading zeros. The number n can't be represented as an empty string.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Output
Print the first type from the list "byte, short, int, long, BigInteger", that can store the natural number n, in accordance with the data given above.
Examples
Input
127
Output
byte
Input
130
Output
short
Input
123456789101112131415161718192021222324
Output
BigInteger | def limit(n,l,z):
if abs(n) <= abs(l) or n == l-1:
print(z)
exit()
else:
pass
a = int(input())
limit(a,-127,'byte')
limit(a,-32767,'short')
limit(a,-2147483647,'int')
limit(a,-9223372036854775807,'long')
print('BigInteger') | {
"input": [
"123456789101112131415161718192021222324\n",
"127\n",
"130\n"
],
"output": [
"BigInteger\n",
"byte\n",
"short\n"
]
} |
781 | 12 | Heidi has finally found the mythical Tree of Life β a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).
To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree β these are paths of length 2, i.e., consisting of two edges. Help her!
Input
The first line of the input contains a single integer n β the number of vertices in the tree (1 β€ n β€ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b β the labels of the vertices connected by the edge (1 β€ a < b β€ n). It is guaranteed that the input represents a tree.
Output
Print one integer β the number of lifelines in the tree.
Examples
Input
4
1 2
1 3
1 4
Output
3
Input
5
1 2
2 3
3 4
3 5
Output
4
Note
In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5. | def main():
n = int(input())
l = [0] * (n + 1)
for _ in range(n - 1):
a, b = map(int, input().split())
l[a] += 1
l[b] += 1
res = 0
for x in l:
res += x * (x - 1)
print(res // 2)
if __name__ == '__main__':
main()
| {
"input": [
"4\n1 2\n1 3\n1 4\n",
"5\n1 2\n2 3\n3 4\n3 5\n"
],
"output": [
"3\n",
"4\n"
]
} |
782 | 11 | Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.
Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.
As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 100, 0 β€ k β€ min(20, n - 1)) β the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.
Each of the next n - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ n) β indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.
Output
Print one integer β the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).
Examples
Input
2 0
1 2
Output
1
Input
2 1
1 2
Output
3
Input
4 1
1 2
2 3
3 4
Output
9
Input
7 2
1 2
2 3
1 4
4 5
1 6
6 7
Output
91
Note
In the first sample, Ostap has to paint both vertices black.
In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.
In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. | def main():
n, k = map(int, input().split())
cnt = [[[0] * 21 for _ in (0, 1)] for _ in range(n + 1)]
edges, mod = [[] for _ in range(n + 1)], 1000000007
for _ in range(n - 1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
def dfs(u, f):
cnt[u][0][0] = cnt[u][1][k] = 1
for v in edges[u]:
if v != f:
dfs(v, u)
tmp0, tmp1 = [0] * 21, [0] * 21
for i in range(k + 1):
for j in range(k + 1):
if i != k:
tmp0[j if i < j else i + 1] += cnt[u][0][j] * cnt[v][0][i]
if i < j:
tmp1[j] += cnt[u][1][j] * cnt[v][0][i]
elif i != k:
tmp0[i + 1] += cnt[u][1][j] * cnt[v][0][i]
if i > j:
tmp1[i - 1] += cnt[u][0][j] * cnt[v][1][i]
else:
tmp0[j] += cnt[u][0][j] * cnt[v][1][i]
tmp1[max(i - 1, j)] += cnt[u][1][j] * cnt[v][1][i]
for i in range(21):
tmp0[i] %= mod
tmp1[i] %= mod
cnt[u][0] = tmp0
cnt[u][1] = tmp1
dfs(1, 1)
print(sum(cnt[1][1][j] for j in range(k + 1)) % mod)
if __name__ == '__main__':
main()
| {
"input": [
"7 2\n1 2\n2 3\n1 4\n4 5\n1 6\n6 7\n",
"4 1\n1 2\n2 3\n3 4\n",
"2 0\n1 2\n",
"2 1\n1 2\n"
],
"output": [
"91\n",
"9\n",
"1\n",
"3\n"
]
} |
783 | 10 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.
Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:
1. the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN",
2. or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB".
Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.
Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of clubs in the league.
Each of the next n lines contains two words β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.
Output
It it is not possible to choose short names and satisfy all constraints, print a single line "NO".
Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input.
If there are multiple answers, print any of them.
Examples
Input
2
DINAMO BYTECITY
FOOTBALL MOSCOW
Output
YES
DIN
FOO
Input
2
DINAMO BYTECITY
DINAMO BITECITY
Output
NO
Input
3
PLAYFOOTBALL MOSCOW
PLAYVOLLEYBALL SPB
GOGO TECHNOCUP
Output
YES
PLM
PLS
GOG
Input
3
ABC DEF
ABC EFG
ABD OOO
Output
YES
ABD
ABE
ABO
Note
In the first sample Innokenty can choose first option for both clubs.
In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.
In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.
In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | from sys import stdin
n = int(stdin.readline().strip())
T,A = [],[]
N,M = {},{}
for _ in range(n):
t,h = stdin.readline().split()
n1,n2 = t[:3],t[:2]+h[0]
N[n1] = N.get(n1,0)+1
T.append((n1,n2))
A.append(n1)
def solve():
for i in range(n):
n1,n2 = T[i]
if n1 not in M and N[n1]==1:
M[n1] = i
continue
while n2 in M:
j = M[n2]
if n2==T[j][1]:
return False
M[n2],A[i]=i,n2
i,n2 = j,T[j][1]
else:
M[n2],A[i] = i,n2
return True
if solve():
print("YES")
print('\n'.join(A))
else:
print("NO")
| {
"input": [
"3\nABC DEF\nABC EFG\nABD OOO\n",
"2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n",
"3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n",
"2\nDINAMO BYTECITY\nDINAMO BITECITY\n"
],
"output": [
"YES\nABD\nABE\nABO\n",
"YES\nDIN\nFOO\n",
"YES\nPLM\nPLS\nGOG\n",
"NO\n"
]
} |
784 | 7 | A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs <image> and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of schools.
Output
Print single integer: the minimum cost of tickets needed to visit all schools.
Examples
Input
2
Output
0
Input
10
Output
4
Note
In the first example we can buy a ticket between the schools that costs <image>. | def find(n):
return (n + 1) // 2 - 1
print(find(int(input())))
| {
"input": [
"10\n",
"2\n"
],
"output": [
"4\n",
"0\n"
]
} |
785 | 10 | Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array a with indices from [l, r) can be implemented as follows:
1. If the segment [l, r) is already sorted in non-descending order (that is, for any i such that l β€ i < r - 1 a[i] β€ a[i + 1]), then end the function call;
2. Let <image>;
3. Call mergesort(a, l, mid);
4. Call mergesort(a, mid, r);
5. Merge segments [l, mid) and [mid, r), making the segment [l, r) sorted in non-descending order. The merge algorithm doesn't call any other functions.
The array in this problem is 0-indexed, so to sort the whole array, you need to call mergesort(a, 0, n).
The number of calls of function mergesort is very important, so Ivan has decided to calculate it while sorting the array. For example, if a = {1, 2, 3, 4}, then there will be 1 call of mergesort β mergesort(0, 4), which will check that the array is sorted and then end. If a = {2, 1, 3}, then the number of calls is 3: first of all, you call mergesort(0, 3), which then sets mid = 1 and calls mergesort(0, 1) and mergesort(1, 3), which do not perform any recursive calls because segments (0, 1) and (1, 3) are sorted.
Ivan has implemented the program that counts the number of mergesort calls, but now he needs to test it. To do this, he needs to find an array a such that a is a permutation of size n (that is, the number of elements in a is n, and every integer number from [1, n] can be found in this array), and the number of mergesort calls when sorting the array is exactly k.
Help Ivan to find an array he wants!
Input
The first line contains two numbers n and k (1 β€ n β€ 100000, 1 β€ k β€ 200000) β the size of a desired permutation and the number of mergesort calls required to sort it.
Output
If a permutation of size n such that there will be exactly k calls of mergesort while sorting it doesn't exist, output - 1. Otherwise output n integer numbers a[0], a[1], ..., a[n - 1] β the elements of a permutation that would meet the required conditions. If there are multiple answers, print any of them.
Examples
Input
3 3
Output
2 1 3
Input
4 1
Output
1 2 3 4
Input
5 6
Output
-1 | n,k=map(int,input().split())
if not k&1:exit(print(-1))
k-=1
a=[int(i+1) for i in range(n)]
def f(l,r):
global k
if k<2or r-l<2:return
k-=2
m=(l+r)//2
a[m],a[m-1]=a[m-1],a[m]
f(l,m)
f(m,r)
f(0,n)
if k:exit(print(-1))
for i in a:
print(int(i),end=' ')
| {
"input": [
"3 3\n",
"5 6\n",
"4 1\n"
],
"output": [
"3 1 2 \n",
"-1\n",
"1 2 3 4 \n"
]
} |
786 | 9 | Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.
Help Petya to split the integers. Each of n integers should be exactly in one group.
Input
The first line contains a single integer n (2 β€ n β€ 60 000) β the number of integers Petya has.
Output
Print the smallest possible absolute difference in the first line.
In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.
Examples
Input
4
Output
0
2 1 4
Input
2
Output
1
1 1
Note
In the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.
In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1. |
def case_not_4(n):
res = n*(n+1)//4
a = []
s = res
i = n
while (s != 0):
if (s >= i):
s -= i
a.append(i)
i -= 1
if (res*4 == n*(n+1)):
print(0)
else:
print(1)
print(len(a), end=' ')
for i in a:
print(i, end=' ')
n = int(input())
case_not_4(n) | {
"input": [
"2\n",
"4\n"
],
"output": [
"1\n1 1",
"0\n2 4 1\n"
]
} |
787 | 8 | Alice and Bob begin their day with a quick game. They first choose a starting number X0 β₯ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi β₯ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
Input
The input contains a single integer X2 (4 β€ X2 β€ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.
Output
Output a single integer β the minimum possible X0.
Examples
Input
14
Output
6
Input
20
Output
15
Input
8192
Output
8191
Note
In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:
* Alice picks prime 5 and announces X1 = 10
* Bob picks prime 7 and announces X2 = 14.
In the second case, let X0 = 15.
* Alice picks prime 2 and announces X1 = 16
* Bob picks prime 5 and announces X2 = 20. | from math import sqrt
import sys
# from io import StringIO
#
# sys.stdin = StringIO(open(__file__.replace('.py', '.in')).read())
def largest_prime_factor(n):
for i in range(2, int(sqrt(n) + 1)):
if n % i == 0:
return largest_prime_factor(n // i)
return n
x2 = int(input())
p2 = largest_prime_factor(x2)
m = sys.maxsize
for x1 in range(x2 - p2 + 1, x2 + 1):
p1 = largest_prime_factor(x1)
if p1 != x1 and m > x1 - p1 + 1:
m = x1 - p1 + 1
print(m)
| {
"input": [
"8192\n",
"20\n",
"14\n"
],
"output": [
"8191\n",
"15\n",
"6\n"
]
} |
788 | 8 | You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.
Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions.
Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) β the bottom left corner. Then she starts moving in the snake fashion β all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2).
Lara has already moved to a neighbouring cell k times. Can you determine her current position?
Input
The only line contains three integers n, m and k (2 β€ n, m β€ 109, n is always even, 0 β€ k < nΒ·m). Note that k doesn't fit into 32-bit integer type!
Output
Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times.
Examples
Input
4 3 0
Output
1 1
Input
4 3 11
Output
1 2
Input
4 3 7
Output
3 2
Note
Here is her path on matrix 4 by 3:
<image> | def inpmap():
return list(map(int, input().split()))
n, m, k = inpmap()
if k < n:
print(k + 1, 1)
else:
k -= n
a, b = divmod(k, (m - 1))
print(n - a, m - b if a % 2 else b + 2)
| {
"input": [
"4 3 0\n",
"4 3 7\n",
"4 3 11\n"
],
"output": [
"1 1\n",
"3 2\n",
"1 2\n"
]
} |
789 | 9 | Recently Vasya found a golden ticket β a sequence which consists of n digits a_1a_2... a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. Note that each digit of sequence should belong to exactly one segment.
Help Vasya! Tell him if the golden ticket he found is lucky or not.
Input
The first line contains one integer n (2 β€ n β€ 100) β the number of digits in the ticket.
The second line contains n digits a_1 a_2 ... a_n (0 β€ a_i β€ 9) β the golden ticket. Digits are printed without spaces.
Output
If the golden ticket is lucky then print "YES", otherwise print "NO" (both case insensitive).
Examples
Input
5
73452
Output
YES
Input
4
1248
Output
NO
Note
In the first example the ticket can be divided into 7, 34 and 52: 7=3+4=5+2.
In the second example it is impossible to divide ticket into segments with equal sum. | def check(i):
s = 0
for x in b:
s += x
if s == i:
s = 0
if s == 0:
return True
return False
a = int(input())
b = [int(i) for i in list(input())]
for i in range(max(1, sum(b))):
if check(i):
print("YES")
break
else:
print("NO") | {
"input": [
"4\n1248\n",
"5\n73452\n"
],
"output": [
"NO\n",
"YES\n"
]
} |
790 | 7 | Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 β€ x_1, x_2, x_3 β€ n, 0 β€ y_1, y_2, y_3 β€ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Input
The single line contains three integers n, m, k (1β€ n, m β€ 10^9, 2 β€ k β€ 10^9).
Output
If there are no such points, print "NO".
Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i β coordinates of the points, one point per line. If there are multiple solutions, print any of them.
You can print each letter in any case (upper or lower).
Examples
Input
4 3 3
Output
YES
1 0
2 3
4 1
Input
4 4 7
Output
NO
Note
In the first example area of the triangle should be equal to nm/k = 4. The triangle mentioned in the output is pictured below:
<image>
In the second example there is no triangle with area nm/k = 16/7. | def gcd(a, b):
while b:
a, b = b, a % b
return a
n, m, k = map(int, input().split())
if n*m*2 % k:
print("NO")
else:
print("YES")
g1 = gcd(n, k)
n //= g1
k //= g1
g2 = gcd(m, k)
m //= g2
k //= g2
if k == 1:
if g1 == 1:
m *= 2
else:
n *= 2
print('0 0')
print('0', m)
print(n, '0')
| {
"input": [
"4 4 7\n",
"4 3 3\n"
],
"output": [
"NO\n",
"YES\n0 0\n4 0\n0 2\n"
]
} |
791 | 8 | Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.
Lyft has become so popular so that it is now used by all m taxi drivers in the city, who every day transport the rest of the city residents β n riders.
Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).
The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.
But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver i the number a_{i} β the number of riders that would call the i-th taxi driver when all drivers and riders are at their home?
The taxi driver can neither transport himself nor other taxi drivers.
Input
The first line contains two integers n and m (1 β€ n,m β€ 10^5) β number of riders and taxi drivers.
The second line contains n + m integers x_1, x_2, β¦, x_{n+m} (1 β€ x_1 < x_2 < β¦ < x_{n+m} β€ 10^9), where x_i is the coordinate where the i-th resident lives.
The third line contains n + m integers t_1, t_2, β¦, t_{n+m} (0 β€ t_i β€ 1). If t_i = 1, then the i-th resident is a taxi driver, otherwise t_i = 0.
It is guaranteed that the number of i such that t_i = 1 is equal to m.
Output
Print m integers a_1, a_2, β¦, a_{m}, where a_i is the answer for the i-th taxi driver. The taxi driver has the number i if among all the taxi drivers he lives in the i-th smallest coordinate (see examples for better understanding).
Examples
Input
3 1
1 2 3 10
0 0 1 0
Output
3
Input
3 2
2 3 4 5 6
1 0 0 0 1
Output
2 1
Input
1 4
2 4 6 10 15
1 1 1 1 0
Output
0 0 0 1
Note
In the first example, we have only one taxi driver, which means an order from any of n riders will go to him.
In the second example, the first taxi driver lives at the point with the coordinate 2, and the second one lives at the point with the coordinate 6. Obviously, the nearest taxi driver to the rider who lives on the 3 coordinate is the first one, and to the rider who lives on the coordinate 5 is the second one. The rider who lives on the 4 coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.
In the third example, we have one rider and the taxi driver nearest to him is the fourth one. | n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
def next(k,a):
i=k+1
while a[i]!=1: i+=1
return i
ans=[0]*(m+1)
k=-1
k=next(k,b)
ans[1]=k
for i in range(2,m+1):
kk=next(k,b)
for j in range(k+1,kk):
if a[j]-a[k]<=a[kk]-a[j]:
ans[i-1]+=1
else:
ans[i]+=1
k=kk
ans[m]+=(n+m-1-k)
for i in range(1,m+1):
print(ans[i],end=' ') | {
"input": [
"1 4\n2 4 6 10 15\n1 1 1 1 0\n",
"3 2\n2 3 4 5 6\n1 0 0 0 1\n",
"3 1\n1 2 3 10\n0 0 1 0\n"
],
"output": [
"0 0 0 1\n",
"2 1\n",
"3\n"
]
} |
792 | 9 | You are given an angle ang.
The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = ang or report that there is no such n-gon.
<image>
If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed 998244353.
Input
The first line contains single integer T (1 β€ T β€ 180) β the number of queries.
Each of the next T lines contains one integer ang (1 β€ ang < 180) β the angle measured in degrees.
Output
For each query print single integer n (3 β€ n β€ 998244353) β minimal possible number of vertices in the regular n-gon or -1 if there is no such n.
Example
Input
4
54
50
2
178
Output
10
18
90
180
Note
The answer for the first query is on the picture above.
The answer for the second query is reached on a regular 18-gon. For example, \angle{v_2 v_1 v_6} = 50^{\circ}.
The example angle for the third query is \angle{v_{11} v_{10} v_{12}} = 2^{\circ}.
In the fourth query, minimal possible n is 180 (not 90). | import math
def C():
T = int(input())
for i in range(T):
angle = int(input())
d = math.gcd(180,angle)
if(angle + d >= 180):
print(2*180// d)
continue
print(180//d)
C()
| {
"input": [
"4\n54\n50\n2\n178\n"
],
"output": [
"10\n18\n90\n180\n"
]
} |
793 | 10 | Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split.
Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic gem is chosen and split, it takes M units of space (since it is split into M gems); if a magic gem is not split, it takes 1 unit.
How many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is N units? Print the answer modulo 1000000007 (10^9+7). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ.
Input
The input contains a single line consisting of 2 integers N and M (1 β€ N β€ 10^{18}, 2 β€ M β€ 100).
Output
Print one integer, the total number of configurations of the resulting set of gems, given that the total amount of space taken is N units. Print the answer modulo 1000000007 (10^9+7).
Examples
Input
4 2
Output
5
Input
3 2
Output
3
Note
In the first example each magic gem can split into 2 normal gems, and we know that the total amount of gems are 4.
Let 1 denote a magic gem, and 0 denote a normal gem.
The total configurations you can have is:
* 1 1 1 1 (None of the gems split);
* 0 0 1 1 (First magic gem splits into 2 normal gems);
* 1 0 0 1 (Second magic gem splits into 2 normal gems);
* 1 1 0 0 (Third magic gem splits into 2 normal gems);
* 0 0 0 0 (First and second magic gems split into total 4 normal gems).
Hence, answer is 5. | import sys
MOD = 10**9+7
# Polymod
def polymod(P,Q):
assert(Q[-1]==1)
n = len(Q)
while len(P)>=n:
p = P[-1]
for i in range(n):
P[-i-1] -= p*Q[-i-1]
assert(P[-1]==0)
P.pop()
return P
def polyprod(P,Q):
n = len(P)
m = len(Q)
W = [0]*(n+m-1)
for i in range(n):
for j in range(m):
W[i+j]+=P[i]*Q[j]
return [w%MOD for w in W]
# Calc A^m * B
def power(A,B,m,mult):
if m == 0:
return B
while m>1:
if m%2==1:
B = mult(A,B)
A = mult(A,A)
m//=2
return mult(A,B)
def calc_nth_term(init,linear_coeff,n):
def mult(A,B):
return polymod(polyprod(A,B),linear_coeff)
ans = power([0,1],[1],n,mult)
return sum(ans[i]*init[i] for i in range(len(ans)))
n,m = [int(x) for x in input().split()]
linear_rec = [0]*(m+1)
linear_rec[0] = -1
linear_rec[m-1] = -1
linear_rec[m] = 1
print(calc_nth_term([1]*m,linear_rec,n)%MOD)
| {
"input": [
"3 2\n",
"4 2\n"
],
"output": [
"3\n",
"5\n"
]
} |
794 | 12 | Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an U-shaped parabola through each pair of the points that have different x coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.
The internal area of an U-shaped parabola is the part of the plane that lies strictly above the parabola when the y axis is directed upwards.
Input
The first line contains a single integer n (1 β€ n β€ 100 000) β the number of points.
The next n lines describe the points, the i-th of them contains two integers x_i and y_i β the coordinates of the i-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed 10^6 by absolute value.
Output
In the only line print a single integer β the number of U-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).
Examples
Input
3
-1 0
0 2
1 0
Output
2
Input
5
1 0
1 -1
0 -1
-1 0
-1 -1
Output
1
Note
On the pictures below all U-shaped parabolas that pass through at least two given points are drawn for each of the examples. The U-shaped parabolas that do not have any given point inside their internal area are drawn in red.
<image> The first example. <image> The second example. | import sys
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
N = int(input())
A = [None]*N
for i in range(N):
x, y = map(int, sys.stdin.readline().split())
A[i] = (x, y-x*x)
A.sort()
upper = []
for p in reversed(A):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
while len(upper) >= 2 and upper[-1][0] == upper[-2][0]:
upper.pop()
print(len(upper) - 1)
| {
"input": [
"3\n-1 0\n0 2\n1 0\n",
"5\n1 0\n1 -1\n0 -1\n-1 0\n-1 -1\n"
],
"output": [
"2\n",
"1\n"
]
} |
795 | 11 | Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen n distinct positive integers and put all of them in a set S. Now he defines a magical permutation to be:
* A permutation of integers from 0 to 2^x - 1, where x is a non-negative integer.
* The [bitwise xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of any two consecutive elements in the permutation is an element in S.
Since Kuro is really excited about magical permutations, he wants to create the longest magical permutation possible. In other words, he wants to find the largest non-negative integer x such that there is a magical permutation of integers from 0 to 2^x - 1. Since he is a newbie in the subject, he wants you to help him find this value of x and also the magical permutation for that x.
Input
The first line contains the integer n (1 β€ n β€ 2 β
10^5) β the number of elements in the set S.
The next line contains n distinct integers S_1, S_2, β¦, S_n (1 β€ S_i β€ 2 β
10^5) β the elements in the set S.
Output
In the first line print the largest non-negative integer x, such that there is a magical permutation of integers from 0 to 2^x - 1.
Then print 2^x integers describing a magical permutation of integers from 0 to 2^x - 1. If there are multiple such magical permutations, print any of them.
Examples
Input
3
1 2 3
Output
2
0 1 3 2
Input
2
2 3
Output
2
0 2 1 3
Input
4
1 2 3 4
Output
3
0 1 3 2 6 7 5 4
Input
2
2 4
Output
0
0
Input
1
20
Output
0
0
Input
1
1
Output
1
0 1
Note
In the first example, 0, 1, 3, 2 is a magical permutation since:
* 0 β 1 = 1 β S
* 1 β 3 = 2 β S
* 3 β 2 = 1 β S
Where β denotes [bitwise xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation. | def size(k):
return int(math.log2(k))
def v2(k):
if k%2==1:
return 0
else:
return 1+v2(k//2)
n=int(input())
s=list(map(int,input().split()))
import math
s.sort()
used=[]
use=0
found={0:1}
good=0
for guy in s:
big=size(guy)
if guy not in found:
used.append(guy)
use+=1
new=[]
for boi in found:
new.append(boi^guy)
for guy in new:
found[guy]=1
if use==big+1:
good=use
if good==0:
print(0)
print(0)
else:
useful=used[:good]
perm=["0"]
curr=0
for i in range(2**good-1):
curr^=useful[v2(i+1)]
perm.append(str(curr))
print(good)
print(" ".join(perm)) | {
"input": [
"1\n1\n",
"1\n20\n",
"2\n2 4\n",
"3\n1 2 3\n",
"2\n2 3\n",
"4\n1 2 3 4\n"
],
"output": [
"1\n0 1 ",
"0 \n0",
"0 \n0",
"2\n0 1 3 2 ",
"2\n0 2 1 3 ",
"3\n0 1 3 2 6 7 5 4 "
]
} |
796 | 8 | Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he understood, and he's ready to face the evils of the Empire!
The rebels have s spaceships, each with a certain attacking power a.
They want to send their spaceships to destroy the empire bases and steal enough gold and supplies in order to keep the rebellion alive.
The empire has b bases, each with a certain defensive power d, and a certain amount of gold g.
A spaceship can attack all the bases which have a defensive power less than or equal to its attacking power.
If a spaceship attacks a base, it steals all the gold in that base.
The rebels are still undecided which spaceship to send out first, so they asked for the Doctor's help. They would like to know, for each spaceship, the maximum amount of gold it can steal.
Input
The first line contains integers s and b (1 β€ s, b β€ 10^5), the number of spaceships and the number of bases, respectively.
The second line contains s integers a (0 β€ a β€ 10^9), the attacking power of each spaceship.
The next b lines contain integers d, g (0 β€ d β€ 10^9, 0 β€ g β€ 10^4), the defensive power and the gold of each base, respectively.
Output
Print s integers, the maximum amount of gold each spaceship can steal, in the same order as the spaceships are given in the input.
Example
Input
5 4
1 3 5 2 4
0 1
4 2
2 8
9 4
Output
1 9 11 9 11
Note
The first spaceship can only attack the first base.
The second spaceship can attack the first and third bases.
The third spaceship can attack the first, second and third bases. | s, b = map(int, input().split())
a = list(map(int, input().split()))
z = [[-1, 0]] + sorted(list(map(int, input().split())) for _ in range(b))
for i in range(1, b+1):
z[i][1] += z[i-1][1]
v = [p[0] for p in z]
def binary_search(v, x):
l, r = 0, len(v)-1
while l <= r:
m = l+r >> 1
if v[m] > x:
r = m-1
else:
l = m+1
return r+1
res = [z[binary_search(v, i) - 1][1] for i in a]
print(*res)
| {
"input": [
"5 4\n1 3 5 2 4\n0 1\n4 2\n2 8\n9 4\n"
],
"output": [
"1 9 11 9 11 "
]
} |
797 | 7 | You are given two binary strings x and y, which are binary representations of some two integers (let's denote these integers as f(x) and f(y)). You can choose any integer k β₯ 0, calculate the expression s_k = f(x) + f(y) β
2^k and write the binary representation of s_k in reverse order (let's denote it as rev_k). For example, let x = 1010 and y = 11; you've chosen k = 1 and, since 2^1 = 10_2, so s_k = 1010_2 + 11_2 β
10_2 = 10000_2 and rev_k = 00001.
For given x and y, you need to choose such k that rev_k is lexicographically minimal (read notes if you don't know what does "lexicographically" means).
It's guaranteed that, with given constraints, k exists and is finite.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Next 2T lines contain a description of queries: two lines per query. The first line contains one binary string x, consisting of no more than 10^5 characters. Each character is either 0 or 1.
The second line contains one binary string y, consisting of no more than 10^5 characters. Each character is either 0 or 1.
It's guaranteed, that 1 β€ f(y) β€ f(x) (where f(x) is the integer represented by x, and f(y) is the integer represented by y), both representations don't have any leading zeroes, the total length of x over all queries doesn't exceed 10^5, and the total length of y over all queries doesn't exceed 10^5.
Output
Print T integers (one per query). For each query print such k that rev_k is lexicographically minimal.
Example
Input
4
1010
11
10001
110
1
1
1010101010101
11110000
Output
1
3
0
0
Note
The first query was described in the legend.
In the second query, it's optimal to choose k = 3. The 2^3 = 1000_2 so s_3 = 10001_2 + 110_2 β
1000_2 = 10001 + 110000 = 1000001 and rev_3 = 1000001. For example, if k = 0, then s_0 = 10111 and rev_0 = 11101, but rev_3 = 1000001 is lexicographically smaller than rev_0 = 11101.
In the third query s_0 = 10 and rev_0 = 01. For example, s_2 = 101 and rev_2 = 101. And 01 is lexicographically smaller than 101.
The quote from Wikipedia: "To determine which of two strings of characters comes when arranging in lexicographical order, their first letters are compared. If they differ, then the string whose first letter comes earlier in the alphabet comes before the other string. If the first letters are the same, then the second letters are compared, and so on. If a position is reached where one string has no more letters to compare while the other does, then the first (shorter) string is deemed to come first in alphabetical order." | def solve():
x = input()
y = input().rjust(len(x), '0')
j = y.rfind('1')
i = x.rfind('1', 0, j + 1)
print(j - i)
for _ in range(int(input())):
solve() | {
"input": [
"4\n1010\n11\n10001\n110\n1\n1\n1010101010101\n11110000\n"
],
"output": [
"1\n3\n0\n0\n"
]
} |
798 | 7 | Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down c lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during d practical classes, after which it is unusable.
Polycarp's pencilcase can hold no more than k writing implements, so if Polycarp wants to take x pens and y pencils, they will fit in the pencilcase if and only if x + y β€ k.
Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!
Note that you don't have to minimize the number of writing implements (though their total number must not exceed k).
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases in the input. Then the test cases follow.
Each test case is described by one line containing five integers a, b, c, d and k, separated by spaces (1 β€ a, b, c, d, k β€ 100) β the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively.
In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.
Output
For each test case, print the answer as follows:
If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer -1. Otherwise, print two non-negative integers x and y β the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed k).
Example
Input
3
7 5 4 5 8
7 5 4 5 2
20 53 45 26 4
Output
7 1
-1
1 3
Note
There are many different answers for the first test case; x = 7, y = 1 is only one of them. For example, x = 3, y = 1 is also correct.
x = 1, y = 3 is the only correct answer for the third test case. | def ceil(x, y):
return x // y + bool(x % y)
for _ in range(int(input())):
a, b, c, d, k = map(int, input().split())
u, v = ceil(a, c), ceil(b, d)
if u + v > k:
print('-1')
else:
print(u, v)
| {
"input": [
"3\n7 5 4 5 8\n7 5 4 5 2\n20 53 45 26 4\n"
],
"output": [
"2 1\n-1\n1 3\n"
]
} |
799 | 11 | The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.
Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left.
Initially, the cursor is in the first (leftmost) character.
Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position.
Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence.
Formally, correct text (CT) must satisfy the following rules:
* any line without brackets is CT (the line can contain whitespaces);
* If the first character of the string β is (, the last β is ), and all the rest form a CT, then the whole line is a CT;
* two consecutively written CT is also CT.
Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me).
The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command.
The correspondence of commands and characters is as follows:
* L β move the cursor one character to the left (remains in place if it already points to the first character);
* R β move the cursor one character to the right;
* any lowercase Latin letter or bracket (( or )) β write the entered character to the position where the cursor is now.
For a complete understanding, take a look at the first example and its illustrations in the note below.
You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to:
* check if the current text in the editor is a correct text;
* if it is, print the least number of colors that required, to color all brackets.
If two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is 2, and for the bracket sequence (()(()())())(()) β is 3.
Write a program that prints the minimal number of colors after processing each command.
Input
The first line contains an integer n (1 β€ n β€ 10^6) β the number of commands.
The second line contains s β a sequence of commands. The string s consists of n characters. It is guaranteed that all characters in a string are valid commands.
Output
In a single line print n integers, where the i-th number is:
* -1 if the line received after processing the first i commands is not valid text,
* the minimal number of colors in the case of the correct text.
Examples
Input
11
(RaRbR)L)L(
Output
-1 -1 -1 -1 -1 -1 1 1 -1 -1 2
Input
11
(R)R(R)Ra)c
Output
-1 -1 1 1 -1 -1 1 1 1 -1 1
Note
In the first example, the text in the editor will take the following form:
1. (
^
2. (
^
3. (a
^
4. (a
^
5. (ab
^
6. (ab
^
7. (ab)
^
8. (ab)
^
9. (a))
^
10. (a))
^
11. (())
^ | import traceback
def push(stack, delta):
if stack:
_, d, mn, mx = stack[-1]
else:
d, mn, mx = 0, 0, 0
stack.append((delta, d + delta, min(d + delta, mn), max(d + delta, mx)))
def main():
n = int(input())
ss = input()
left = [(0, 0,0,0)]
right = [(0, 0,0,0)] * n
res = []
try:
for s in ss:
if s == 'R':
delta = right.pop()[0]
push(left, -delta)
elif s == 'L':
if len(left) > 1:
delta = left.pop()[0]
push(right, -delta)
else:
if left:
left.pop()
if s == '(':
delta = 1
elif s == ')':
delta = -1
else:
delta = 0
push(left, delta)
_, ld, lmn, lmx = left[-1]
_, rd, rmn, rmx = right[-1]
if ld == rd and lmn >= 0 and rmn >= 0:
res.append(max(ld, lmx, rmx))
else:
res.append(-1)
except Exception as e:
print(e)
traceback.print_exc()
print("size left %d size right %d"%(len(left), len(right)))
print(' '.join(map(str, res)))
if __name__ == "__main__":
main() | {
"input": [
"11\n(R)R(R)Ra)c\n",
"11\n(RaRbR)L)L(\n"
],
"output": [
"-1 -1 1 1 -1 -1 1 1 1 -1 1 ",
"-1 -1 -1 -1 -1 -1 1 1 -1 -1 2 "
]
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.