index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
1,000 | 12 | In Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems.
Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price.
Ann decided that she wants to buy such non-empty subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems exactly by k. Note that k may be positive, negative or zero.
Unfortunately, Ann is not sure on which segment the sale operates, but she has q assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that).
Currently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by k.
Input
The first line contains two integers n and k (1 β€ n β€ 100 000, - 109 β€ k β€ 109) β the number of books and the needed difference between the number of math problems and the number of economics problems.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ 2), where ti is 1 if the i-th book is on math or 2 if the i-th is on economics.
The third line contains n integers a1, a2, ..., an (0 β€ ai β€ 109), where ai is the number of problems in the i-th book.
The fourth line contains a single integer q (1 β€ q β€ 100 000) β the number of assumptions.
Each of the next q lines contains two integers li and ri (1 β€ li β€ ri β€ n) describing the i-th Ann's assumption.
Output
Print q lines, in the i-th of them print the number of subsegments for the i-th Ann's assumption.
Examples
Input
4 1
1 1 1 2
1 1 1 1
4
1 2
1 3
1 4
3 4
Output
2
3
4
1
Input
4 0
1 2 1 2
0 0 0 0
1
1 4
Output
10
Note
In the first sample Ann can buy subsegments [1;1], [2;2], [3;3], [2;4] if they fall into the sales segment, because the number of math problems is greater by 1 on them that the number of economics problems. So we should count for each assumption the number of these subsegments that are subsegments of the given segment.
Segments [1;1] and [2;2] are subsegments of [1;2].
Segments [1;1], [2;2] and [3;3] are subsegments of [1;3].
Segments [1;1], [2;2], [3;3], [2;4] are subsegments of [1;4].
Segment [3;3] is subsegment of [3;4]. | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import ceil
def prod(a, mod=10 ** 9 + 7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
n, k = map(int, input().split())
# a, b = map(int, input().split())
# c, d = map(int, input().split())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
# s = input()
for i in range(n):
# math = eco + k
# math - eco = k
if t[i] == 2:
a[i] *= -1
count = [0] * (n + 1)
pre = [0]
for i in a:
pre += [pre[-1] + i]
index = {}
cc = list(set(pre))
for i in range(len(cc)):
index[cc[i]] = i
minusK = [-1]*(n + 1)
plusK = [-1] * (n + 1)
zero = [-1] * (n + 1)
for i in range(n + 1):
if pre[i] - k in index:
minusK[i] = index[pre[i] - k]
if pre[i] + k in index:
plusK[i] = index[pre[i] + k]
zero[i] = index[pre[i]]
BLOCK_SIZE = 320
blocks = [[] for i in range(BLOCK_SIZE)]
q = int(input())
ans = [0]*q
for i in range(q):
l, r = map(int, input().split())
blocks[l // BLOCK_SIZE] += [[l-1, r, i]]
for i in range(len(blocks)):
if not blocks[i]: continue
blocks[i] = sorted(blocks[i], key=lambda x: x[1])
left = right = BLOCK_SIZE * i
res = 0
count[zero[left]] += 1
for l, r, ind in blocks[i]:
while right < r:
right += 1
if minusK[right] != -1:
res += count[minusK[right]]
count[zero[right]] += 1
while left < l:
count[zero[left]] -= 1
if plusK[left] != -1:
res -= count[plusK[left]]
left += 1
while left > l:
left -= 1
if plusK[left] != -1:
res += count[plusK[left]]
count[zero[left]] += 1
ans[ind] = res
while left <= right:
count[zero[left]] -= 1
if plusK[left] != -1:
res -= count[plusK[left]]
left += 1
assert res == 0
for i in ans:
print(i) | {
"input": [
"4 1\n1 1 1 2\n1 1 1 1\n4\n1 2\n1 3\n1 4\n3 4\n",
"4 0\n1 2 1 2\n0 0 0 0\n1\n1 4\n"
],
"output": [
"2\n3\n4\n1\n",
"10\n"
]
} |
1,001 | 8 | Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way:
<image>
This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder of division of polynomial <image> by polynomial <image>, it is also denoted as <image>.
Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials <image>. If the polynomial <image> is zero, the result is <image>, otherwise the result is the value the algorithm returns for pair <image>. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question.
You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair <image> to pair <image>.
Input
You are given a single integer n (1 β€ n β€ 150) β the number of steps of the algorithm you need to reach.
Output
Print two polynomials in the following format.
In the first line print a single integer m (0 β€ m β€ n) β the degree of the polynomial.
In the second line print m + 1 integers between - 1 and 1 β the coefficients of the polynomial, from constant to leading.
The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials.
If there is no answer for the given n, print -1.
If there are multiple answer, print any of them.
Examples
Input
1
Output
1
0 1
0
1
Input
2
Output
2
-1 0 1
1
0 1
Note
In the second example you can print polynomials x2 - 1 and x. The sequence of transitions is
(x2 - 1, x) β (x, - 1) β ( - 1, 0).
There are two steps in it. | n = int(input())
def print_poly(a):
print(len(a) - 1)
print(' '.join(map(str, a)))
def shift_add(a, mul, b):
c = [0] * (len(a) + 1)
for i in range(len(a)): c[i + 1] = a[i] * mul
for i in range(len(b)): c[i] += b[i]
return c
a = [0, 1]
b = [1]
for i in range(n - 1):
c = shift_add(a, 1, b)
if max(c) <= 1 and min(c) >= -1:
a, b = c, a
else:
c = shift_add(a, -1, b)
if max(c) <= 1 and min(c) >= -1:
a, b = c, a
else:
print('> <')
if a[-1] == -1:
a = list(map(lambda x: -x, a))
if b[-1] == -1:
b = list(map(lambda x: -x, b))
print_poly(a)
print_poly(b)
| {
"input": [
"1\n",
"2\n"
],
"output": [
"1\n0 1\n0\n1\n",
"2\n1 0 1\n1\n0 1\n"
]
} |
1,002 | 7 |
Input
The input contains a single integer a (10 β€ a β€ 999).
Output
Output 0 or 1.
Examples
Input
13
Output
1
Input
927
Output
1
Input
48
Output
0 | def main():
n = int(input())
print(n & 1)
if __name__ == '__main__':
main()
| {
"input": [
"13\n",
"48\n",
"927\n"
],
"output": [
"1\n",
"0\n",
"1\n"
]
} |
1,003 | 9 | Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u β v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuroβs body and sting him.
Kuro wants to know how many pair of city (u, v) he can take as his route. Since heβs not really bright, he asked you to help him with this problem.
Input
The first line contains three integers n, x and y (1 β€ n β€ 3 β
10^5, 1 β€ x, y β€ n, x β y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
n - 1 lines follow, each line contains two integers a and b (1 β€ a, b β€ n, a β b), describes a road connecting two towns a and b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.
Examples
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
Note
On the first example, Kuro can choose these pairs:
* (1, 2): his route would be 1 β 2,
* (2, 3): his route would be 2 β 3,
* (3, 2): his route would be 3 β 2,
* (2, 1): his route would be 2 β 1,
* (3, 1): his route would be 3 β 2 β 1.
Kuro can't choose pair (1, 3) since his walking route would be 1 β 2 β 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
On the second example, Kuro can choose the following pairs:
* (1, 2): his route would be 1 β 2,
* (2, 1): his route would be 2 β 1,
* (3, 2): his route would be 3 β 1 β 2,
* (3, 1): his route would be 3 β 1. |
import sys
import threading
from collections import defaultdict
n,x,y=list(map(int,input().split()))
adj=defaultdict(list)
for _ in range(n-1):
a,b=list(map(int,input().split()))
adj[a].append(b)
adj[b].append(a)
def fun(node,par,dest,ans):
cnt=1
for ch in adj[node]:
if ch != par:
cnt+=fun(ch,node,dest,ans)
if node==dest:
ans[0]=cnt*ans[0]
return cnt
def main():
ans=[1]
t=fun(x,0,y,ans)
fun(y,0,x,ans)
print(t*(t-1)-ans[0])
if __name__=="__main__":
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join() | {
"input": [
"3 1 3\n1 2\n2 3\n",
"3 1 3\n1 2\n1 3\n"
],
"output": [
"5\n",
"4\n"
]
} |
1,004 | 10 | You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n.
In a single move, you can choose any position i between 1 and n and increase a_i by 1.
Let's calculate c_r (0 β€ r β€ m-1) β the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder.
Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m.
Find the minimum number of moves to satisfy the above requirement.
Input
The first line of input contains two integers n and m (1 β€ n β€ 2 β
10^5, 1 β€ m β€ n). It is guaranteed that m is a divisor of n.
The second line of input contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9), the elements of the array.
Output
In the first line, print a single integer β the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m.
In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}.
Examples
Input
6 3
3 2 0 6 10 12
Output
3
3 2 0 7 10 14
Input
4 2
0 1 2 3
Output
0
0 1 2 3 | from sys import stdin
def solve():
n, m = map(int, stdin.readline().split())
a = list(map(int, stdin.readline().split()))
ans = 0
b = sorted(map(list, zip(map(lambda x: x % m, a), range(n))))
j = 0
need = n // m
for i in range(m):
e = j
while e < len(b) and b[e][0] == i:
e += 1
if e - j >= need:
for t in range(j + need, e):
b.append(b[t])
j = e
else:
for _ in range(need - (e - j)):
w = b.pop()
ans += (i - w[0]) % m
a[w[1]] += (i - w[0]) % m
j = e
print(ans)
print(*a)
solve()
| {
"input": [
"4 2\n0 1 2 3\n",
"6 3\n3 2 0 6 10 12\n"
],
"output": [
"0\n0 1 2 3 \n",
"3\n3 2 0 7 10 14 "
]
} |
1,005 | 10 | Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.
The Manhattan distance between two cells (x_1, y_1) and (x_2, y_2) is defined as |x_1 - x_2| + |y_1 - y_2|. For example, the Manhattan distance between the cells (5, 2) and (7, 1) equals to |5-7|+|2-1|=3.
<image> Example of a rhombic matrix.
Note that rhombic matrices are uniquely defined by n, m, and the coordinates of the cell containing the zero.
She drew a nΓ m rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of nβ
m numbers). Note that Sonya will not give you n and m, so only the sequence of numbers in this matrix will be at your disposal.
Write a program that finds such an nΓ m rhombic matrix whose elements are the same as the elements in the sequence in some order.
Input
The first line contains a single integer t (1β€ tβ€ 10^6) β the number of cells in the matrix.
The second line contains t integers a_1, a_2, β¦, a_t (0β€ a_i< t) β the values in the cells in arbitrary order.
Output
In the first line, print two positive integers n and m (n Γ m = t) β the size of the matrix.
In the second line, print two integers x and y (1β€ xβ€ n, 1β€ yβ€ m) β the row number and the column number where the cell with 0 is located.
If there are multiple possible answers, print any of them. If there is no solution, print the single integer -1.
Examples
Input
20
1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4
Output
4 5
2 2
Input
18
2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1
Output
3 6
2 3
Input
6
2 1 0 2 1 2
Output
-1
Note
You can see the solution to the first example in the legend. You also can choose the cell (2, 2) for the cell where 0 is located. You also can choose a 5Γ 4 matrix with zero at (4, 2).
In the second example, there is a 3Γ 6 matrix, where the zero is located at (2, 3) there.
In the third example, a solution does not exist. | def get(n,m,a,b,t):
freq=[0]*(t+1)
for i in range(n):
for j in range(m):
val=abs(i-a)+abs(j-b)
freq[val]+=1
return freq
t=int(input())
a=list(map(int,input().split()))
mx=max(a)
f=[0]*(t+1)
for i in a:
f[i]+=1
b=1
for i in range(1,mx+1):
if f[i]!=4*i:
b=i
break
n=1
a=-1
x=0
y=0
mila=False
while n*n<=t:
if t%n==0:
m=t//n
a=n+m-mx-b
x,y=n,m
if a>0 and a<=n and b>0 and b<=m and f==get(n,m,a-1,b-1,t):
mila=True
break
if a>0 and a<=m and b>0 and b<=n and f==get(n,m,b-1,a-1,t):
mila=True
a,b=b,a
break
n+=1
if not mila:
print(-1)
else:
print(x,y)
print(a,b) | {
"input": [
"20\n1 0 2 3 5 3 2 1 3 2 3 1 4 2 1 4 2 3 2 4\n",
"6\n2 1 0 2 1 2\n",
"18\n2 2 3 2 4 3 3 3 0 2 4 2 1 3 2 1 1 1\n"
],
"output": [
"4 5\n2 2\n",
"-1\n",
"3 6\n2 3\n"
]
} |
1,006 | 10 | Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In this problem no two ever existed orders will have the same price.
The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.
<image> The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10.
There are two possible actions in this orderbook:
1. Somebody adds a new order of some direction with some price.
2. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.
It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" β in this case you just accept the best BUY offer.
You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:
1. "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book.
2. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.
The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.
Input
The first line contains an integer n (1 β€ n β€ 363 304) β the number of actions in the log.
Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 β€ p β€ 308 983 066), describing an action type and price.
All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.
Output
Output the number of ways to restore directions of ADD actions modulo 10^9 + 7.
Examples
Input
6
ADD 1
ACCEPT 1
ADD 2
ACCEPT 2
ADD 3
ACCEPT 3
Output
8
Input
4
ADD 1
ADD 2
ADD 3
ACCEPT 2
Output
2
Input
7
ADD 1
ADD 2
ADD 3
ADD 4
ADD 5
ACCEPT 3
ACCEPT 5
Output
0
Note
In the first example each of orders may be BUY or SELL.
In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order. | from sys import stdin
from heapq import heappush, heappop
def main():
n, r, m = int(input()), 0, 1000000007
bb, ss, bs = [0], [m], []
for s in stdin.read().splitlines():
if s[1] == 'D':
p = int(s[4:])
if ss and ss[0] < p:
heappush(ss, p)
elif bb and -bb[0] > p:
heappush(bb, -p)
else:
bs.append(p)
else:
p = int(s[7:])
if -bb[0] < p < ss[0]:
r += 1
elif p == ss[0]:
heappop(ss)
elif p == -bb[0]:
heappop(bb)
else:
print(0)
return
for x in bs:
if x < p:
heappush(bb, -x)
elif x > p:
heappush(ss, x)
bs = []
print((len(bs) + 1) * pow(2, r, m) % m)
if __name__ == '__main__':
main()
| {
"input": [
"6\nADD 1\nACCEPT 1\nADD 2\nACCEPT 2\nADD 3\nACCEPT 3\n",
"4\nADD 1\nADD 2\nADD 3\nACCEPT 2\n",
"7\nADD 1\nADD 2\nADD 3\nADD 4\nADD 5\nACCEPT 3\nACCEPT 5\n"
],
"output": [
"8",
"2",
"0"
]
} |
1,007 | 10 | Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.
Vova can only use 2 Γ 1 bricks to put in the wall (he has infinite supply of them, however).
Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).
Note that Vova can't put bricks vertically.
Vova is a perfectionist, so he considers the wall completed when:
* all parts of the wall has the same height;
* the wall has no empty spaces inside it.
Can Vova complete the wall using any amount of bricks (possibly zero)?
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of parts in the wall.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β the initial heights of the parts of the wall.
Output
Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.
Examples
Input
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
Note
In the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].
In the second example Vova can put no bricks in the wall.
In the third example the wall is already complete. | def f():
b = [a[0]]
for e in a[1:]:
if b != []:
if e > b[-1]:
print('NO')
return
elif e == b[-1]:
b.pop()
else:
b.append(e)
else:
b.append(e)
if len(b)==0:
print('YES')
else:
if len(set(b))==1 and b[0]==max(a):
print('YES')
else:
print('NO')
n=int(input())
a=[int(i) for i in input().split()]
f() | {
"input": [
"2\n10 10\n",
"3\n4 5 3\n",
"5\n2 1 1 2 5\n"
],
"output": [
"YES\n",
"NO\n",
"YES\n"
]
} |
1,008 | 9 | Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:
* if the current length is at least 2, divide the base into 2 equal halves and destroy them separately, or
* burn the current base. If it contains no avenger in it, it takes A amount of power, otherwise it takes his B β
n_a β
l amount of power, where n_a is the number of avengers and l is the length of the current base.
Output the minimum power needed by Thanos to destroy the avengers' base.
Input
The first line contains four integers n, k, A and B (1 β€ n β€ 30, 1 β€ k β€ 10^5, 1 β€ A,B β€ 10^4), where 2^n is the length of the base, k is the number of avengers and A and B are the constants explained in the question.
The second line contains k integers a_{1}, a_{2}, a_{3}, β¦, a_{k} (1 β€ a_{i} β€ 2^n), where a_{i} represents the position of avenger in the base.
Output
Output one integer β the minimum power needed to destroy the avengers base.
Examples
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
Note
Consider the first example.
One option for Thanos is to burn the whole base 1-4 with power 2 β
2 β
4 = 16.
Otherwise he can divide the base into two parts 1-2 and 3-4.
For base 1-2, he can either burn it with power 2 β
1 β
2 = 4 or divide it into 2 parts 1-1 and 2-2.
For base 1-1, he can burn it with power 2 β
1 β
1 = 2. For 2-2, he can destroy it with power 1, as there are no avengers. So, the total power for destroying 1-2 is 2 + 1 = 3, which is less than 4.
Similarly, he needs 3 power to destroy 3-4. The total minimum power needed is 6. | from bisect import bisect,bisect_left
def rec(i,j):
x=bisect(ar,j)-bisect_left(ar,i)
if x==0:
return a
if i==j:
return b*x
m=(i+j)>>1
return min(b*(j-i+1)*x,rec(i,m)+rec(m+1,j))
n,k,a,b = map(int,input().split())
ar=list(map(int,input().split()))
ar.sort()
print(rec(1,2**n)) | {
"input": [
"3 2 1 2\n1 7\n",
"2 2 1 2\n1 3\n"
],
"output": [
"8",
"6"
]
} |
1,009 | 7 | Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1 β€ n β€ m β€ 5β
10^8).
Output
Print the number of moves to transform n to m, or -1 if there is no solution.
Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120 β 240 β 720 β 1440 β 4320 β 12960 β 25920 β 51840. The are 7 steps in total.
In the second example, no moves are needed. Thus, the answer is 0.
In the third example, it is impossible to transform 48 to 72. | a,b = map(int,input().split())
def rec(n,m,sc):
if n<m:rec(n * 2, m, sc + 1); rec(n * 3, m, sc + 1)
if n == m: print(sc);exit(0)
rec(a,b,0)
if 1: print('-1') | {
"input": [
"42 42\n",
"48 72\n",
"120 51840\n"
],
"output": [
"0\n",
"-1\n",
"7\n"
]
} |
1,010 | 9 | You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.
The substring s_{l}, s_{l+1}, ... , s_{r} is good if r - l + 1 = f(s_l ... s_r).
For example string s = 1011 has 5 good substrings: s_1 ... s_1 = 1, s_3 ... s_3 = 1, s_4 ... s_4 = 1, s_1 ... s_2 = 10 and s_2 ... s_4 = 011.
Your task is to calculate the number of good substrings of string s.
You have to answer t independent queries.
Input
The first line contains one integer t (1 β€ t β€ 1000) β the number of queries.
The only line of each query contains string s (1 β€ |s| β€ 2 β
10^5), consisting of only digits 0 and 1.
It is guaranteed that β_{i=1}^{t} |s_i| β€ 2 β
10^5.
Output
For each query print one integer β the number of good substrings of string s.
Example
Input
4
0110
0101
00001000
0001000
Output
4
3
4
3 | LOG = 20
def solve(s):
n = len(s)
res = 0
z = 0
for t in range(0, n):
if s[t] == '0':
z += 1
continue
for l in range(1, min(LOG, n - t + 1)):
x = int(s[t:t+l], 2)
# print(l, t, x, l + z)
if l + z >= x:
res += 1
# print(t, l, x, res, z)
z = 0
return res
t = int(input())
while t > 0:
t -= 1
s = input()
print(solve(s)) | {
"input": [
"4\n0110\n0101\n00001000\n0001000\n"
],
"output": [
"4\n3\n4\n3\n"
]
} |
1,011 | 7 | Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.
Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but the cost of the radiator with k sections is equal to k^2 burles.
Since rooms can have different sizes, you calculated that you need at least sum_i sections in total in the i-th room.
For each room calculate the minimum cost to install at most c_i radiators with total number of sections not less than sum_i.
Input
The first line contains single integer n (1 β€ n β€ 1000) β the number of rooms.
Each of the next n lines contains the description of some room. The i-th line contains two integers c_i and sum_i (1 β€ c_i, sum_i β€ 10^4) β the maximum number of radiators and the minimum total number of sections in the i-th room, respectively.
Output
For each room print one integer β the minimum possible cost to install at most c_i radiators with total number of sections not less than sum_i.
Example
Input
4
1 10000
10000 1
2 6
4 6
Output
100000000
1
18
10
Note
In the first room, you can install only one radiator, so it's optimal to use the radiator with sum_1 sections. The cost of the radiator is equal to (10^4)^2 = 10^8.
In the second room, you can install up to 10^4 radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.
In the third room, there 7 variants to install radiators: [6, 0], [5, 1], [4, 2], [3, 3], [2, 4], [1, 5], [0, 6]. The optimal variant is [3, 3] and it costs 3^2+ 3^2 = 18. | def f():
a=input().split()
c=int(a[0])
s=int(a[1])
m=s//c
q=s%c
print(m**2*(c-q)+(m+1)**2*q)
n=int(input())
i=0
while i<n:
f()
i+=1
| {
"input": [
"4\n1 10000\n10000 1\n2 6\n4 6\n"
],
"output": [
"100000000\n1\n18\n10\n"
]
} |
1,012 | 8 | This is the easy version of this problem. The only difference is the constraint on k β the number of gifts in the offer. In this version: k=2.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β today the offer "k of goods for the price of one" is held in store. Remember, that in this problem k=2.
Using this offer, Vasya can buy exactly k of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.
More formally, for each good, its price is determined by a_i β the number of coins it costs. Initially, Vasya has p coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:
* Vasya can buy one good with the index i if he currently has enough coins (i.e p β₯ a_i). After buying this good, the number of Vasya's coins will decrease by a_i, (i.e it becomes p := p - a_i).
* Vasya can buy a good with the index i, and also choose exactly k-1 goods, the price of which does not exceed a_i, if he currently has enough coins (i.e p β₯ a_i). Thus, he buys all these k goods, and his number of coins decreases by a_i (i.e it becomes p := p - a_i).
Please note that each good can be bought no more than once.
For example, if the store now has n=5 goods worth a_1=2, a_2=4, a_3=3, a_4=5, a_5=7, respectively, k=2, and Vasya has 6 coins, then he can buy 3 goods. A good with the index 1 will be bought by Vasya without using the offer and he will pay 2 coins. Goods with the indices 2 and 3 Vasya will buy using the offer and he will pay 4 coins. It can be proved that Vasya can not buy more goods with six coins.
Help Vasya to find out the maximum number of goods he can buy.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases in the test.
The next lines contain a description of t test cases.
The first line of each test case contains three integers n, p, k (2 β€ n β€ 2 β
10^5, 1 β€ p β€ 2β
10^9, k=2) β the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.
The second line of each test case contains n integers a_i (1 β€ a_i β€ 10^4) β the prices of goods.
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5. It is guaranteed that in this version of the problem k=2 for all test cases.
Output
For each test case in a separate line print one integer m β the maximum number of goods that Vasya can buy.
Example
Input
6
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
2 10000 2
10000 10000
2 9999 2
10000 10000
5 13 2
8 2 8 2 5
3 18 2
1 2 3
Output
3
4
2
0
4
3 | def mi():
return map(int, input().split())
for _ in range(int(input())):
n,p,k=mi()
a = sorted(list(mi()))
i=0
while i<n:
if i>=k:
a[i]+=a[i-k]
if a[i]>p:
break
i+=1
print (i) | {
"input": [
"6\n5 6 2\n2 4 3 5 7\n5 11 2\n2 4 3 5 7\n2 10000 2\n10000 10000\n2 9999 2\n10000 10000\n5 13 2\n8 2 8 2 5\n3 18 2\n1 2 3\n"
],
"output": [
"3\n4\n2\n0\n4\n3\n"
]
} |
1,013 | 8 | Alicia has an array, a_1, a_2, β¦, a_n, of non-negative integers. For each 1 β€ i β€ n, she has found a non-negative integer x_i = max(0, a_1, β¦, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, β¦, b_n: b_i = a_i - x_i.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}.
Alicia gives you the values b_1, b_2, β¦, b_n and asks you to restore the values a_1, a_2, β¦, a_n. Can you help her solve the problem?
Input
The first line contains one integer n (3 β€ n β€ 200 000) β the number of elements in Alicia's array.
The next line contains n integers, b_1, b_2, β¦, b_n (-10^9 β€ b_i β€ 10^9).
It is guaranteed that for the given array b there is a solution a_1, a_2, β¦, a_n, for all elements of which the following is true: 0 β€ a_i β€ 10^9.
Output
Print n integers, a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9), such that if you calculate x according to the statement, b_1 will be equal to a_1 - x_1, b_2 will be equal to a_2 - x_2, ..., and b_n will be equal to a_n - x_n.
It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.
Examples
Input
5
0 1 1 -2 1
Output
0 1 2 0 3
Input
3
1000 999999000 -1000000000
Output
1000 1000000000 0
Input
5
2 1 2 2 3
Output
2 3 5 7 10
Note
The first test was described in the problem statement.
In the second test, if Alicia had an array a = \{1000, 1000000000, 0\}, then x = \{0, 1000, 1000000000\} and b = \{1000-0, 1000000000-1000, 0-1000000000\} = \{1000, 999999000, -1000000000\}. | def I():return list(map(int,input().split()))
n=int(input())
b=I()
a=[b[0]]
m=a[0]
for i in range(1,n):
a.append(m+b[i])
m=max(a[i],m)
print(*a) | {
"input": [
"3\n1000 999999000 -1000000000\n",
"5\n2 1 2 2 3\n",
"5\n0 1 1 -2 1\n"
],
"output": [
"1000 1000000000 0\n",
"2 3 5 7 10\n",
"0 1 2 0 3\n"
]
} |
1,014 | 7 | You are given a special jigsaw puzzle consisting of nβ
m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece.
Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.
Input
The test consists of multiple test cases. The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next t lines contain descriptions of test cases.
Each test case contains two integers n and m (1 β€ n,m β€ 10^5).
Output
For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).
Example
Input
3
1 3
100000 100000
2 2
Output
YES
NO
YES
Note
For the first test case, this is an example solution:
<image>
For the second test case, we can show that no solution exists.
For the third test case, this is an example solution:
<image> | def main():
m,n =map(int,input().split())
if m*n<=4 or n==1 or m==1:
print("YES")
else:
print("NO")
t = int(input())
while t:
main()
t-=1 | {
"input": [
"3\n1 3\n100000 100000\n2 2\n"
],
"output": [
"YES\nNO\nYES\n"
]
} |
1,015 | 7 | Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored AΒ·BΒ·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.
At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) Γ (B - 2) Γ (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 Γ 1 Γ 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B ΠΈ C.
Given number n, find the minimally possible and maximally possible number of stolen hay blocks.
Input
The only line contains integer n from the problem's statement (1 β€ n β€ 109).
Output
Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
4
Output
28 41
Input
7
Output
47 65
Input
12
Output
48 105
Note
Let's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 Γ 4 Γ 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) Γ (4 - 2) Γ (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 Γ 3 Γ 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) Γ (3 - 2) Γ (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks. | from math import sqrt
p, n = [], int(input())
def f(x, y): return (x + 2) * (y + 2) + (2 * (x + y + 2) * n) // (x * y)
for x in range(2, int(sqrt(n)) + 1):
if n % x == 0: p.append(x)
p += [n // x for x in reversed(p)]
p.append(n)
u = v = f(1, 1)
for m in p:
for x in range(1, int(sqrt(m)) + 1):
if m % x == 0: u = min(u, f(x, m // x))
print(u, v) | {
"input": [
"12\n",
"4\n",
"7\n"
],
"output": [
"48 105\n",
"28 41\n",
"47 65\n"
]
} |
1,016 | 11 | Berland regional ICPC contest has just ended. There were m participants numbered from 1 to m, who competed on a problemset of n problems numbered from 1 to n.
Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to exactly k consecutive tasks of the problemset. The authors choose the segment of k consecutive tasks for themselves independently of each other. The segments can coincide, intersect or not intersect at all.
The i-th participant is interested in listening to the tutorial of all consecutive tasks from l_i to r_i. Each participant always chooses to listen to only the problem author that tells the tutorials to the maximum number of tasks he is interested in. Let this maximum number be a_i. No participant can listen to both of the authors, even if their segments don't intersect.
The authors want to choose the segments of k consecutive tasks for themselves in such a way that the sum of a_i over all participants is maximized.
Input
The first line contains three integers n, m and k (1 β€ n, m β€ 2000, 1 β€ k β€ n) β the number of problems, the number of participants and the length of the segment of tasks each of the problem authors plans to tell the tutorial to.
The i-th of the next m lines contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ n) β the segment of tasks the i-th participant is interested in listening to the tutorial to.
Output
Print a single integer β the maximum sum of a_i over all participants.
Examples
Input
10 5 3
1 3
2 4
6 9
6 9
1 8
Output
14
Input
10 3 3
2 4
4 6
3 5
Output
8
Input
4 4 1
3 3
1 1
2 2
4 4
Output
2
Input
5 4 5
1 2
2 3
3 4
4 5
Output
8
Note
In the first example the first author can tell the tutorial to problems from 1 to 3 and the second one β from 6 to 8. That way the sequence of a_i will be [3, 2, 3, 3, 3]. Notice that the last participant can't listen to both author, he only chooses the one that tells the maximum number of problems he's interested in.
In the second example the first one can tell problems 2 to 4, the second one β 4 to 6.
In the third example the first one can tell problems 1 to 1, the second one β 2 to 2. Or 4 to 4 and 3 to 3. Every pair of different problems will get the same sum of 2.
In the fourth example the first one can tell problems 1 to 5, the second one β 1 to 5 as well. | n, m, k = map(int, input().split());a = [list(map(int, input().split())) for _ in range(m)]
def solv(lst):
res = sum(lst[:k]);s = res
for i in range(n-k):s += lst[i+k] - lst[i];res = max(res, s)
return res
a.sort(key=lambda x: sum(x)/2);apr = [0]*n
for el in a:
for i in range(el[0]-1, el[1]):apr[i] += 1
res = solv(apr);bpr = [0]*n
for r, l in a:
for i in range(r-1, l):apr[i] -= 1;bpr[i] += 1
nres = solv(apr) + solv(bpr);res = max(res, nres)
print(res) | {
"input": [
"10 5 3\n1 3\n2 4\n6 9\n6 9\n1 8\n",
"4 4 1\n3 3\n1 1\n2 2\n4 4\n",
"5 4 5\n1 2\n2 3\n3 4\n4 5\n",
"10 3 3\n2 4\n4 6\n3 5\n"
],
"output": [
"\n14\n",
"\n2\n",
"\n8\n",
"\n8\n"
]
} |
1,017 | 9 | You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 β€ j < c_i.
Now you decided to unite chains in one graph in the following way:
1. the first chain is skipped;
2. the 1-st vertex of the i-th chain is connected by an edge with the a_i-th vertex of the (i - 1)-th chain;
3. the last (c_i-th) vertex of the i-th chain is connected by an edge with the b_i-th vertex of the (i - 1)-th chain.
<image> Picture of the first test case. Dotted lines are the edges added during uniting process
Calculate the length of the longest simple cycle in the resulting graph.
A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains the single integer n (2 β€ n β€ 10^5) β the number of chains you have.
The second line of each test case contains n integers c_1, c_2, ..., c_n (2 β€ c_i β€ 10^9) β the number of vertices in the corresponding chains.
The third line of each test case contains n integers a_1, a_2, ..., a_n (a_1 = -1; 1 β€ a_i β€ c_{i - 1}).
The fourth line of each test case contains n integers b_1, b_2, ..., b_n (b_1 = -1; 1 β€ b_i β€ c_{i - 1}).
Both a_1 and b_1 are equal to -1, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of n over all test cases doesn't exceed 10^5.
Output
For each test case, print the length of the longest simple cycle.
Example
Input
3
4
3 4 3 3
-1 1 2 2
-1 2 2 3
2
5 6
-1 5
-1 1
3
3 5 2
-1 1 1
-1 3 5
Output
7
11
8
Note
In the first test case, the longest simple cycle is shown below:
<image>
We can't increase it with the first chain, since in such case it won't be simple β the vertex 2 on the second chain will break simplicity. | import math
def solve(n,a,b,c):
ans=0
prev=0
for i in range(1,n):
cur = c[i] + 1 + abs(a[i]-b[i])
if(a[i]!=b[i]):
cur = max(cur, prev-abs(a[i]-b[i])+c[i]+1)
ans = max(ans,cur)
prev = cur
print(ans)
t = int(input())
for i in range(t):
n = int(input())
c = list(map(int,input().split()))
a = list(map(int,input().split()))
b = list(map(int,input().split()))
solve(n,a,b,c)
| {
"input": [
"3\n4\n3 4 3 3\n-1 1 2 2\n-1 2 2 3\n2\n5 6\n-1 5\n-1 1\n3\n3 5 2\n-1 1 1\n-1 3 5\n"
],
"output": [
"\n7\n11\n8\n"
]
} |
1,018 | 8 | This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.
To bake a Napoleon cake, one has to bake n dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps n times:
* place a new cake layer on the top of the stack;
* after the i-th layer is placed, pour a_i units of cream on top of the stack.
When x units of cream are poured on the top of the stack, top x layers of the cake get drenched in the cream. If there are less than x layers, all layers get drenched and the rest of the cream is wasted. If x = 0, no layer gets drenched.
<image> The picture represents the first test case of the example.
Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 20 000). Description of the test cases follows.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of layers in the cake.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ n) β the amount of cream poured on the cake after adding each layer.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, print a single line with n integers. The i-th of the integers should be equal to 1 if the i-th layer from the bottom gets drenched, and 0 otherwise.
Example
Input
3
6
0 3 0 0 1 3
10
0 0 0 1 0 5 0 0 0 2
3
0 0 0
Output
1 1 0 1 1 1
0 1 1 1 1 1 0 0 1 1
0 0 0 | def solve():
n = int(input())
a = list(map(int, input().split()))
ans = [0] * n
cur = 0
for i in reversed(range(n)):
cur = max(cur, a[i])
if cur > 0:
ans[i] = 1
cur -= 1
print(*ans)
t = int(input())
for _ in range(t):
solve() | {
"input": [
"3\n6\n0 3 0 0 1 3\n10\n0 0 0 1 0 5 0 0 0 2\n3\n0 0 0\n"
],
"output": [
"\n1 1 0 1 1 1 \n0 1 1 1 1 1 0 0 1 1 \n0 0 0 \n"
]
} |
1,019 | 10 | After rejecting 10^{100} data structure problems, Errorgorn is very angry at Anton and decided to kill him.
Anton's DNA can be represented as a string a which only contains the characters "ANTON" (there are only 4 distinct characters).
Errorgorn can change Anton's DNA into string b which must be a permutation of a. However, Anton's body can defend against this attack. In 1 second, his body can swap 2 adjacent characters of his DNA to transform it back to a. Anton's body is smart and will use the minimum number of moves.
To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string B. Can you help him?
Input
The first line of input contains a single integer t (1 β€ t β€ 100000) β the number of testcases.
The first and only line of each testcase contains 1 string a (1 β€ |a| β€ 100000). a consists of only the characters "A", "N", "O" and "T".
It is guaranteed that the sum of |a| over all testcases does not exceed 100000.
Output
For each testcase, print a single string, b. If there are multiple answers, you can output any one of them. b must be a permutation of the string a.
Example
Input
4
ANTON
NAAN
AAAAAA
OAANTTON
Output
NNOTA
AANN
AAAAAA
TNNTAOOA
Note
For the first testcase, it takes 7 seconds for Anton's body to transform NNOTA to ANTON:
NNOTA β NNOAT β NNAOT β NANOT β NANTO β ANNTO β ANTNO β ANTON.
Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.
For the second testcase, it takes 2 seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted. | import itertools
from collections import Counter
def readline():
return map(int, input().split())
def solve():
s = input()
total = Counter()
p = Counter()
letters = set(s)
for a in s:
total[a] += 1
for b in letters:
if b != a:
p[b + a] += total[b]
def score(perm):
return sum(
p[b + a]
for (i, a) in enumerate(perm)
for b in perm[i+1:]
)
winner = max(itertools.permutations(letters), key=score)
print(''.join(a * total[a] for a in winner))
def main():
t = int(input())
for __ in range(t):
solve()
if __name__ == '__main__':
main()
| {
"input": [
"4\nANTON\nNAAN\nAAAAAA\nOAANTTON\n"
],
"output": [
"\nNNOTA\nAANN\nAAAAAA\nTNNTAOOA\n"
]
} |
1,020 | 8 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
Input
The first line contains integer n (1 β€ n β€ 105) β the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 β€ si β€ 4). The integers are separated by a space, si is the number of children in the i-th group.
Output
Print the single number β the minimum number of taxis necessary to drive all children to Polycarpus.
Examples
Input
5
1 2 4 3 3
Output
4
Input
8
2 3 4 4 2 1 3 1
Output
5
Note
In the first test we can sort the children into four cars like this:
* the third group (consisting of four children),
* the fourth group (consisting of three children),
* the fifth group (consisting of three children),
* the first and the second group (consisting of one and two children, correspondingly).
There are other ways to sort the groups into four cars. | from collections import Counter
def ceil(n, k): return n // k + (n % k != 0)
n = int(input())
c = Counter(list(map(int, input().split())))
print(c[4] + c[3] + c[2] // 2 + max(c[1] - c[3], 0) // 4 + ceil(2*(c[2] % 2) + max(c[1] - c[3], 0) % 4, 4)) | {
"input": [
"5\n1 2 4 3 3\n",
"8\n2 3 4 4 2 1 3 1\n"
],
"output": [
"4\n",
"5\n"
]
} |
1,021 | 9 | Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges.
Recently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time.
You are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.
Input
The input file consists of three lines, each of them contains a pair of numbers ββ coordinates of the pillar. Any coordinate doesn't exceed 1000 by absolute value, and is given with at most six digits after decimal point.
Output
Output the smallest possible area of the ancient arena. This number should be accurate to at least 6 digits after the decimal point. It's guaranteed that the number of angles in the optimal polygon is not larger than 100.
Examples
Input
0.000000 0.000000
1.000000 1.000000
0.000000 1.000000
Output
1.00000000 | from math import *
p = [list(map(float, input().split())) for i in range(3)]
a, b, c = [hypot(p[i][0] - p[(i+1)%3][0], p[i][1] - p[(i+1)%3][1]) for i in range(3)]
A, B, C = [acos((y*y+z*z-x*x)/(2*y*z)) for x, y, z in [(a, b, c), (b, c, a), (c, a, b)]]
R = a/sin(A)*0.5
def g(x,y):return x if y<1e-3 else g(y,fmod(x,y))
u=2*g(pi, g(A,g(B,C)))
print(R*R*sin(u)*pi/u)
| {
"input": [
"0.000000 0.000000\n1.000000 1.000000\n0.000000 1.000000\n"
],
"output": [
"1.0\n"
]
} |
1,022 | 8 | For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"
Dr. Suess, How The Grinch Stole Christmas
Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street.
The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets).
After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food.
The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets.
Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street.
Your task is to write a program that will determine the minimum possible value of k.
Input
The first line of the input contains two space-separated integers n and t (2 β€ n β€ 5Β·105, 1 β€ t β€ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop).
It is guaranteed that there is at least one segment with a house.
Output
If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k.
Examples
Input
6 6
HSHSHS
Output
1
Input
14 100
...HHHSSS...SH
Output
0
Input
23 50
HHSS.......SSHHHHHHHHHH
Output
8
Note
In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back.
In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction.
In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home. | def check(n, casas):
#print('n:',n)
global T,N,street
current = n
time = T
need = 0
last_house = 0
for ind, i in enumerate(street):
time -= 1
if i == 'S':
current += 1
elif i == 'H':
need += 1
if need == 1:
last_house = ind
if need > 0 and current >= need:
#print('p',time, ind-last_house)
current -= need
casas -= need
need = 0
if casas > 0:
if (ind-last_house)*2 >= N-last_house-1:
time -= N-last_house-1 + N-ind-1
return time >= 0
time -= (ind-last_house)*2
else:
time -= ind-last_house
#print('lugar:',i,ind,current, time, need, last_house)
if casas == 0:
break
#print(time)
return time >= 0 and casas == 0
N,T = [int(i) for i in input().split()]
street = input().rstrip('.')
N = len(street)
C = street.count('H')
S = street.count('S')
l = max(C-S, 0)
r = 500005
#print(N, C)
while l < r:
mid = (l+r)//2
if check(mid, C):
r = mid
else:
l = mid + 1
print(l if l < 500005 else -1) | {
"input": [
"23 50\nHHSS.......SSHHHHHHHHHH\n",
"14 100\n...HHHSSS...SH\n",
"6 6\nHSHSHS\n"
],
"output": [
"8\n",
"0\n",
"1\n"
]
} |
1,023 | 9 | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.
The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that.
Input
The first line contains integer n (1 β€ n β€ 5000) β amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1 β€ li < ri β€ 106) β starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1).
Output
Output integer k β amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order.
Examples
Input
3
3 10
20 30
1 3
Output
3
1 2 3
Input
4
3 10
20 30
1 3
1 39
Output
1
4
Input
3
1 5
2 6
3 7
Output
0 | class Event:
def __init__(self, span_id, point, open=False, close=False):
self.span_id, self.point = span_id, point
self.open, self.close = open, close
self.sort_key = 2 * point + (1 if open else 0)
self.count = 0
class Span:
def __init__(self, left, right):
self.left, self.right = left, right
n = int(input())
events = 2 * n * [ None ]
spans = n * [ None ]
for i in range(n):
a, b = map(int, input().split())
spans[i] = Span(a, b)
events[2 * i] = Event(i + 1, a, open=True)
events[2 * i + 1] = Event(i + 1, b, close=True)
events.sort(key=lambda event: event.sort_key)
def fail():
print(0)
import sys; sys.exit()
singles = set()
multiple = None
open_span_ids = set()
for event in events:
if event.close:
open_span_ids.remove(event.span_id)
else:
open_span_ids.add(event.span_id)
if len(open_span_ids) == 3:
#print('triple')
fail()
elif len(open_span_ids) == 2:
for id in open_span_ids:
if id in singles:
if multiple == None:
multiple = id
elif id != multiple:
#print('two doubles')
fail()
else:
singles.add(id)
#print(singles)
if multiple != None:
result = [ multiple ]
elif len(singles) > 0:
result = sorted(singles)
else:
result = list(range(1, n + 1))
print(len(result))
print(' '.join(list(map(str, result))))
| {
"input": [
"3\n1 5\n2 6\n3 7\n",
"4\n3 10\n20 30\n1 3\n1 39\n",
"3\n3 10\n20 30\n1 3\n"
],
"output": [
"0\n",
"1\n4 ",
"3\n1 2 3 "
]
} |
1,024 | 9 | Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 β€ a, b β€ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number β the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors. | def gcd(a,b): return 0 if b == 0 else a//b + gcd(b, a%b)
print(gcd(*(int(x) for x in input().split()))) | {
"input": [
"1 1\n",
"199 200\n",
"3 2\n"
],
"output": [
"1\n",
"200\n",
"3\n"
]
} |
1,025 | 7 | Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 Γ 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.
The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:
* First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.
* Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off.
Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!
Input
The first line of the input contains integer n (1 β€ n β€ 105) β the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi β the coordinates of the i-th alarm clock (0 β€ xi, yi β€ 100).
Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.
Output
In a single line print a single integer β the minimum number of segments Inna will have to draw if she acts optimally.
Examples
Input
4
0 0
0 1
0 2
1 0
Output
2
Input
4
0 0
0 1
1 0
1 1
Output
2
Input
4
1 1
1 2
2 3
3 3
Output
3
Note
In the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.
In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game. | def minMoves(x, y):
return min(sum(x), sum(y))
MAX = 101
n = int(input())
x = [0] * MAX
y = [0] * MAX
for i in range(n):
a, b = map(int, input().split())
x[a] = 1
y[b] = 1
print(minMoves(x, y)) | {
"input": [
"4\n0 0\n0 1\n1 0\n1 1\n",
"4\n0 0\n0 1\n0 2\n1 0\n",
"4\n1 1\n1 2\n2 3\n3 3\n"
],
"output": [
"2",
"2",
"3"
]
} |
1,026 | 9 | Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).
Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from 1 to 4. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the i-th player is ai, the attack skill is bi.
Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.
We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.
The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.
Input
The input contain the players' description in four lines. The i-th line contains two space-separated integers ai and bi (1 β€ ai, bi β€ 100) β the defence and the attack skill of the i-th player, correspondingly.
Output
If the first team can win, print phrase "Team 1" (without the quotes), if the second team can win, print phrase "Team 2" (without the quotes). If no of the teams can definitely win, print "Draw" (without the quotes).
Examples
Input
1 100
100 1
99 99
99 99
Output
Team 1
Input
1 1
2 2
3 3
2 2
Output
Team 2
Input
3 3
2 2
1 1
2 2
Output
Draw
Note
Let consider the first test sample. The first team can definitely win if it will choose the following arrangement: the first player plays attack, the second player plays defence.
Consider the second sample. The order of the choosing roles for players makes sense in this sample. As the members of the first team choose first, the members of the second team can beat them (because they know the exact defence value and attack value of the first team). | def f():
a, b = map(int, input().split())
A, B = map(int, input().split())
return ((a, B), (A, b))
def g(u, v): return u[0] > v[1] and u[1] > v[0]
x, y = f(), f()
if any(all(g(j, i) for i in y) for j in x): print('Team 1')
elif all(any(g(i, j) for i in y) for j in x): print('Team 2')
else: print('Draw')
| {
"input": [
"1 1\n2 2\n3 3\n2 2\n",
"3 3\n2 2\n1 1\n2 2\n",
"1 100\n100 1\n99 99\n99 99\n"
],
"output": [
"Team 2\n",
"Draw\n",
"Team 1\n"
]
} |
1,027 | 8 | Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.
Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.
You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.
Please be careful that answer might not fit in 32 bit data type.
Input
The first line will contain two space separated integers n, x (1 β€ n, x β€ 105). The next line will contain n space separated integers: c1, c2, ..., cn (1 β€ ci β€ 105).
Output
Output a single integer representing the answer to the problem.
Examples
Input
2 3
4 1
Output
11
Input
4 2
5 1 2 1
Output
10
Input
3 3
1 1 1
Output
6
Note
Look at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 Γ 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.
Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 Γ 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2 Γ 4 = 8 hours. Hence you will need to spend 11 hours.
So overall, minimum of both the cases is 11 hours.
Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours. | def mi():
return map(int, input().split())
n,k = mi()
a = list(mi())
a.sort()
s = 0
for i in a:
s+=i*k
k-=1
k = max(k,1)
print (s) | {
"input": [
"3 3\n1 1 1\n",
"4 2\n5 1 2 1\n",
"2 3\n4 1\n"
],
"output": [
"6\n",
"10\n",
"11\n"
]
} |
1,028 | 10 | Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties:
* for all x <image> the following inequality holds l β€ x β€ r;
* 1 β€ |S| β€ k;
* lets denote the i-th element of the set S as si; value <image> must be as small as possible.
Help Victor find the described set.
Input
The first line contains three space-separated integers l, r, k (1 β€ l β€ r β€ 1012; 1 β€ k β€ min(106, r - l + 1)).
Output
Print the minimum possible value of f(S). Then print the cardinality of set |S|. Then print the elements of the set in any order.
If there are multiple optimal sets, you can print any of them.
Examples
Input
8 15 3
Output
1
2
10 11
Input
8 30 7
Output
0
5
14 9 28 11 16
Note
Operation <image> represents the operation of bitwise exclusive OR. In other words, it is the XOR operation. | def f(arr):
val = 0
for x in arr:
val ^= x
return val
def solve(l, r, k):
ret = [l]
if k >= 2:
cand = [l, l + 1]
if f(cand) < f(ret):
ret = cand
if l + 2 <= r:
cand = [l + 1, l + 2]
if f(cand) < f(ret):
ret = cand
if k >= 3:
x = 1
while x <= l:
x *= 2
if x + x // 2 <= r:
ret = [x - 1, x + x // 2, x + x // 2 - 1]
if k >= 4:
cand = [l, l + 1, l + 2, l + 3]
if f(cand) < f(ret):
ret = cand
if l + 4 <= r:
cand = [l + 1, l + 2, l + 3, l + 4]
if f(cand) < f(ret):
ret = cand
return ret
l, r, k = map(int, input().split())
ans = solve(l, r, k)
print(f(ans))
print(len(ans))
print(' '.join(map(str, ans)))
| {
"input": [
"8 30 7\n",
"8 15 3\n"
],
"output": [
"0\n4\n8 9 10 11\n",
"1\n2\n8 9\n"
]
} |
1,029 | 9 | Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.
For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.
Input
The first line contains three integers m, t, r (1 β€ m, t, r β€ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit.
The next line contains m space-separated numbers wi (1 β€ i β€ m, 1 β€ wi β€ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.
Output
If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.
If that is impossible, print - 1.
Examples
Input
1 8 3
10
Output
3
Input
2 10 1
5 8
Output
1
Input
1 1 3
10
Output
-1
Note
Anya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.
It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.
In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.
In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.
In the third sample test the answer is - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes. | def main():
m, t, r = map(int, input().split())
gh = sorted(map(int, input().split()), reverse=True)
if r > t:
print(-1)
return
l = [False] * 600
for g in gh:
g -= t
for i in range(g, g + r - sum(l[i] for i in range(g, g + t))):
l[i] = True
print(sum(l))
if __name__ == '__main__':
main()
| {
"input": [
"1 1 3\n10\n",
"1 8 3\n10\n",
"2 10 1\n5 8\n"
],
"output": [
"-1\n",
"3\n",
"1\n"
]
} |
1,030 | 10 | After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t β the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w β the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.
Two ways to add edges to the graph are considered equal if they have the same sets of added edges.
Since Vitaly does not study at the university, he asked you to help him with this task.
Input
The first line of the input contains two integers n and m (<image> β the number of vertices in the graph and the number of edges in the graph.
Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 β€ ai, bi β€ n) β the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.
It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.
Output
Print in the first line of the output two space-separated integers t and w β the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.
Examples
Input
4 4
1 2
1 3
4 2
4 3
Output
1 2
Input
3 3
1 2
2 3
3 1
Output
0 1
Input
3 0
Output
3 1
Note
The simple cycle is a cycle that doesn't contain any vertex twice. | n, m = [int(x) for x in input().split()]
E = {i:[] for i in range(n)}
for i in range(m):
u, v = [int(x)-1 for x in input().split()]
E[v].append(u)
E[u].append(v)
def dfs():
visited = [False for i in range(n)]
colour = [0 for i in range(n)]
ans = 0
for v in range(n):
if visited[v]: continue
stack = [(v, 0)]
part = [0, 0]
while stack:
node, c = stack.pop()
if not visited[node]:
part[c] += 1
visited[node] = True
colour[node] = c
stack.extend((u,c^1) for u in E[node])
elif c != colour[node]:
return (0, 1)
ans += (part[0]*(part[0] - 1) + part[1]*(part[1] - 1)) // 2
return (1, ans)
if m == 0:
print(3, n*(n-1)*(n-2)//6)
elif max(len(E[v]) for v in E) == 1:
print(2, m*(n-2))
else:
ans = dfs()
print(ans[0], ans[1])
| {
"input": [
"4 4\n1 2\n1 3\n4 2\n4 3\n",
"3 0\n",
"3 3\n1 2\n2 3\n3 1\n"
],
"output": [
"1 2",
"3 1",
"0 1"
]
} |
1,031 | 8 | Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.
The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.
It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.
Input
The first line contains number n (1 β€ n β€ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 β€ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.
Output
Print a single number β the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.
Examples
Input
3
0 2 0
Output
1
Input
5
4 2 3 0 1
Output
3
Input
7
0 3 1 0 5 2 6
Output
2
Note
In the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.
In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.
In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7. | def main():
input()
kn, res = 0, -1
aa = list(map(int, input().split()))[::-1]
while aa:
bb = []
res += 1
for a in reversed(aa):
if a <= kn:
kn += 1
else:
bb.append(a)
aa = bb
print(res)
if __name__ == '__main__':
main()
| {
"input": [
"3\n0 2 0\n",
"7\n0 3 1 0 5 2 6\n",
"5\n4 2 3 0 1\n"
],
"output": [
"1",
"2",
"3"
]
} |
1,032 | 8 | Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph β something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) β the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 β€ aj β€ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 β€ uj, vj β€ n, uj β vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 1
Output
-1 | n, m = (int(x) for x in input().split())
edges = []
for i in range(m):
w, in_tree = input().split()
edges.append([int(w), i, int(in_tree)])
sorted_edges = sorted(edges, key = lambda e: (e[0], -e[2]))
print
def free_edge():
for y in range(3, n+1):
for x in range(2, y):
yield [x, y]
f = free_edge()
k = 2
for e in sorted_edges:
if e[2]:
e += [1, k]
k += 1
else:
free = next(f)
if free[1] >= k:
print(-1)
break
else:
e += free
else:
sorted_edges.sort(key = lambda e: e[1])
for e in sorted_edges:
print(e[3], e[4])
| {
"input": [
"3 3\n1 0\n2 1\n3 1\n",
"4 5\n2 1\n3 1\n4 0\n1 1\n5 0\n"
],
"output": [
"-1\n",
"1 3\n1 4\n2 3\n1 2\n2 4\n"
]
} |
1,033 | 9 | Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>.
The success of the operation relies on the number of pairs (i, j) (1 β€ i < j β€ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.
Input
The first line of the input contains the single integer n (1 β€ n β€ 200 000) β the number of watchmen.
Each of the following n lines contains two integers xi and yi (|xi|, |yi| β€ 109).
Some positions may coincide.
Output
Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.
Examples
Input
3
1 1
7 5
1 5
Output
2
Input
6
0 0
0 1
0 2
-1 1
0 1
1 1
Output
11
Note
In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances. | from collections import defaultdict
import sys
n = int(input())
R, C, V = defaultdict(int), defaultdict(int), defaultdict(int)
for line in sys.stdin:
x, y = [int(x) for x in line.split()]
V[(x, y)] += 1
R[x] += 1
C[y] += 1
def C_n_2(x): return x * (x - 1) // 2
print(sum(C_n_2(R[k]) for k in R) + sum(C_n_2(C[k]) for k in C) - sum(C_n_2(V[k]) for k in V))
| {
"input": [
"3\n1 1\n7 5\n1 5\n",
"6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1\n"
],
"output": [
"2\n",
"11\n"
]
} |
1,034 | 7 | Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
Input
The first line of the input contains two integers n and h (1 β€ n β€ 1000, 1 β€ h β€ 1000) β the number of friends and the height of the fence, respectively.
The second line contains n integers ai (1 β€ ai β€ 2h), the i-th of them is equal to the height of the i-th person.
Output
Print a single integer β the minimum possible valid width of the road.
Examples
Input
3 7
4 5 14
Output
4
Input
6 1
1 1 1 1 1 1
Output
6
Input
6 5
7 6 8 9 10 5
Output
11
Note
In the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.
In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.
In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11. | def f(): return map(int, input().split())
n, h = f()
print(n + sum(q > h for q in f())) | {
"input": [
"3 7\n4 5 14\n",
"6 1\n1 1 1 1 1 1\n",
"6 5\n7 6 8 9 10 5\n"
],
"output": [
"4\n",
"6\n",
"11\n"
]
} |
1,035 | 7 | Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.
The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.
Input
The first line of the input contains four space-separated positive integer numbers not exceeding 100 β lengthes of the sticks.
Output
Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length.
Examples
Input
4 2 1 3
Output
TRIANGLE
Input
7 2 2 4
Output
SEGMENT
Input
3 5 9 1
Output
IMPOSSIBLE | def readln(inp=None): return tuple(map(int, (inp or input()).split()))
a, b, c, d = sorted(readln())
if b + c > d or a + b > c:
print('TRIANGLE')
elif b + c == d or a + b == c:
print('SEGMENT')
else:
print('IMPOSSIBLE')
| {
"input": [
"3 5 9 1\n",
"7 2 2 4\n",
"4 2 1 3\n"
],
"output": [
"IMPOSSIBLE\n",
"SEGMENT\n",
"TRIANGLE\n"
]
} |
1,036 | 9 | Recently Irina arrived to one of the most famous cities of Berland β the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.
Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace n. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than T time units.
Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T. It is guaranteed that there is at least one route from showplace 1 to showplace n such that Irina will spend no more than T time units passing it.
Input
The first line of the input contains three integers n, m and T (2 β€ n β€ 5000, 1 β€ m β€ 5000, 1 β€ T β€ 109) β the number of showplaces, the number of roads between them and the time of Irina's stay in Berlatov respectively.
The next m lines describes roads in Berlatov. i-th of them contains 3 integers ui, vi, ti (1 β€ ui, vi β€ n, ui β vi, 1 β€ ti β€ 109), meaning that there is a road starting from showplace ui and leading to showplace vi, and Irina spends ti time units to pass it. It is guaranteed that the roads do not form cyclic routes.
It is guaranteed, that there is at most one road between each pair of showplaces.
Output
Print the single integer k (2 β€ k β€ n) β the maximum number of showplaces that Irina can visit during her journey from showplace 1 to showplace n within time not exceeding T, in the first line.
Print k distinct integers in the second line β indices of showplaces that Irina will visit on her route, in the order of encountering them.
If there are multiple answers, print any of them.
Examples
Input
4 3 13
1 2 5
2 3 7
2 4 8
Output
3
1 2 4
Input
6 6 7
1 2 2
1 3 3
3 6 3
2 4 2
4 6 2
6 5 1
Output
4
1 2 4 6
Input
5 5 6
1 3 3
3 5 3
1 2 2
2 4 3
4 5 2
Output
3
1 3 5 | # -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 1/20/20
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def solve(N, M, T, edges):
g = collections.defaultdict(list)
for u, v, t in edges:
g[u].append((v, t))
dp = [[T+1 for _ in range(N+1)] for _ in range(N + 1)]
pre = [[0 for _ in range(N+1)] for _ in range(N + 1)]
dp[1][1] = 0
pre[1][1] = 0
# q = [(0, 0, -1, 1)]
# heapq.heapify(q)
# while q:
# _, pcost, pdist, pcity = heapq.heappop(q)
# pdist = -pdist
# if pcost > dp[pcity][pdist]:
# continue
# for dest, ncost in g[pcity]:
# cost = pcost + ncost
# dist = pdist + 1
# if cost <= T and dp[dest][dist] > cost:
# dp[dest][dist] = cost
# pre[dest][dist] = pcity
# heapq.heappush(q, (cost/dist, cost, -dist, dest))
q = [(1, 1, 0)]
while q:
nq = []
for city, dist, pcost in q:
dist += 1
for dest, ncost in g[city]:
cost = pcost + ncost
if cost <= T and dp[dest][dist] > cost:
dp[dest][dist] = cost
pre[dest][dist] = city
nq.append((dest, dist, cost))
q = nq
# print(dp[N])
ans = max([i for i in range(N, -1, -1) if dp[N][i] <= T])
print(ans)
path = []
k = N
l = ans
while k:
path.append(k)
k = pre[k][l]
l -= 1
print(' '.join(map(str, path[::-1])))
N, M, T = map(int, input().split())
edges = []
for i in range(M):
u, v, t = map(int, input().split())
edges.append((u, v, t))
solve(N, M, T, edges) | {
"input": [
"4 3 13\n1 2 5\n2 3 7\n2 4 8\n",
"6 6 7\n1 2 2\n1 3 3\n3 6 3\n2 4 2\n4 6 2\n6 5 1\n",
"5 5 6\n1 3 3\n3 5 3\n1 2 2\n2 4 3\n4 5 2\n"
],
"output": [
"3\n1 2 4 ",
"4\n1 2 4 6 ",
"3\n1 3 5 "
]
} |
1,037 | 7 | Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.
Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport.
To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.
Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.
Print the minimum cost Vladik has to pay to get to the olympiad.
Input
The first line contains three integers n, a, and b (1 β€ n β€ 105, 1 β€ a, b β€ n) β the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach.
The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.
Output
Print single integer β the minimum cost Vladik has to pay to get to the olympiad.
Examples
Input
4 1 4
1010
Output
1
Input
5 5 2
10110
Output
0
Note
In the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1.
In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company. | def min_cost(a,b,l):
return (l[a-1]!=l[b-1])+0
n,a,b=map(int,input().split())
l=input()
print(min_cost(a,b,l))
| {
"input": [
"4 1 4\n1010\n",
"5 5 2\n10110\n"
],
"output": [
"1\n",
"0\n"
]
} |
1,038 | 9 | Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1 = 2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.
Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1 = 2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.
A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.
While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions:
* How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109 + 7.
* What is the maximum length of a substring that can appear in some valid splitting?
* What is the minimum number of substrings the message can be spit in?
Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".
Input
The first line contains an integer n (1 β€ n β€ 103) denoting the length of the message.
The second line contains the message s of length n that consists of lowercase English letters.
The third line contains 26 integers a1, a2, ..., a26 (1 β€ ax β€ 103) β the maximum lengths of substring each letter can appear in.
Output
Print three lines.
In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109 + 7.
In the second line print the length of the longest substring over all the ways.
In the third line print the minimum number of substrings over all the ways.
Examples
Input
3
aab
2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
3
2
2
Input
10
abcdeabcde
5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
401
4
3
Note
In the first example the three ways to split the message are:
* a|a|b
* aa|b
* a|ab
The longest substrings are "aa" and "ab" of length 2.
The minimum number of substrings is 2 in "a|ab" or "aa|b".
Notice that "aab" is not a possible splitting because the letter 'a' appears in a substring of length 3, while a1 = 2. |
import sys
mod = pow(10, 9) + 7
n = int(sys.stdin.readline())
s = sys.stdin.readline()[:-1]
a = [int(x) for x in sys.stdin.readline().split()]
dp = [0 for _ in range(n+1)]
dp[0] = 1
def ci(c):
return ord(c)-ord('a')
l = 0
for i in range(1, n+1):
# f: represents the farther
# we can get from x (going from
# right to left) without breaking
# the splitting rules
f = 0
for x in range(i-1, -1, -1):
f = max(f, i-a[ci(s[x])])
if f > x:
# we broke the rule
continue
dp[i] = (dp[i]+dp[x]) % mod
l = max(l, i-x)
print(dp[n])
print(l)
res = 1
m = 9999
j = 0
for i in range(n):
m = min([a[ci(s[x])] for x in range(j, i+1)])
if m < i-j+1:
res += 1
j = i
print(res)
| {
"input": [
"3\naab\n2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
"10\nabcdeabcde\n5 5 5 5 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n"
],
"output": [
"3\n2\n2\n",
"401\n4\n3\n"
]
} |
1,039 | 8 | The Easter Rabbit laid n eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
* Each of the seven colors should be used to paint at least one egg.
* Any four eggs lying sequentially should be painted different colors.
Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.
Input
The only line contains an integer n β the amount of eggs (7 β€ n β€ 100).
Output
Print one line consisting of n characters. The i-th character should describe the color of the i-th egg in the order they lie in the circle. The colors should be represented as follows: "R" stands for red, "O" stands for orange, "Y" stands for yellow, "G" stands for green, "B" stands for blue, "I" stands for indigo, "V" stands for violet.
If there are several answers, print any of them.
Examples
Input
8
Output
ROYGRBIV
Input
13
Output
ROYGBIVGBIVYG
Note
The way the eggs will be painted in the first sample is shown on the picture:
<image> | def s():
n = int(input())
print('ROY',('GBIV'*((n-3)//4+1))[:n-3],sep='')
s()
| {
"input": [
"8\n",
"13\n"
],
"output": [
"ROYGBIVG",
"ROYGBIVGBIVGB"
]
} |
1,040 | 7 | You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n (1 β€ n β€ 200) β length of the text.
The second line contains text of single-space separated words s1, s2, ..., si, consisting only of small and capital Latin letters.
Output
Print one integer number β volume of text.
Examples
Input
7
NonZERO
Output
5
Input
24
this is zero answer text
Output
0
Input
24
Harbour Space University
Output
1
Note
In the first example there is only one word, there are 5 capital letters in it.
In the second example all of the words contain 0 capital letters. | def g(word):
return len([c for c in word if c.isupper()])
n = input()
print(max([g(w) for w in input().split()])) | {
"input": [
"24\nthis is zero answer text\n",
"7\nNonZERO\n",
"24\nHarbour Space University\n"
],
"output": [
"0\n",
"5\n",
"1\n"
]
} |
1,041 | 9 | Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.
At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.
Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.
Input
The first line contains two integers n and m (1 β€ n β€ 22; <image>) β the number of guests at the party (including Arseny) and the number of pairs of people which are friends.
Each of the next m lines contains two integers u and v (1 β€ u, v β€ n; u β v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected.
Output
In the first line print the minimum number of steps required to make all pairs of guests friends.
In the second line print the ids of guests, who are selected at each step.
If there are multiple solutions, you can output any of them.
Examples
Input
5 6
1 2
1 3
2 3
2 5
3 4
4 5
Output
2
2 3
Input
4 4
1 2
1 3
1 4
3 4
Output
1
1
Note
In the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4, 1) and (4, 2) are not friends. Guest 3 or 5 can introduce them.
In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step. | from collections import defaultdict
def count(x):
c=0
while x > 0:
c+=1
x &= (x-1)
return c
n,m=map(int,input().split())
g=defaultdict(list)
for _ in range(m):
u, v = map(int,input().split())
u-=1;v-=1
g[u].append(v)
g[v].append(u)
mask1=0;mask2=0;MAX=(1<<n)-1
a=[0]*(1 << n)
dp=[MAX]*(1 << n)
if m == (n*(n-1))//2:
print(0)
exit(0)
for i,j in g.items():
mask1 = (1 << i);mask2=0;mask2 |= mask1
for k in j:
mask2 |= (1 << k)
dp[mask2]=mask1
a[mask1]=mask2
for i in range(0,(1 << n)-1):
if dp[i] != MAX:
#print('HEllo')
temp = dp[i] ^ i
for j in range(n):
if temp & (1 << j) != 0:
nmask = i | a[(1 << j)]
dp[nmask]=dp[i] | (1 << j) if count(dp[i] | (1 << j)) < count(dp[nmask]) else dp[nmask]
ans = []
for i in range(n):
if dp[-1] & (1 << i) != 0:
ans.append(i+1)
print(len(ans))
print(*ans)
| {
"input": [
"4 4\n1 2\n1 3\n1 4\n3 4\n",
"5 6\n1 2\n1 3\n2 3\n2 5\n3 4\n4 5\n"
],
"output": [
"1\n1 \n",
"2\n2 3 \n"
]
} |
1,042 | 11 | You are given a sequence of positive integers a1, a2, ..., an.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.
You stop performing the operation when there is no pair of equal consecutive elements.
For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second β [5, 3, 2, 2], after the third β [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.
Determine the final sequence after you stop performing the operation.
Input
The first line contains a single integer n (2 β€ n β€ 2Β·105) β the number of elements in the sequence.
The second line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
In the first line print a single integer k β the number of elements in the sequence after you stop performing the operation.
In the second line print k integers β the sequence after you stop performing the operation.
Examples
Input
6
5 2 1 1 2 2
Output
2
5 4
Input
4
1000000000 1000000000 1000000000 1000000000
Output
1
1000000002
Input
7
4 10 22 11 12 5 6
Output
7
4 10 22 11 12 5 6
Note
The first example is described in the statements.
In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].
In the third example there are no two equal consecutive elements initially, so the sequence does not change. | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n = mint()
a = []
for i in mints():
if len(a) > 0 and a[-1] == i:
a[-1] += 1
while len(a) > 1 and a[-2] == a[-1]:
a.pop()
a[-1] += 1
else:
a.append(i)
print(len(a))
print(*a) | {
"input": [
"7\n4 10 22 11 12 5 6\n",
"6\n5 2 1 1 2 2\n",
"4\n1000000000 1000000000 1000000000 1000000000\n"
],
"output": [
"7\n4 10 22 11 12 5 6\n",
"2\n5 4\n",
"1\n1000000002\n"
]
} |
1,043 | 9 | You're given Q queries of the form (L, R).
For each query you have to find the number of such x that L β€ x β€ R and there exist integer numbers a > 0, p > 1 such that x = ap.
Input
The first line contains the number of queries Q (1 β€ Q β€ 105).
The next Q lines contains two integers L, R each (1 β€ L β€ R β€ 1018).
Output
Output Q lines β the answers to the queries.
Example
Input
6
1 4
9 9
5 7
12 29
137 591
1 1000000
Output
2
1
0
3
17
1111
Note
In query one the suitable numbers are 1 and 4. | import sys
readline = sys.stdin.buffer.readline
J = set()
for i in range(2000):
J.add(i**2)
J.add(i**3)
Ri = set()
for p in range(5, 61, 2):
if p%3 == 0:
continue
for base in range(2, 10**9):
if base in J:
continue
bp = pow(base, p)
if bp > 10**18:
break
Ri.add(bp)
Ri = list(Ri)
Ri.sort()
LL = len(Ri)
def calc(x):
res = 0
ng = 10**9+1
ok = 0
while abs(ok-ng) > 1:
med = (ok+ng)//2
if med*med <= x:
ok = med
else:
ng = med
res += ok
ng = 10**6+1
ok = 0
while abs(ok-ng) > 1:
med = (ok+ng)//2
if med*med*med <= x:
ok = med
else:
ng = med
res += ok
ng = 10**3+1
ok = 0
while abs(ok-ng) > 1:
med = (ok+ng)//2
if med*med*med*med*med*med <= x:
ok = med
else:
ng = med
res -= ok
ng = LL
ok = -1
while abs(ok-ng) > 1:
med = (ok+ng)//2
if Ri[med] <= x:
ok = med
else:
ng = med
res += ok+1
return res
Q = int(readline())
Ans = [None]*Q
for qu in range(Q):
L, R = map(int, readline().split())
Ans[qu] = calc(R) - calc(L-1)
print('\n'.join(map(str, Ans))) | {
"input": [
"6\n1 4\n9 9\n5 7\n12 29\n137 591\n1 1000000\n"
],
"output": [
"2\n1\n0\n3\n17\n1111\n"
]
} |
1,044 | 10 | There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.
Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).
When a slime with a value x eats a slime with a value y, the eaten slime disappears, and the value of the remaining slime changes to x - y.
The slimes will eat each other until there is only one slime left.
Find the maximum possible value of the last slime.
Input
The first line of the input contains an integer n (1 β€ n β€ 500 000) denoting the number of slimes.
The next line contains n integers a_i (-10^9 β€ a_i β€ 10^9), where a_i is the value of i-th slime.
Output
Print an only integer β the maximum possible value of the last slime.
Examples
Input
4
2 1 2 1
Output
4
Input
5
0 -1 -1 -1 -1
Output
4
Note
In the first example, a possible way of getting the last slime with value 4 is:
* Second slime eats the third slime, the row now contains slimes 2, -1, 1
* Second slime eats the third slime, the row now contains slimes 2, -2
* First slime eats the second slime, the row now contains 4
In the second example, the first slime can keep eating slimes to its right to end up with a value of 4. | def f(a):
if len(a)==1:
return a[0]
pos=0
neg=0
ans=0
a=sorted(a)
for i in a[1:len(a)-1]:
ans+=abs(i)
ans-=a[0]
ans+=a[-1]
return ans
s=input()
a=list(map(int,input().strip().split()))
print(f(a)) | {
"input": [
"5\n0 -1 -1 -1 -1\n",
"4\n2 1 2 1\n"
],
"output": [
"4\n",
"4\n"
]
} |
1,045 | 7 | You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.
The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^9).
Output
Print one integer β the minimum possible value of |sum(A) - sum(B)| if you divide the initial sequence 1, 2, ..., n into two sets A and B.
Examples
Input
3
Output
0
Input
5
Output
1
Input
6
Output
1
Note
Some (not all) possible answers to examples:
In the first example you can divide the initial sequence into sets A = \{1, 2\} and B = \{3\} so the answer is 0.
In the second example you can divide the initial sequence into sets A = \{1, 3, 4\} and B = \{2, 5\} so the answer is 1.
In the third example you can divide the initial sequence into sets A = \{1, 4, 5\} and B = \{2, 3, 6\} so the answer is 1. | def sx(n):
print((n*(n+1)//2)%2)
s = int(input())
sx(s)
| {
"input": [
"6\n",
"5\n",
"3\n"
],
"output": [
"1\n",
"1\n",
"0\n"
]
} |
1,046 | 7 | You are given an array of n integers: a_1, a_2, β¦, a_n. Your task is to find some non-zero integer d (-10^3 β€ d β€ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least βn/2β). Note that those positive numbers do not need to be an integer (e.g., a 2.5 counts as a positive number). If there are multiple values of d that satisfy the condition, you may print any of them. In case that there is no such d, print a single integer 0.
Recall that β x β represents the smallest integer that is not less than x and that zero (0) is neither positive nor negative.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of elements in the array.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (-10^3 β€ a_i β€ 10^3).
Output
Print one integer d (-10^3 β€ d β€ 10^3 and d β 0) that satisfies the given condition. If there are multiple values of d that satisfy the condition, you may print any of them. In case that there is no such d, print a single integer 0.
Examples
Input
5
10 0 -7 2 6
Output
4
Input
7
0 0 1 -1 0 0 2
Output
0
Note
In the first sample, n = 5, so we need at least β5/2β = 3 positive numbers after division. If d = 4, the array after division is [2.5, 0, -1.75, 0.5, 1.5], in which there are 3 positive numbers (namely: 2.5, 0.5, and 1.5).
In the second sample, there is no valid d, so 0 should be printed. | input()
s=list(map(int,input().split()))
def g(a,d):
z=0
for x in a:
if x/d>0:
z=z+1
return z
if g(s,2)>=len(s)/2:
print(2)
elif g(s,-2)>=len(s)/2:
print(-2)
else:
print(0)
| {
"input": [
"7\n0 0 1 -1 0 0 2\n",
"5\n10 0 -7 2 6"
],
"output": [
"0",
"1"
]
} |
1,047 | 8 | One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:
<image> By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n rows and n columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.
Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?
Input
The first line of the input contains a single integer n (3 β€ n β€ 50) β the size of the board.
The following n lines describe the board. The i-th line (1 β€ i β€ n) contains a single string of length n. Its j-th character (1 β€ j β€ n) is equal to "." if the cell in the i-th row and the j-th column is free; it is equal to "#" if it's occupied.
You can assume that the board contains at least one free cell.
Output
Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).
Examples
Input
3
#.#
...
#.#
Output
YES
Input
4
##.#
#...
####
##.#
Output
NO
Input
5
#.###
....#
#....
###.#
#####
Output
YES
Input
5
#.###
....#
#....
....#
#..##
Output
NO
Note
The following sketches show the example boards and their tilings if such tilings exist:
<image> | def B():
n=int(input())
G=[list(input()) for _ in range(n)]
for i in range(n):
for j in range(n):
if G[i][j] == '.':
if i+2<n and 0<j<n-1 and G[i+1][j-1:j+2] == ['.']*3 and G[i+2][j] == '.': G[i+1][j-1:j+2],G[i+2][j]='###','#'
else: return 1
return 0
print("YNEOS"[B()::2]) | {
"input": [
"3\n#.#\n...\n#.#\n",
"5\n#.###\n....#\n#....\n....#\n#..##\n",
"4\n##.#\n#...\n####\n##.#\n",
"5\n#.###\n....#\n#....\n###.#\n#####\n"
],
"output": [
"YES\n",
"NO\n",
"NO\n",
"YES\n"
]
} |
1,048 | 9 | The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The i-th picture has a non-negative weight w_i, and the probability of the i-th picture being displayed is \frac{w_i}{β_{j=1}^nw_j}. That is to say, the probability of a picture to be displayed is proportional to its weight.
However, Nauuo discovered that some pictures she does not like were displayed too often.
To solve this problem, she came up with a great idea: when she saw a picture she likes, she would add 1 to its weight; otherwise, she would subtract 1 from its weight.
Nauuo will visit the website m times. She wants to know the expected weight of each picture after all the m visits modulo 998244353. Can you help her?
The expected weight of the i-th picture can be denoted by \frac {q_i} {p_i} where \gcd(p_i,q_i)=1, you need to print an integer r_i satisfying 0β€ r_i<998244353 and r_iβ
p_iβ‘ q_i\pmod{998244353}. It can be proved that such r_i exists and is unique.
Input
The first line contains two integers n and m (1β€ nβ€ 50, 1β€ mβ€ 50) β the number of pictures and the number of visits to the website.
The second line contains n integers a_1,a_2,β¦,a_n (a_i is either 0 or 1) β if a_i=0 , Nauuo does not like the i-th picture; otherwise Nauuo likes the i-th picture. It is guaranteed that there is at least one picture which Nauuo likes.
The third line contains n integers w_1,w_2,β¦,w_n (1β€ w_iβ€50) β the initial weights of the pictures.
Output
The output contains n integers r_1,r_2,β¦,r_n β the expected weights modulo 998244353.
Examples
Input
2 1
0 1
2 1
Output
332748119
332748119
Input
1 2
1
1
Output
3
Input
3 3
0 1 1
4 3 5
Output
160955686
185138929
974061117
Note
In the first example, if the only visit shows the first picture with a probability of \frac 2 3, the final weights are (1,1); if the only visit shows the second picture with a probability of \frac1 3, the final weights are (2,2).
So, both expected weights are \frac2 3β
1+\frac 1 3β
2=\frac4 3 .
Because 332748119β
3β‘ 4\pmod{998244353}, you need to print 332748119 instead of \frac4 3 or 1.3333333333.
In the second example, there is only one picture which Nauuo likes, so every time Nauuo visits the website, w_1 will be increased by 1.
So, the expected weight is 1+2=3.
Nauuo is very naughty so she didn't give you any hint of the third example. | P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [[] for _ in range(M+1)]
X[0] = [1]
def calc(L):
su = sum(L)
pl = 0
pd = 0
RE = []
for i in range(len(L)):
a = li + i
b = di - (len(L) - 1 - i)
pd = b * L[i] * pow(su*(a+b), P-2, P)
RE.append((pl+pd)%P)
pl = a * L[i] * pow(su*(a+b), P-2, P)
RE.append(pl%P)
return RE
for i in range(M):
X[i+1] = calc(X[i])
ne = 0
po = 0
for i in range(M+1):
po = (po + X[M][i] * (li + i)) % P
ne = (ne + X[M][i] * (di - M + i)) % P
for i in range(N):
print(po * B[i] * pow(li, P-2, P) % P if A[i] else ne * B[i] * pow(di, P-2, P) % P)
| {
"input": [
"1 2\n1\n1\n",
"2 1\n0 1\n2 1\n",
"3 3\n0 1 1\n4 3 5\n"
],
"output": [
"3\n",
"332748119\n332748119\n",
"160955686\n185138929\n974061117\n"
]
} |
1,049 | 10 | Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers.
Note that all n1 + n2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.
Input
The only line contains four space-separated integers n1, n2, k1, k2 (1 β€ n1, n2 β€ 100, 1 β€ k1, k2 β€ 10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly.
Output
Print the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than k1 footmen stand successively, and no more than k2 horsemen stand successively.
Examples
Input
2 1 1 10
Output
1
Input
2 3 1 2
Output
5
Input
2 4 1 1
Output
0
Note
Let's mark a footman as 1, and a horseman as 2.
In the first sample the only beautiful line-up is: 121
In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121 | n,m,x,y=map(int,input().split())
D={}
def d(a,b,i,j):
if min(a,b,i,j) < 0:
return 0
if not a+b:
return 1
v=(a,b,i,j)
if v in D:
return D[v]
r=(d(a,b-1,x,j-1)+d(a-1,b,i-1,y))%10**8
D[v]=r
return r
print(d(n,m,x,y)) | {
"input": [
"2 1 1 10\n",
"2 3 1 2\n",
"2 4 1 1\n"
],
"output": [
"1\n",
"5\n",
"0\n"
]
} |
1,050 | 9 | You are given a sequence of n digits d_1d_2 ... d_{n}. You need to paint all the digits in two colors so that:
* each digit is painted either in the color 1 or in the color 2;
* if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color 2, then the resulting sequence of n digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit).
For example, for the sequence d=914 the only valid coloring is 211 (paint in the color 1 two last digits, paint in the color 2 the first digit). But 122 is not a valid coloring (9 concatenated with 14 is not a non-decreasing sequence).
It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.
Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.
Input
The first line contains a single integer t (1 β€ t β€ 10000) β the number of test cases in the input.
The first line of each test case contains an integer n (1 β€ n β€ 2β
10^5) β the length of a given sequence of digits.
The next line contains a sequence of n digits d_1d_2 ... d_{n} (0 β€ d_i β€ 9). The digits are written in a row without spaces or any other separators. The sequence can start with 0.
It is guaranteed that the sum of the values ββof n for all test cases in the input does not exceed 2β
10^5.
Output
Print t lines β the answers to each of the test cases in the input.
If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of n digits t_1t_2 ... t_n (1 β€ t_i β€ 2), where t_i is the color the i-th digit is painted in. If there are several feasible solutions, print any of them.
If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign).
Example
Input
5
12
040425524644
1
0
9
123456789
2
98
3
987
Output
121212211211
1
222222222
21
-
Note
In the first test case, d=040425524644. The output t=121212211211 is correct because 0022444 (painted in 1) concatenated with 44556 (painted in 2) is 002244444556 which is a sorted sequence of n given digits. | import sys
input=sys.stdin.readline
def solve(n,D):
E=sorted(D)
Ans=[0]*n
idx=0
for i,d in enumerate(D):
if d==E[idx]:
idx+=1
Ans[i]=1
for i,d in enumerate(D):
if Ans[i]:
continue
if d!=E[idx]:
return ['-']
idx+=1
Ans[i]=2
return Ans
t=int(input())
for _ in range(t):
n=int(input())
D=list(map(int,list(input().strip())))
print(*solve(n,D),sep='') | {
"input": [
"5\n12\n040425524644\n1\n0\n9\n123456789\n2\n98\n3\n987\n"
],
"output": [
"121212211211\n1\n111111111\n21\n-\n"
]
} |
1,051 | 8 | Suppose there is a h Γ w grid consisting of empty or full cells. Let's make some definitions:
* r_{i} is the number of consecutive full cells connected to the left side in the i-th row (1 β€ i β€ h). In particular, r_i=0 if the leftmost cell of the i-th row is empty.
* c_{j} is the number of consecutive full cells connected to the top end in the j-th column (1 β€ j β€ w). In particular, c_j=0 if the topmost cell of the j-th column is empty.
In other words, the i-th row starts exactly with r_i full cells. Similarly, the j-th column starts exactly with c_j full cells.
<image> These are the r and c values of some 3 Γ 4 grid. Black cells are full and white cells are empty.
You have values of r and c. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of r and c. Since the answer can be very large, find the answer modulo 1000000007 (10^{9} + 7). In other words, find the remainder after division of the answer by 1000000007 (10^{9} + 7).
Input
The first line contains two integers h and w (1 β€ h, w β€ 10^{3}) β the height and width of the grid.
The second line contains h integers r_{1}, r_{2}, β¦, r_{h} (0 β€ r_{i} β€ w) β the values of r.
The third line contains w integers c_{1}, c_{2}, β¦, c_{w} (0 β€ c_{j} β€ h) β the values of c.
Output
Print the answer modulo 1000000007 (10^{9} + 7).
Examples
Input
3 4
0 3 1
0 2 3 0
Output
2
Input
1 1
0
1
Output
0
Input
19 16
16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12
6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4
Output
797922655
Note
In the first example, this is the other possible case.
<image>
In the second example, it's impossible to make a grid to satisfy such r, c values.
In the third example, make sure to print answer modulo (10^9 + 7). | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
def go():
c = 0
for i in range(n):
for j in range(m):
if j > a[i] and i > b[j]:
c += 1
elif (j < a[i] and i == b[j]) or (j == a[i] and i < b[j]):
print(0)
return
print(pow(2, c, 1000000007))
go()
| {
"input": [
"19 16\n16 16 16 16 15 15 0 5 0 4 9 9 1 4 4 0 8 16 12\n6 12 19 15 8 6 19 19 14 6 9 16 10 11 15 4\n",
"3 4\n0 3 1\n0 2 3 0\n",
"1 1\n0\n1\n"
],
"output": [
"797922655\n",
"2\n",
"0\n"
]
} |
1,052 | 8 | For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) β₯ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 β₯ 5.
You are given an array a of n integers. Find some interesting nonempty subarray of a, or tell that it doesn't exist.
An array b is a subarray of an array a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.
Input
The first line contains integer number t (1 β€ t β€ 10 000). Then t test cases follow.
The first line of each test case contains a single integer n (2β€ n β€ 2β
10^5) β the length of the array.
The second line of each test case contains n integers a_1, a_2, ..., a_n (0β€ a_i β€ 10^9) β the elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output "NO" in a separate line if there is no interesting nonempty subarray in a.
Otherwise, output "YES" in a separate line. In the next line, output two integers l and r (1β€ l β€ r β€ n) β bounds of the chosen subarray. If there are multiple answers, print any.
You can print each letter in any case (upper or lower).
Example
Input
3
5
1 2 3 4 5
4
2 0 1 9
2
2019 2020
Output
NO
YES
1 4
NO
Note
In the second test case of the example, one of the interesting subarrays is a = [2, 0, 1, 9]: max(a) - min(a) = 9 - 0 = 9 β₯ 4. | def solve(a,n):
for i in range(n-1):
if abs(a[i+1]-a[i]) >= 2:
print("YES")
print(i+1,i+2)
return
print("NO")
for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
solve(a,n)
| {
"input": [
"3\n5\n1 2 3 4 5\n4\n2 0 1 9\n2\n2019 2020\n"
],
"output": [
"NO\nYES\n1 2\nNO\n"
]
} |
1,053 | 12 | [SIHanatsuka - EMber](https://soundcloud.com/hanatsuka/sihanatsuka-ember)
[SIHanatsuka - ATONEMENT](https://soundcloud.com/hanatsuka/sihanatsuka-atonement)
Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.
One day, Nora's adoptive father, Phoenix Wyle, brought Nora n boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.
She labelled all n boxes with n distinct integers a_1, a_2, β¦, a_n and asked ROBO to do the following action several (possibly zero) times:
* Pick three distinct indices i, j and k, such that a_i β£ a_j and a_i β£ a_k. In other words, a_i divides both a_j and a_k, that is a_j mod a_i = 0, a_k mod a_i = 0.
* After choosing, Nora will give the k-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.
* After doing so, the box k becomes unavailable for any further actions.
Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.
Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?
As the number of such piles can be very large, you should print the answer modulo 10^9 + 7.
Input
The first line contains an integer n (3 β€ n β€ 60), denoting the number of boxes.
The second line contains n distinct integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 60), where a_i is the label of the i-th box.
Output
Print the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 10^9 + 7.
Examples
Input
3
2 6 8
Output
2
Input
5
2 3 4 9 12
Output
4
Input
4
5 7 2 9
Output
1
Note
Let's illustrate the box pile as a sequence b, with the pile's bottommost box being at the leftmost position.
In the first example, there are 2 distinct piles possible:
* b = [6] ([2, 6, 8] \xrightarrow{(1, 3, 2)} [2, 8])
* b = [8] ([2, 6, 8] \xrightarrow{(1, 2, 3)} [2, 6])
In the second example, there are 4 distinct piles possible:
* b = [9, 12] ([2, 3, 4, 9, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, 12] \xrightarrow{(1, 3, 4)} [2, 3, 4])
* b = [4, 12] ([2, 3, 4, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, 12] \xrightarrow{(2, 3, 4)} [2, 3, 9])
* b = [4, 9] ([2, 3, 4, 9, 12] \xrightarrow{(1, 5, 3)} [2, 3, 9, 12] \xrightarrow{(2, 4, 3)} [2, 3, 12])
* b = [9, 4] ([2, 3, 4, 9, 12] \xrightarrow{(2, 5, 4)} [2, 3, 4, 12] \xrightarrow{(1, 4, 3)} [2, 3, 12])
In the third sequence, ROBO can do nothing at all. Therefore, there is only 1 valid pile, and that pile is empty. | MOD = 1000000007
def isSubset(a, b):
return (a & b) == a
def isIntersect(a, b):
return (a & b) != 0
# Solve for each weakly connected component (WCC)
def cntOrder(s, t):
p = len(s)
m = len(t)
inMask = [0 for i in range(m)]
for x in range(p):
for i in range(m):
if t[i] % s[x] == 0:
inMask[i] |= 1 << x
cnt = [0 for mask in range(1<<p)]
for mask in range(1<<p):
for i in range(m):
if isSubset(inMask[i], mask):
cnt[mask] += 1
dp = [[0 for mask in range(1<<p)] for k in range(m+1)]
for i in range(m):
dp[1][inMask[i]] += 1
for k in range(m):
for mask in range(1<<p):
for i in range(m):
if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask):
dp[k+1][mask | inMask[i]] = (dp[k+1][mask | inMask[i]] + dp[k][mask]) % MOD
dp[k+1][mask] = (dp[k+1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD
return dp[m][(1<<p)-1]
def dfs(u):
global a, graph, degIn, visited, s, t
visited[u] = True
if degIn[u] == 0:
s.append(a[u])
else:
t.append(a[u])
for v in graph[u]:
if not visited[v]:
dfs(v)
def main():
global a, graph, degIn, visited, s, t
# Reading input
n = int(input())
a = list(map(int, input().split()))
# Pre-calculate C(n, k)
c = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
c[i][0] = 1
for j in range(1, i+1):
c[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD
# Building divisibility graph
degIn = [0 for u in range(n)]
graph = [[] for u in range(n)]
for u in range(n):
for v in range(n):
if u != v and a[v] % a[u] == 0:
graph[u].append(v)
graph[v].append(u)
degIn[v] += 1
# Solve for each WCC of divisibility graph and combine result
ans = 1
curLen = 0
visited = [False for u in range(n)]
for u in range(n):
if not visited[u]:
s = []
t = []
dfs(u)
if len(t) > 0:
sz = len(t) - 1
cnt = cntOrder(s, t)
# Number of orders for current WCC
ans = (ans * cnt) % MOD
# Number of ways to insert <sz> number to array of <curLen> elements
ans = (ans * c[curLen + sz][sz]) % MOD
curLen += sz
print(ans)
if __name__ == "__main__":
main() | {
"input": [
"4\n5 7 2 9\n",
"3\n2 6 8\n",
"5\n2 3 4 9 12\n"
],
"output": [
"1\n",
"2\n",
"4\n"
]
} |
1,054 | 10 | You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose some 1 β€ i, j β€ 9 and change the number at the position (i, j) to any other number in range [1; 9]) to make it anti-sudoku. The anti-sudoku is the 9 Γ 9 field, in which:
* Any number in this field is in range [1; 9];
* each row contains at least two equal elements;
* each column contains at least two equal elements;
* each 3 Γ 3 block (you can read what is the block in the link above) contains at least two equal elements.
It is guaranteed that the answer exists.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
Each test case consists of 9 lines, each line consists of 9 characters from 1 to 9 without any whitespaces β the correct solution of the sudoku puzzle.
Output
For each test case, print the answer β the initial field with at most 9 changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.
Example
Input
1
154873296
386592714
729641835
863725149
975314628
412968357
631457982
598236471
247189563
Output
154873396
336592714
729645835
863725145
979314628
412958357
631457992
998236471
247789563 | def solve():
for _ in range(9):
print(input().replace("9", "6"))
t = int(input())
for _ in range(t):
solve()
| {
"input": [
"1\n154873296\n386592714\n729641835\n863725149\n975314628\n412968357\n631457982\n598236471\n247189563\n"
],
"output": [
"254873296\n386692714\n729641935\n873725149\n975324628\n412968367\n632457982\n598237471\n247189564\n"
]
} |
1,055 | 11 | Madeline has an array a of n integers. A pair (u, v) of integers forms an inversion in a if:
* 1 β€ u < v β€ n.
* a_u > a_v.
Madeline recently found a magical paper, which allows her to write two indices u and v and swap the values a_u and a_v. Being bored, she decided to write a list of pairs (u_i, v_i) with the following conditions:
* all the pairs in the list are distinct and form an inversion in a.
* all the pairs that form an inversion in a are in the list.
* Starting from the given array, if you swap the values at indices u_1 and v_1, then the values at indices u_2 and v_2 and so on, then after all pairs are processed, the array a will be sorted in non-decreasing order.
Construct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the length of the array.
Next line contains n integers a_1,a_2,...,a_n (1 β€ a_i β€ 10^9) β elements of the array.
Output
Print -1 if no such list exists. Otherwise in the first line you should print a single integer m (0 β€ m β€ (n(n-1))/(2)) β number of pairs in the list.
The i-th of the following m lines should contain two integers u_i, v_i (1 β€ u_i < v_iβ€ n).
If there are multiple possible answers, you may find any of them.
Examples
Input
3
3 1 2
Output
2
1 3
1 2
Input
4
1 8 1 6
Output
2
2 4
2 3
Input
5
1 1 1 2 2
Output
0
Note
In the first sample test case the array will change in this order [3,1,2] β [2,1,3] β [1,2,3].
In the second sample test case it will be [1,8,1,6] β [1,6,1,8] β [1,1,6,8].
In the third sample test case the array is already sorted. | n = int(input())
a = list(map(int, input().split()))
ans = []
def f(l):
return -l[1],l[2], l[0]
for i in range(n):
for j in range(i+1, n):
if a[i]>a[j]:
ans.append((i+1, j+1, a[i]))
ans.sort(key=f)
print(len(ans))
for i in ans:
print(*i[:2]) | {
"input": [
"4\n1 8 1 6\n",
"5\n1 1 1 2 2\n",
"3\n3 1 2\n"
],
"output": [
"2\n2 4\n2 3\n",
"0\n",
"2\n1 3\n1 2\n"
]
} |
1,056 | 7 | You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i β j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| β€ 1) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).
Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 50) β the length of a. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100), where a_i is the i-th element of a.
Output
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
Example
Input
5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
Output
YES
YES
NO
NO
YES
Note
In the first test case of the example, we can perform the following sequence of moves:
* choose i=1 and j=3 and remove a_i (so a becomes [2; 2]);
* choose i=1 and j=2 and remove a_j (so a becomes [2]).
In the second test case of the example, we can choose any possible i and j any move and it doesn't matter which element we remove.
In the third test case of the example, there is no way to get rid of 2 and 4. | def f(l):
for i in range(len(l)-1):
if l[i+1]-l[i]>1:
return "NO"
return "YES"
for i in range(int(input())):
n=int(input())
l=set(map(int,input().split()))
l=list(l)
l.sort()
print(f(l)) | {
"input": [
"5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100\n"
],
"output": [
"YES\nYES\nNO\nNO\nYES\n"
]
} |
1,057 | 10 | Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.
Let's represent the city as an area of n Γ n square blocks. Yura needs to move from the block with coordinates (s_x,s_y) to the block with coordinates (f_x,f_y). In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are m instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate x or with the same coordinate y as the location.
Help Yura to find the smallest time needed to get home.
Input
The first line contains two integers n and m β the size of the city and the number of instant-movement locations (1 β€ n β€ 10^9, 0 β€ m β€ 10^5).
The next line contains four integers s_x s_y f_x f_y β the coordinates of Yura's initial position and the coordinates of his home ( 1 β€ s_x, s_y, f_x, f_y β€ n).
Each of the next m lines contains two integers x_i y_i β coordinates of the i-th instant-movement location (1 β€ x_i, y_i β€ n).
Output
In the only line print the minimum time required to get home.
Examples
Input
5 3
1 1 5 5
1 2
4 1
3 3
Output
5
Input
84 5
67 59 41 2
39 56
7 2
15 3
74 18
22 7
Output
42
Note
In the first example Yura needs to reach (5, 5) from (1, 1). He can do that in 5 minutes by first using the second instant-movement location (because its y coordinate is equal to Yura's y coordinate), and then walking (4, 1) β (4, 2) β (4, 3) β (5, 3) β (5, 4) β (5, 5). | from heapq import heappush, heappop;import sys;input=sys.stdin.readline;INF = 10**10
def dijkstra(N, G, s):
dist = [INF] * N;que = [(0, s)];dist[s] = 0
while que:
c, v = heappop(que)
if dist[v] < c:continue
for t, cost in G[v]:
if dist[v] + cost < dist[t]:dist[t] = dist[v] + cost;heappush(que, (dist[t], t))
return dist[1]
N, M = map(int, input().split());sx, sy, fx, fy = map(int, input().split());vs = [];g = [set() for _ in range(M+2)]
for i in range(M):x, y = map(int, input().split());g[0].add((i+2, min(abs(x-sx), abs(y-sy))));g[i+2].add((1, abs(x-fx)+abs(y-fy)));vs.append((i+2, x, y))
vs.sort(key=lambda x:x[1])
for (b, bx, by), (i, x, y) in zip(vs, vs[1:]):c = x-bx;g[i].add((b, c));g[b].add((i, c))
vs.sort(key=lambda x:x[2])
for (b, bx, by), (i, x, y) in zip(vs, vs[1:]):c = y-by;g[i].add((b, c));g[b].add((i, c))
print(min(dijkstra(M+2, g, 0), abs(fy-sy)+abs(fx-sx))) | {
"input": [
"84 5\n67 59 41 2\n39 56\n7 2\n15 3\n74 18\n22 7\n",
"5 3\n1 1 5 5\n1 2\n4 1\n3 3\n"
],
"output": [
"42\n",
"5\n"
]
} |
1,058 | 9 | This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n Γ m. This table consists of symbols 0 and 1.
You can make such operation: select 3 different cells that belong to one 2 Γ 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).
Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations.
It can be proved that it is always possible.
Input
The first line contains a single integer t (1 β€ t β€ 5000) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains two integers n, m (2 β€ n, m β€ 100).
Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.
It is guaranteed that the sum of nm for all test cases does not exceed 20000.
Output
For each test case print the integer k (0 β€ k β€ 3nm) β the number of operations.
In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 β€ x_1, x_2, x_3 β€ n, 1 β€ y_1, y_2, y_3 β€ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 Γ 2 square.
Example
Input
5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101
Output
1
1 1 2 1 2 2
2
2 1 3 1 3 2
1 2 1 3 2 3
4
1 1 1 2 2 2
1 3 1 4 2 3
3 2 4 1 4 2
3 3 4 3 4 4
4
1 2 2 1 2 2
1 4 1 5 2 5
4 1 4 2 5 1
4 4 4 5 3 4
2
1 3 2 2 2 3
1 2 2 1 2 2
Note
In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.
In the second test case:
* operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:
011
001
000
* operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:
000
000
000
In the fifth test case:
* operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:
010
110
* operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:
000
000
| def ans(i,j):
x=i+1 if i<n else i-1
y=j+1 if j<m else j-1
print(i,j,i,y,x,y)
print(i,j,x,j,x,y)
print(i,j,i,y,x,j)
for _ in range(int(input())):
n,m=map(int,input().split())
l=[list(map(int,list(input()))) for i in range(n)]
print(sum(sum(z) for z in l)*3)
for i in range(n):
for j in range(m):
if l[i][j]==1:
ans(i+1,j+1) | {
"input": [
"5\n2 2\n10\n11\n3 3\n011\n101\n110\n4 4\n1111\n0110\n0110\n1111\n5 5\n01011\n11001\n00010\n11011\n10000\n2 3\n011\n101\n"
],
"output": [
"9\n1 1 2 1 2 2 \n1 1 1 2 2 2 \n1 1 2 1 1 2 \n2 1 1 1 1 2 \n2 1 2 2 1 2 \n2 1 1 1 2 2 \n2 2 1 2 1 1 \n2 2 2 1 1 1 \n2 2 1 2 2 1 \n18\n1 2 2 2 2 3 \n1 2 1 3 2 3 \n1 2 2 2 1 3 \n1 3 2 3 2 2 \n1 3 1 2 2 2 \n1 3 2 3 1 2 \n2 1 3 1 3 2 \n2 1 2 2 3 2 \n2 1 3 1 2 2 \n2 3 3 3 3 2 \n2 3 2 2 3 2 \n2 3 3 3 2 2 \n3 1 2 1 2 2 \n3 1 3 2 2 2 \n3 1 2 1 3 2 \n3 2 2 2 2 3 \n3 2 3 3 2 3 \n3 2 2 2 3 3 \n36\n1 1 2 1 2 2 \n1 1 1 2 2 2 \n1 1 2 1 1 2 \n1 2 2 2 2 3 \n1 2 1 3 2 3 \n1 2 2 2 1 3 \n1 3 2 3 2 4 \n1 3 1 4 2 4 \n1 3 2 3 1 4 \n1 4 2 4 2 3 \n1 4 1 3 2 3 \n1 4 2 4 1 3 \n2 2 3 2 3 3 \n2 2 2 3 3 3 \n2 2 3 2 2 3 \n2 3 3 3 3 4 \n2 3 2 4 3 4 \n2 3 3 3 2 4 \n3 2 4 2 4 3 \n3 2 3 3 4 3 \n3 2 4 2 3 3 \n3 3 4 3 4 4 \n3 3 3 4 4 4 \n3 3 4 3 3 4 \n4 1 3 1 3 2 \n4 1 4 2 3 2 \n4 1 3 1 4 2 \n4 2 3 2 3 3 \n4 2 4 3 3 3 \n4 2 3 2 4 3 \n4 3 3 3 3 4 \n4 3 4 4 3 4 \n4 3 3 3 4 4 \n4 4 3 4 3 3 \n4 4 4 3 3 3 \n4 4 3 4 4 3 \n36\n1 2 2 2 2 3 \n1 2 1 3 2 3 \n1 2 2 2 1 3 \n1 4 2 4 2 5 \n1 4 1 5 2 5 \n1 4 2 4 1 5 \n1 5 2 5 2 4 \n1 5 1 4 2 4 \n1 5 2 5 1 4 \n2 1 3 1 3 2 \n2 1 2 2 3 2 \n2 1 3 1 2 2 \n2 2 3 2 3 3 \n2 2 2 3 3 3 \n2 2 3 2 2 3 \n2 5 3 5 3 4 \n2 5 2 4 3 4 \n2 5 3 5 2 4 \n3 4 4 4 4 5 \n3 4 3 5 4 5 \n3 4 4 4 3 5 \n4 1 5 1 5 2 \n4 1 4 2 5 2 \n4 1 5 1 4 2 \n4 2 5 2 5 3 \n4 2 4 3 5 3 \n4 2 5 2 4 3 \n4 4 5 4 5 5 \n4 4 4 5 5 5 \n4 4 5 4 4 5 \n4 5 5 5 5 4 \n4 5 4 4 5 4 \n4 5 5 5 4 4 \n5 1 4 1 4 2 \n5 1 5 2 4 2 \n5 1 4 1 5 2 \n12\n1 2 2 2 2 3 \n1 2 1 3 2 3 \n1 2 2 2 1 3 \n1 3 2 3 2 2 \n1 3 1 2 2 2 \n1 3 2 3 1 2 \n2 1 1 1 1 2 \n2 1 2 2 1 2 \n2 1 1 1 2 2 \n2 3 1 3 1 2 \n2 3 2 2 1 2 \n2 3 1 3 2 2 \n"
]
} |
1,059 | 10 | There are n cells, numbered 1,2,..., n from left to right. You have to place a robot at any cell initially. The robot must make exactly k moves.
In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell i, it must move to either the cell i-1 or the cell i+1, as long as it lies between 1 and n (endpoints inclusive). The cells, in the order they are visited (including the cell the robot is placed), together make a good path.
Each cell i has a value a_i associated with it. Let c_0, c_1, ..., c_k be the sequence of cells in a good path in the order they are visited (c_0 is the cell robot is initially placed, c_1 is the cell where the robot is after its first move, and so on; more formally, c_i is the cell that the robot is at after i moves). Then the value of the path is calculated as a_{c_0} + a_{c_1} + ... + a_{c_k}.
Your task is to calculate the sum of values over all possible good paths. Since this number can be very large, output it modulo 10^9 + 7. Two good paths are considered different if the starting cell differs or there exists an integer i β [1, k] such that the current cell of the robot after exactly i moves is different in those paths.
You must process q updates to a and print the updated sum each time. Each update changes the value of exactly one cell. See the input format and the sample input-output for more details.
Input
The first line of the input contains three space-separated integers n, k and q (2 β€ n β€ 5000; 1 β€ k β€ 5000; 1 β€ q β€ 2 β
10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
q lines follow. Each line contains two space-separated integers i and x (1 β€ i β€ n; 1 β€ x β€ 10^9) indicating that you must change the value of a_i to x.
Output
Print q integers. The i-th integer should be the sum of values over all good paths after the first i updates are performed. Since the answers may be large, print them modulo 10^9 + 7.
Examples
Input
5 1 5
3 5 1 4 2
1 9
2 4
3 6
4 6
5 2
Output
62
58
78
86
86
Input
5 2 5
3 5 1 4 2
1 9
2 4
3 6
4 6
5 2
Output
157
147
207
227
227
Input
4 40 6
92 21 82 46
3 56
1 72
4 28
1 97
2 49
2 88
Output
239185261
666314041
50729936
516818968
766409450
756910476
Note
In the first example, the good paths are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), (4, 3), (4, 5), (5, 4).
Initially the values of a are [3, 5, 1, 4, 2]. After the first update, they become [9, 5, 1, 4, 2]. After the second update, they become [9, 4, 1, 4, 2], and so on. | import sys
sys.setrecursionlimit(10**5)
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.buffer.readline().split())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
inf = 10**16
md = 10**9+7
n, k, q = MI()
aa = LI()
dp = [[1]*n for _ in range(k+1)]
for i in range(k):
for j in range(n):
if j == 0:
dp[i+1][j] = dp[i][j+1]
elif j == n-1:
dp[i+1][j] = dp[i][j-1]
else:
dp[i+1][j] = (dp[i][j-1]+dp[i][j+1])%md
# p2D(dp)
ss = []
for j in range(n):
cur = 0
for i in range(k+1):
cur += dp[i][j]*dp[k-i][j]
cur %= md
ss.append(cur)
ans = sum(a*c%md for a, c in zip(aa, ss))%md
# print(ans)
for _ in range(q):
i, x = MI()
i -= 1
ans = (ans+(x-aa[i])*ss[i])%md
aa[i] = x
print(ans)
| {
"input": [
"4 40 6\n92 21 82 46\n3 56\n1 72\n4 28\n1 97\n2 49\n2 88\n",
"5 2 5\n3 5 1 4 2\n1 9\n2 4\n3 6\n4 6\n5 2\n",
"5 1 5\n3 5 1 4 2\n1 9\n2 4\n3 6\n4 6\n5 2\n"
],
"output": [
"\n239185261\n666314041\n50729936\n516818968\n766409450\n756910476\n",
"\n157\n147\n207\n227\n227\n",
"\n62\n58\n78\n86\n86\n"
]
} |
1,060 | 10 | Baby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it:
* pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range;
* stick some of the elements together in the same order they were in the array;
* end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece.
More formally, he partitions the sequence a_l, a_{l + 1}, ..., a_r into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length x, then no value occurs strictly more than β x/2 β times in it.
He didn't pick a range yet, so he's wondering: for q ranges (l, r), what is the minimum number of pieces he needs to partition the elements a_l, a_{l + 1}, ..., a_r into so that the partitioning is beautiful.
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Note that it does not have to be contiguous.
Input
The first line contains two integers n and q (1 β€ n,q β€ 3 β
10^5) β the length of the array a and the number of queries.
The second line contains n integers a_1, a_2, ..., a_{n} (1 β€ a_i β€ n) β the elements of the array a.
Each of the next q lines contains two integers l and r (1 β€ l β€ r β€ n) β the range of this query.
Output
For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists.
Example
Input
6 2
1 3 2 3 3 2
1 6
2 5
Output
1
2
Note
In the first query, you can just put the whole array in one subsequence, since its length is 6, and no value occurs more than 3 times in it.
In the second query, the elements of the query range are [3,2,3,3]. You can't put them all in one subsequence, since its length is 4, and 3 occurs more than 2 times. However, you can partition it into two subsequences: [3] and [2,3,3]. | import sys
input = sys.stdin.readline
n, q = map(int, input().split())
counts = [0] * (n + 1)
c_amt = [0] * (n + 3); c_amt[0] = n + 1
max_count = 0
moves = 0
def add(x):
global max_count, moves
moves += 1
v = l[x]
c_amt[counts[v]] -= 1
counts[v] += 1
c_amt[counts[v]] += 1
max_count = max(counts[v], max_count)
def remove(x):
global max_count, moves
moves += 1
v = l[x]
c_amt[counts[v]] -= 1
if max_count == counts[v] and c_amt[counts[v]] == 0:
max_count -= 1
counts[v] -= 1
c_amt[counts[v]] += 1
l = list(map(int, input().split()))
left = 0
right = -1
out = [0] * q
queries = []
for i in range(q):
ll, rr = map(int, input().split())
queries.append((ll-1,rr-1,i))
k = 547
queries.sort(key = lambda x: 2 * n * (x[0]//k) + (x[1] * ((-1) ** (x[0]//k))))
for ll, rr, i in queries:
while right < rr:
add(right + 1)
right += 1
while right > rr:
remove(right)
right -= 1
while left > ll:
add(left - 1)
left -= 1
while left < ll:
remove(left)
left += 1
sz = rr - ll + 1
top = max_count
other = sz-top
out[i] = max(1, top-other)
print('\n'.join(map(str,out)))
| {
"input": [
"6 2\n1 3 2 3 3 2\n1 6\n2 5\n"
],
"output": [
"\n1\n2\n"
]
} |
1,061 | 10 | You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image> | from functools import lru_cache
M = 10 ** 9 + 7
@lru_cache(5)
def inv(x):
return pow(x, M - 2, M)
@lru_cache(None)
def dp(u, v):
# u before v
if u == 0:
return 0
if v == 0:
return 1
return (dp(u - 1, v) * inv(2) + dp(u, v - 1) * inv(2)) % M
def main():
n = int(input())
link = [[float('inf') for j in range(n + 1)] for i in range(n + 1)]
for _ in range(n - 1):
u, v = [int(word) for word in input().split()]
link[u][v] = 1
link[v][u] = 1
for w in range(1, n + 1):
for u in range(1, n + 1):
for v in range(1, n + 1):
link[u][v] = min(link[u][v], link[u][w] + link[w][v])
ans = 0
for start in range(1, n + 1):
for u in range(1, n + 1):
for v in range(u + 1, n + 1):
lca = (link[start][u] + link[start][v] - link[u][v]) // 2
ans += dp(link[start][u] - lca, link[start][v] - lca)
ans %= M
ans *= inv(n)
ans %= M
print(ans)
if __name__ == "__main__":
main()
| {
"input": [
"5\n1 2\n1 3\n1 4\n2 5\n",
"3\n1 2\n1 3\n",
"6\n2 1\n2 3\n6 1\n1 4\n2 5\n"
],
"output": [
"500000007",
"166666669",
"500000009"
]
} |
1,062 | 7 | At a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew three points with integer coordinates, and joined them with segments of straight lines, then he showed the triangle to Peter. Peter said that Bob's triangle is not right-angled, but is almost right-angled: the triangle itself is not right-angled, but it is possible to move one of the points exactly by distance 1 so, that all the coordinates remain integer, and the triangle become right-angled. Bob asks you to help him and find out if Peter tricks him. By the given coordinates of the triangle you should find out if it is right-angled, almost right-angled, or neither of these.
Input
The first input line contains 6 space-separated integers x1, y1, x2, y2, x3, y3 β coordinates of the triangle's vertices. All the coordinates are integer and don't exceed 100 in absolute value. It's guaranteed that the triangle is nondegenerate, i.e. its total area is not zero.
Output
If the given triangle is right-angled, output RIGHT, if it is almost right-angled, output ALMOST, and if it is neither of these, output NEITHER.
Examples
Input
0 0 2 0 0 1
Output
RIGHT
Input
2 3 4 5 6 6
Output
NEITHER
Input
-1 0 2 0 0 1
Output
ALMOST | s = list(map(int,input().split()))
def dis(a,b,c,d):
return ((a-c)**2 + (b-d)**2)
def ass(s):
a,b,c,d,e,f = s
AB = dis(a,b,c,d)
BC = dis(c,d,e,f)
CA = dis(e,f,a,b)
x = max(AB,BC,CA)
return x == AB+BC+CA-x and AB and BC and CA
if ass(s):
print("RIGHT")
exit()
for i in range(6):
s[i] -= 1
if ass(s): print("ALMOST");exit()
s[i] += 2
if ass(s): print("ALMOST");exit()
s[i] -=1
print("NEITHER") | {
"input": [
"-1 0 2 0 0 1\n",
"2 3 4 5 6 6\n",
"0 0 2 0 0 1\n"
],
"output": [
"ALMOST\n",
"NEITHER\n",
"RIGHT\n"
]
} |
1,063 | 7 | Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies.
Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions:
* Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer.
* Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that.
* Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that.
* Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that.
* Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that.
* Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that.
* Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that.
Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.
Input
The first line contains integer n (1 β€ n β€ 200) β the number of game parts. The next line contains n integers, the i-th integer β ci (1 β€ ci β€ 3) represents the number of the computer, on which you can complete the game part number i.
Next n lines contain descriptions of game parts. The i-th line first contains integer ki (0 β€ ki β€ n - 1), then ki distinct integers ai, j (1 β€ ai, j β€ n; ai, j β i) β the numbers of parts to complete before part i.
Numbers on all lines are separated by single spaces. You can assume that the parts of the game are numbered from 1 to n in some way. It is guaranteed that there are no cyclic dependencies between the parts of the game.
Output
On a single line print the answer to the problem.
Examples
Input
1
1
0
Output
1
Input
5
2 2 1 1 3
1 5
2 5 1
2 5 4
1 5
0
Output
7
Note
Note to the second sample: before the beginning of the game the best strategy is to stand by the third computer. First we complete part 5. Then we go to the 1-st computer and complete parts 3 and 4. Then we go to the 2-nd computer and complete parts 1 and 2. In total we get 1+1+2+1+2, which equals 7 hours. | f = lambda: [int(q) - 1 for q in input().split()]
def g():
for i in p:
if h[i] == k and not v[i]: return i
r = range(int(input()))
t, h = 1e9, f()
u = [set(f()[1:]) for i in r]
for k in (0, 1, 2):
p = list(r)
d = -1
v = [q.copy() for q in u]
while p:
i = g()
while i != None:
d += 1
p.remove(i)
for q in v: q.discard(i)
i = g()
k = (k + 1) % 3
d += 1
t = min(d, t)
print(t) | {
"input": [
"1\n1\n0\n",
"5\n2 2 1 1 3\n1 5\n2 5 1\n2 5 4\n1 5\n0\n"
],
"output": [
"1\n",
"7\n"
]
} |
1,064 | 7 | Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
Input
The first line contains a single integer n (1 β€ n β€ 105), that is the number of cafe visitors.
Each of the following n lines has two space-separated integers hi and mi (0 β€ hi β€ 23; 0 β€ mi β€ 59), representing the time when the i-th person comes into the cafe.
Note that the time is given in the chronological order. All time is given within one 24-hour period.
Output
Print a single integer β the minimum number of cashes, needed to serve all clients next day.
Examples
Input
4
8 0
8 10
8 10
8 45
Output
2
Input
3
0 12
10 11
22 22
Output
1
Note
In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.
In the second sample all visitors will come in different times, so it will be enough one cash. | #!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
cnt = {}
for _ in range(n):
hm = readln()
cnt[hm] = cnt.get(hm, 0) + 1
print(max(cnt.values()))
| {
"input": [
"3\n0 12\n10 11\n22 22\n",
"4\n8 0\n8 10\n8 10\n8 45\n"
],
"output": [
"1\n",
"2\n"
]
} |
1,065 | 8 | Gerald plays the following game. He has a checkered field of size n Γ n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:
* At least one of the chips at least once fell to the banned cell.
* At least once two chips were on the same cell.
* At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row).
In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 1000, 0 β€ m β€ 105) β the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 β€ xi, yi β€ n) β the coordinates of the i-th banned cell. All given cells are distinct.
Consider the field rows numbered from top to bottom from 1 to n, and the columns β from left to right from 1 to n.
Output
Print a single integer β the maximum points Gerald can earn in this game.
Examples
Input
3 1
2 2
Output
0
Input
3 0
Output
1
Input
4 3
3 1
3 2
3 3
Output
1
Note
In the first test the answer equals zero as we can't put chips into the corner cells.
In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.
In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4). | def solve():
n, m = map(int, input().split())
a = [0 for x in range(n)]
b = [0 for x in range(n)]
for i in range(m):
row, col = map(int, input().split())
row -= 1
col -= 1
a[row] += 1
b[col] += 1
res = 0
for i in range(1, n - 1):
if a[i] == 0: res+=1
if b[i] == 0: res+=1
if a[i] == 0 and b[i] == 0 and i == n - i - 1: res-=1
print(res)
solve() | {
"input": [
"4 3\n3 1\n3 2\n3 3\n",
"3 1\n2 2\n",
"3 0\n"
],
"output": [
"1\n",
"0\n",
"1\n"
]
} |
1,066 | 7 | Little Vasya has received a young builderβs kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
Input
The first line contains an integer N (1 β€ N β€ 1000) β the number of bars at Vasyaβs disposal. The second line contains N space-separated integers li β the lengths of the bars. All the lengths are natural numbers not exceeding 1000.
Output
In one line output two numbers β the height of the largest tower and their total number. Remember that Vasya should use all the bars.
Examples
Input
3
1 2 3
Output
1 3
Input
4
6 5 6 7
Output
2 3 | def most_common(lst):
return max(set(lst), key=lst.count)
n = int(input())
a = list(map(int,input().split()))
b = set(a)
print(a.count(most_common(a)),len(b)) | {
"input": [
"3\n1 2 3\n",
"4\n6 5 6 7\n"
],
"output": [
"1 3\n",
"2 3\n"
]
} |
1,067 | 10 | This is yet another problem on regular bracket sequences.
A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.
For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
Input
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5Β·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 β€ ai, bi β€ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi β with a closing one.
Output
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.
Print -1, if there is no answer. If the answer is not unique, print any of them.
Examples
Input
(??)
1 2
2 8
Output
4
()() | from collections import namedtuple
from heapq import heappush, heappop
Diff = namedtuple("Diff", ["diff", "idx"])
def solver(brackets):
heap = []
opens = 0
cost = 0
for i, c in enumerate(brackets):
opens += int(c == "(") - int(c == ")")
if c == "?":
brackets[i] = ")"
o, c = map(int, input().split())
heappush(heap, Diff(o - c, i))
opens -= 1
cost += c
if opens < 0:
if not heap:
return -1, None
diff, idx = heappop(heap)
brackets[idx] = "("
opens += 2
cost += diff
return (-1, None) if opens != 0 else (cost, brackets)
def main():
cost, brackets = solver(list(input()))
if cost == -1:
print(-1)
else:
print(cost)
print("".join(brackets))
if __name__ == "__main__":
main()
| {
"input": [
"(??)\n1 2\n2 8\n"
],
"output": [
"4\n()()"
]
} |
1,068 | 7 | The police department of your city has just started its journey. Initially, they donβt have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.
Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.
Input
The first line of input will contain an integer n (1 β€ n β€ 105), the number of events. The next line will contain n space-separated integers.
If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.
Output
Print a single integer, the number of crimes which will go untreated.
Examples
Input
3
-1 -1 1
Output
2
Input
8
1 -1 1 -1 -1 1 1 1
Output
1
Input
11
-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1
Output
8
Note
Lets consider the second example:
1. Firstly one person is hired.
2. Then crime appears, the last hired person will investigate this crime.
3. One more person is hired.
4. One more crime appears, the last hired person will investigate this crime.
5. Crime appears. There is no free policeman at the time, so this crime will go untreated.
6. One more person is hired.
7. One more person is hired.
8. One more person is hired.
The answer is one, as one crime (on step 5) will go untreated. | def qc(v):
t,c=0,0
for x in v:
if t+x<0:
c+=1
t+=x
if t<0:
t=0
return c
input()
v=[int(x) for x in input().split()]
print(qc(v)) | {
"input": [
"11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1\n",
"3\n-1 -1 1\n",
"8\n1 -1 1 -1 -1 1 1 1\n"
],
"output": [
"8\n",
"2\n",
"1\n"
]
} |
1,069 | 7 | Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights a1, ..., an. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
Input
The first line contains a single integer n (3 β€ n β€ 100) β the number of holds.
The next line contains n space-separated integers ai (1 β€ ai β€ 1000), where ai is the height where the hold number i hangs. The sequence ai is increasing (i.e. each element except for the first one is strictly larger than the previous one).
Output
Print a single number β the minimum difficulty of the track after removing a single hold.
Examples
Input
3
1 4 6
Output
5
Input
5
1 2 3 4 5
Output
2
Input
5
1 2 3 7 8
Output
4
Note
In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.
In the second test after removing every hold the difficulty equals 2.
In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer β 4. | t=int(input())
a=list(map(int,input().split()))
def diff(a):
return max(a[i+1]-a[i] for i in range(len(a)-1))
print(min(diff(a[:i+1]+a[i+2:])for i in range(t-2))) | {
"input": [
"3\n1 4 6\n",
"5\n1 2 3 4 5\n",
"5\n1 2 3 7 8\n"
],
"output": [
"5\n",
"2\n",
"4\n"
]
} |
1,070 | 10 | Polycarp loves geometric progressions β he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = cΒ·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.
Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.
Input
The first line contains an integer n (1 β€ n β€ 105) β the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.
Output
Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.
Examples
Input
4
3 6 12 24
Output
0
Input
4
-8 -16 24 -32
Output
1
Input
4
0 1 2 3
Output
2 | def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return 0 if a == 0 else "inf"
return a / b
pref, suff = [["init", 1]], [["init", 1]]
for i in range(1, n):
d = div(l[i], l[i-1])
if pref[-1][0] == "init":
pass
elif d != pref[-1][0]:
for j in range(i, n):
pref += [["null", 0]]
break
pref += [[d, 1]]
for i in range(n - 1, -1, -1):
d = div(l[i], l[i-1])
if l[i - 1] == 0 and l[i] != 0:
suff[-1][0] = suff[-2][0] if len(suff) > 1 else 1
if d != suff[-1][0] and suff[-1][0] != "init":
for j in range(i-1, -1,-1):
suff += [["null", 0]]
break
suff += [[d, 1]]
#print(pref)
#print(suff)
if pref[-1][1] == 1: return 0
if pref[-2][1] == 1 or suff[-2][1] == 1: return 1
for i in range(1,n-1):
pr, sf = pref[i - 1], suff[n - i - 2]
dv = div(l[i+1], l[i-1])
#print(pr,sf,dv,l[i-1:i+2])
if pr[0] == "init" and sf[0] == "init": return 1
if pr[0] == "init" and dv == sf[0]:
return 1
elif sf[0] == "init" and dv == pr[0]:
return 1
elif dv == pr[0] and dv == sf[0]:
return 1
return 2
print(main())
| {
"input": [
"4\n3 6 12 24\n",
"4\n-8 -16 24 -32\n",
"4\n0 1 2 3\n"
],
"output": [
"0\n",
"1\n",
"2\n"
]
} |
1,071 | 11 | In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.
Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city.
Input
First line of input consists of two integers n and m (1 β€ n β€ 100, 0 β€ m β€ 200).
Next line contains n integers a1, a2, ..., an (0 β€ ai β€ 100).
Next line contains n integers b1, b2, ..., bn (0 β€ bi β€ 100).
Then m lines follow, each of them consists of two integers p and q (1 β€ p, q β€ n, p β q) denoting that there is an undirected road between cities p and q.
It is guaranteed that there is at most one road between each pair of cities.
Output
If the conditions can not be met output single word "NO".
Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i β j) or how many soldiers should stay in city i (if i = j).
If there are several possible answers you may output any of them.
Examples
Input
4 4
1 2 6 3
3 5 3 1
1 2
2 3
3 4
4 2
Output
YES
1 0 0 0
2 0 0 0
0 5 1 0
0 0 2 1
Input
2 0
1 2
2 1
Output
NO | from sys import stdin, stdout, stderr
from collections import deque
n,m = map(int,stdin.readline().split())
ai = [int(x) for x in stdin.readline().split()]
bi = [int(x) for x in stdin.readline().split()]
N = 2*n+2
M = 4*m + 6*n
cap = [None for i in range(M)]
flow = [0 for i in range(M)]
adj = [[] for i in range(N)]
s = 0
t = 2*n+1
INF = 0x3f3f3f3f
eid = 0
def add_edge(a,b,c):
global eid, adj, cap
adj[a].append((b,eid))
cap[eid] = c
eid += 1
for i in range(m):
a,b = map(int,stdin.readline().split())
add_edge(a,n+b,INF)
add_edge(n+b,a,0)
add_edge(b,n+a,INF)
add_edge(n+a,b,0)
for i in range(n):
add_edge(s,i+1,ai[i])
add_edge(i+1,s,0)
add_edge(n+i+1,t,bi[i])
add_edge(t,n+i+1,0)
add_edge(i+1,n+i+1,INF)
add_edge(n+i+1,i+1,0)
ans = 0
while True:
par = [None for i in range(N)]
minf = [INF for i in range(N)]
bfs = deque()
bfs.append(s)
par[s] = (-1,-1)
while bfs:
u = bfs.pop()
if u == t:
break
for v,e in adj[u]:
if par[v] is None and flow[e] < cap[e]:
bfs.append(v)
par[v] = (u,e)
minf[v] = min(minf[u], cap[e] - flow[e])
v = t
if par[t] is None: break
while par[v][0] != -1:
u,e = par[v]
flow[e] += minf[t]
flow[e^1] -= minf[t]
v = u
ans += minf[t]
if ans != sum(ai) or ans != sum(bi):
stdout.write('NO\n')
else:
stdout.write('YES\n')
grid = [[0 for j in range(n)] for i in range(n)]
for u in range(1,n+1):
for v,e in adj[u]:
if flow[e] > 0 and 1 <= v-n and v-n <= n:
grid[u-1][v-n-1] += flow[e]
stdout.write('\n'.join([' '.join([str(x) for x in line]) for line in grid]) + '\n')
| {
"input": [
"4 4\n1 2 6 3\n3 5 3 1\n1 2\n2 3\n3 4\n4 2\n",
"2 0\n1 2\n2 1\n"
],
"output": [
"YES\n1 0 0 0 \n2 0 0 0 \n0 5 1 0 \n0 0 2 1 \n",
"NO\n"
]
} |
1,072 | 8 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.
Limak will repeat the following operation till everything is destroyed.
Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.
Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
Input
The first line contains single integer n (1 β€ n β€ 105).
The second line contains n space-separated integers h1, h2, ..., hn (1 β€ hi β€ 109) β sizes of towers.
Output
Print the number of operations needed to destroy all towers.
Examples
Input
6
2 1 4 6 2 2
Output
3
Input
7
3 3 3 1 3 3 3
Output
2
Note
The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.
<image> After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | def main():
input()
hh = list(map(int, input().split()))
for f in True, False:
m = 1
for i, h in enumerate(hh):
if h > m:
hh[i] = m
else:
m = h
m += 1
if f:
hh.reverse()
print(max(hh))
if __name__ == '__main__':
main()
| {
"input": [
"6\n2 1 4 6 2 2\n",
"7\n3 3 3 1 3 3 3\n"
],
"output": [
"3",
"2"
]
} |
1,073 | 9 | You are given a rectangular field of n Γ m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.
For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.
The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit β- the answer modulo 10. The matrix should be printed without any spaces.
To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input
The first line contains two integers n, m (1 β€ n, m β€ 1000) β the number of rows and columns in the field.
Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.
Output
Print the answer as a matrix as described above. See the examples to precise the format of the output.
Examples
Input
3 3
*.*
.*.
*.*
Output
3.3
.5.
3.3
Input
4 5
**..*
..***
.*.*.
*.*.*
Output
46..3
..732
.6.4.
5.4.3
Note
In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner). | from collections import deque
dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
componentsizes = {}
componentid = 0
n, m = map(int, input().split())
field = [list(input()) for _ in range(n)]
def valid(y, x):
return y >= 0 and x >= 0 and y < n and x < m
def component(y, x):
size = 1
q = deque([(y, x)])
field[y][x] = componentid
while q:
y, x = q.pop()
for i, j in dirs:
if valid(y+i, x+j) and field[y+i][x+j] == ".":
q.appendleft((y+i, x+j))
field[y+i][x+j] = componentid
size += 1
return size
def solve(y, x):
connected = set()
for i, j in dirs:
if valid(y+i, x+j) and type(field[y+i][x+j]) is int:
connected.add(field[y+i][x+j])
return (sum(componentsizes[i] for i in connected)+1)%10
for i in range(n):
for j in range(m):
if field[i][j] == ".":
componentsizes[componentid] = component(i, j)
componentid += 1
output = [[] for _ in range(n)]
for i in range(n):
for j in range(m):
output[i].append(str(solve(i, j)) if field[i][j] == "*" else ".")
print("\n".join(["".join(row) for row in output]))
| {
"input": [
"4 5\n**..*\n..***\n.*.*.\n*.*.*\n",
"3 3\n*.*\n.*.\n*.*\n"
],
"output": [
"46..3\n..732\n.6.4.\n5.4.3\n",
"3.3\n.5.\n3.3\n"
]
} |
1,074 | 10 | A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.
Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.
As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
Input
The first line contains five integers n, k, a, b, and q (1 β€ k β€ n β€ 200 000, 1 β€ b < a β€ 10 000, 1 β€ q β€ 200 000) β the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.
The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:
* 1 di ai (1 β€ di β€ n, 1 β€ ai β€ 10 000), representing an update of ai orders on day di, or
* 2 pi (1 β€ pi β€ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi?
It's guaranteed that the input will contain at least one query of the second type.
Output
For each query of the second type, print a line containing a single integer β the maximum number of orders that the factory can fill over all n days.
Examples
Input
5 2 2 1 8
1 1 2
1 5 3
1 2 1
2 2
1 4 2
1 3 2
2 1
2 3
Output
3
6
4
Input
5 4 10 1 6
1 1 5
1 5 5
1 3 2
1 5 2
2 1
2 2
Output
7
1
Note
Consider the first sample.
We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.
For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.
For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders. | from functools import reduce
class SegmentTree():
def __init__(self, L, function = lambda x,y: x+y, initilizer = None):
self.function = function
self.initilizer = initilizer
N = self.size = len(L)
M = 1 << N.bit_length()
self.margin = 2*M - N
self.L = [None for i in range(self.margin)] + L
for i in range(M-1, 0, -1):
x, y = self.L[i<<1], self.L[i<<1|1]
self.L[i] = None if x is None or y is None else function(x, y)
def modify(self, pos, value):
p = pos + self.margin
self.L[p] = value
while p > 1:
x, y = self.L[p], self.L[p^1]
if p&1: x, y = y, x
self.L[p>>1] = None if x is None or y is None else self.function(x, y)
p>>=1
def query(self, left, right):
l, r = left + self.margin, right + self.margin
stack = []
void = True
if self.initilizer is not None:
void = False
result = self.initilizer
while l < r:
if l&1:
if void:
result = self.L[l]
void = False
else:
result = self.function(result, self.L[l])
l+=1
if r&1:
r-=1
stack.append(self.L[r])
l>>=1
r>>=1
init = stack.pop() if void else result
return reduce(self.function, reversed(stack), init)
import sys
n, k, a, b, q = [int(x) for x in input().split()]
orders = [0]*(n+2)
a_tree, b_tree = SegmentTree(orders, initilizer = 0), SegmentTree(orders, initilizer = 0)
for line in sys.stdin:
s = [int(x) for x in line.split()]
if s[0] == 1:
orders[s[1]] += s[2]
a_tree.modify(s[1], min(a, orders[s[1]]))
b_tree.modify(s[1], min(b, orders[s[1]]))
else:
query = b_tree.query(0, s[1]) + a_tree.query(s[1]+k, n+1)
print(query)
| {
"input": [
"5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2\n",
"5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3\n"
],
"output": [
"7\n1\n",
"3\n6\n4\n"
]
} |
1,075 | 9 | International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.
For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.
You are given a list of abbreviations. For each of them determine the year it stands for.
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the number of abbreviations to process.
Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.
Output
For each abbreviation given in the input, find the year of the corresponding Olympiad.
Examples
Input
5
IAO'15
IAO'2015
IAO'1
IAO'9
IAO'0
Output
2015
12015
1991
1989
1990
Input
4
IAO'9
IAO'99
IAO'999
IAO'9999
Output
1989
1999
2999
9999 | def solve(x):
l = len(x)
if l == 1: return '19' + ('8' if x == '9' else '9') + x
if l == 2: return ('19' if x == '99' else '20') + x
if l == 3: return ('3' if int(x) <= 98 else '2') + x
if l >= 4:
y = int((l - 4) * '1' + '3098')
return ('1' if int(x) <= y else '') + x
n = int(input())
for i in range(n):
k = input()[4:]
print(solve(k))
| {
"input": [
"5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0\n",
"4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999\n"
],
"output": [
"2015\n12015\n1991\n1989\n1990\n",
"1989\n1999\n2999\n9999\n"
]
} |
1,076 | 7 | While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
<image>
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":
<image> <image>
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
Input
The first line of the input contains the only integer n (1 β€ n β€ 9) β the number of digits in the phone number that Mike put in.
The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.
Output
If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line.
Examples
Input
3
586
Output
NO
Input
2
09
Output
NO
Input
9
123456789
Output
YES
Input
3
911
Output
YES
Note
You can find the picture clarifying the first sample case in the statement above. | def main():
input()
l = list(map(int, input()))
for s in {0, 4, 5, 6, 7, 8, 9}, {1, 2, 4, 5, 7, 8}, {1, 2, 3, 4, 5, 6, 8}, {2, 3, 5, 6, 8, 9}:
if all(x in s for x in l):
print("NO")
return
print("YES")
if __name__ == '__main__':
main()
| {
"input": [
"9\n123456789\n",
"3\n911\n",
"3\n586\n",
"2\n09\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n",
"NO\n"
]
} |
1,077 | 11 | zscoder wants to generate an input file for some programming competition problem.
His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.
Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a' from the text file and y seconds to copy the contents of the entire text file, and duplicate it.
zscoder wants to find the minimum amount of time needed for him to create the input file of exactly n letters 'a'. Help him to determine the amount of time needed to generate the input.
Input
The only line contains three integers n, x and y (1 β€ n β€ 107, 1 β€ x, y β€ 109) β the number of letters 'a' in the input file and the parameters from the problem statement.
Output
Print the only integer t β the minimum amount of time needed to generate the input file.
Examples
Input
8 1 1
Output
4
Input
8 1 10
Output
8 | def fi(n):
if n == 1:
return x
elif n == 2:
return x + min(x, y)
else:
if n % 2 == 1:
return min(fi(n-1), fi(n+1)) + x
else:
return fi(n//2) + min(y, x * (n//2))
n,x,y = map(int, input().split())
print(fi(n)) | {
"input": [
"8 1 10\n",
"8 1 1\n"
],
"output": [
"8",
"4"
]
} |
1,078 | 11 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.
The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.
One move happens as follows. Lets say there are m β₯ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move.
Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.
Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
Input
The first line of input contains a single integer n (2 β€ n β€ 200 000) β the number of stickers, initially located on the wall.
The second line contains n integers a1, a2, ..., an ( - 10 000 β€ ai β€ 10 000) β the numbers on stickers in order from left to right.
Output
Print one integer β the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
Examples
Input
3
2 4 8
Output
14
Input
4
1 -7 -2 3
Output
-3
Note
In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.
In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. |
def f(a):
n = len(a)
dp = [0] * n
s = [0] * (n+1)
for i in range(0, n):
s[i+1] = s[i] + a[i]
#print(s)
maxdiffyet = s[n]
#print(f"maxdiffyet = {maxdiffyet}")
for i in range(n-2, -1, -1):
dp[i] = maxdiffyet
#print(f"dp[{i}] = {dp[i]}, s[{i}] = {s[i]}, maxdiffyet({i}) = {maxdiffyet} -> {max(maxdiffyet, s[i+1] - dp[i])}")
maxdiffyet = max(maxdiffyet, s[i+1] - dp[i])
#print(dp)
return dp[0]
n = int(input())
a = [int(x) for x in input().split(' ')]
print(f(a))
| {
"input": [
"3\n2 4 8\n",
"4\n1 -7 -2 3\n"
],
"output": [
"14\n",
"-3\n"
]
} |
1,079 | 7 | Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.
Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).
Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly n movements were made by the operator and the ball was under shell x at the end. Now he wonders, what was the initial position of the ball?
Input
The first line of the input contains an integer n (1 β€ n β€ 2Β·109) β the number of movements made by the operator.
The second line contains a single integer x (0 β€ x β€ 2) β the index of the shell where the ball was found after n movements.
Output
Print one integer from 0 to 2 β the index of the shell where the ball was initially placed.
Examples
Input
4
2
Output
1
Input
1
1
Output
0
Note
In the first sample, the ball was initially placed beneath the middle shell and the operator completed four movements.
1. During the first move operator swapped the left shell and the middle shell. The ball is now under the left shell.
2. During the second move operator swapped the middle shell and the right one. The ball is still under the left shell.
3. During the third move operator swapped the left shell and the middle shell again. The ball is again in the middle.
4. Finally, the operators swapped the middle shell and the right shell. The ball is now beneath the right shell. | def solve():
n = int(input())
num = n%6
k = int(input())
arr = [[0,1,2],[1,0,2],[1,2,0],[2,1,0],[2,0,1],[0,2,1]]
print(arr[num][k])
solve()
| {
"input": [
"4\n2\n",
"1\n1\n"
],
"output": [
"1\n",
"0\n"
]
} |
1,080 | 10 | You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
Input
The first line has one integer n (4 β€ n β€ 1 000) β the number of vertices.
The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 β€ xi, yi β€ 109) β the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
Output
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
4
0 0
0 1
1 1
1 0
Output
0.3535533906
Input
6
5 0
10 0
12 -4
10 -8
5 -8
3 -4
Output
1.0000000000
Note
Here is a picture of the first sample
<image>
Here is an example of making the polygon non-convex.
<image>
This is not an optimal solution, since the maximum distance we moved one point is β 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most β 0.3535533906. | n = int(input())
P = []
def h(p1, p2, m):
return abs(((p2[0] - p1[0])*(m[1] - p1[1])-(p2[1] - p1[1])*(m[0] - p1[0]))\
/((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1])**2) ** 0.5)
for i in range(n):
P.append(list(map(int, input().split())))
answer = float("inf")
for i in range(n):
cw = P[(i + 1) % n]
ucw = P[i - 1]
answer = min(answer, h(cw, ucw, P[i])/2)
print(answer)
| {
"input": [
"6\n5 0\n10 0\n12 -4\n10 -8\n5 -8\n3 -4\n",
"4\n0 0\n0 1\n1 1\n1 0\n"
],
"output": [
"1.00000000\n",
"0.35355339\n"
]
} |
1,081 | 7 | Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town ViΔkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1Β·2Β·3Β·...Β·(x - 1)Β·x. For example 4! = 1Β·2Β·3Β·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
Input
The first and single line contains two integers A and B (1 β€ A, B β€ 109, min(A, B) β€ 12).
Output
Print a single integer denoting the greatest common divisor of integers A! and B!.
Example
Input
4 3
Output
6
Note
Consider the sample.
4! = 1Β·2Β·3Β·4 = 24. 3! = 1Β·2Β·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6. | def f(x):return 1 if x==0 else x*f(x-1)
print(f(min(map(int,input().split()))))
| {
"input": [
"4 3\n"
],
"output": [
"6\n"
]
} |
1,082 | 12 | The elections to Berland parliament are happening today. Voting is in full swing!
Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 β€ k β€ n) top candidates will take seats in the parliament.
After the end of the voting the number of votes for each candidate is calculated. In the resulting table the candidates are ordered by the number of votes. In case of tie (equal number of votes) they are ordered by the time of the last vote given. The candidate with ealier last vote stands higher in the resulting table.
So in the resulting table candidates are sorted by the number of votes (more votes stand for the higher place) and if two candidates have equal number of votes they are sorted by the time of last vote (earlier last vote stands for the higher place).
There is no way for a candidate with zero votes to take a seat in the parliament. So it is possible that less than k candidates will take a seat in the parliament.
In Berland there are m citizens who can vote. Each of them will vote for some candidate. Each citizen will give a vote to exactly one of n candidates. There is no option "against everyone" on the elections. It is not accepted to spoil bulletins or not to go to elections. So each of m citizens will vote for exactly one of n candidates.
At the moment a citizens have voted already (1 β€ a β€ m). This is an open election, so for each citizen it is known the candidate for which the citizen has voted. Formally, the j-th citizen voted for the candidate gj. The citizens who already voted are numbered in chronological order; i.e. the (j + 1)-th citizen voted after the j-th.
The remaining m - a citizens will vote before the end of elections, each of them will vote for one of n candidates.
Your task is to determine for each of n candidates one of the three possible outcomes:
* a candidate will be elected to the parliament regardless of votes of the remaining m - a citizens;
* a candidate has chance to be elected to the parliament after all n citizens have voted;
* a candidate has no chances to be elected to the parliament regardless of votes of the remaining m - a citizens.
Input
The first line contains four integers n, k, m and a (1 β€ k β€ n β€ 100, 1 β€ m β€ 100, 1 β€ a β€ m) β the number of candidates, the number of seats in the parliament, the number of Berland citizens and the number of citizens who already have voted.
The second line contains a sequence of a integers g1, g2, ..., ga (1 β€ gj β€ n), where gj is the candidate for which the j-th citizen has voted. Citizens who already voted are numbered in increasing order of voting times.
Output
Print the sequence consisting of n integers r1, r2, ..., rn where:
* ri = 1 means that the i-th candidate is guaranteed to take seat in the parliament regardless of votes of the remaining m - a citizens;
* ri = 2 means that the i-th candidate has a chance to take a seat in the parliament, i.e. the remaining m - a citizens can vote in such a way that the candidate will take a seat in the parliament;
* ri = 3 means that the i-th candidate will not take a seat in the parliament regardless of votes of the remaining m - a citizens.
Examples
Input
3 1 5 4
1 2 1 3
Output
1 3 3
Input
3 1 5 3
1 3 1
Output
2 3 2
Input
3 2 5 3
1 3 1
Output
1 2 2 | class State:
__slots__ = ['candidate', 'votes', 'last_vote']
def __init__(self, cand, votes, last):
self.candidate = cand
self.votes = votes
self.last_vote = last
def beats(self, other, extra):
return self.votes + extra > other.votes
def main():
candidates, seats, people, voted = map(int, input().split())
votes = [0 for i in range(candidates)]
last_vote = [0 for i in range(candidates)]
if candidates == 1:
print(1)
return
v = list(map(int, input().split()))
for t in range(voted):
cand = v[t] - 1
votes[cand] += 1
last_vote[cand] = t
states = [State(i, votes[i], last_vote[i]) for i in range(candidates)]
states = sorted(states, key = lambda x : (x.votes, -x.last_vote))
res = [0 for i in range(candidates)]
for i in range(candidates):
if i < candidates - seats:
low = candidates - seats
if states[i].beats(states[low], people - voted):
res[states[i].candidate] = 2
else:
res[states[i].candidate] = 3
else:
extra = people - voted
other = i - 1
place = i
if extra == 0 and states[i].votes == 0:
res[states[i].candidate] = 3
continue
while other >= 0 and extra > 0:
needed = states[i].votes - states[other].votes + 1
if needed <= extra:
extra -= needed;
place -= 1
other -= 1
else:
break
res[states[i].candidate] = (1 if place + seats >= candidates and states[i].votes > 0 else 2)
for i in res:
print(i, end = ' ')
main()
| {
"input": [
"3 1 5 3\n1 3 1\n",
"3 2 5 3\n1 3 1\n",
"3 1 5 4\n1 2 1 3\n"
],
"output": [
"2 3 2 ",
"1 2 2 ",
"1 3 3 "
]
} |
1,083 | 7 | Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted by x1, x2, ..., xn and y1, y2, ..., yn respectively. They reveal their sequences, and repeat until all of 2n integers become distinct, which is the only final state to be kept and considered.
Then they count the number of ordered pairs (i, j) (1 β€ i, j β€ n) such that the value xi xor yj equals to one of the 2n integers. Here xor means the [bitwise exclusive or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.
Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.
Input
The first line of input contains a positive integer n (1 β€ n β€ 2 000) β the length of both sequences.
The second line contains n space-separated integers x1, x2, ..., xn (1 β€ xi β€ 2Β·106) β the integers finally chosen by Koyomi.
The third line contains n space-separated integers y1, y2, ..., yn (1 β€ yi β€ 2Β·106) β the integers finally chosen by Karen.
Input guarantees that the given 2n integers are pairwise distinct, that is, no pair (i, j) (1 β€ i, j β€ n) exists such that one of the following holds: xi = yj; i β j and xi = xj; i β j and yi = yj.
Output
Output one line β the name of the winner, that is, "Koyomi" or "Karen" (without quotes). Please be aware of the capitalization.
Examples
Input
3
1 2 3
4 5 6
Output
Karen
Input
5
2 4 6 8 10
9 7 5 3 1
Output
Karen
Note
In the first example, there are 6 pairs satisfying the constraint: (1, 1), (1, 2), (2, 1), (2, 3), (3, 2) and (3, 3). Thus, Karen wins since 6 is an even number.
In the second example, there are 16 such pairs, and Karen wins again. | import sys
def main():
print("Karen")
if __name__ == '__main__':
main()
| {
"input": [
"3\n1 2 3\n4 5 6\n",
"5\n2 4 6 8 10\n9 7 5 3 1\n"
],
"output": [
"Karen\n",
"Karen\n"
]
} |
1,084 | 7 | Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.
A time is considered lucky if it contains a digit '7'. For example, 13: 07 and 17: 27 are lucky, while 00: 48 and 21: 34 are not lucky.
Note that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at hh: mm.
Formally, find the smallest possible non-negative integer y such that the time representation of the time xΒ·y minutes before hh: mm contains the digit '7'.
Jamie uses 24-hours clock, so after 23: 59 comes 00: 00.
Input
The first line contains a single integer x (1 β€ x β€ 60).
The second line contains two two-digit integers, hh and mm (00 β€ hh β€ 23, 00 β€ mm β€ 59).
Output
Print the minimum number of times he needs to press the button.
Examples
Input
3
11 23
Output
2
Input
5
01 07
Output
0
Note
In the first sample, Jamie needs to wake up at 11:23. So, he can set his alarm at 11:17. He would press the snooze button when the alarm rings at 11:17 and at 11:20.
In the second sample, Jamie can set his alarm at exactly at 01:07 which is lucky. | def lucky(a,b):
return '7' in str(a)+str(b)
x = int(input())
t = 0
h,m = map(int,input().split())
while not lucky(h,m):
t+=1
m -= x
while m<0:
m+=60
h-=1
h%=24
print(t)
| {
"input": [
"3\n11 23\n",
"5\n01 07\n"
],
"output": [
"2\n",
"0\n"
]
} |
1,085 | 8 | Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.
Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.
Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.
Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.
Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.
Input
The first line contains two integers N and K (0 β€ N β€ 1018, 1 β€ K β€ 105) β the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces.
The second line contains K integers a1, a2, ..., aK (1 β€ ai β€ 1018 for all i) β the capacities of boxes.
Output
Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input.
If there are many correct answers, output any of them.
Examples
Input
19 3
5 4 10
Output
2 4
Input
28 3
5 6 30
Output
1 5 | #!/usr/bin/env python
def main():
N, K = map(int, input().split())
a = [int(c) for c in input().split()]
rem = min([(N % e, i) for i, e in enumerate(a)])
a, b = rem[1] + 1, N // a[rem[1]]
print(a, b)
if __name__ == '__main__':
main()
| {
"input": [
"19 3\n5 4 10\n",
"28 3\n5 6 30\n"
],
"output": [
"2 4\n",
"1 5\n"
]
} |
1,086 | 11 | This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either β although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.
In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number n.
In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.
Given n, determine the total number of possible bus number variants.
Input
The first line contains one integer n (1 β€ n β€ 10^{18}) β the number of the bus that was seen by Vasya. It is guaranteed that this number does not start with 0.
Output
Output a single integer β the amount of possible variants of the real bus number.
Examples
Input
97
Output
2
Input
2028
Output
13
Note
In the first sample, only variants 97 and 79 are possible.
In the second sample, the variants (in the increasing order) are the following: 208, 280, 802, 820, 2028, 2082, 2208, 2280, 2802, 2820, 8022, 8202, 8220. | n = str(input())
k = len(n)
dig = [0 for i in range(10)]
for x in n:
dig[int(x)]+=1
ans = 0
fact = [1]
for i in range(1,20):
fact.append(fact[i-1]*i)
def foo(i, tot, val, z):
if(i>=10):
global ans
ans += fact[tot]//val
if(z>0):
val = val//fact[z]
val = val*fact[z-1]
ans -= (fact[tot-1])//val
return
if(dig[i]==0):
foo(i+1, tot, val, z)
for x in range(1, dig[i]+1):
if(i!=0):
foo(i+1, tot+x, val*fact[x], z)
if(i==0):
foo(i+1, tot+x, val*fact[x], x)
foo(0, 0, 1,0)
print(ans) | {
"input": [
"2028\n",
"97\n"
],
"output": [
"13\n",
"2\n"
]
} |
1,087 | 10 | The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] β are not.
A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] β are not.
For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.
Input
The first line contains the number n~(1 β€ n β€ 10^3) β the length of the initial sequence. The following line contains n integers a_1, a_2, ..., a_n~(-10^9 β€ a_i β€ 10^9) β the sequence itself.
Output
In the single line output one integer β the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.
Examples
Input
3
2 1 1
Output
2
Input
4
1 1 1 1
Output
7
Note
In the first test case, two good subsequences β [a_1, a_2, a_3] and [a_2, a_3].
In the second test case, seven good subsequences β [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. | mod=998244353
def ncr(n,r):
if n<r or n==0:
return 0
if r==0:
return 1
return (fac[n]*invfac[r]*invfac[n-r])%mod
n=int(input())
a=list(map(int,input().split()))
fac = [1] * (n + 1)
invfac = [1] * (n + 1)
for i in range(1, n + 1):
fac[i] = (i * fac[i - 1]) % mod
invfac[i] = pow(fac[i], mod - 2, mod)
dp=[0]*(n+1)
for i in range(n-1,-1,-1):
if a[i]>0:
for j in range(min(n,i+a[i]+1),n):
dp[i]=(dp[i]+dp[j]*ncr(j-i-1,a[i]))%mod
dp[i]=(dp[i]+ncr(n-i-1,a[i]))%mod
print(sum(dp)%mod) | {
"input": [
"4\n1 1 1 1\n",
"3\n2 1 1\n"
],
"output": [
"7\n",
"2\n"
]
} |
1,088 | 7 | There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly β you can find them later yourselves if you want.
To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", "D" and "C") and a rank (in the increasing order "6", "7", "8", "9", "T", "J", "Q", "K" and "A"). At the beginning of the game one suit is arbitrarily chosen as trump.
The players move like that: one player puts one or several of his cards on the table and the other one should beat each of them with his cards.
A card beats another one if both cards have similar suits and the first card has a higher rank then the second one. Besides, a trump card can beat any non-trump card whatever the cardsβ ranks are. In all other cases you can not beat the second card with the first one.
You are given the trump suit and two different cards. Determine whether the first one beats the second one or not.
Input
The first line contains the tramp suit. It is "S", "H", "D" or "C".
The second line contains the description of the two different cards. Each card is described by one word consisting of two symbols. The first symbol stands for the rank ("6", "7", "8", "9", "T", "J", "Q", "K" and "A"), and the second one stands for the suit ("S", "H", "D" and "C").
Output
Print "YES" (without the quotes) if the first cards beats the second one. Otherwise, print "NO" (also without the quotes).
Examples
Input
H
QH 9S
Output
YES
Input
S
8D 6D
Output
YES
Input
C
7H AS
Output
NO | def rank(c):
s="6789TJQKA"
return s.find(c)
t=input()
s=input()
s1, s2=s.split(sep=" ")
if s1[1]==t and s2[1]!=t:
print('YES')
elif s1[1]==s2[1] and rank(s1[0])>=rank(s2[0]):
print('YES')
else:
print('NO') | {
"input": [
"C\n7H AS\n",
"H\nQH 9S\n",
"S\n8D 6D\n"
],
"output": [
"NO\n",
"YES\n",
"YES\n"
]
} |
1,089 | 9 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.
Input
The single line contains an integer n (1 β€ n β€ 106) β the sum of digits of the required lucky number.
Output
Print on the single line the result β the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.
Examples
Input
11
Output
47
Input
10
Output
-1 | def f(n):
s=n//7
n%=7
s-=n%4
if s<0:
return '-1'
n+=n%4*7
return '4'*(n//4)+'7'*s
print(f(int(input())))
| {
"input": [
"11\n",
"10\n"
],
"output": [
"47\n",
"-1\n"
]
} |
1,090 | 12 | There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| β€ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| β€ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k β the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| β€ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| β€ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | rint = lambda: int(input())
rmint = lambda: map(int, input().split())
rlist = lambda: list(rmint())
n = rint()
a = [0, 0] * (10 ** 5 + 1)
for c in rlist(): a[c] += 1
pr = 0; t = 0; ans = 0; g = 0
for i in range(1, 2 * 10 ** 5 + 1):
if a[i] < 2:
t = 0
pr = a[i]
else:
t += a[i]
nx = a[i+1]
if pr + t + nx > ans:
ans = pr + t + nx
g = i
r = g+1; l = g+1
while a[l-1] > 1: l -= 1
while a[r] > 1: r += 1
print(ans)
# print(l,r)
def out(x,y=1):
while y:
print(x,end=' ')
y -= 1
for i in range(l,r): out(i)
out(r,a[r])
for i in range(r-1,l-1,-1): out(i,a[i]-1)
out(l-1,a[l-1])
| {
"input": [
"3\n5 1 4\n",
"7\n4 3 5 1 2 2 1\n",
"5\n3 7 5 1 5\n",
"7\n2 2 3 2 1 2 2\n"
],
"output": [
"2\n4 5\n",
"5\n1 2 3 2 1 \n",
"2\n5 5 \n",
"7\n1 2 3 2 2 2 2 \n"
]
} |
1,091 | 9 | Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b".
Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string t, and swap s_{pos_1} with t_{pos_2}.
You have to determine the minimum number of operations Monocarp has to perform to make s and t equal, and print any optimal sequence of operations β or say that it is impossible to make these strings equal.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^{5}) β the length of s and t.
The second line contains one string s consisting of n characters "a" and "b".
The third line contains one string t consisting of n characters "a" and "b".
Output
If it is impossible to make these strings equal, print -1.
Otherwise, in the first line print k β the minimum number of operations required to make the strings equal. In each of the next k lines print two integers β the index in the string s and the index in the string t that should be used in the corresponding swap operation.
Examples
Input
4
abab
aabb
Output
2
3 3
3 2
Input
1
a
b
Output
-1
Input
8
babbaabb
abababaa
Output
3
2 6
1 3
7 8
Note
In the first example two operations are enough. For example, you can swap the third letter in s with the third letter in t. Then s = "abbb", t = "aaab". Then swap the third letter in s and the second letter in t. Then both s and t are equal to "abab".
In the second example it's impossible to make two strings equal. | def solve(n,a,b):
s=[];c=0;ans=[]
for i in range(n):
if a[i]!=b[i]:s.append([a[i],b[i],i+1]);c+=1
if c%2!=0:return -1
s.sort();i=1
while i<c:
if s[i][0]==s[i-1][0]:ans.append([s[i][2],s[i-1][2]])
else:ans.append([s[i][2],s[i][2]]);ans.append([s[i-1][2],s[i][2]])
i+=2
return ans
n=int(input());a=list(input());b=list(input());p=solve(n,a,b)
if p==-1:print(-1)
else:
print(len(p))
for it in p:
print(*it)
| {
"input": [
"1\na\nb\n",
"8\nbabbaabb\nabababaa\n",
"4\nabab\naabb\n"
],
"output": [
"-1\n",
"3\n2 6\n1 3\n7 8\n",
"2\n3 3\n3 2\n"
]
} |
1,092 | 11 | You have a password which you often type β a string s of length n. Every character of this string is one of the first m lowercase Latin letters.
Since you spend a lot of time typing it, you want to buy a new keyboard.
A keyboard is a permutation of the first m Latin letters. For example, if m = 3, then there are six possible keyboards: abc, acb, bac, bca, cab and cba.
Since you type your password with one finger, you need to spend time moving your finger from one password character to the next. The time to move from character s_i to character s_{i+1} is equal to the distance between these characters on keyboard. The total time you have to spend typing the password with a keyboard is called the slowness of this keyboard.
More formaly, the slowness of keyboard is equal to β_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |, where pos_x is position of letter x in keyboard.
For example, if s is aacabc and the keyboard is bac, then the total time of typing this password is |pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c| = |2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3| = 0 + 1 + 1 + 1 + 2 = 5.
Before buying a new keyboard you want to know the minimum possible slowness that the keyboard can have.
Input
The first line contains two integers n and m (1 β€ n β€ 10^5, 1 β€ m β€ 20).
The second line contains the string s consisting of n characters. Each character is one of the first m Latin letters (lowercase).
Output
Print one integer β the minimum slowness a keyboard can have.
Examples
Input
6 3
aacabc
Output
5
Input
6 4
aaaaaa
Output
0
Input
15 4
abacabadabacaba
Output
16
Note
The first test case is considered in the statement.
In the second test case the slowness of any keyboard is 0.
In the third test case one of the most suitable keyboards is bacd. | n, m = map(int, input().split())
a = list(map(str, input().strip()))
dp = [10 ** 10] * (1 << 20)
cnt = [0] * (1 << 20)
def get(x):
return 1 << (ord(x) - ord('a'))
for i, v in enumerate(a):
if i:
cnt[get(a[i]) | get(a[i - 1])] += 1
for i in range(m):
for j in range(1 << m):
if (1 << i) & j:
cnt[j] += cnt[j ^ (1 << i)]
# print(bin(j), bin(j ^ 1 << i), cnt[j])
# for i in range(1 << m):
# for j in range(m):
# if not i & (1 << j):
# cnt[i | (1 << j)] += cnt[i]
# print(bin(i | (1 << j)), bin(i), cnt[i | 1 << j])
dp[0] = 0
for i in range(1 << m):
for j in range(m):
if not i & (1 << j):
dp[i | (1 << j)] = min(dp[i | (1 << j)],
dp[i] + n - 1 - cnt[i | (1 << j)] - cnt[(1 << m) - 1 - (i | (1 << j))])
print(dp[(1 << m) - 1])
| {
"input": [
"15 4\nabacabadabacaba\n",
"6 3\naacabc\n",
"6 4\naaaaaa\n"
],
"output": [
"16\n",
"5\n",
"0\n"
]
} |
1,093 | 12 | You are given two strings s and t both of length n and both consisting of lowercase Latin letters.
In one move, you can choose any length len from 1 to n and perform the following operation:
* Choose any contiguous substring of the string s of length len and reverse it;
* at the same time choose any contiguous substring of the string t of length len and reverse it as well.
Note that during one move you reverse exactly one substring of the string s and exactly one substring of the string t.
Also note that borders of substrings you reverse in s and in t can be different, the only restriction is that you reverse the substrings of equal length. For example, if len=3 and n=5, you can reverse s[1 ... 3] and t[3 ... 5], s[2 ... 4] and t[2 ... 4], but not s[1 ... 3] and t[1 ... 2].
Your task is to say if it is possible to make strings s and t equal after some (possibly, empty) sequence of moves.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 β€ q β€ 10^4) β the number of test cases. Then q test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the length of s and t.
The second line of the test case contains one string s consisting of n lowercase Latin letters.
The third line of the test case contains one string t consisting of n lowercase Latin letters.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer on it β "YES" (without quotes) if it is possible to make strings s and t equal after some (possibly, empty) sequence of moves and "NO" otherwise.
Example
Input
4
4
abcd
abdc
5
ababa
baaba
4
asdf
asdg
4
abcd
badc
Output
NO
YES
NO
YES | from collections import *
def f(s):
c = Counter(s)
if c.most_common()[0][1]>1:
return c
return c,sum(s[i]>s[j] for i in range(len(s))for j in range(i,len(s)))&1
for _ in range(int(input())):
n,s,t=input(),input(),input()
print("YNEOS"[f(s)!=f(t)::2]) | {
"input": [
"4\n4\nabcd\nabdc\n5\nababa\nbaaba\n4\nasdf\nasdg\n4\nabcd\nbadc\n"
],
"output": [
"NO\nYES\nNO\nYES\n"
]
} |
1,094 | 7 | We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location β is denoted by an integer in \{0, β¦, |s|\}, with the following meaning:
* If β = 0, then the cursor is located before the first character of s.
* If β = |s|, then the cursor is located right after the last character of s.
* If 0 < β < |s|, then the cursor is located between s_β and s_{β+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments β once.
* The Cut action. Set c β s_right, then set s β s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at β = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_β times.
4. If β = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that β β€ |s| at any time.
Input
The first line of input contains a single integer t (1 β€ t β€ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 β€ x β€ 10^6). The second line of each test case consists of the initial string s (1 β€ |s| β€ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that β β€ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, β = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get β = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_β = 2 times: we get s = 23131.
* Step 4: β = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_β = 3 times: we get s = 23131131131.
* Step 4: β = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_β = 1 time: we get s = 23131131131.
* Step 4: β = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_β = 3 times: we get s = 2313113113111311311131131.
* Step 4: β = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_β = 1 times: we get s = 2313113113111311311131131.
* Step 4: β = 5 = x, so we stop.
At the end of the procedure, s has length 25. | def solve(l,s):
n = len(s)
for i in range(l):
n += (n-i-1)*(int(s[i])-1)
n %= 7 + 10**9
if len(s) < l:
s += s[i+1:]*(int(s[i])-1)
return n
for _ in range(int(input())):
l = int(input())
s = input()
print(solve(l,s)) | {
"input": [
"4\n5\n231\n7\n2323\n6\n333\n24\n133321333\n"
],
"output": [
"25\n1438\n1101\n686531475\n"
]
} |
1,095 | 11 | Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n Γ n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.
Input
The first line contains one integer n (2 β€ n β€ 1000), n is even.
Output
Output n lines with n numbers each β the required matrix. Separate numbers with spaces. If there are several solutions, output any.
Examples
Input
2
Output
0 1
1 0
Input
4
Output
0 1 3 2
1 0 2 3
3 2 0 1
2 3 1 0 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
matrix = [[0] * n for _ in range(n)]
for i in range(n - 1):
for j in range(n - 1):
matrix[i][j] = i + j - (n - 1 if i + j >= n - 1 else 0)
matrix[i][-1] = matrix[-1][i] = (matrix[i - 1][i] + 1) % (n - 1)
matrix[i][n - i - 1] = matrix[n - i - 1][i] = n - 1
matrix[i][i] = 0
ans = '\n'.join(' '.join(map(str, matrix[i])) for i in range(n))
sys.stdout.buffer.write(ans.encode('utf-8'))
| {
"input": [
"2\n",
"4\n"
],
"output": [
"0 1 \n1 0 \n",
"0 2 3 1 \n2 0 1 3 \n3 1 0 2 \n1 3 2 0 \n"
]
} |
1,096 | 7 | You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 Γ 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures.
Your task is to say if you can clear the whole field by placing such figures.
More formally, the problem can be described like this:
The following process occurs while at least one a_i is greater than 0:
1. You place one figure 2 Γ 1 (choose some i from 1 to n and replace a_i with a_i + 2);
2. then, while all a_i are greater than zero, replace each a_i with a_i - 1.
And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next 2t lines describe test cases. The first line of the test case contains one integer n (1 β€ n β€ 100) β the number of columns in the Tetris field. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100), where a_i is the initial height of the i-th column of the Tetris field.
Output
For each test case, print the answer β "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.
Example
Input
4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
Output
YES
NO
YES
YES
Note
The first test case of the example field is shown below:
<image>
Gray lines are bounds of the Tetris field. Note that the field has no upper bound.
One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes [2, 0, 2]. Then place the figure in the second column and after the second step of the process, the field becomes [0, 0, 0].
And the second test case of the example field is shown below:
<image>
It can be shown that you cannot do anything to end the process.
In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0, 2]. Then place the figure in the first column and after the second step of the process, the field becomes [0, 0].
In the fourth test case of the example, place the figure in the first column, then the field becomes [102] after the first step of the process, and then the field becomes [0] after the second step of the process. |
def solve(n, A):
return len({a%2 for a in A}) == 1
t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int, input().split()))
print("YES" if solve(n, A) else "NO")
| {
"input": [
"4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\n"
],
"output": [
"YES\nNO\nYES\nYES\n"
]
} |
1,097 | 7 | Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state.
In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.
If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.
Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.
Input
The first line consists of a single integer t (1 β€ t β€ 50) β the number of test cases. The description of the test cases follows.
The first line of each test case consists of two space-separated integers n, m (1 β€ n, m β€ 50) β the number of rows and columns in the matrix.
The following n lines consist of m integers each, the j-th integer on the i-th line denoting a_{i,j} (a_{i,j} β \{0, 1\}).
Output
For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).
Example
Input
4
2 2
0 0
0 0
2 2
0 0
0 1
2 3
1 0 1
1 1 0
3 3
1 0 0
0 0 0
1 0 0
Output
Vivek
Ashish
Vivek
Ashish
Note
For the first case: One possible scenario could be: Ashish claims cell (1, 1), Vivek then claims cell (2, 2). Ashish can neither claim cell (1, 2), nor cell (2, 1) as cells (1, 1) and (2, 2) are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win.
For the second case: Ashish claims cell (1, 1), the only cell that can be claimed in the first move. After that Vivek has no moves left.
For the third case: Ashish cannot make a move, so Vivek wins.
For the fourth case: If Ashish claims cell (2, 3), Vivek will have no moves left. | def main():
n, m = list(map(int, input().split()))
N = [0]*n
M = [0]*m
for ni in range(n):
for mi, f in enumerate(input().split(" ")):
if f == "1":
N[ni] = 1
M[mi] = 1
z = min(n - sum(N), m - sum(M))
print("Vivek" if z % 2 == 0 else "Ashish")
for t in range(int(input())):
main() | {
"input": [
"4\n2 2\n0 0\n0 0\n2 2\n0 0\n0 1\n2 3\n1 0 1\n1 1 0\n3 3\n1 0 0\n0 0 0\n1 0 0\n"
],
"output": [
"Vivek\nAshish\nVivek\nAshish\n"
]
} |
1,098 | 7 | You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b and c in any (arbitrary) order.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The only line of the test case contains three integers x, y, and z (1 β€ x, y, z β€ 10^9).
Output
For each test case, print the answer:
* "NO" in the only line of the output if a solution doesn't exist;
* or "YES" in the first line and any valid triple of positive integers a, b and c (1 β€ a, b, c β€ 10^9) in the second line. You can print a, b and c in any order.
Example
Input
5
3 2 3
100 100 100
50 49 49
10 30 20
1 1000000000 1000000000
Output
YES
3 2 1
YES
100 100 100
NO
NO
YES
1 1 1000000000 | def main():
for _ in range(int(input())):
x, y, z = sorted(map(int, input().split()))
print('NO' if y < z else f'YES\n{x} {x} {z}')
if __name__ == '__main__':
main()
| {
"input": [
"5\n3 2 3\n100 100 100\n50 49 49\n10 30 20\n1 1000000000 1000000000\n"
],
"output": [
"YES\n3 2 2\nYES\n100 100 100\nNO\nNO\nYES\n1000000000 1 1\n"
]
} |
1,099 | 10 | You are given a sequence of n integers a_1, a_2, β¦, a_n.
You have to construct two sequences of integers b and c with length n that satisfy:
* for every i (1β€ iβ€ n) b_i+c_i=a_i
* b is non-decreasing, which means that for every 1<iβ€ n, b_iβ₯ b_{i-1} must hold
* c is non-increasing, which means that for every 1<iβ€ n, c_iβ€ c_{i-1} must hold
You have to minimize max(b_i,c_i). In other words, you have to minimize the maximum number in sequences b and c.
Also there will be q changes, the i-th change is described by three integers l,r,x. You should add x to a_l,a_{l+1}, β¦, a_r.
You have to find the minimum possible value of max(b_i,c_i) for the initial sequence and for sequence after each change.
Input
The first line contains an integer n (1β€ nβ€ 10^5).
The secound line contains n integers a_1,a_2,β¦,a_n (1β€ iβ€ n, -10^9β€ a_iβ€ 10^9).
The third line contains an integer q (1β€ qβ€ 10^5).
Each of the next q lines contains three integers l,r,x (1β€ lβ€ rβ€ n,-10^9β€ xβ€ 10^9), desribing the next change.
Output
Print q+1 lines.
On the i-th (1 β€ i β€ q+1) line, print the answer to the problem for the sequence after i-1 changes.
Examples
Input
4
2 -1 7 3
2
2 4 -3
3 4 2
Output
5
5
6
Input
6
-9 -10 -9 -6 -5 4
3
2 6 -9
1 2 -10
4 6 -3
Output
3
3
3
1
Input
1
0
2
1 1 -1
1 1 -1
Output
0
0
-1
Note
In the first test:
* The initial sequence a = (2, -1, 7, 3). Two sequences b=(-3,-3,5,5),c=(5,2,2,-2) is a possible choice.
* After the first change a = (2, -4, 4, 0). Two sequences b=(-3,-3,5,5),c=(5,-1,-1,-5) is a possible choice.
* After the second change a = (2, -4, 6, 2). Two sequences b=(-4,-4,6,6),c=(6,0,0,-4) is a possible choice. | import sys
input = sys.stdin.readline
n = int(input())
A = list(map(int, input().split()))
dif = [b - a for a, b in zip([0] + A, A)]
K = sum(d for i, d in enumerate(dif) if i == 0 or d > 0)
print((K + 1) // 2)
def add(x, v):
global K
if x == 0 or dif[x] > 0:
K -= dif[x]
dif[x] += v
if x == 0 or dif[x] > 0:
K += dif[x]
for _ in range(int(input())):
l, r, x = map(int, input().split())
l -= 1
add(l, x)
if r < n: add(r, -x)
print((K + 1) // 2) | {
"input": [
"4\n2 -1 7 3\n2\n2 4 -3\n3 4 2\n",
"6\n-9 -10 -9 -6 -5 4\n3\n2 6 -9\n1 2 -10\n4 6 -3\n",
"1\n0\n2\n1 1 -1\n1 1 -1\n"
],
"output": [
"5\n5\n6\n",
"3\n3\n3\n1\n",
"0\n0\n-1\n"
]
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.