index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
1,900 | 8 | You are given a sequence of n integers a_1, a_2, ..., a_n. Let us call an index j (2 β€ j β€ {{n-1}}) a hill if a_j > a_{{j+1}} and a_j > a_{{j-1}}; and let us call it a valley if a_j < a_{{j+1}} and a_j < a_{{j-1}}.
Let us define the intimidation value of a sequence as the sum of the number of hills and the number of valleys in the sequence. You can change exactly one integer in the sequence to any number that you want, or let the sequence remain unchanged. What is the minimum intimidation value that you can achieve?
Input
The first line of the input contains a single integer t (1 β€ t β€ 10000) β the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 β€ n β€ 3β
10^5).
The second line of each test case contains n space-separated integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 3β
10^5.
Output
For each test case, print a single integer β the minimum intimidation value that you can achieve.
Example
Input
4
3
1 5 3
5
2 2 2 2 2
6
1 6 2 5 2 10
5
1 6 2 5 1
Output
0
0
1
0
Note
In the first test case, changing a_2 to 2 results in no hills and no valleys.
In the second test case, the best answer is just to leave the array as it is.
In the third test case, changing a_3 to 6 results in only one valley (at the index 5).
In the fourth test case, changing a_3 to 6 results in no hills and no valleys. | def f(i, j, k):
return a[i] < a[j] > a[k] or a[i] > a[j] < a[k] if 0 <= i < n and 0 <= j < n and 0 <= k < n else 0
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
m = sum(f(i-1, i, i+1)for i in range(n))
o=0
for i in range(n):
o = min(o, f(i-2,i-1,i-1)+f(i-1,i-1,i+1)+f(i-1,i+1,i+2)-f(i-2,i-1,i)-f(i-1,i,i+1)-f(i,i+1,i+2), f(i-2,i-1,i+1)+f(i-1,i+1,i+1)+f(i+1,i+1,i+2)-f(i-2,i-1,i)-f(i-1,i,i+1)-f(i,i+1,i+2))
print(m+o) | {
"input": [
"4\n3\n1 5 3\n5\n2 2 2 2 2\n6\n1 6 2 5 2 10\n5\n1 6 2 5 1\n"
],
"output": [
"\n0\n0\n1\n0\n"
]
} |
1,901 | 11 | Let F_k denote the k-th term of Fibonacci sequence, defined as below:
* F_0 = F_1 = 1
* for any integer n β₯ 0, F_{n+2} = F_{n+1} + F_n
You are given a tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
We call a tree a Fib-tree, if its number of vertices equals F_k for some k, and at least one of the following conditions holds:
* The tree consists of only 1 vertex;
* You can divide it into two Fib-trees by removing some edge of the tree.
Determine whether the given tree is a Fib-tree or not.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
Then n-1 lines follow, each of which contains two integers u and v (1β€ u,v β€ n, u β v), representing an edge between vertices u and v. It's guaranteed that given edges form a tree.
Output
Print "YES" if the given tree is a Fib-tree, or "NO" otherwise.
You can print your answer in any case. For example, if the answer is "YES", then the output "Yes" or "yeS" will also be considered as correct answer.
Examples
Input
3
1 2
2 3
Output
YES
Input
5
1 2
1 3
1 4
1 5
Output
NO
Input
5
1 3
1 2
4 5
3 4
Output
YES
Note
In the first sample, we can cut the edge (1, 2), and the tree will be split into 2 trees of sizes 1 and 2 correspondently. Any tree of size 2 is a Fib-tree, as it can be split into 2 trees of size 1.
In the second sample, no matter what edge we cut, the tree will be split into 2 trees of sizes 1 and 4. As 4 isn't F_k for any k, it's not Fib-tree.
In the third sample, here is one possible order of cutting the edges so that all the trees in the process are Fib-trees: (1, 3), (1, 2), (4, 5), (3, 4). | import io,os
from collections import deque
def solve(N, edges):
fib = [1, 1]
while fib[-1] < N: fib.append(fib[-2] + fib[-1])
fibToIndex = {x: i for i, x in enumerate(fib)}
if N not in fibToIndex: return "NO"
graph = [[] for i in range(N)]
for u, v in edges:graph[u].append(v);graph[v].append(u)
root = 0; q = [root]; parent = [-1] * N
for u in q:
q += graph[u]
for v in graph[u]: parent[v] = u; graph[v].remove(u)
children = graph; subTreeSize = [-1] * N
for u in q[::-1]: subTreeSize[u] = 1 + sum(subTreeSize[v] for v in children[u])
def isFib(root, numNodes):
if numNodes <= 3: return True
i = fibToIndex[numNodes]; F1 = fib[i - 1]; F2 = fib[i - 2]; q = deque([root])
while q:
u = q.popleft(); count = subTreeSize[u]
if count == F1 or count == F2:
p = parent[u]; parent[u] = -1; children[p].remove(u)
while parent[p] != -1: subTreeSize[p] -= count; p = parent[p]
return isFib(u, count) and isFib(p, numNodes - count)
q += graph[u]
return False
if isFib(root, N): return "YES"
return "NO"
DEBUG = False
if DEBUG:N = 196418;edges = [(i, i + 1) for i in range(N - 1)];print(solve(N, edges));exit()
if __name__ == "__main__":input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline;(N,) = [int(x) for x in input().split()];edges = [[int(x) - 1 for x in input().split()] for i in range(N - 1)];print(solve(N, edges)) | {
"input": [
"3\n1 2\n2 3\n",
"5\n1 3\n1 2\n4 5\n3 4\n",
"5\n1 2\n1 3\n1 4\n1 5\n"
],
"output": [
"\nYES\n",
"\nYES\n",
"\nNO\n"
]
} |
1,902 | 8 | Baby Badawy's first words were "AND 0 SUM BIG", so he decided to solve the following problem. Given two integers n and k, count the number of arrays of length n such that:
* all its elements are integers between 0 and 2^k-1 (inclusive);
* the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of all its elements is 0;
* the sum of its elements is as large as possible.
Since the answer can be very large, print its remainder when divided by 10^9+7.
Input
The first line contains an integer t (1 β€ t β€ 10) β the number of test cases you need to solve.
Each test case consists of a line containing two integers n and k (1 β€ n β€ 10^{5}, 1 β€ k β€ 20).
Output
For each test case, print the number of arrays satisfying the conditions. Since the answer can be very large, print its remainder when divided by 10^9+7.
Example
Input
2
2 2
100000 20
Output
4
226732710
Note
In the first example, the 4 arrays are:
* [3,0],
* [0,3],
* [1,2],
* [2,1]. | def I(): return map(int, input().split())
t, = I()
r = range
for _ in r(t):
n, p = I()
print(pow(n, p) % 1000000007)
| {
"input": [
"2\n2 2\n100000 20\n"
],
"output": [
"\n4\n226732710\n"
]
} |
1,903 | 8 | You are given an array a_1, a_2, ..., a_n consisting of n distinct integers. Count the number of pairs of indices (i, j) such that i < j and a_i β
a_j = i + j.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t cases follow.
The first line of each test case contains one integer n (2 β€ n β€ 10^5) β the length of array a.
The second line of each test case contains n space separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2 β
n) β the array a. It is guaranteed that all elements are distinct.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output the number of pairs of indices (i, j) such that i < j and a_i β
a_j = i + j.
Example
Input
3
2
3 1
3
6 1 5
5
3 1 5 9 2
Output
1
1
3
Note
For the first test case, the only pair that satisfies the constraints is (1, 2), as a_1 β
a_2 = 1 + 2 = 3
For the second test case, the only pair that satisfies the constraints is (2, 3).
For the third test case, the pairs that satisfy the constraints are (1, 2), (1, 5), and (2, 3). | def f(A):
x=0
for i in range(n):
for j in range(A[i]-2-i,n, A[i]):
if i<j:
if (i+j+2 ==A[i]*A[j]) :
x=x+1
return x
t= int(input())
for _ in range(t):
n=int(input())
l=list(map (int,input().split()))
print(f(l)) | {
"input": [
"3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2\n"
],
"output": [
"1\n1\n3\n"
]
} |
1,904 | 7 | Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter β its complexity. The complexity of the i-th chore equals hi.
As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi β€ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).
In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?
Input
The first input line contains three integers n, a and b (2 β€ n β€ 2000; a, b β₯ 1; a + b = n) β the total number of chores, the number of Petya's chores and the number of Vasya's chores.
The next line contains a sequence of integers h1, h2, ..., hn (1 β€ hi β€ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different.
All numbers on the lines are separated by single spaces.
Output
Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.
Examples
Input
5 2 3
6 2 3 100 1
Output
3
Input
7 3 4
1 1 9 1 1 1 1
Output
0
Note
In the first sample the possible values of x are 3, 4 or 5.
In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4. | def inp(): return map(int, input().split())
n,a,b = inp()
h = list(inp())
h.sort()
print(h[b] - h[b-1]) | {
"input": [
"5 2 3\n6 2 3 100 1\n",
"7 3 4\n1 1 9 1 1 1 1\n"
],
"output": [
"3",
"0"
]
} |
1,905 | 8 | Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.
Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (ai) represents the number of meters the guest is going to take up if he sits at the restaurant table.
Long before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than p. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.
Maxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible n! orders of guests in the queue. Help Maxim, calculate this number.
Input
The first line contains integer n (1 β€ n β€ 50) β the number of guests in the restaurant. The next line contains integers a1, a2, ..., an (1 β€ ai β€ 50) β the guests' sizes in meters. The third line contains integer p (1 β€ p β€ 50) β the table's length in meters.
The numbers in the lines are separated by single spaces.
Output
In a single line print a real number β the answer to the problem. The answer will be considered correct, if the absolute or relative error doesn't exceed 10 - 4.
Examples
Input
3
1 2 3
3
Output
1.3333333333
Note
In the first sample the people will come in the following orders:
* (1, 2, 3) β there will be two people in the restaurant;
* (1, 3, 2) β there will be one person in the restaurant;
* (2, 1, 3) β there will be two people in the restaurant;
* (2, 3, 1) β there will be one person in the restaurant;
* (3, 1, 2) β there will be one person in the restaurant;
* (3, 2, 1) β there will be one person in the restaurant.
In total we get (2 + 1 + 2 + 1 + 1 + 1) / 6 = 8 / 6 = 1.(3). | n = input()
n = int(n)
arr = [0] * n
fact = [0] * 51
a = input().split()
p = input()
p = int(p)
for i in range(n):
arr[i] = int(a[i])
if n == 1:
if arr[0] <= p:
print(1)
else:
print(0)
exit(0)
def pre():
fact[0] = 1
for i in range(1, 51):
fact[i] = fact[i - 1] * i
def get(arr, min_sum, max_sum):
ways = [[0 for i in range(max_sum + 1)] for i in range(len(arr) + 1)]
ways[0][0] = 1
for i in range(len(arr)):
for j in range(i, -1, -1):
for k in range(max_sum, -1, -1):
if k + arr[i] <= max_sum:
ways[j + 1][k + arr[i]] += ways[j][k]
ans = 0
counted = 0
for i in range(0, len(arr) + 1):
for j in range(min_sum, max_sum + 1):
ans += fact[i] * fact[n - i - 1] * ways[i][j] * i
counted += fact[i] * fact[n - i - 1] * ways[i][j]
return ans, counted
pre()
tot = 0
count = 0
sm = 0
for i in range(n):
sm += arr[i]
arr1 = [0] * (n - 1)
got = 0
for j in range(n):
if j == i:
continue
arr1[got] = arr[j]
got += 1
how_many = get(arr1, max(0, p - arr[i] + 1), p)
tot += how_many[0]
count += how_many[1]
def get_div(a, b): #a / b
res = a // b
a %= b
for i in range(1, 10):
a = int(a)
a *= 10
x = a // b
x1 = x
res += pow(10, -i) * x1
a -= x * b
return res
if sm <= p:
print(n)
else:
print(get_div(tot, fact[n]))
| {
"input": [
"3\n1 2 3\n3\n"
],
"output": [
"1.3333333333\n"
]
} |
1,906 | 8 | Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.
After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.
Input
The first line contains three integers: n, s, t (1 β€ n β€ 105; 1 β€ s, t β€ n) β the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1, p2, ..., pn (1 β€ pi β€ n) β the shuffling operation parameters. It is guaranteed that all pi's are distinct.
Note that s can equal t.
Output
If the marble can move from position s to position t, then print on a single line a non-negative integer β the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.
Examples
Input
4 2 1
2 3 4 1
Output
3
Input
4 3 3
4 1 3 2
Output
0
Input
4 3 4
1 2 3 4
Output
-1
Input
3 1 3
2 1 3
Output
-1 | def cs(f,l,v):
s=set()
t,c=f,0
while 1:
if t==l:
return c
t=v[t]
if t in s:
return -1
s.add(t)
c+=1
n,f,l=[int (c)-1 for c in input().split()]
v=[int (c)-1 for c in input().split()]
print(cs(f,l,v)) | {
"input": [
"4 3 4\n1 2 3 4\n",
"4 3 3\n4 1 3 2\n",
"4 2 1\n2 3 4 1\n",
"3 1 3\n2 1 3\n"
],
"output": [
"-1\n",
"0\n",
"3\n",
"-1\n"
]
} |
1,907 | 8 | The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that after it the brightest minds will become his subordinates, and the toughest part of conquering the world will be completed.
The final round of the Codeforces World Finals 20YY is scheduled for DD.MM.YY, where DD is the day of the round, MM is the month and YY are the last two digits of the year. Bob is lucky to be the first finalist form Berland. But there is one problem: according to the rules of the competition, all participants must be at least 18 years old at the moment of the finals. Bob was born on BD.BM.BY. This date is recorded in his passport, the copy of which he has already mailed to the organizers. But Bob learned that in different countries the way, in which the dates are written, differs. For example, in the US the month is written first, then the day and finally the year. Bob wonders if it is possible to rearrange the numbers in his date of birth so that he will be at least 18 years old on the day DD.MM.YY. He can always tell that in his motherland dates are written differently. Help him.
According to another strange rule, eligible participant must be born in the same century as the date of the finals. If the day of the finals is participant's 18-th birthday, he is allowed to participate.
As we are considering only the years from 2001 to 2099 for the year of the finals, use the following rule: the year is leap if it's number is divisible by four.
Input
The first line contains the date DD.MM.YY, the second line contains the date BD.BM.BY. It is guaranteed that both dates are correct, and YY and BY are always in [01;99].
It could be that by passport Bob was born after the finals. In this case, he can still change the order of numbers in date.
Output
If it is possible to rearrange the numbers in the date of birth so that Bob will be at least 18 years old on the DD.MM.YY, output YES. In the other case, output NO.
Each number contains exactly two digits and stands for day, month or year in a date. Note that it is permitted to rearrange only numbers, not digits.
Examples
Input
01.01.98
01.01.80
Output
YES
Input
20.10.20
10.02.30
Output
NO
Input
28.02.74
28.02.64
Output
NO | t = tuple(map(int, input().split('.')))
dc = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
def f(d, m, y):
if m not in range(13) or d > dc[m] + (m == 2 and y % 4 == 0):
return False
else:
return t[2] - y > 18 or t[2] - y == 18 and (m, d) <= (t[1], t[0])
a, b, c = map(int, input().split('.'))
print('YES' if any((f(a, b, c), f(a, c, b), f(b, a, c), f(b, c, a), f(c, a, b), f(c, b, a))) else 'NO') | {
"input": [
"20.10.20\n10.02.30\n",
"28.02.74\n28.02.64\n",
"01.01.98\n01.01.80\n"
],
"output": [
"NO\n",
"NO\n",
"YES\n"
]
} |
1,908 | 8 | A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).
Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.
Input
The first line contains a pair of integer numbers n and v (1 β€ n β€ 105; 1 β€ v β€ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 β€ ti β€ 2; 1 β€ pi β€ 104), where ti is the vehicle type (1 β a kayak, 2 β a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.
Output
In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.
Examples
Input
3 2
1 2
2 7
1 3
Output
7
2 | kk=lambda:map(int,input().split())
ll=lambda:list(kk())
def pop(ls):
if not ls: return 0, -1
return ls.pop(-1)
def pop1():
v,i=pop(l1)
v2,i2 = pop(l1)
return v+v2,i,i2
def pop2():
return pop(l2)
n,v = kk()
l1, l2 = [],[]
for i in range(n):
t,k = kk()
if t == 1: l1.append((k,i+1))
else: l2.append((k,i+1))
l1.sort()
l2.sort()
total = 0
printed = []
if v%2:
v1,i11 = pop(l1)
total+=v1
printed.append(i11)
v-=1
v1,i11,i12=pop1()
v2,i2=pop2()
while v > 0 and (v1 > 0 or v2 > 0):
if v1 < v2:
total+=v2
printed.append(i2)
v2,i2 = pop2()
else:
total+= v1
printed.extend([i11,i12])
v1,i11,i12 = pop1()
v-=2
print(total)
print(" ".join([str(p) for p in printed if p != -1]))
| {
"input": [
"3 2\n1 2\n2 7\n1 3\n"
],
"output": [
"7\n2\n"
]
} |
1,909 | 9 | Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of n playing cards. Let's describe the house they want to make:
1. The house consists of some non-zero number of floors.
2. Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card.
3. Each floor besides for the lowest one should contain less rooms than the floor below.
Please note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more.
While bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of n cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using exactly n cards.
Input
The single line contains integer n (1 β€ n β€ 1012) β the number of cards.
Output
Print the number of distinct heights that the houses made of exactly n cards can have.
Examples
Input
13
Output
1
Input
6
Output
0
Note
In the first sample you can build only these two houses (remember, you must use all the cards):
<image>
Thus, 13 cards are enough only for two floor houses, so the answer is 1.
The six cards in the second sample are not enough to build any house. | import sys
n = int(sys.stdin.readline())
def sum (n):
return ((n+1)*n)//2
a=1
res = 0
while (3*sum(a-1) +2*a <= n):
if (n-2*a)% 3 == 0 :
res += 1
a+=1
print (res) | {
"input": [
"13\n",
"6\n"
],
"output": [
"1\n",
"0\n"
]
} |
1,910 | 10 | Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k β₯ 1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a1, a2, ..., ak and b1, b2, ..., bk satisfying the following requirements:
* k β₯ 1
* <image>
* <image>
* <image>
* <image> t is a substring of string saisai + 1... sbi (string s is considered as 1-indexed).
As the number of ways can be rather large print it modulo 109 + 7.
Input
Input consists of two lines containing strings s and t (1 β€ |s|, |t| β€ 105). Each string consists of lowercase Latin letters.
Output
Print the answer in a single line.
Examples
Input
ababa
aba
Output
5
Input
welcometoroundtwohundredandeightytwo
d
Output
274201
Input
ddd
d
Output
12 | def main():
s, t = input(), input()
n, m = len(s), len(t)
t = '$'.join((t, s))
p = [0]
k = 0
for i in range(1, n + m + 1):
while k and t[k] != t[i]:
k = p[k - 1]
if t[k] == t[i]:
k += 1
p.append(k)
ans = [0] * n
sums = [0] * (n + 1)
curs = 0
was = False
j = 0
MOD = 1000000007
for i in range(n):
if p[i + m + 1] == m:
if not was:
was = True
curs = 1
while j <= i - m:
curs = (curs + sums[j] + 1) % MOD
j += 1
ans[i] = curs
sums[i] = (sums[i - 1] + ans[i]) % MOD
print(sum(ans) % MOD)
if __name__ == '__main__':
main()
| {
"input": [
"ababa\naba\n",
"ddd\nd\n",
"welcometoroundtwohundredandeightytwo\nd\n"
],
"output": [
"5\n",
"12\n",
"274201\n"
]
} |
1,911 | 8 | In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.
A string is a bHTML table, if it satisfies the grammar:
TABLE ::= <table>ROWS</table>
ROWS ::= ROW | ROW ROWS
ROW ::= <tr>CELLS</tr>
CELLS ::= CELL | CELL CELLS
CELL ::= <td></td> | <td>TABLE</td>
Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.
As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.
Input
For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.
Output
Print the sizes of all the tables in the non-decreasing order.
Examples
Input
<table><tr><td></td></tr></table>
Output
1
Input
<table>
<tr>
<td>
<table><tr><td></td></tr><tr><td></
td
></tr><tr
><td></td></tr><tr><td></td></tr></table>
</td>
</tr>
</table>
Output
1 4
Input
<table><tr><td>
<table><tr><td>
<table><tr><td>
<table><tr><td></td><td></td>
</tr><tr><td></td></tr></table>
</td></tr></table>
</td></tr></table>
</td></tr></table>
Output
1 1 1 3 | import sys
R=str.replace
s=R(R(R(R(R(''.join(sys.stdin.readlines()),'\n',''),'</tr>',''),'<tr>',''),'><',' '),'>','').split()[1:]
def f(k):
r=0;a=[]
while s[0]!='/table':
if s[0]=='table':
s.pop(0);a+=f(k+1)
else:r+=s[0]=='td';s.pop(0)
s.pop(0)
return[r]+a
print(' '.join(map(str,sorted(f(1))))) | {
"input": [
"<table><tr><td></td></tr></table>\n",
"<table>\n<tr>\n<td>\n<table><tr><td></td></tr><tr><td></\ntd\n></tr><tr\n><td></td></tr><tr><td></td></tr></table>\n</td>\n</tr>\n</table>\n",
"<table><tr><td>\n<table><tr><td>\n<table><tr><td>\n<table><tr><td></td><td></td>\n</tr><tr><td></td></tr></table>\n</td></tr></table>\n</td></tr></table>\n</td></tr></table>\n"
],
"output": [
"\n",
"\n",
"\n"
]
} |
1,912 | 9 | Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins.
You have to calculate how many fights will happen and who will win the game, or state that game won't end.
Input
First line contains a single integer n (2 β€ n β€ 10), the number of cards.
Second line contains integer k1 (1 β€ k1 β€ n - 1), the number of the first soldier's cards. Then follow k1 integers that are the values on the first soldier's cards, from top to bottom of his stack.
Third line contains integer k2 (k1 + k2 = n), the number of the second soldier's cards. Then follow k2 integers that are the values on the second soldier's cards, from top to bottom of his stack.
All card values are different.
Output
If somebody wins in this game, print 2 integers where the first one stands for the number of fights before end of game and the second one is 1 or 2 showing which player has won.
If the game won't end and will continue forever output - 1.
Examples
Input
4
2 1 3
2 4 2
Output
6 2
Input
3
1 2
2 1 3
Output
-1
Note
First sample:
<image>
Second sample:
<image> |
def main():
n = int(input())
a = list(map(int, input().split()))[1:]
b = list(map(int, input().split()))[1:]
st = set()
st.add((tuple(a), tuple(b)))
t = 0
while len(a) and len(b):
t += 1
if a[0] > b[0]:
a.extend([b[0], a[0]])
else:
b.extend([a[0], b[0]])
a.pop(0)
b.pop(0)
if (tuple(a), tuple(b)) in st:
print(-1)
return 0
st.add((tuple(a), tuple(b)))
print(t, 1 + (len(a) == 0))
if __name__ == '__main__':
main()
| {
"input": [
"4\n2 1 3\n2 4 2\n",
"3\n1 2\n2 1 3\n"
],
"output": [
"6 2\n",
"-1\n"
]
} |
1,913 | 9 | Edo has got a collection of n refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.
Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.
Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of ββthe door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.
Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x1, y1) and the upper right corner (x2, y2), then its center is located at (<image>, <image>) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.
The sides of the refrigerator door must also be parallel to coordinate axes.
Input
The first line contains two integers n and k (1 β€ n β€ 100 000, 0 β€ k β€ min(10, n - 1)) β the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator.
Next n lines describe the initial plan of placing magnets. Each line contains four integers x1, y1, x2, y2 (1 β€ x1 < x2 β€ 109, 1 β€ y1 < y2 β€ 109) β the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide.
Output
Print a single integer β the minimum area of the door of refrigerator, which can be used to place at least n - k magnets, preserving the relative positions.
Examples
Input
3 1
1 1 2 2
2 2 3 3
3 3 4 4
Output
1
Input
4 1
1 1 2 2
1 9 2 10
9 9 10 10
9 1 10 2
Output
64
Input
3 0
1 1 2 2
1 1 1000000000 1000000000
1 3 8 12
Output
249999999000000001
Note
In the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly.
In the second test sample it doesn't matter which magnet to remove, the answer will not change β we need a fridge with door width 8 and door height 8.
In the third sample you cannot remove anything as k = 0. | from sys import*
#
def check(u, d, l, r):
used = [pointsx[i][1] for i in range(l)]
used += [pointsx[-1 - i][1] for i in range(r)]
used += [pointsy[i][1] for i in range(u)]
used += [pointsy[-1 - i][1] for i in range(d)]
if len(set(used)) > k:
return DOHERA
dx = pointsx[-1 - r][0] - pointsx[l][0]
dy = pointsy[-1 - d][0] - pointsy[u][0]
dx += dx & 1
dy += dy & 1
dx = max(2, dx)
dy = max(2, dy)
return dx * dy
#
(n, k) = map(int, input().split())
pointsx = []
pointsy = []
DOHERA = 10 ** 228
for i in range(n):
a = list(map(int, input().split()))
pointsx += [(a[0] + a[2], i)]
pointsy += [(a[1] + a[3], i)]
(pointsx, pointsy) = (sorted(pointsx), sorted(pointsy))
ans = DOHERA
for u in range(0, k + 1):
for d in range(0, k + 1):
for l in range(0, k + 1):
for r in range(0, k + 1):
if l + r <= k and u + d <= k:
ans = min(ans, check(u, d, l, r))
print(ans // 4)
# Made By Mostafa_Khaled | {
"input": [
"4 1\n1 1 2 2\n1 9 2 10\n9 9 10 10\n9 1 10 2\n",
"3 1\n1 1 2 2\n2 2 3 3\n3 3 4 4\n",
"3 0\n1 1 2 2\n1 1 1000000000 1000000000\n1 3 8 12\n"
],
"output": [
"64\n",
"1\n",
"249999999000000001\n"
]
} |
1,914 | 7 | You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.
The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.
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. Don't use the function input() in Python2 instead of it use the function raw_input().
Input
The first line contains a non-negative integer a.
The second line contains a non-negative integer b.
The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.
Output
Print the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".
Examples
Input
9
10
Output
<
Input
11
10
Output
>
Input
00012345
12345
Output
=
Input
0123
9
Output
>
Input
0123
111
Output
> | def main():
a=input().lstrip('0')
b=input().lstrip('0')
if(len(a)!=len(b)):
print('<' if len(a)<len(b) else '>')
else:
print('>' if a>b else ('<' if a<b else '='))
if __name__=='__main__':
main() | {
"input": [
"11\n10\n",
"9\n10\n",
"0123\n9\n",
"0123\n111\n",
"00012345\n12345\n"
],
"output": [
">\n",
"<\n",
">\n",
">\n",
"=\n"
]
} |
1,915 | 8 | A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle β a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.
The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.
Determine if it is possible for the islanders to arrange the statues in the desired order.
Input
The first line contains a single integer n (2 β€ n β€ 200 000) β the total number of islands.
The second line contains n space-separated integers ai (0 β€ ai β€ n - 1) β the statue currently placed on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct.
The third line contains n space-separated integers bi (0 β€ bi β€ n - 1) β the desired statues of the ith island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.
Output
Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.
Examples
Input
3
1 0 2
2 0 1
Output
YES
Input
2
1 0
0 1
Output
YES
Input
4
1 2 3 0
0 3 2 1
Output
NO
Note
In the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.
In the second sample, the islanders can simply move statue 1 from island 1 to island 2.
In the third sample, no sequence of movements results in the desired position. | #!/usr/bin/python3
def main():
number_islands = int(input())
current_order = tuple(map(int, input().split()))
desired_order = tuple(map(int, input().split()))
print("YES" if rotation_of(current_order, desired_order) else "NO")
def rotation_of(seq1, seq2):
if len(seq1) != len(seq2):
return False
elif len(seq1) == 0:
return True
seq1 = list(seq1)
seq2 = list(seq2)
seq1.remove(0)
seq2.remove(0)
seq1 = ''.join((str(_) for _ in seq1))
seq2 = ''.join((str(_) for _ in seq2))
return seq2 in (seq1 + seq1)
if __name__ == '__main__':
main()
| {
"input": [
"3\n1 0 2\n2 0 1\n",
"4\n1 2 3 0\n0 3 2 1\n",
"2\n1 0\n0 1\n"
],
"output": [
"YES",
"NO",
"YES"
]
} |
1,916 | 7 | Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm.
Formally, find the biggest integer d, such that all integers a, a + 1, a + 2, ..., b are divisible by d. To make the problem even more complicated we allow a and b to be up to googol, 10100 β such number do not fit even in 64-bit integer type!
Input
The only line of the input contains two integers a and b (1 β€ a β€ b β€ 10100).
Output
Output one integer β greatest common divisor of all integers from a to b inclusive.
Examples
Input
1 2
Output
1
Input
61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576
Output
61803398874989484820458683436563811772030917980576 | def gcd(a,b):
if a==b:
print(str(a))
else:
print(1)
a,b = map(int,input().split(" "))
gcd(a,b) | {
"input": [
"61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576\n",
"1 2\n"
],
"output": [
"61803398874989484820458683436563811772030917980576\n",
"1\n"
]
} |
1,917 | 10 | Today Pari and Arya are playing a game called Remainders.
Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value <image> for any positive integer x?
Note, that <image> means the remainder of x after dividing it by y.
Input
The first line of the input contains two integers n and k (1 β€ n, k β€ 1 000 000) β the number of ancient integers and value k that is chosen by Pari.
The second line contains n integers c1, c2, ..., cn (1 β€ ci β€ 1 000 000).
Output
Print "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.
Examples
Input
4 5
2 3 5 12
Output
Yes
Input
2 7
2 3
Output
No
Note
In the first sample, Arya can understand <image> because 5 is one of the ancient numbers.
In the second sample, Arya can't be sure what <image> is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7. | #prime factorize the k
import math
a=input().split(' ')
n=int(a[0])
k=int(a[1])
t=True
def gcd(a, b):
if b==0: return a
else: return gcd(b, a%b)
C=set(map(int, input().split()))
Composite=False
a=math.floor(math.sqrt(k+1))
if k%2==0: Composite=True
else:
for i in range(3, a+1, 2):
if k%i==0:
Composite=True
break
if not Composite:
if k>max(C):print ('NO')
else:
A=set()
z=True
for i in C:
if i in A: pass
if i%k==0:
z=False
print ('YES')
break
else: A.add(i)
if z: print('NO')
else:
A=set()
m=1
for i in C:
if i in A: pass
else:
A.add(i)
m*=i/gcd(m,i)
m%=k
if m==0:
t=False
print('YES')
break
if t: print('NO')
| {
"input": [
"4 5\n2 3 5 12\n",
"2 7\n2 3\n"
],
"output": [
"Yes",
"No"
]
} |
1,918 | 9 | Find an n Γ n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
Input
The only line contains odd integer n (1 β€ n β€ 49).
Output
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.
Examples
Input
1
Output
1
Input
3
Output
2 1 4
3 5 7
6 9 8 | def m(n):
for r in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
(n * ((r + col - 1 + n // 2) % n) +
((r + 2 * col - 2) % n) + 1
for col in range(1, n + 1))))
n=int(input())
m(n) | {
"input": [
"1\n",
"3\n"
],
"output": [
"1\n",
"2 1 4\n3 5 7\n6 9 8\n"
]
} |
1,919 | 9 | Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes.
Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days β the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.
When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint β one for each of k colors.
Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.
The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.
Input
The first line of input contains three integers n, m and k (2 β€ n β€ 200 000, 0 β€ m β€ 200 000, 1 β€ k β€ 200 000) β the number of socks, the number of days and the number of available colors respectively.
The second line contain n integers c1, c2, ..., cn (1 β€ ci β€ k) β current colors of Arseniy's socks.
Each of the following m lines contains two integers li and ri (1 β€ li, ri β€ n, li β ri) β indices of socks which Arseniy should wear during the i-th day.
Output
Print one integer β the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.
Examples
Input
3 2 3
1 2 3
1 2
2 3
Output
2
Input
3 2 2
1 1 2
1 2
2 1
Output
0
Note
In the first sample, Arseniy can repaint the first and the third socks to the second color.
In the second sample, there is no need to change any colors. | from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
from bisect import bisect_left
def dfs(x):
stack=[x]
d={}
while stack:
x=stack.pop()
if x in visited:
continue
if c[x] in d:
d[c[x]]+=1
else:
d[c[x]]=1
visited.add(x)
for i in graph[x]:
if i not in visited:
stack.append(i)
z=0
ma=0
for i in d:
z+=d[i]
ma=max(ma,d[i])
return z-ma
n,m,k=map(int,input().split())
c=list(map(int,input().split()))
graph={i:set() for i in range(n)}
for i in range(m):
a,b=map(int,input().split())
graph[a-1].add(b-1)
graph[b-1].add(a-1)
count=0
visited=set()
for i in range(n):
if i not in visited:
count+=dfs(i)
print(count) | {
"input": [
"3 2 3\n1 2 3\n1 2\n2 3\n",
"3 2 2\n1 1 2\n1 2\n2 1\n"
],
"output": [
"2",
"0"
]
} |
1,920 | 11 | PolandBall has an undirected simple graph consisting of n vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red.
Colorfulness of the graph is a value min(dr, dw), where dr is the diameter of the red subgraph and dw is the diameter of white subgraph. The diameter of a graph is a largest value d such that shortest path between some pair of vertices in it is equal to d. If the graph is not connected, we consider its diameter to be -1.
PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to k. Can you help him and find any graph which satisfies PolandBall's requests?
Input
The only one input line contains two integers n and k (2 β€ n β€ 1000, 1 β€ k β€ 1000), representing graph's size and sought colorfulness.
Output
If it's impossible to find a suitable graph, print -1.
Otherwise, you can output any graph which fulfills PolandBall's requirements. First, output m β the number of red edges in your graph. Then, you should output m lines, each containing two integers ai and bi, (1 β€ ai, bi β€ n, ai β bi) which means that there is an undirected red edge between vertices ai and bi. Every red edge should be printed exactly once, you can print the edges and the vertices of every edge in arbitrary order.
Remember that PolandBall's graph should remain simple, so no loops or multiple edges are allowed.
Examples
Input
4 1
Output
-1
Input
5 2
Output
4
1 2
2 3
3 4
4 5
Note
In the first sample case, no graph can fulfill PolandBall's requirements.
In the second sample case, red graph is a path from 1 to 5. Its diameter is 4. However, white graph has diameter 2, because it consists of edges 1-3, 1-4, 1-5, 2-4, 2-5, 3-5. |
def PolandBall():
# entrada
n, k = map(int, input().split())
# condiciones que no cumplen con los requisitos
if n < 4 or k > 3 or k == 1 or (k == 2 and n == 4):
print('-1')
return
if k == 2 or n==4:
print(n-1)
for i in range(1, n):
print(str(i)+' '+str(i+1))
return
# si k=3 y n>4
print(n)
print('1 2')
print('2 3')
print('3 5')
for i in range(4, n+1):
print('1 '+str(i))
PolandBall()
# Casos de prueba:
# 4 1 ##respuesta -1
# 5 2 ##respuesta 4
# 2 1 ##respuesta -1
# 2 3 ##respuesta -1
# 3 3 ##respuesta -1
# 4 2 ##respuesta -1
# 7 2 ##respuesta 6
# 100 2 ##respuesta 99
# 500 2 ##respuesta 499
# 1000 2 ##respuesta 999
# 4 3 ##respuesta 3
# 7 3 ##respuesta 7
# 100 3 ##respuesta 100
# 500 3 ##respuesta 500
# 1000 3 ##respuesta 1000
# 1000 1000 ##respuesta -1
#cualkier otro caso del generados del codeforce va a funcionar xq el problema dio accepted | {
"input": [
"4 1\n",
"5 2\n"
],
"output": [
"-1\n",
"4\n1 2\n2 3\n3 4\n4 5\n"
]
} |
1,921 | 8 | You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1 and the i-th character of s2.
For example, f("ab", "ba") = "aa", and f("nzwzl", "zizez") = "niwel".
You found two strings x and y of the same length and consisting of only lowercase English letters. Find any string z such that f(x, z) = y, or print -1 if no such string z exists.
Input
The first line of input contains the string x.
The second line of input contains the string y.
Both x and y consist only of lowercase English letters, x and y have same length and this length is between 1 and 100.
Output
If there is no string z such that f(x, z) = y, print -1.
Otherwise, print a string z such that f(x, z) = y. If there are multiple possible answers, print any of them. The string z should be the same length as x and y and consist only of lowercase English letters.
Examples
Input
ab
aa
Output
ba
Input
nzwzl
niwel
Output
xiyez
Input
ab
ba
Output
-1
Note
The first case is from the statement.
Another solution for the second case is "zizez"
There is no solution for the third case. That is, there is no z such that f("ab", z) = "ba". | def check(a,b):
w=''
for i in range(len(a)):
if a[i]<b[i]:
return -1
return b
a=input()
b=input()
print(check(a,b))
| {
"input": [
"ab\naa\n",
"ab\nba\n",
"nzwzl\nniwel\n"
],
"output": [
"aa\n",
"-1\n",
"niwel\n"
]
} |
1,922 | 12 | You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.
Input
The first line contains two integers n and k (2 β€ n β€ 105, 2 β€ k β€ min (n, 20)) β the length of the array and the number of segments you need to split the array into.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β the elements of the array.
Output
Print single integer: the minimum possible total cost of resulting subsegments.
Examples
Input
7 3
1 1 3 3 3 2 1
Output
1
Input
10 2
1 2 1 2 1 2 1 2 1 2
Output
8
Input
13 3
1 2 2 2 1 2 1 1 1 2 2 1 1
Output
9
Note
In the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.
In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.
In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1. | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = [0]+list(map(int, input().split()))
buc = [0]*(n+1)
dp_p = [n*(n-1)//2]*(n+1)
dp_c = [0]*(n+1)
dp_p[0] = 0
buc[a[1]] = 1
L = R = 1
ans = 0
def cal(l, r):
global L, R, ans
while L < l:
ans += 1-buc[a[L]]
buc[a[L]] -= 1
L += 1
while L > l:
L -= 1
ans += buc[a[L]]
buc[a[L]] += 1
while R < r:
R += 1
ans += buc[a[R]]
buc[a[R]] += 1
while R > r:
ans += 1-buc[a[R]]
buc[a[R]] -= 1
R -= 1
def solve(lb, rb, l, r):
global ans, L
if lb > rb or l > r:
return
mid = (l+r)//2
d = 0
res = 9223372036854775807
cal(lb, mid)
for i in range(lb, rb+1):
ans += 1-buc[a[L]]
buc[a[L]] -= 1
L += 1
if res > dp_p[i]+ans:
res = dp_p[i]+ans
d = i
dp_c[mid] = res
solve(lb, d, l, mid-1)
solve(d, rb, mid+1, r)
for cur in range(1, m+1):
solve(0, n-1, 1, n)
dp_p, dp_c = dp_c, dp_p
print(dp_p[n])
| {
"input": [
"10 2\n1 2 1 2 1 2 1 2 1 2\n",
"13 3\n1 2 2 2 1 2 1 1 1 2 2 1 1\n",
"7 3\n1 1 3 3 3 2 1\n"
],
"output": [
"8",
"9",
"1"
]
} |
1,923 | 9 | In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.
When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 β€ i β€ j β€ n and put it into a set S. gcd here means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
Note that even if a number is put into the set S twice or more, it only appears once in the set.
Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.
Input
The first line contains a single integer m (1 β€ m β€ 1000) β the size of the set S.
The second line contains m integers s1, s2, ..., sm (1 β€ si β€ 106) β the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.
Output
If there is no solution, print a single line containing -1.
Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000.
In the second line print n integers a1, a2, ..., an (1 β€ ai β€ 106) β the sequence.
We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106.
If there are multiple solutions, print any of them.
Examples
Input
4
2 4 6 12
Output
3
4 6 12
Input
2
2 3
Output
-1
Note
In the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 β€ i β€ j β€ n. | def gcd(a,b):
if a%b==0:
return b
return gcd(b,a%b)
n=int(input())
a=[int(i) for i in input().split()]
s=a[0]
for i in a:
s=gcd(s,i)
if s==a[0]:
print(3*n)
for i in a:
print(s,i,s,end=' ')
else:
print(-1)
| {
"input": [
"4\n2 4 6 12\n",
"2\n2 3\n"
],
"output": [
"8\n2 2 4 2 6 2 12 2\n",
"-1\n"
]
} |
1,924 | 8 | There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.
Also, each minute Vasya's bank account receives CΒ·k, where k is the amount of received but unread messages.
Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.
Determine the maximum amount of money Vasya's bank account can hold after T minutes.
Input
The first line contains five integers n, A, B, C and T (1 β€ n, A, B, C, T β€ 1000).
The second string contains n integers ti (1 β€ ti β€ T).
Output
Output one integer β the answer to the problem.
Examples
Input
4 5 5 3 5
1 5 5 4
Output
20
Input
5 3 1 1 3
2 2 2 1 1
Output
15
Input
5 5 3 4 5
1 2 3 4 5
Output
35
Note
In the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, nΒ·A = 20 in total.
In the second sample the messages can be read at any integer moment.
In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4Β·3) + (5 - 3Β·3) + (5 - 2Β·3) + (5 - 1Β·3) + 5 = - 5 points. This is 35 in total. | def main():
n, A, B, C, T = map(int, input().split())
res = (n * T - sum(map(int, input().split()))) * (C - B) if C > B else 0
print(res + A * n)
if __name__ == "__main__":
main()
| {
"input": [
"4 5 5 3 5\n1 5 5 4\n",
"5 3 1 1 3\n2 2 2 1 1\n",
"5 5 3 4 5\n1 2 3 4 5\n"
],
"output": [
"20\n",
"15\n",
"35\n"
]
} |
1,925 | 9 | After passing a test, Vasya got himself a box of n candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya chooses a single integer k, same for all days. After that, in the morning he eats k candies from the box (if there are less than k candies in the box, he eats them all), then in the evening Petya eats 10\% of the candies remaining in the box. If there are still candies left in the box, the process repeats β next day Vasya eats k candies again, and Petya β 10\% of the candies left in a box, and so on.
If the amount of candies in the box is not divisible by 10, Petya rounds the amount he takes from the box down. For example, if there were 97 candies in the box, Petya would eat only 9 of them. In particular, if there are less than 10 candies in a box, Petya won't eat any at all.
Your task is to find out the minimal amount of k that can be chosen by Vasya so that he would eat at least half of the n candies he initially got. Note that the number k must be integer.
Input
The first line contains a single integer n (1 β€ n β€ 10^{18}) β the initial amount of candies in the box.
Output
Output a single integer β the minimal amount of k that would allow Vasya to eat at least half of candies he got.
Example
Input
68
Output
3
Note
In the sample, the amount of candies, with k=3, would change in the following way (Vasya eats first):
68 β 65 β 59 β 56 β 51 β 48 β 44 β 41 \\\ β 37 β 34 β 31 β 28 β 26 β 23 β 21 β 18 β 17 β 14 \\\ β 13 β 10 β 9 β 6 β 6 β 3 β 3 β 0.
In total, Vasya would eat 39 candies, while Petya β 29. | n=int(input())
def f(k):
s=m=n
while s>0and m:
l=min(k,m);s-=2*l;m-=l;m-=m//10
return s<=0
l=[0,n]
while l[1]-l[0]>1:
m=sum(l)//2;l[f(m)]=m
print(l[1]) | {
"input": [
"68\n"
],
"output": [
"3\n"
]
} |
1,926 | 7 | On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home. | #n=int(input())
n,m=map(int,input().split())
vert=[]
for i in range(n):
v=int(input())
vert.append(v)
horz=[]
for i in range(m):
x1,x2,y=map(int,input().split())
if x1==1:
horz.append(x2)
vert.sort()
horz.sort()
vert.append(1000000000)
def next(k,a,x):
while k<len(a) and a[k]<x:
k+=1
return k
num=next(0,horz,vert[0])
ans=len(horz)-num
for i in range(1,len(vert)):
num2=next(num,horz,vert[i])
t=i+len(horz)-num2
if t<ans: ans=t
num=num2
print(ans)
| {
"input": [
"0 0\n",
"2 3\n4\n6\n1 4 3\n1 5 2\n1 6 5\n",
"2 3\n6\n8\n1 5 6\n1 9 4\n2 4 2\n",
"0 2\n1 1000000000 4\n1 1000000000 2\n",
"1 3\n4\n1 5 3\n1 9 4\n4 6 6\n"
],
"output": [
"0",
"2",
"1",
"2",
"1"
]
} |
1,927 | 12 | Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move:
* (1, 0);
* (0, 1);
* (-1, 0);
* (0, -1).
There are also n distinct key points at this plane. The i-th point is p_i = (x_i, y_i). It is guaranteed that 0 β€ x_i and 0 β€ y_i and there is no key point (0, 0).
Let the first level points be such points that max(x_i, y_i) = 1, the second level points be such points that max(x_i, y_i) = 2 and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level i + 1 if he does not visit all the points of level i. He starts visiting the points from the minimum level of point from the given set.
The distance between two points (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2| where |v| is the absolute value of v.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of key points.
Each of the next n lines contains two integers x_i, y_i (0 β€ x_i, y_i β€ 10^9) β x-coordinate of the key point p_i and y-coordinate of the key point p_i. It is guaranteed that all the points are distinct and the point (0, 0) is not in this set.
Output
Print one integer β the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
Examples
Input
8
2 2
1 4
2 3
3 1
3 4
1 1
4 3
1 2
Output
15
Input
5
2 1
1 0
2 0
3 2
0 3
Output
9
Note
The picture corresponding to the first example: <image>
There is one of the possible answers of length 15.
The picture corresponding to the second example: <image>
There is one of the possible answers of length 9. | n = int(input())
f = [0] * (n + 1)
p = [(0, 0, 0)] * (n + 1)
for i in range(1, n + 1):
x, y = map(int, input().split())
p[i] = (x, y, max(x, y))
p.sort(key=lambda x : (x[2], x[0] - x[1]))
def dis(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
lasi = lasj = 0
i = 1
while i <= n:
j = i
while j < n and p[j + 1][2] == p[i][2]:
j += 1
for k in {i, j}:
f[i ^ j ^ k] = dis(p[i], p[j]) + min(f[l] + dis(p[l], p[k]) for l in {lasi, lasj})
lasi, lasj = i, j
i = j + 1
print(min(f[lasi], f[lasj])) | {
"input": [
"5\n2 1\n1 0\n2 0\n3 2\n0 3\n",
"8\n2 2\n1 4\n2 3\n3 1\n3 4\n1 1\n4 3\n1 2\n"
],
"output": [
"9\n",
"15\n"
]
} |
1,928 | 10 | You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β colors of lamps in the garland).
You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.
A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.
In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i β t_{i + 1} should be satisfied.
Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of lamps.
The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' β colors of lamps in the garland.
Output
In the first line of the output print one integer r β the minimum number of recolors needed to obtain a diverse garland from the given one.
In the second line of the output print one string t of length n β a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG | X = {"R","G","B"}
def comp(a,b):
x = {a,b}
t = list(X^x)
return t[0]
N = int(input())
S = [i for i in input()]
if(N == 1):
print(0)
print("".join(S))
exit()
count = 0
for i in range(N-2):
if(S[i] == S[i+1]):
S[i+1] = comp(S[i],S[i+2])
count+=1
if(S[-1] == S[-2]):
count+=1
S[-1] = comp(S[-2],S[-2])
print(count)
print("".join(S))
| {
"input": [
"8\nBBBGBRRR\n",
"9\nRBGRRBRGG\n",
"13\nBBRRRRGGGGGRR\n"
],
"output": [
"2\nBRBGBRGR",
"2\nRBGRGBRGR",
"6\nBGRGRBGRGRGRG"
]
} |
1,929 | 8 | You are given a string, consisting of lowercase Latin letters.
A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) β "ab" and (2, 3) β "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.
Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
You also have to answer T separate queries.
Input
The first line contains a single integer T (1 β€ T β€ 100) β the number of queries.
Each of the next T lines contains string s (1 β€ |s| β€ 100) β the string for the next query. It is guaranteed that it contains only lowercase Latin letters.
Note that in hacks you have to set T = 1.
Output
Print T lines. The i-th line should contain the answer to the i-th query.
If the answer for the i-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.
If there are multiple answers, print any of them.
Otherwise print "No answer" for that query.
Example
Input
4
abcd
gg
codeforces
abaca
Output
cadb
gg
codfoerces
No answer
Note
In the first example answer "bdac" is also correct.
The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.
There are lots of valid answers for the third example. | def check(s):
return all(ord(s[i])!=ord(s[i-1])+1 and ord(s[i])!=ord(s[i-1])-1 for i in range(1,len(s)))
for _ in range(int(input())):
s=input()
n=len(s)
s=sorted(s)
s1=''
s2=''
for i in s:
if (ord(i)-97)&1:
s1+=i
else:
s2+=i
if check(s1+s2):
print(s1+s2)
elif check(s2+s1):
print(s2+s1)
else:
print('No answer') | {
"input": [
"4\nabcd\ngg\ncodeforces\nabaca\n"
],
"output": [
"bdac\ngg\ncceeoosdfr\nNo answer\n"
]
} |
1,930 | 11 | Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?
The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides.
Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Input
The input consists of a single string s (2 β€ |s| β€ 10^6). The string s consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
Output
Output a palindrome t that is a subsequence of s and |t| β₯ β (|s|)/(2) β.
If there are multiple solutions, you may print any of them. You don't have to maximise the length of t.
If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
Examples
Input
cacbac
Output
aba
Input
abc
Output
a
Input
cbacacacbcbababacbcb
Output
cbaaacbcaaabc
Note
In the first example, other valid answers include "cacac", "caac", "aca" and "ccc". | def gns():
return list(map(int,input().split()))
s=input()
l=len(s)
i,j=0,l-1
ans=[]
t=l//4
for i in range(t):
x=i*2
y=l-2-i*2
if s[x]==s[y] or s[x]==s[y+1]:
ans.append(s[x])
else:
ans.append(s[x+1])
if l%4>=2:
ans=ans+[s[l//2]]+ans[::-1]
else:
ans=ans+ans[::-1]
ans=''.join(ans)
print(ans) | {
"input": [
"cbacacacbcbababacbcb\n",
"abc\n",
"cacbac\n"
],
"output": [
"cbaaacbcaaabc",
"a\n",
"cacac"
]
} |
1,931 | 10 | The only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string "RGBRGBRGB ...".
A string a is a substring of string b if there exists a positive integer i such that a_1 = b_i, a_2 = b_{i + 1}, a_3 = b_{i + 2}, ..., a_{|a|} = b_{i + |a| - 1}. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer q independent queries.
Input
The first line of the input contains one integer q (1 β€ q β€ 2 β
10^5) β the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters 'R', 'G' and 'B'.
It is guaranteed that the sum of n over all queries does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each query print one integer β the minimum number of characters you need to change in the initial string s so that after changing there will be a substring of length k in s that is also a substring of the infinite string "RGBRGBRGB ...".
Example
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Output
1
0
3
Note
In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".
In the second example, the substring is "BRG". | import sys
input = sys.stdin.readline
q = int(input())
aux = 'RGB'
def fun(k,s,ini):
tam = 0
ans = int(1e20)
change = 0
i = 0
j = 0
while len(s) > i:
while len(s) > i and k > tam:
change += (1 if aux[(ini+i)%3] != s[i] else 0)
tam += 1
i += 1
if tam == k:
ans = min(ans,change)
change -= (1 if s[j] != aux[(ini+j)%3] else 0)
j += 1
tam -= 1
return ans
for _ in range(q):
n,k = map(int,input().split(' '))
s = input()
print(min(fun(k,s,0),min(fun(k,s,1),fun(k,s,2))))
| {
"input": [
"3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR\n"
],
"output": [
"1\n0\n3\n"
]
} |
1,932 | 12 | Authors have come up with the string s consisting of n lowercase Latin letters.
You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.
For all i from 1 to n-1 the following properties hold: s[p_i] β€ s[p_{i + 1}] and s[q_i] β€ s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.
Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.
If there are multiple answers, you can print any of them.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 2 β
10^5, 1 β€ k β€ 26) β the length of the string and the number of distinct characters required.
The second line of the input contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, all p_i are distinct integers from 1 to n) β the permutation p.
The third line of the input contains n integers q_1, q_2, ..., q_n (1 β€ q_i β€ n, all q_i are distinct integers from 1 to n) β the permutation q.
Output
If it is impossible to find the suitable string, print "NO" on the first line.
Otherwise print "YES" on the first line and string s on the second line. It should consist of n lowercase Latin letters, contain at least k distinct characters and suit the given permutations.
If there are multiple answers, you can print any of them.
Example
Input
3 2
1 2 3
1 3 2
Output
YES
abb | def main():
n, m = map(int, input().split())
abc = list('zyxwvutsrqponmlkjihgfedcba'[26 - m:])
res = [abc[0]] * (n + 1)
res[0], pool, f = 'YES\n', [False] * (n + 1), 0
for p, q in zip(map(int, input().split()),
map(int, input().split())):
if pool[p]:
f -= 1
else:
pool[p] = True
f += 1
if pool[q]:
f -= 1
else:
pool[q] = True
f += 1
res[p] = abc[-1]
if not f:
del abc[-1]
if not abc:
break
print('NO' if abc else ''.join(res))
if __name__ == '__main__':
main()
| {
"input": [
"3 2\n1 2 3\n1 3 2\n"
],
"output": [
"YES\nabb\n"
]
} |
1,933 | 8 | Consider a tunnel on a one-way road. During a particular day, n cars numbered from 1 to n entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.
A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.
Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.
Traffic regulations prohibit overtaking inside the tunnel. If car i overtakes any other car j inside the tunnel, car i must be fined. However, each car can be fined at most once.
Formally, let's say that car i definitely overtook car j if car i entered the tunnel later than car j and exited the tunnel earlier than car j. Then, car i must be fined if and only if it definitely overtook at least one other car.
Find the number of cars that must be fined.
Input
The first line contains a single integer n (2 β€ n β€ 10^5), denoting the number of cars.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), denoting the ids of cars in order of entering the tunnel. All a_i are pairwise distinct.
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ n), denoting the ids of cars in order of exiting the tunnel. All b_i are pairwise distinct.
Output
Output the number of cars to be fined.
Examples
Input
5
3 5 2 1 4
4 3 2 5 1
Output
2
Input
7
5 2 3 6 7 1 4
2 3 6 7 1 4 5
Output
6
Input
2
1 2
1 2
Output
0
Note
The first example is depicted below:
<image>
Car 2 definitely overtook car 5, while car 4 definitely overtook cars 1, 2, 3 and 5. Cars 2 and 4 must be fined.
In the second example car 5 was definitely overtaken by all other cars.
In the third example no car must be fined. | import sys
def I():
return sys.stdin.readline().strip()
n = int(I())
a = list(map(int, I().split()))
a.reverse()
b = list(map(int, I().split()))
b.reverse()
c = 0
v = [ False for _ in range( 100005 ) ]
while len(b):
out = b.pop()
if a[ -1 ] != out:
c += 1
v[ out ] = True
while len(a) > 0 and v[ a[ -1 ] ]:
a.pop()
print( c )
| {
"input": [
"2\n1 2\n1 2\n",
"7\n5 2 3 6 7 1 4\n2 3 6 7 1 4 5\n",
"5\n3 5 2 1 4\n4 3 2 5 1\n"
],
"output": [
"0\n",
"6\n",
"2\n"
]
} |
1,934 | 7 | Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume.
There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrease the current volume by 1, 2, or 5. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than 0.
As Bob is so angry, he wants to change the volume to b using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given a and b, finds the minimum number of presses to change the TV volume from a to b.
Input
Each test contains multiple test cases. The first line contains the number of test cases T (1 β€ T β€ 1 000). Then the descriptions of the test cases follow.
Each test case consists of one line containing two integers a and b (0 β€ a, b β€ 10^{9}) β the current volume and Bob's desired volume, respectively.
Output
For each test case, output a single integer β the minimum number of presses to change the TV volume from a to b. If Bob does not need to change the volume (i.e. a=b), then print 0.
Example
Input
3
4 0
5 14
3 9
Output
2
3
2
Note
In the first example, Bob can press the -2 button twice to reach 0. Note that Bob can not press -5 when the volume is 4 since it will make the volume negative.
In the second example, one of the optimal ways for Bob is to press the +5 twice, then press -1 once.
In the last example, Bob can press the +5 once, then press +1. | def I(): return map(int, input().split())
for _ in range(int(input())):
a, b = sorted(I())
print(((b-a)//5)+((b-a-(((b-a)//5*5)))//2)+((b-a-(((b-a)//5*5))) % 2))
| {
"input": [
"3\n4 0\n5 14\n3 9\n"
],
"output": [
"2\n3\n2\n"
]
} |
1,935 | 12 | Consider the following experiment. You have a deck of m cards, and exactly one card is a joker. n times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.
Let x be the number of times you have taken the joker out of the deck during this experiment. Assuming that every time you shuffle the deck, all m! possible permutations of cards are equiprobable, what is the expected value of x^k? Print the answer modulo 998244353.
Input
The only line contains three integers n, m and k (1 β€ n, m < 998244353, 1 β€ k β€ 5000).
Output
Print one integer β the expected value of x^k, taken modulo 998244353 (the answer can always be represented as an irreducible fraction a/b, where b mod 998244353 β 0; you have to print a β
b^{-1} mod 998244353).
Examples
Input
1 1 1
Output
1
Input
1 1 5000
Output
1
Input
2 2 2
Output
499122178
Input
998244352 1337 5000
Output
326459680 | def inv(a):
return pow(a, MOD-2, MOD) %MOD
def fat(a):
ans = 1
for i in range(1, a+1):
ans = (ans*i)%MOD
return ans
MOD = 998244353
n, m, k = map(int, input().split())
p = inv(m)
# O(Burro) O(n2)-> FΓ³rmula da experanΓ§a = sum(x^k * C(n, x) * p^x * q^(n-x))
'''
resp = 0
q = (1 - p + MOD) % MOD
for x in range(1, n+1):
resp += pow(x, k, MOD) %MOD * fat(n) %MOD * invfat(n-x) %MOD * invfat(x) %MOD *pow(p, x, MOD) %MOD * pow(q, n-x, MOD) %MOD
'''
# O(menos burro) O(nlog(k)) -> atualiza somatΓ³rio usando valores ja calculados
if n<=k:
q = (1 - p + MOD) % MOD
inv_q = inv(q)
p_aux = p
q_aux = pow(q, n-1, MOD)
fn = n
resp = n * p%MOD * q_aux%MOD
resp = resp%MOD
for i in range(2, n+1):
x = pow(i, k, MOD)
p_aux = p_aux * p %MOD
q_aux = q_aux * inv_q
fn = fn*(n-i+1)%MOD*inv(i)%MOD
resp = resp + x * fn %MOD * p_aux %MOD * q_aux %MOD
resp = resp%MOD
print(resp)
# O(inteligente) O(k2) -> A partir da FGM M(X), identifica padrΓ£o das derivadas
# k-Γ©sima derivada de M(X) = E(x^k)
# E(x^k) = n!/(n-k)! * p^k + k*(deriv[k-1] - sum(ind[i]*deriv[i])) + sum(ind[i]*deriv[i+1])
else:
deriv = [(n*p)%MOD] #E(x) = np
resp = n*n%MOD*p%MOD*p%MOD - n*p%MOD*p%MOD + n*p%MOD #E(x^2) = n^2p^2 - np^2 + np
deriv.append(resp%MOD)
fn = (n*(n-1))%MOD
v=[1];
for i in range(3, k+1):
fn = (fn * (n-i+1) %MOD)%MOD
w = [(-(i-1)*v[0])%MOD]
for j in range(len(v)-1):
w.append((v[j] - (i-1)*v[j+1]%MOD)%MOD)
w.append((v[-1] + i-1)%MOD)
v = tuple(w)
resp = (fn * pow(p, i, MOD))%MOD
for j in range(len(v)):
resp = (resp + v[j]*deriv[j]%MOD)%MOD
resp = resp%MOD
resp %= MOD
deriv.append(resp)
print(deriv[k-1])
| {
"input": [
"998244352 1337 5000\n",
"1 1 1\n",
"1 1 5000\n",
"2 2 2\n"
],
"output": [
"326459680\n",
"1\n",
"1\n",
"499122178\n"
]
} |
1,936 | 9 | There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.
You can perform the following operation: choose some subsegment [l, r] (1β€ l β€ r β€ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1}, ..., a_r by \frac{a_l + a_{l+1} + ... + a_r}{r-l+1}. For example, if for volumes [1, 3, 6, 7] you choose l = 2, r = 3, new volumes of water will be [1, 4.5, 4.5, 7]. You can perform this operation any number of times.
What is the lexicographically smallest sequence of volumes of water that you can achieve?
As a reminder:
A sequence a is lexicographically smaller than a sequence b of the same length if and only if the following holds: in the first (leftmost) position where a and b differ, the sequence a has a smaller element than the corresponding element in b.
Input
The first line contains an integer n (1 β€ n β€ 10^6) β the number of water tanks.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6) β initial volumes of water in the water tanks, in liters.
Because of large input, reading input as doubles is not recommended.
Output
Print the lexicographically smallest sequence you can get. In the i-th line print the final volume of water in the i-th tank.
Your answer is considered correct if the absolute or relative error of each a_i does not exceed 10^{-9}.
Formally, let your answer be a_1, a_2, ..., a_n, and the jury's answer be b_1, b_2, ..., b_n. Your answer is accepted if and only if \frac{|a_i - b_i|}{max{(1, |b_i|)}} β€ 10^{-9} for each i.
Examples
Input
4
7 5 5 7
Output
5.666666667
5.666666667
5.666666667
7.000000000
Input
5
7 8 8 10 12
Output
7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
Input
10
3 9 5 5 1 7 5 3 8 7
Output
3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
Note
In the first sample, you can get the sequence by applying the operation for subsegment [1, 3].
In the second sample, you can't get any lexicographically smaller sequence. | def main():
from sys import stdin,stdout
ans = []
stdin.readline()
for ai in map(int, map(int, stdin.readline().split())):
cnt=1
while ans and ai*ans[-1][0]<=ans[-1][1]*cnt:
c, r = ans.pop()
ai+=r
cnt+=c
ans.append((cnt, ai))
for i, res in ans:
m = str(res/i)
stdout.write((m+"\n")*i)
main()
| {
"input": [
"4\n7 5 5 7\n",
"5\n7 8 8 10 12\n",
"10\n3 9 5 5 1 7 5 3 8 7\n"
],
"output": [
"5.666666666666667\n5.666666666666667\n5.666666666666667\n7\n",
"7\n8\n8\n10\n12\n",
"3\n5.0\n5.0\n5.0\n5.0\n5.0\n5.0\n5.0\n7.5\n7.5\n"
]
} |
1,937 | 7 | A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^6) β the length of Dima's sequence.
The second line contains string of length n, consisting of characters "(" and ")" only.
Output
Print a single integer β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
Examples
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
Note
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds. | def brackets():
num = int(input())
risultato = 0
brackets = input()
c = 0
for i in brackets:
if i == ")":
c -= 1
if c < 0:
risultato += 2
elif i == "(":
c += 1
if c != 0:
print(-1)
else:
print(risultato)
brackets() | {
"input": [
"3\n(()\n",
"8\n))((())(\n"
],
"output": [
"-1\n",
"6"
]
} |
1,938 | 8 | Koa the Koala and her best friend want to play a game.
The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts.
Let's describe a move in the game:
* During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player.
More formally: if the current score of the player is x and the chosen element is y, his new score will be x β y. Here β denotes [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Note that after a move element y is removed from a.
* The game ends when the array is empty.
At the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw.
If both players play optimally find out whether Koa will win, lose or draw the game.
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 10^4) β the number of test cases. Description of the test cases follows.
The first line of each test case contains the integer n (1 β€ n β€ 10^5) β the length of a.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β elements of a.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case print:
* WIN if Koa will win the game.
* LOSE if Koa will lose the game.
* DRAW if the game ends in a draw.
Examples
Input
3
3
1 2 2
3
2 2 3
5
0 0 0 2 2
Output
WIN
LOSE
DRAW
Input
4
5
4 1 5 1 3
4
1 0 1 6
1
0
2
5 4
Output
WIN
WIN
DRAW
WIN
Note
In testcase 1 of the first sample we have:
a = [1, 2, 2]. Here Koa chooses 1, other player has to choose 2, Koa chooses another 2. Score for Koa is 1 β 2 = 3 and score for other player is 2 so Koa wins. | import sys
def input():
return sys.stdin.buffer.readline()[:-1]
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
for i in range(29, -1, -1):
one, zero = 0, 0
for x in a:
if (x >> i) & 1:
one += 1
else:
zero += 1
if one%2 == 0:
continue
else:
if one%4 == 3 and zero%2 == 0:
print("LOSE")
else:
print("WIN")
break
else:
print("DRAW") | {
"input": [
"3\n3\n1 2 2\n3\n2 2 3\n5\n0 0 0 2 2\n",
"4\n5\n4 1 5 1 3\n4\n1 0 1 6\n1\n0\n2\n5 4\n"
],
"output": [
"WIN\nLOSE\nDRAW\n",
"WIN\nWIN\nDRAW\nWIN\n"
]
} |
1,939 | 8 | Alice and Bob are playing a fun game of tree tag.
The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges.
Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.
If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.
Determine the winner if both players play optimally.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^4). Description of the test cases follows.
The first line of each test case contains five integers n,a,b,da,db (2β€ nβ€ 10^5, 1β€ a,bβ€ n, aβ b, 1β€ da,dbβ€ n-1) β the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively.
The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1β€ u, vβ€ n, uβ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output a single line containing the winner of the game: "Alice" or "Bob".
Example
Input
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
Output
Alice
Bob
Alice
Alice
Note
In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move.
<image>
In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice.
<image> | from collections import deque
def dist(G, n, s):
D = [None] * n;Q = deque();Q.append(s);D[s] = 0
while Q:
f = Q.popleft()
for t in G[f]:
if D[t] is None:D[t] = D[f] + 1;Q.append(t)
return D
for ti in range(int(input())):
n, a, b, da, db = map(int, input().split());a -= 1;b -= 1;G = [[] for _ in range(n)]
for _ in range(n-1):u, v = map(int, input().split());G[u-1].append(v-1);G[v-1].append(u-1)
Da = dist(G, n, a);me = max(enumerate(Da), key=lambda x: x[1])[0]
print("Alice") if Da[b] <= da or db <= 2 * da or max(dist(G, n, me)) <= 2 * da else print("Bob") | {
"input": [
"4\n4 3 2 1 2\n1 2\n1 3\n1 4\n6 6 1 2 5\n1 2\n6 5\n2 3\n3 4\n4 5\n9 3 9 2 5\n1 2\n1 6\n1 9\n1 3\n9 5\n7 9\n4 8\n4 3\n11 8 11 3 3\n1 2\n11 9\n4 9\n6 5\n2 10\n3 2\n5 9\n8 3\n7 4\n7 10\n"
],
"output": [
"Alice\nBob\nAlice\nAlice\n"
]
} |
1,940 | 11 | For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | import math
n = int(input())
A = list(map(int, input().split()))
A.sort()
def dfs(A):
if len(A) == 1: return 1
k = 1 << int(math.log2(A[0] ^ A[-1]))
for i, a in enumerate(A):
if a & k:
break
return 1 + max(dfs(A[:i]), dfs(A[i:]))
print(n - dfs(A)) | {
"input": [
"5\n0 1 5 2 6\n",
"7\n6 9 8 7 3 5 2\n"
],
"output": [
"1\n",
"2\n"
]
} |
1,941 | 11 | Polycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.
Each friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i Γ w_i (if they are standing) or w_i Γ h_i (if they are lying on the side).
The j-th friend can be placed in front of the i-th friend on the photo if his rectangle is lower and narrower than the rectangle of the i-th friend. Formally, at least one of the following conditions must be fulfilled:
* h_j < h_i and w_j < w_i (both friends are standing or both are lying);
* w_j < h_i and h_j < w_i (one of the friends is standing and the other is lying).
For example, if n = 3, h=[3,5,3] and w=[4,4,3], then:
* the first friend can be placed in front of the second: w_1 < h_2 and h_1 < w_2 (one of the them is standing and the other one is lying);
* the third friend can be placed in front of the second: h_3 < h_2 and w_3 < w_2 (both friends are standing or both are lying).
In other cases, the person in the foreground will overlap the person in the background.
Help Polycarp for each i find any j, such that the j-th friend can be located in front of the i-th friend (i.e. at least one of the conditions above is fulfilled).
Please note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend i any other friend j who can be located in front of him. Think about it as you need to solve n separate independent subproblems.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of friends.
This is followed by n lines, each of which contains a description of the corresponding friend. Each friend is described by two integers h_i and w_i (1 β€ h_i, w_i β€ 10^9) β height and width of the i-th friend, respectively.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case output n integers on a separate line, where the i-th number is the index of a friend that can be placed in front of the i-th. If there is no such friend, then output -1.
If there are several answers, output any.
Example
Input
4
3
3 4
5 4
3 3
3
1 3
2 2
3 1
4
2 2
3 1
6 3
5 4
4
2 2
2 3
1 1
4 4
Output
-1 3 -1
-1 -1 -1
-1 -1 2 2
3 3 -1 3
Note
The first test case is described in the statement.
In the third test case, the following answers are also correct:
* [-1, -1, 1, 2];
* [-1, -1, 1, 1];
* [-1, -1, 2, 1]. | import sys
def correctPlacement(n, fren):
fren.sort()
# print(fren)
ans = ['-1']*n
# print(fren)
# print(ans)
j = 0
k = -1
for i in range(n):
while fren[j][0] != fren[i][0]:
if k == -1 or fren[j][1] < fren[k][1]:
k = j
j += 1
if k != -1 and fren[k][1] < fren[i][1]:
ans[fren[i][2]-1] = str(fren[k][2])
print(' '.join(ans))
def main():
for t in range(int(input())):
n = int(input())
fren = []
for i in range(1, n+1):
h, w = map(int, input().split())
if h > w: fren.append([h, w, i])
else: fren.append([w, h, i])
correctPlacement(n, fren)
if __name__ == "__main__":
main() | {
"input": [
"4\n3\n3 4\n5 4\n3 3\n3\n1 3\n2 2\n3 1\n4\n2 2\n3 1\n6 3\n5 4\n4\n2 2\n2 3\n1 1\n4 4\n"
],
"output": [
"\n-1 3 -1 \n-1 -1 -1 \n-1 -1 2 2 \n3 3 -1 3 \n"
]
} |
1,942 | 11 | You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length n, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.
For example, if n=6 and the level is described by the string "**.*..", then the following game scenario is possible:
* the sheep at the 4 position moves to the right, the state of the level: "**..*.";
* the sheep at the 2 position moves to the right, the state of the level: "*.*.*.";
* the sheep at the 1 position moves to the right, the state of the level: ".**.*.";
* the sheep at the 3 position moves to the right, the state of the level: ".*.**.";
* the sheep at the 2 position moves to the right, the state of the level: "..***.";
* the sheep are lined up and the game ends.
For a given level, determine the minimum number of moves you need to make to complete the level.
Input
The first line contains one integer t (1 β€ t β€ 10^4). Then t test cases follow.
The first line of each test case contains one integer n (1 β€ n β€ 10^6).
The second line of each test case contains a string of length n, consisting of the characters '.' (empty space) and '*' (sheep) β the description of the level.
It is guaranteed that the sum of n over all test cases does not exceed 10^6.
Output
For each test case output the minimum number of moves you need to make to complete the level.
Example
Input
5
6
**.*..
5
*****
3
.*.
3
...
10
*.*...*.**
Output
1
0
0
0
9 | def answer():
last=[0]*(n+1)
c1,c2,d=0,0,0
for i in range(n-1,-1,-1):
if(s[i]=='*'):c1+=1
else:d+=c1
last[i]=d
ans=1e15
c1,c2,d=0,0,0
for i in range(n):
if(s[i]=='*'):c1+=1
else:d+=c1
ans=min(ans,d+last[i+1])
return ans
for T in range(int(input())):
n=int(input())
s=input()
print(answer())
| {
"input": [
"5\n6\n**.*..\n5\n*****\n3\n.*.\n3\n...\n10\n*.*...*.**\n"
],
"output": [
"\n1\n0\n0\n0\n9\n"
]
} |
1,943 | 7 | To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.
The system has n planets in total. On each of them Qwerty can buy or sell items of m types (such as food, medicine, weapons, alcohol, and so on). For each planet i and each type of items j Qwerty knows the following:
* aij β the cost of buying an item;
* bij β the cost of selling an item;
* cij β the number of remaining items.
It is not allowed to buy more than cij items of type j on planet i, but it is allowed to sell any number of items of any kind.
Knowing that the hold of Qwerty's ship has room for no more than k items, determine the maximum profit which Qwerty can get.
Input
The first line contains three space-separated integers n, m and k (2 β€ n β€ 10, 1 β€ m, k β€ 100) β the number of planets, the number of question types and the capacity of Qwerty's ship hold, correspondingly.
Then follow n blocks describing each planet.
The first line of the i-th block has the planet's name as a string with length from 1 to 10 Latin letters. The first letter of the name is uppercase, the rest are lowercase. Then in the i-th block follow m lines, the j-th of them contains three integers aij, bij and cij (1 β€ bij < aij β€ 1000, 0 β€ cij β€ 100) β the numbers that describe money operations with the j-th item on the i-th planet. The numbers in the lines are separated by spaces.
It is guaranteed that the names of all planets are different.
Output
Print a single number β the maximum profit Qwerty can get.
Examples
Input
3 3 10
Venus
6 5 3
7 6 5
8 6 10
Earth
10 9 0
8 6 4
10 9 3
Mars
4 3 0
8 4 12
7 2 5
Output
16
Note
In the first test case you should fly to planet Venus, take a loan on 74 units of money and buy three items of the first type and 7 items of the third type (3Β·6 + 7Β·8 = 74). Then the ranger should fly to planet Earth and sell there all the items he has bought. He gets 3Β·9 + 7Β·9 = 90 units of money for the items, he should give 74 of them for the loan. The resulting profit equals 16 units of money. We cannot get more profit in this case. | I=lambda:map(int,input().split())
R=range
n,m,k=I()
def r(a,b,c=k):
q=0
for a,b in sorted((b[i][1]-a[i][0],a[i][2])for i in R(m))[::-1]:
if a<1or c<1:break
q+=a*min(b,c);c-=b
return q
w=[]
for _ in '0'*n:I();w+=[[list(I())for _ in '0'*m]]
print(max(r(w[i],w[j])for i in R(n)for j in R(n))) | {
"input": [
"3 3 10\nVenus\n6 5 3\n7 6 5\n8 6 10\nEarth\n10 9 0\n8 6 4\n10 9 3\nMars\n4 3 0\n8 4 12\n7 2 5\n"
],
"output": [
"16\n"
]
} |
1,944 | 9 | Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?
Input
The first input line contains integer n (1 β€ n β€ 105) β amount of squares in the stripe. The second line contains n space-separated numbers β they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.
Output
Output the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.
Examples
Input
4
1 2 3 3
Output
1
Input
5
1 2 3 4 5
Output
0 | #! /usr/bin/python3
def solve():
n = int(input())
a = []
total = 0
for i in input().strip().split():
a.append(int(i))
for i in range(0, n):
total = total + a[i]
if (total % 3 != 0 or n < 3):
print(0)
return
part = total // 3
c = [0] * 100005
right = part * 2
right_sum = [0] * 100005
i = n - 1
while (i >= 0):
right_sum[i] = right_sum[i + 1] + a[i]
if right_sum[i] == part:
c[i] = c[i + 1] + 1
else:
c[i] = c[i + 1]
i = i - 1
ret = 0
s = 0
for i in range(0, n - 1):
s = s + a[i]
if (s == part):
ret = ret + c[i + 1]
if (part == 0):
ret = ret - 1
#print("ret = ", ret)
print(ret)
solve() | {
"input": [
"5\n1 2 3 4 5\n",
"4\n1 2 3 3\n"
],
"output": [
"0\n",
"1\n"
]
} |
1,945 | 9 | Learn, learn and learn again β Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of n numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by - 1. The second operation is to take some suffix and multiply all numbers in it by - 1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?
Input
The first line contains integer n (1 β€ n β€ 105) β amount of elements in the sequence. The second line contains n integers ai ( - 104 β€ ai β€ 104) β the sequence itself.
Output
The first and the only line of the output should contain the answer to the problem.
Examples
Input
3
-1 -2 -3
Output
6
Input
5
-4 2 0 5 0
Output
11
Input
5
-1 10 -5 10 -2
Output
18 | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def main():
n = int(input())
a = list(map(int,input().split()))
dp = [0 if a[-1]>0 else a[-1]]
dp1 = [0 if a[-1]<0 else a[-1]]
xx = a[-1]
for i in range(n-2,0,-1):
xx += a[i]
dp.append(min(dp[-1],xx))
dp1.append(max(dp1[-1],xx))
dp.reverse()
dp1.reverse()
tot = sum(a)
ans = abs(tot)
x = 0
for i in range(n-1):
x += a[i]
ans = max(ans,tot+abs(x)-x+max(abs(dp[i])-dp[i],abs(dp1[i])-dp1[i]))
print(ans)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main() | {
"input": [
"5\n-4 2 0 5 0\n",
"3\n-1 -2 -3\n",
"5\n-1 10 -5 10 -2\n"
],
"output": [
"11\n",
"6\n",
"18\n"
]
} |
1,946 | 8 | One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.
The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 β€ i β€ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 β€ pi β€ i.
In order not to get lost, Vasya decided to act as follows.
* Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.
* Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal.
Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.
Input
The first line contains integer n (1 β€ n β€ 103) β the number of rooms. The second line contains n integers pi (1 β€ pi β€ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.
Output
Print a single number β the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
2
1 2
Output
4
Input
4
1 1 2 3
Output
20
Input
5
1 1 1 1 1
Output
62 | #!/usr/bin/env python3
n = int(input())
jmp = list(map(lambda x: x - 1, map(int, input().split())))
cache = { }
def DP(i,j):
if (i,j) not in cache:
if i == j:
cache[i,j] = 0
elif i + 1 == j:
cache[i,j] = DP(jmp[i], i) + 2
else:
cache[i,j] = sum(DP(k, k+1) for k in range(i,j))
return cache[i,j]
print(DP(0, n) % (10**9 + 7))
| {
"input": [
"4\n1 1 2 3\n",
"5\n1 1 1 1 1\n",
"2\n1 2\n"
],
"output": [
"20\n",
"62\n",
"4\n"
]
} |
1,947 | 9 | Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.
Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.
Input
The first line contains a single positive integer n (1 β€ n β€ 5000) β the number of exams Valera will take.
Each of the next n lines contains two positive space-separated integers ai and bi (1 β€ bi < ai β€ 109) β the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.
Output
Print a single integer β the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.
Examples
Input
3
5 2
3 1
4 2
Output
2
Input
3
6 1
5 2
4 3
Output
6
Note
In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.
In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. | C = 0
def main():
n = int(input())
a = 0
for b, c in sorted(tuple(map(int, input().split())) for _ in range(n)):
a = b if a > c else c
print(a)
if __name__ == '__main__':
main() | {
"input": [
"3\n5 2\n3 1\n4 2\n",
"3\n6 1\n5 2\n4 3\n"
],
"output": [
"2\n",
"6\n"
]
} |
1,948 | 9 | Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | def main():
n, l, ones, j = int(input()), [], [], 0
for i in range(n):
degree, s = map(int, input().split())
l.append((degree, s))
j += degree
if degree == 1:
ones.append(i)
print(j // 2)
while ones:
i = ones.pop()
degree, j = l[i]
if degree == 1:
print(i, j)
degree, s = l[j]
s ^= i
degree -= 1
l[j] = degree, s
if degree == 1:
ones.append(j)
if __name__ == '__main__':
main()
| {
"input": [
"2\n1 1\n1 0\n",
"3\n2 3\n1 0\n1 0\n"
],
"output": [
"1\n0 1\n",
"2\n1 0\n2 0\n"
]
} |
1,949 | 7 | One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm Γ b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
<image>
After making a paper ship from the square piece, Vasya looked on the remaining (a - b) mm Γ b mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
Input
The first line of the input contains two integers a, b (1 β€ b < a β€ 1012) β the sizes of the original sheet of paper.
Output
Print a single integer β the number of ships that Vasya will make.
Examples
Input
2 1
Output
2
Input
10 7
Output
6
Input
1000000000000 1
Output
1000000000000
Note
Pictures to the first and second sample test.
<image> | def c(a,b):
return a and b and b//a+c(b%a,a)
a,b=[int(x) for x in input().split()]
print(c(a,b)) | {
"input": [
"2 1\n",
"10 7\n",
"1000000000000 1\n"
],
"output": [
"2\n",
"6\n",
"1000000000000\n"
]
} |
1,950 | 10 | Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.
Input
The first line contains integer n (1 β€ n β€ 2000) β the number of the points painted on the plane.
Next n lines contain two integers each xi, yi ( - 100 β€ xi, yi β€ 100) β the coordinates of the i-th point. It is guaranteed that no two given points coincide.
Output
In the first line print an integer β the number of triangles with the non-zero area among the painted points.
Examples
Input
4
0 0
1 1
2 0
2 2
Output
3
Input
3
0 0
1 1
2 0
Output
1
Input
1
1 1
Output
0
Note
Note to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).
Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).
Note to the third sample test. A single point doesn't form a single triangle. | from fractions import *
n=int(input())
s=n*(n-1)*(n-2)//6
p=[tuple(map(int,input().split())) for _ in range(n)]
def f(a,b):g=gcd(a,b);return a//g+((b//g)<<20)
for i in range(n):
k,(x,y)=0,p[i]
l=sorted(f(x-X,y-Y) for X,Y in p[:i])
for j in range(1, i):
k=k+1 if l[j]==l[j-1] else 0
s-=k
print(s)
| {
"input": [
"4\n0 0\n1 1\n2 0\n2 2\n",
"1\n1 1\n",
"3\n0 0\n1 1\n2 0\n"
],
"output": [
"3\n",
"0",
"1"
]
} |
1,951 | 10 | You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR.
Find the maximum possible value of <image> after performing at most k operations optimally.
Input
The first line contains three integers n, k and x (1 β€ n β€ 200 000, 1 β€ k β€ 10, 2 β€ x β€ 8).
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 109).
Output
Output the maximum value of a bitwise OR of sequence elements after performing operations.
Examples
Input
3 1 2
1 1 1
Output
3
Input
4 2 3
1 2 4 8
Output
79
Note
For the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is <image>.
For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result. | import sys
#sys.stdin = open("input.txt")
#sys.stdout = open("output.txt", "w")
n, k, x = (int(x) for x in input().split())
l = [int(x) for x in input().split()]
pref = [0] * n
suff = [0] * n
pref[0] = l[0]
for i in range(1, n):
pref[i] = pref[i - 1] | l[i]
suff[n - 1] = l[n - 1]
for i in range(n - 2, -1, -1):
suff[i] = suff[i + 1] | l[i]
def get_pref(index):
if (index < 0):
return 0
else:
return pref[index]
def get_suff(index):
if (index >= n):
return 0
else:
return suff[index]
power = x ** k
ans = 0
for i in range(n):
contender = get_pref(i - 1) | (l[i] * power) | get_suff(i + 1)
if (contender > ans):
ans = contender
print(ans)
| {
"input": [
"3 1 2\n1 1 1\n",
"4 2 3\n1 2 4 8\n"
],
"output": [
" 3\n",
" 79\n"
]
} |
1,952 | 9 | A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 β€ |s| β€ 2Β·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Examples
Input
aabc
Output
abba
Input
aabcd
Output
abcba | d=[0]*26
s = input()
n = len(s)%2
def num2chr(x):
return chr(x+97)
for c in s:
try:
d[ord(c)-97] +=1
except Exception as e:
print(c, ord(c)-97, ord("a"))
print(e)
#print(d)
i=0
j=25
while i < j:
if d[i] % 2 == 0:
i=i+1
continue
if d[j] % 2 == 0:
j=j-1
continue
d[i] += 1
d[j] -= 1
center = ""
if d[i]%2 == 1:
d[i] = d[i] - 1
center=chr(i+97)
ans=[0]*(sum(d)//2)
i=0
j=0
while j<26:
#print(i,j,d)
if d[j]<2:
j=j+1
continue
ans[i]=97+j
d[j]=d[j]-2
i=i+1
#print(ans)
s="".join(list(map(chr, ans)))
print(s+center+s[::-1]) | {
"input": [
"aabcd\n",
"aabc\n"
],
"output": [
"abcba\n",
"abba\n"
]
} |
1,953 | 8 | In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.
When a query appears server may react in three possible ways:
1. If server is free and query queue is empty, then server immediately starts to process this query.
2. If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue.
3. If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed.
As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.
For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.
Input
The first line of the input contains two integers n and b (1 β€ n, b β€ 200 000) β the number of queries and the maximum possible size of the query queue.
Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di (1 β€ ti, di β€ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.
Output
Print the sequence of n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or - 1 if the corresponding query will be rejected.
Examples
Input
5 1
2 9
4 8
10 9
15 2
19 1
Output
11 19 -1 21 22
Input
4 1
2 8
4 8
10 9
15 2
Output
10 18 27 -1
Note
Consider the first sample.
1. The server will start to process first query at the moment 2 and will finish to process it at the moment 11.
2. At the moment 4 second query appears and proceeds to the queue.
3. At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected.
4. At the moment 11 server will finish to process first query and will take the second query from the queue.
5. At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue.
6. At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there.
7. Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue.
8. Server finishes to process query number 5 at the moment 22. | n,b=map(int,input().split())
def Q():
a=[0];l=0
for i in range(n):
t,d=map(int,input().split())
a+=[t+d if t>a[-1] else a[-1]+d]
while a[l]<=t: l+=1
if len(a)-l-1>b: a.pop(); yield "-1"
else: yield str(a[-1])
print(' '.join(Q())) | {
"input": [
"4 1\n2 8\n4 8\n10 9\n15 2\n",
"5 1\n2 9\n4 8\n10 9\n15 2\n19 1\n"
],
"output": [
"10 18 27 -1\n",
"11 19 -1 21 22\n"
]
} |
1,954 | 8 | We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.
After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.
Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 500 000, 0 β€ k β€ 109) β the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.
The second line contains n integers, the i-th of them is ci (1 β€ ci β€ 109) β initial wealth of the i-th person.
Output
Print a single line containing the difference between richest and poorest peoples wealth.
Examples
Input
4 1
1 1 4 2
Output
2
Input
3 1
2 2 2
Output
0
Note
Lets look at how wealth changes through day in the first sample.
1. [1, 1, 4, 2]
2. [2, 1, 3, 2] or [1, 2, 3, 2]
So the answer is 3 - 1 = 2
In second sample wealth will remain the same for each person. | def main():
n, k = map(int, input().split())
l = sorted(map(int, input().split()))
lo, hi = l[0], l[-1]
while lo < hi - 1:
mid = (lo + hi) // 2
t = k
for x in l:
if x > mid:
lo = mid
break
t -= mid - x
if t < 0:
hi = mid
break
else:
lo = mid
m1 = lo
lo, hi = l[0], l[-1]
l.reverse()
while lo < hi - 1:
mid = (lo + hi) // 2
t = k
for x in l:
if x < mid:
hi = mid
break
t -= x - mid
if t < 0:
lo = mid
break
else:
hi = mid
print(hi - m1 if hi > m1 else 1 if sum(l) % n else 0)
if __name__ == '__main__':
main()
| {
"input": [
"4 1\n1 1 4 2\n",
"3 1\n2 2 2\n"
],
"output": [
"2\n",
"0\n"
]
} |
1,955 | 8 | Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | #!/usr/bin/env python3
import sys
import threading
from bisect import *
def ri():
return map(int, input().split())
def dfs(v, d, c, w):
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i, d, c, w)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1 + add[d]
ans[v] = str(add[d])
d -= 1
n = int(input())
dist = [0] * (2*10**5+3)
add = [0] * (2*10**5+3)
ans = [''] * (n+1)
a = [0] * (n+1)
def solve():
c = [[] for i in range(n+1)]
w = [0] * (n+1)
for i, j in enumerate(ri()):
a[i+1] = j
for i in range(2, n+1):
t1, t2 = ri()
c[t1].append(i)
w[i] = t2
dfs(1, 0, c, w)
print(' '.join(ans))
sys.setrecursionlimit(10**5*3 + 100)
threading.stack_size(10**8 + 10**7)
thread = threading.Thread(target=solve)
thread.start()
| {
"input": [
"5\n9 7 8 6 5\n1 1\n2 1\n3 1\n4 1\n",
"5\n2 5 1 4 6\n1 7\n1 1\n3 5\n3 6\n"
],
"output": [
"4 3 2 1 0 ",
"1 0 1 0 0 "
]
} |
1,956 | 7 | You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist.
Divisor of n is any such natural number, that n can be divided by it without remainder.
Input
The first line contains two integers n and k (1 β€ n β€ 1015, 1 β€ k β€ 109).
Output
If n has less than k divisors, output -1.
Otherwise, output the k-th smallest divisor of n.
Examples
Input
4 2
Output
2
Input
5 3
Output
-1
Input
12 5
Output
6
Note
In the first example, number 4 has three divisors: 1, 2 and 4. The second one is 2.
In the second example, number 5 has only two divisors: 1 and 5. The third divisor doesn't exist, so the answer is -1. | def r():
return list(map(int, input().split()))
n, k = r()
l = []
for i in range(1, int(n ** (1 / 2)) + 1):
if n % i == 0:
l.append(i)
if i * i != n:
l.append(n // i)
if k > len(l):
print(-1)
exit()
l.sort()
print(l[k - 1]) | {
"input": [
"12 5\n",
"4 2\n",
"5 3\n"
],
"output": [
"6\n",
"2\n",
"-1\n"
]
} |
1,957 | 8 | Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.
Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).
Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.
The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 β€ i β€ r1 and l2 β€ j β€ r2. In particular, when the periods intersect, the distance between them is 0.
Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of time periods when Anton can attend chess classes.
Each of the following n lines of the input contains two integers l1, i and r1, i (1 β€ l1, i β€ r1, i β€ 109) β the i-th variant of a period of time when Anton can attend chess classes.
The following line of the input contains a single integer m (1 β€ m β€ 200 000) β the number of time periods when Anton can attend programming classes.
Each of the following m lines of the input contains two integers l2, i and r2, i (1 β€ l2, i β€ r2, i β€ 109) β the i-th variant of a period of time when Anton can attend programming classes.
Output
Output one integer β the maximal possible distance between time periods.
Examples
Input
3
1 5
2 6
2 3
2
2 4
6 8
Output
3
Input
3
1 5
2 6
3 7
2
2 4
1 4
Output
0
Note
In the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.
In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | def f():
a, b = 1000000001, -1
for i in range(int(input())):
s = input().split()
a = min(a, int(s[1]))
b = max(b, int(s[0]))
return a,b
a , b =f()
a1, b1=f()
print(max(0, b1-a, b-a1)) | {
"input": [
"3\n1 5\n2 6\n2 3\n2\n2 4\n6 8\n",
"3\n1 5\n2 6\n3 7\n2\n2 4\n1 4\n"
],
"output": [
"3\n",
"0\n"
]
} |
1,958 | 8 | Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.
Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p.
Now the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let s be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed:
i := (s div 50) mod 475
repeat 25 times:
i := (i * 96 + 42) mod 475
print (26 + i)
Here "div" is the integer division operator, "mod" is the modulo (the remainder of division) operator.
As the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of s.
You're in the lead of the elimination round of 8VC Venture Cup 2017, having x points. You believe that having at least y points in the current round will be enough for victory.
To change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though.
You want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of successful hacks you have to do to achieve that?
Input
The only line contains three integers p, x and y (26 β€ p β€ 500; 1 β€ y β€ x β€ 20000) β your place in Codecraft-17, your current score in the elimination round of 8VC Venture Cup 2017, and the smallest number of points you consider sufficient for winning the current round.
Output
Output a single integer β the smallest number of successful hacks you have to do in order to both win the elimination round of 8VC Venture Cup 2017 and ensure getting a Codecraft-17 T-shirt.
It's guaranteed that your goal is achievable for any valid input data.
Examples
Input
239 10880 9889
Output
0
Input
26 7258 6123
Output
2
Input
493 8000 8000
Output
24
Input
101 6800 6500
Output
0
Input
329 19913 19900
Output
8
Note
In the first example, there is no need to do any hacks since 10880 points already bring the T-shirt to the 239-th place of Codecraft-17 (that is, you). In this case, according to the pseudocode, the T-shirts will be given to the participants at the following places:
475 422 84 411 453 210 157 294 146 188 420 367 29 356 398 155 102 239 91 133 365 312 449 301 343
In the second example, you have to do two successful and one unsuccessful hack to make your score equal to 7408.
In the third example, you need to do as many as 24 successful hacks to make your score equal to 10400.
In the fourth example, it's sufficient to do 6 unsuccessful hacks (and no successful ones) to make your score equal to 6500, which is just enough for winning the current round and also getting the T-shirt. | def f(p, d, x, y):
x+=d*50
if x<y:
return
s=(x//50)%475
for i in range(25):
s=(96*s+42)%475
if s+26==p:
print(0 if d<0 else (d+1)>>1)
exit()
p, x, y=map(int, input().split())
for i in range(-500, 500):
f(p, i, x, y)
| {
"input": [
"493 8000 8000\n",
"239 10880 9889\n",
"329 19913 19900\n",
"101 6800 6500\n",
"26 7258 6123\n"
],
"output": [
"24",
"0",
"8",
"0",
"2"
]
} |
1,959 | 9 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.
Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n β€ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.
Your task is to determine the number of options for the score the participant could have before the judges rated the participant.
Input
The first line contains two integers k and n (1 β€ n β€ k β€ 2 000) β the number of jury members and the number of scores Polycarp remembers.
The second line contains k integers a1, a2, ..., ak ( - 2 000 β€ ai β€ 2 000) β jury's marks in chronological order.
The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 β€ bj β€ 4 000 000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.
Output
Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).
Examples
Input
4 1
-5 5 0 20
10
Output
3
Input
2 2
-2000 -2000
3998000 4000000
Output
1
Note
The answer for the first example is 3 because initially the participant could have - 10, 10 or 15 points.
In the second example there is only one correct initial score equaling to 4 002 000. | def read():
return [int(x) for x in input().split()]
k, n = read()
a = read()
b = read()
c = []
for x in a:
c.append((c[-1] if c else 0) + x)
c = set(c)
z = set()
s = 0
for x in a:
s += x
i = b[0] - s
for y in b[1:]:
if y - i not in c:
break
else:
z.add(i)
print(len(z))
| {
"input": [
"4 1\n-5 5 0 20\n10\n",
"2 2\n-2000 -2000\n3998000 4000000\n"
],
"output": [
"3\n",
"1\n"
]
} |
1,960 | 11 | You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.
Some long and uninteresting story was removed...
The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.
A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:
* a β€ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;
* there is a position 1 β€ j β€ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.
For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.
Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.
Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.
Note that some words can be equal.
Input
The first line contains two integers n and m (2 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m.
Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 β€ li β€ 100 000, 1 β€ si, j β€ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence.
It is guaranteed that the total length of all words is not greater than 100 000.
Output
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes).
If the required is possible, in the second line print k β the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers β these letters. Note that you don't need to minimize the value k.
You can print the letters in any order. If there are multiple answers, print any of them.
Examples
Input
4 3
1 2
1 1
3 1 3 2
2 1 1
Output
Yes
2
2 3
Input
6 5
2 1 2
2 1 2
3 1 2 3
2 1 5
2 4 4
2 4 4
Output
Yes
0
Input
4 3
4 3 2 2 1
3 1 1 3
3 2 3 3
2 3 1
Output
No
Note
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:
* 2'
* 1
* 1 3' 2'
* 1 1
The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.
In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.
In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered. | from collections import defaultdict, deque
def main():
n,m = map(int, input().split())
cap = [None]*(m+1)
same_cap = defaultdict(list)
q = deque()
def apply_cap(a, c):
if cap[a] is not None:
return cap[a] == c
q.append((a,c))
while q:
b = q.pop()
if b[1] == c:
if cap[b[0]] is None:
cap[b[0]] = c
q.extend(same_cap[b[0]])
same_cap[b[0]] = []
elif cap[b[0]]!=c:
return False
return True
def same(a,b):
same_cap[b].append((a,True))
same_cap[a].append((b,False))
if cap[a] == False:
return apply_cap(b, False)
if cap[b] == True:
return apply_cap(a, True)
return True
def process(p,c):
lp = p[0]
lc = c[0]
for i in range(1, min(lp,lc)+1):
if p[i]>c[i]:
return apply_cap(p[i], True) and apply_cap(c[i], False)
if p[i]<c[i]:
return same(p[i], c[i])
return lp<=lc
p = list(map(int, input().split()))
for i in range(n-1):
c = list(map(int, input().split()))
if not process(p, c):
print ('No')
break
p = c
else:
print ('Yes')
res = []
for i,b in enumerate(cap):
if b:
res.append(i)
print(len(res))
print(' '.join(map(str,res)))
main() | {
"input": [
"6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4\n",
"4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1\n",
"4 3\n1 2\n1 1\n3 1 3 2\n2 1 1\n"
],
"output": [
"Yes\n0\n",
"No\n",
"Yes\n2\n2 3 "
]
} |
1,961 | 11 | One Martian boy called Zorg wants to present a string of beads to his friend from the Earth β Masha. He knows that Masha likes two colours: blue and red, β and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue β instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.
It is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 β for a blue one. From two strings the Martian puts earlier the string with a red bead in the i-th position, providing that the second string has a blue bead in the i-th position, and the first two beads i - 1 are identical.
At first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index k.
All these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.
Input
The input file contains two integers n and k (2 β€ n β€ 50;1 β€ k β€ 1016) βthe length of a string of beads, and the index of the string, chosen by Zorg.
Output
Output the k-th string of beads, putting 0 for a red bead, and 1 β for a blue one. If it s impossible to find the required string, output the only number -1.
Examples
Input
4 4
Output
0101
Note
Let's consider the example of strings of length 4 β 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110. Zorg will divide them into heaps: {0001, 0111, 1000, 1110}, {0010, 0100, 1011, 1101}, {0011, 1100}, {0101, 1010}, {0110, 1001}. Then he will choose the minimum strings of beads in each heap: 0001, 0010, 0011, 0101, 0110. The forth string β 0101. | def raschot(d, e, g, h):
if d > e:
return 1
key = d, g, h
if key in b:
return b[key]
f = 0
for x in (['0', '1'] if a0[d] == '?' else [a0[d]]):
if d == e:
a = [x]
else:
a = ['0', '1'] if a0[e] == '?' else [a0[e]]
for y in a:
if not ((g and x > y) or (h and x == y == '1')):
f += raschot(d + 1, e - 1, g and x == y, h and x != y)
b[key] = f
return f
n, m = map(int, input().split())
m += 1
a0 = ['?'] * n
for i in range(n):
a0[i] = '0'
b = {}
c = raschot(0, n - 1, True, True)
if m > c:
m -= c
a0[i] = '1'
if a0[0] == '0':
print(''.join(a0))
else:
print(-1)
| {
"input": [
"4 4\n"
],
"output": [
"0101\n"
]
} |
1,962 | 10 | Pushok the dog has been chasing Imp for a few hours already.
<image>
Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.
While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and <image> and <image>.
The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.
Help Imp to find the maximum noise he can achieve by changing the order of the strings.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of strings in robot's memory.
Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Output
Print a single integer β the maxumum possible noise Imp can achieve by changing the order of the strings.
Examples
Input
4
ssh
hs
s
hhhs
Output
18
Input
2
h
s
Output
1
Note
The optimal concatenation in the first sample is ssshhshhhs. | def key(x):
try:
return x.count('h') / x.count('s')
except ZeroDivisionError:
return 10**9
n = int(input())
t = ''.join(sorted((input() for _ in range(n)), key=key))
res, cnt = 0, 0
for ti in t:
if ti == 's':
cnt += 1
if ti == 'h':
res += cnt
print(res)
| {
"input": [
"2\nh\ns\n",
"4\nssh\nhs\ns\nhhhs\n"
],
"output": [
"1",
"18"
]
} |
1,963 | 9 | There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.
A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all n dormitories is written on an envelope. In this case, assume that all the rooms are numbered from 1 to a_1 + a_2 + ... + a_n and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.
For example, in case n=2, a_1=3 and a_2=5 an envelope can have any integer from 1 to 8 written on it. If the number 7 is written on an envelope, it means that the letter should be delivered to the room number 4 of the second dormitory.
For each of m letters by the room number among all n dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^{5}) β the number of dormitories and the number of letters.
The second line contains a sequence a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{10}), where a_i equals to the number of rooms in the i-th dormitory. The third line contains a sequence b_1, b_2, ..., b_m (1 β€ b_j β€ a_1 + a_2 + ... + a_n), where b_j equals to the room number (among all rooms of all dormitories) for the j-th letter. All b_j are given in increasing order.
Output
Print m lines. For each letter print two integers f and k β the dormitory number f (1 β€ f β€ n) and the room number k in this dormitory (1 β€ k β€ a_f) to deliver the letter.
Examples
Input
3 6
10 15 12
1 9 12 23 26 37
Output
1 1
1 9
2 2
2 13
3 1
3 12
Input
2 3
5 10000000000
5 6 9999999999
Output
1 5
2 1
2 9999999994
Note
In the first example letters should be delivered in the following order:
* the first letter in room 1 of the first dormitory
* the second letter in room 9 of the first dormitory
* the third letter in room 2 of the second dormitory
* the fourth letter in room 13 of the second dormitory
* the fifth letter in room 1 of the third dormitory
* the sixth letter in room 12 of the third dormitory | def I(): return(list(map(int,input().split())))
n,m=I()
a,b=I(),I()
arr=[0]*(n+1)
arr[0]=a[0]
for i in range(n-1):
arr[i+1]=arr[i]+a[i+1]
currl=0
for i in range(m):
l=currl
r=n-1
while(l<=r):
mid=(r-l)//2+l
if arr[mid]<b[i]:l=mid+1
else: r=mid-1
print(l+1,b[i]-arr[l-1])
currl=l
| {
"input": [
"2 3\n5 10000000000\n5 6 9999999999\n",
"3 6\n10 15 12\n1 9 12 23 26 37\n"
],
"output": [
"1 5\n2 1\n2 9999999994\n",
"1 1\n1 9\n2 2\n2 13\n3 1\n3 12\n"
]
} |
1,964 | 8 | There are a lot of things which could be cut β trees, paper, "the rope". In this problem you are going to cut a sequence of integers.
There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers.
Cuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, [4, 1, 2, 3, 4, 5, 4, 4, 5, 5] β two cuts β [4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]. On each segment the number of even elements should be equal to the number of odd elements.
The cost of the cut between x and y numbers is |x - y| bitcoins. Find the maximum possible number of cuts that can be made while spending no more than B bitcoins.
Input
First line of the input contains an integer n (2 β€ n β€ 100) and an integer B (1 β€ B β€ 100) β the number of elements in the sequence and the number of bitcoins you have.
Second line contains n integers: a_1, a_2, ..., a_n (1 β€ a_i β€ 100) β elements of the sequence, which contains the equal number of even and odd numbers
Output
Print the maximum possible number of cuts which can be made while spending no more than B bitcoins.
Examples
Input
6 4
1 2 5 10 15 20
Output
1
Input
4 10
1 3 2 4
Output
0
Input
6 100
1 2 3 4 5 6
Output
2
Note
In the first sample the optimal answer is to split sequence between 2 and 5. Price of this cut is equal to 3 bitcoins.
In the second sample it is not possible to make even one cut even with unlimited number of bitcoins.
In the third sample the sequence should be cut between 2 and 3, and between 4 and 5. The total price of the cuts is 1 + 1 = 2 bitcoins. | def scanf(t=int):
return list(map(t, input().split()))
n, b = scanf()
m = scanf()
ct, nct = 0, 0
temp = []
for i in range(n - 1):
if m[i] % 2: nct += 1
else: ct += 1
if ct == nct: temp.append(abs(m[i] - m[i + 1]))
ans, k = 0, 0
for x in sorted(temp):
ans += x
if ans > b: break
k += 1
print(k)
| {
"input": [
"6 100\n1 2 3 4 5 6\n",
"6 4\n1 2 5 10 15 20\n",
"4 10\n1 3 2 4\n"
],
"output": [
"2\n",
"1\n",
"0\n"
]
} |
1,965 | 9 | Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence a_1, a_2, β¦, a_n of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.
Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.
Let's denote the fingers of hand by numbers from 1 to 5. We call a fingering any sequence b_1, β¦, b_n of fingers numbers. A fingering is convenient if for all 1β€ i β€ n - 1 the following holds:
* if a_i < a_{i+1} then b_i < b_{i+1}, because otherwise Paul needs to take his hand off the keyboard to play the (i+1)-st note;
* if a_i > a_{i+1} then b_i > b_{i+1}, because of the same;
* if a_i = a_{i+1} then b_iβ b_{i+1}, because using the same finger twice in a row is dumb. Please note that there is β , not = between b_i and b_{i+1}.
Please provide any convenient fingering or find out that there is none.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) denoting the number of notes.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2β
10^5) denoting the positions of notes on the keyboard.
Output
If there is no convenient fingering, print -1. Otherwise, print n numbers b_1, b_2, β¦, b_n, each from 1 to 5, denoting a convenient fingering, separated by spaces.
Examples
Input
5
1 1 4 2 2
Output
1 4 5 4 5
Input
7
1 5 7 8 10 3 1
Output
1 2 3 4 5 4 3
Input
19
3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8
Output
1 3 4 5 4 5 4 5 4 5 4 5 4 3 5 4 3 5 4
Note
The third sample test is kinda "Non stop" song by Reflex. |
def get_fingering(notes):
fingering = []
diff = 0
next_diff = None
finger = 0
for i in range(len(notes) - 1):
next_diff = notes[i+1] - notes[i]
if diff == 0:
if next_diff > 0:
finger = 1 + (finger == 1)
elif next_diff < 0:
finger = 5 - (finger == 5)
else:
finger = 3 + (finger == 3)
elif diff > 0:
if finger == 5:
return None
if next_diff < 0:
finger = 5
else:
finger += 1
else:
if finger == 1:
return None
if next_diff > 0:
finger = 1
else:
finger -= 1
fingering.append(finger)
diff = next_diff
return fingering
_ = input()
notes = [int(x) for x in input().split()]
notes.append(notes[-1])
fingering = get_fingering(notes)
if fingering:
print(*fingering)
else:
print(-1)
| {
"input": [
"7\n1 5 7 8 10 3 1\n",
"19\n3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8\n",
"5\n1 1 4 2 2\n"
],
"output": [
"1 2 3 4 5 2 1 \n",
"2 1 2 3 1 2 1 2 1 2 1 4 3 2 1 2 1 2 1 \n",
"2 1 3 2 1 \n"
]
} |
1,966 | 7 | Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.
In the city in which Alice and Bob live, the first metro line is being built. This metro line contains n stations numbered from 1 to n. Bob lives near the station with number 1, while Alice lives near the station with number s. The metro line has two tracks. Trains on the first track go from the station 1 to the station n and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.
Some stations are not yet open at all and some are only partially open β for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.
When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.
Input
The first line contains two integers n and s (2 β€ s β€ n β€ 1000) β the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station 1.
Next lines describe information about closed and open stations.
The second line contains n integers a_1, a_2, β¦, a_n (a_i = 0 or a_i = 1). If a_i = 1, then the i-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track.
The third line contains n integers b_1, b_2, β¦, b_n (b_i = 0 or b_i = 1). If b_i = 1, then the i-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.
Output
Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
5 3
1 1 1 1 1
1 1 1 1 1
Output
YES
Input
5 4
1 0 0 0 1
0 1 1 1 1
Output
YES
Input
5 2
0 1 1 1 1
1 1 1 1 1
Output
NO
Note
In the first example, all stations are opened, so Bob can simply travel to the station with number 3.
In the second example, Bob should travel to the station 5 first, switch to the second track and travel to the station 4 then.
In the third example, Bob simply can't enter the train going in the direction of Alice's home. | def main():
n, s = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
if A[0] and (A[s - 1] or B[s - 1] and any([A[i] and B[i] for i in range(s,n)])):
return"YES"
else:
return"NO"
if __name__ == '__main__':
print(main()) | {
"input": [
"5 4\n1 0 0 0 1\n0 1 1 1 1\n",
"5 3\n1 1 1 1 1\n1 1 1 1 1\n",
"5 2\n0 1 1 1 1\n1 1 1 1 1\n"
],
"output": [
"YES\n",
"YES\n",
"NO\n"
]
} |
1,967 | 8 | There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise.
Vova thinks that people in the i-th flats are disturbed and cannot sleep if and only if 1 < i < n and a_{i - 1} = a_{i + 1} = 1 and a_i = 0.
Vova is concerned by the following question: what is the minimum number k such that if people from exactly k pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number k.
Input
The first line of the input contains one integer n (3 β€ n β€ 100) β the number of flats in the house.
The second line of the input contains n integers a_1, a_2, ..., a_n (a_i β \{0, 1\}), where a_i is the state of light in the i-th flat.
Output
Print only one integer β the minimum number k such that if people from exactly k pairwise distinct flats will turn off the light then nobody will be disturbed.
Examples
Input
10
1 1 0 1 1 0 1 0 1 0
Output
2
Input
5
1 1 0 0 0
Output
0
Input
4
1 1 1 1
Output
0
Note
In the first example people from flats 2 and 7 or 4 and 7 can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.
There are no disturbed people in second and third examples. | import sys
def inpt():
return sys.stdin.readline().strip()
n = int(inpt())
print(max(0, inpt().count('1 0 1')))
| {
"input": [
"10\n1 1 0 1 1 0 1 0 1 0\n",
"4\n1 1 1 1\n",
"5\n1 1 0 0 0\n"
],
"output": [
"2\n",
"0\n",
"0\n"
]
} |
1,968 | 7 | Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v β₯ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v β the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.
Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.
Input
The first line contains one integer n β the number of vertices in the tree (2 β€ n β€ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 β€ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 β€ s_v β€ 10^9), where erased values are replaced by -1.
Output
Output one integer β the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.
Examples
Input
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1 | def core():
n = int(input())
p = [None, None] + [int(x) for x in input().split()]
s = [None] + [int(x) for x in input().split()]
ip = [[] for _ in range(n+1)]
for i in range(2, n+1):
ip[p[i]].append(i)
a = [None, s[1]]
for i in range(2, n+1):
if s[i] == -1:
if ip[i]:
s[i] = min(s[j] for j in ip[i])
else:
s[i] = s[p[i]]
a.append(s[i] - s[p[i]])
if a[-1] < 0:
return -1
#print(n, p, s, a, ip)
return sum(a[1:])
print(core()) | {
"input": [
"3\n1 2\n2 -1 1\n",
"5\n1 1 1 1\n1 -1 -1 -1 -1\n",
"5\n1 2 3 1\n1 -1 2 -1 -1\n"
],
"output": [
"-1\n",
"1\n",
"2\n"
]
} |
1,969 | 8 | Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.
<image> An example of a fridge with h = 7 and two shelves. The shelves are shown in black. The picture corresponds to the first example.
Alyona has n bottles of milk that she wants to put in the fridge. The i-th bottle is a_i cells tall and 1 cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.
Alyona is interested in the largest integer k such that she can put bottles 1, 2, ..., k in the fridge at the same time. Find this largest k.
Input
The first line contains two integers n and h (1 β€ n β€ 10^3, 1 β€ h β€ 10^9) β the number of bottles and the height of the fridge.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ h) β the heights of the bottles.
Output
Print the single integer k β the maximum integer such that Alyona can put the bottles 1, 2, ..., k in the fridge at the same time. If Alyona can put all bottles in the fridge, print n. It is easy to see that Alyona can always put at least one bottle in the fridge.
Examples
Input
5 7
2 3 5 4 1
Output
3
Input
10 10
9 1 1 1 1 1 1 1 1 1
Output
4
Input
5 10
3 1 4 2 4
Output
5
Note
One of optimal locations in the first example is shown on the picture in the statement.
One of optimal locations in the second example is shown on the picture below.
<image>
One of optimal locations in the third example is shown on the picture below.
<image> | n, h = map(int, input().split())
a = list(map(int, input().split()))
def f(right):
return sum(sorted(a[0:right])[::-2]) <= h
r = 0
while r < n and f(r + 1):
r += 1
print(r)
| {
"input": [
"5 10\n3 1 4 2 4\n",
"10 10\n9 1 1 1 1 1 1 1 1 1\n",
"5 7\n2 3 5 4 1\n"
],
"output": [
"5",
"4",
"3"
]
} |
1,970 | 12 |
Input
The input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive.
Output
Output "YES" or "NO".
Examples
Input
NEAT
Output
YES
Input
WORD
Output
NO
Input
CODER
Output
NO
Input
APRILFOOL
Output
NO
Input
AI
Output
YES
Input
JUROR
Output
YES
Input
YES
Output
NO | def li():
return list(map(int, input().split(" ")))
a = "AEFHIKLMNTVWXYZ"
b = "BCDGJOQRSPU"
aa = bb = False
for i in input():
if i in a:
aa = True
else:
bb = True
if aa^bb:
print("Yes")
else:
print("No") | {
"input": [
"WORD\n",
"APRILFOOL\n",
"JUROR\n",
"NEAT\n",
"CODER\n",
"YES\n",
"AI\n"
],
"output": [
"NO",
"NO",
"YES",
"YES",
"NO",
"NO",
"YES"
]
} |
1,971 | 11 | Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?
There are n stores numbered from 1 to n in Nlogonia. The i-th of these stores offers a positive integer a_i.
Each day among the last m days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.
Dora considers Swiper to be her rival, and she considers that she beat Swiper on day i if and only if the least common multiple of the numbers she bought on day i is strictly greater than the least common multiple of the numbers that Swiper bought on day i.
The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.
However, Dora forgot the values of a_i. Help Dora find out if there are positive integer values of a_i such that she beat Swiper on every day. You don't need to find what are the possible values of a_i though.
Note that it is possible for some values of a_i to coincide in a solution.
Input
The first line contains integers m and n (1β€ m β€ 50, 1β€ n β€ 10^4) β the number of days and the number of stores.
After this m lines follow, the i-th line starts with an integer s_i (1β€ s_i β€ n-1), the number of integers Dora bought on day i, followed by s_i distinct integers, the indices of the stores where Dora bought an integer on the i-th day. The indices are between 1 and n.
Output
Output must consist of a single line containing "possible" if there exist positive integers a_i such that for each day the least common multiple of the integers bought by Dora is strictly greater than the least common multiple of the integers bought by Swiper on that day. Otherwise, print "impossible".
Note that you don't have to restore the integers themselves.
Examples
Input
2 5
3 1 2 3
3 3 4 5
Output
possible
Input
10 10
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
Output
impossible
Note
In the first sample, a possible choice for the values of the a_i is 3, 4, 3, 5, 2. On the first day, Dora buys the integers 3, 4 and 3, whose LCM is 12, while Swiper buys integers 5 and 2, whose LCM is 10. On the second day, Dora buys 3, 5 and 2, whose LCM is 30, and Swiper buys integers 3 and 4, whose LCM is 12. | import sys
input = sys.stdin.readline
def solve():
m, n = map(int, input().split())
c = [0]*(n+1)
a = [None]*m
for i in range(m):
s = map(int, input().split())
next(s)
a[i] = list(s)
for i in range(m):
for v in a[i]:
c[v] += 1
for j in range(i+1,m):
for v in a[j]:
if c[v] > 0:
break
else:
print('impossible')
return
for v in a[i]:
c[v] -= 1
print('possible')
solve()
| {
"input": [
"10 10\n1 1\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n",
"2 5\n3 1 2 3\n3 3 4 5\n"
],
"output": [
"impossible",
"possible"
]
} |
1,972 | 9 | The only difference between easy and hard versions is constraints.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following:
* The i-th student randomly chooses a ticket.
* if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.
* if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home.
Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.
The duration of the whole exam for all students is M minutes (max t_i β€ M), so students at the end of the list have a greater possibility to run out of time to pass the exam.
For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.
For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.
Input
The first line of the input contains two integers n and M (1 β€ n β€ 100, 1 β€ M β€ 100) β the number of students and the total duration of the exam in minutes, respectively.
The second line of the input contains n integers t_i (1 β€ t_i β€ 100) β time in minutes that i-th student spends to answer to a ticket.
It's guaranteed that all values of t_i are not greater than M.
Output
Print n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.
Examples
Input
7 15
1 2 3 4 5 6 7
Output
0 0 0 0 0 2 3
Input
5 100
80 40 40 40 60
Output
0 1 1 2 3
Note
The explanation for the example 1.
Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.
In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).
In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M). | def gns():
return list(map(int,input().split()))
n,m=gns()
ns=gns()
dp=[0]*(m+1)
for i in range(n):
c=ns[i]
print(i-dp[-c-1],end=' ')
dp2=list(dp)
for j in range(c,m+1):
dp[j]=max(dp[j],dp2[j-c]+1)
# print(dp)
print()
| {
"input": [
"7 15\n1 2 3 4 5 6 7\n",
"5 100\n80 40 40 40 60\n"
],
"output": [
"0 0 0 0 0 2 3\n",
"0 1 1 2 3\n"
]
} |
1,973 | 12 | The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.
Polycarp is a very famous freelancer. His current rating is r units.
Some very rich customers asked him to complete some projects for their companies. To complete the i-th project, Polycarp needs to have at least a_i units of rating; after he completes this project, his rating will change by b_i (his rating will increase or decrease by b_i) (b_i can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.
Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether.
To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.
Your task is to calculate the maximum possible size of such subset of projects.
Input
The first line of the input contains two integers n and r (1 β€ n β€ 100, 1 β€ r β€ 30000) β the number of projects and the initial rating of Polycarp, respectively.
The next n lines contain projects, one per line. The i-th project is represented as a pair of integers a_i and b_i (1 β€ a_i β€ 30000, -300 β€ b_i β€ 300) β the rating required to complete the i-th project and the rating change after the project completion.
Output
Print one integer β the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose.
Examples
Input
3 4
4 6
10 -2
8 -1
Output
3
Input
5 20
45 -6
34 -15
10 34
1 27
40 -45
Output
5
Input
3 2
300 -300
1 299
1 123
Output
3 | from math import *
MOD = int(1e9)+7
def nextInt():
return int(input())
def nextInts():
return list(map(int,input().split()))
def YN(x):
return "YES" if x else "NO"
def solve():
n,r = nextInts()
pos = []
neg = []
for i in range(n):
a,b = nextInts()
a = max(a,-b)
if b >= 0:
pos.append((a,b))
else:
neg.append((a,b))
pos.sort(key = lambda x:x[0])
neg.sort(key = lambda x:-(x[0]+x[1]))
ans = 0
for t in pos:
if r >= t[0]:
r += t[1]
ans += 1
dp = [-MOD]*60001
dp[r] = ans
for t in neg:
for j in range(t[0],60001):
dp[j+t[1]] = max(dp[j+t[1]],dp[j]+1)
return max(dp)
print(solve())
# q = nextInt()
# for i in range(q):
# print(YN(solve())) | {
"input": [
"3 4\n4 6\n10 -2\n8 -1\n",
"3 2\n300 -300\n1 299\n1 123\n",
"5 20\n45 -6\n34 -15\n10 34\n1 27\n40 -45\n"
],
"output": [
"3",
"3",
"5"
]
} |
1,974 | 11 | Alex decided to go on a touristic trip over the country.
For simplicity let's assume that the country has n cities and m bidirectional roads connecting them. Alex lives in city s and initially located in it. To compare different cities Alex assigned each city a score w_i which is as high as interesting city seems to Alex.
Alex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city v from city u, he may choose as the next city in the trip any city connected with v by the road, except for the city u.
Your task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.
Input
First line of input contains two integers n and m, (1 β€ n β€ 2 β
10^5, 0 β€ m β€ 2 β
10^5) which are numbers of cities and roads in the country.
Second line contains n integers w_1, w_2, β¦, w_n (0 β€ w_i β€ 10^9) which are scores of all cities.
The following m lines contain description of the roads. Each of these m lines contains two integers u and v (1 β€ u, v β€ n) which are cities connected by this road.
It is guaranteed that there is at most one direct road between any two cities, no city is connected to itself by the road and, finally, it is possible to go from any city to any other one using only roads.
The last line contains single integer s (1 β€ s β€ n), which is the number of the initial city.
Output
Output single integer which is the maximum possible sum of scores of visited cities.
Examples
Input
5 7
2 2 8 6 9
1 2
1 3
2 4
3 2
4 5
2 5
1 5
2
Output
27
Input
10 12
1 7 1 9 3 3 6 30 1 10
1 2
1 3
3 5
5 7
2 3
5 4
6 9
4 6
3 7
6 8
9 4
9 10
6
Output
61 | from collections import defaultdict
def get_neighbors(edges):
neighbors = defaultdict(set, {})
for v1, v2 in edges:
neighbors[v1].add(v2)
neighbors[v2].add(v1)
return dict(neighbors)
def get_component(neighbors_map, root):
if root not in neighbors_map:
return {root}
horizon = set(neighbors_map[root])
component = {root}
while horizon:
new_node = horizon.pop()
if new_node in component:
continue
component.add(new_node)
new_neighbors = neighbors_map[new_node].difference(component)
horizon |= new_neighbors
return component
def fn(weights, edges, root):
neihgbors_map = get_neighbors(edges)
if root not in neihgbors_map:
return weights[root]
first_component = get_component(neihgbors_map, root)
neihgbors_map = {k: v for k, v in neihgbors_map.items() if k in first_component}
degrees = {}
leaves = []
for n, neigh in neihgbors_map.items():
degrees[n] = len(neigh)
if len(neigh) == 1 and n != root:
leaves.append(n)
extra_values = defaultdict(int, {})
max_extra = 0
removed_set = set()
while leaves:
leaf = leaves.pop()
value = weights[leaf] + extra_values[leaf]
parent = neihgbors_map.pop(leaf).pop()
neihgbors_map[parent].remove(leaf)
degrees[parent] -= 1
if degrees[parent] == 1 and parent != root:
leaves.append(parent)
mm = max(extra_values[parent], value)
extra_values[parent] = mm
max_extra = max(mm, max_extra)
removed_set.add(leaf)
return sum(weights[n] for n in neihgbors_map) + max_extra
def print_answer(source):
n, m = map(int, source().split())
weights = list(map(int, source().split()))
edges = [[int(k) - 1 for k in source().split()] for _ in range(m)]
root = int(source()) - 1
print(fn(weights, edges, root))
print_answer(input)
if False:
from string_source import string_source
print_answer(string_source("""3 2
1 1335 2
2 1
3 2
2"""))
from string_source import string_source
print_answer(string_source("""1 0
1000000000
1"""))
print_answer(string_source("""10 12
1 7 1 9 3 3 6 30 1 10
1 2
1 3
3 5
5 7
2 3
5 4
6 9
4 6
3 7
6 8
9 4
9 10
6"""))
print_answer(string_source(
"""5 7
2 2 8 6 9
1 2
1 3
2 4
3 2
4 5
2 5
1 5
2"""))
source = string_source("""3 2
1 1335 2
2 1
3 2
2""")
n, m = map(int, source().split())
weights = list(map(int, source().split()))
edges = [[int(k) - 1 for k in source().split()] for _ in range(m)]
root = int(source())
fn(weights, edges, root)
from graphviz import Graph
dot = Graph(format="png", name="xx", filename=f"_files/temp/graph.png")
for idx, w in enumerate(weights):
dot.node(str(idx), label=f"{idx} - {w}")
for s,e in edges:
dot.edge(str(s),str(e))
dot.view(cleanup=True)
sum(weights)
| {
"input": [
"5 7\n2 2 8 6 9\n1 2\n1 3\n2 4\n3 2\n4 5\n2 5\n1 5\n2\n",
"10 12\n1 7 1 9 3 3 6 30 1 10\n1 2\n1 3\n3 5\n5 7\n2 3\n5 4\n6 9\n4 6\n3 7\n6 8\n9 4\n9 10\n6\n"
],
"output": [
"27\n",
"61\n"
]
} |
1,975 | 7 | Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer p (which may be positive, negative, or zero). To combine their tastes, they invented p-binary numbers of the form 2^x + p, where x is a non-negative integer.
For example, some -9-binary ("minus nine" binary) numbers are: -8 (minus eight), 7 and 1015 (-8=2^0-9, 7=2^4-9, 1015=2^{10}-9).
The boys now use p-binary numbers to represent everything. They now face a problem: given a positive integer n, what's the smallest number of p-binary numbers (not necessarily distinct) they need to represent n as their sum? It may be possible that representation is impossible altogether. Help them solve this problem.
For example, if p=0 we can represent 7 as 2^0 + 2^1 + 2^2.
And if p=-9 we can represent 7 as one number (2^4-9).
Note that negative p-binary numbers are allowed to be in the sum (see the Notes section for an example).
Input
The only line contains two integers n and p (1 β€ n β€ 10^9, -1000 β€ p β€ 1000).
Output
If it is impossible to represent n as the sum of any number of p-binary numbers, print a single integer -1. Otherwise, print the smallest possible number of summands.
Examples
Input
24 0
Output
2
Input
24 1
Output
3
Input
24 -1
Output
4
Input
4 -7
Output
2
Input
1 1
Output
-1
Note
0-binary numbers are just regular binary powers, thus in the first sample case we can represent 24 = (2^4 + 0) + (2^3 + 0).
In the second sample case, we can represent 24 = (2^4 + 1) + (2^2 + 1) + (2^0 + 1).
In the third sample case, we can represent 24 = (2^4 - 1) + (2^2 - 1) + (2^2 - 1) + (2^2 - 1). Note that repeated summands are allowed.
In the fourth sample case, we can represent 4 = (2^4 - 7) + (2^1 - 7). Note that the second summand is negative, which is allowed.
In the fifth sample case, no representation is possible. | N, P = map(int, input().split())
def chk(k):
x = N - k*P
if x > 0 and sum(map(int, bin(x)[2:])) <= k <= x:
return 1
return 0
for i in range(1, 100):
if chk(i):
print(i)
break
else:
print(-1)
| {
"input": [
"4 -7\n",
"24 -1\n",
"24 1\n",
"24 0\n",
"1 1\n"
],
"output": [
"2\n",
"4\n",
"3\n",
"2\n",
"-1\n"
]
} |
1,976 | 11 | Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 β€ i β€ n.
Creatnx asks the mirrors one by one, starting from the 1-st mirror. Every day, if he asks i-th mirror, there are two possibilities:
* The i-th mirror tells Creatnx that he is beautiful. In this case, if i = n Creatnx will stop and become happy, otherwise he will continue asking the i+1-th mirror next day;
* In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the 1-st mirror again.
You need to calculate [the expected number](https://en.wikipedia.org/wiki/Expected_value) of days until Creatnx becomes happy.
This number should be found by modulo 998244353. Formally, let M = 998244353. 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}.
Input
The first line contains one integer n (1β€ nβ€ 2β
10^5) β the number of mirrors.
The second line contains n integers p_1, p_2, β¦, p_n (1 β€ p_i β€ 100).
Output
Print the answer modulo 998244353 in a single line.
Examples
Input
1
50
Output
2
Input
3
10 20 50
Output
112
Note
In the first test, there is only one mirror and it tells, that Creatnx is beautiful with probability 1/2. So, the expected number of days until Creatnx becomes happy is 2. | mod = 998244353
def inv_mod(n):
return pow(n, mod - 2, mod)
n = int(input())
p = [int(x) for x in input().split()]
res = 0
for i in p:
res = (res + 1) * 100 * inv_mod(i) % mod
print(res) | {
"input": [
"1\n50\n",
"3\n10 20 50\n"
],
"output": [
"2\n",
"112\n"
]
} |
1,977 | 7 | It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry student
* "P" corresponds to a patient student
Such string describes the row from the last to the first student.
Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index i in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.
<image>
Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.
Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.
Input
The first line contains a single integer t β the number of groups of students (1 β€ t β€ 100). The following 2t lines contain descriptions of groups of students.
The description of the group starts with an integer k_i (1 β€ k_i β€ 100) β the number of students in the group, followed by a string s_i, consisting of k_i letters "A" and "P", which describes the i-th group of students.
Output
For every group output single integer β the last moment a student becomes angry.
Examples
Input
1
4
PPAP
Output
1
Input
3
12
APPAPPPAPPPP
3
AAP
3
PPA
Output
4
1
0
Note
In the first test, after 1 minute the state of students becomes PPAA. After that, no new angry students will appear.
In the second tets, state of students in the first group is:
* after 1 minute β AAPAAPPAAPPP
* after 2 minutes β AAAAAAPAAAPP
* after 3 minutes β AAAAAAAAAAAP
* after 4 minutes all 12 students are angry
In the second group after 1 minute, all students are angry. | def I(): return map(int, input().split())
for _ in range(int(input())):
input()
s = sorted(input().lstrip("P").rstrip("A").split("A"))
print(len(s[-1]))
| {
"input": [
"1\n4\nPPAP\n",
"3\n12\nAPPAPPPAPPPP\n3\nAAP\n3\nPPA\n"
],
"output": [
"1\n",
"4\n1\n0\n"
]
} |
1,978 | 7 | The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices i and j (1 β€ i, j β€ n) such that |i-j|=1 and a_i>0 and apply a_i = a_i - 1, a_j = a_j + 1. She may also decide to not do anything on some days because she is lazy.
Bessie wants to maximize the number of haybales in pile 1 (i.e. to maximize a_1), and she only has d days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 1 if she acts optimally!
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 100) β the number of test cases. Next 2t lines contain a description of test cases β two lines per test case.
The first line of each test case contains integers n and d (1 β€ n,d β€ 100) β the number of haybale piles and the number of days, respectively.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 100) β the number of haybales in each pile.
Output
For each test case, output one integer: the maximum number of haybales that may be in pile 1 after d days if Bessie acts optimally.
Example
Input
3
4 5
1 0 3 2
2 2
100 1
1 8
0
Output
3
101
0
Note
In the first test case of the sample, this is one possible way Bessie can end up with 3 haybales in pile 1:
* On day one, move a haybale from pile 3 to pile 2
* On day two, move a haybale from pile 3 to pile 2
* On day three, move a haybale from pile 2 to pile 1
* On day four, move a haybale from pile 2 to pile 1
* On day five, do nothing
In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 2 to pile 1 on the second day. | def I(): return(list(map(int,input().split())))
for __ in range(int(input())):
n,d=I()
a=I()
s=a[0]
for i in range(1,n):
if d>i*a[i]:
s+=a[i]
d-=(i*a[i])
else:
s+=d//i
break
print(s)
| {
"input": [
"3\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0\n"
],
"output": [
"3\n101\n0\n"
]
} |
1,979 | 7 | Dreamoon is a big fan of the Codeforces contests.
One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing!
Based on this, you come up with the following problem:
There is a person who participated in n Codeforces rounds. His place in the first round is a_1, his place in the second round is a_2, ..., his place in the n-th round is a_n.
You are given a positive non-zero integer x.
Please, find the largest v such that this person can collect all the places from 1 to v after x more rated contests.
In other words, you need to find the largest v, such that it is possible, that after x more rated contests, for each 1 β€ i β€ v, there will exist a contest where this person took the i-th place.
For example, if n=6, x=2 and a=[3,1,1,5,7,10] then answer is v=5, because if on the next two contest he will take places 2 and 4, then he will collect all places from 1 to 5, so it is possible to get v=5.
Input
The first line contains an integer t (1 β€ t β€ 5) denoting the number of test cases in the input.
Each test case contains two lines. The first line contains two integers n, x (1 β€ n, x β€ 100). The second line contains n positive non-zero integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 100).
Output
For each test case print one line containing the largest v, such that it is possible that after x other contests, for each 1 β€ i β€ v, there will exist a contest where this person took the i-th place.
Example
Input
5
6 2
3 1 1 5 7 10
1 100
100
11 1
1 1 1 1 1 1 1 1 1 1 1
1 1
1
4 57
80 60 40 20
Output
5
101
2
2
60
Note
The first test case is described in the statement.
In the second test case, the person has one hundred future contests, so he can take place 1,2,β¦,99 and place 101 on them in some order, to collect places 1,2,β¦,101. | I = input
pr = print
def main():
for _ in range(int(I())):
n,x = map(int,I().split())
ar = set(map(int,I().split()))
pr(list(set(range(1,205)) - ar)[x]-1)
main()
| {
"input": [
"5\n6 2\n3 1 1 5 7 10\n1 100\n100\n11 1\n1 1 1 1 1 1 1 1 1 1 1\n1 1\n1\n4 57\n80 60 40 20\n"
],
"output": [
"5\n101\n2\n2\n60\n"
]
} |
1,980 | 7 | Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ
c=b.
For n β₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
For the fixed integer n, Orac decided to add f(n) to n.
For example, if he had an integer n=5, the new value of n will be equal to 10. And if he had an integer n=6, n will be changed to 8.
Orac loved it so much, so he decided to repeat this operation several times.
Now, for two positive integers n and k, Orac asked you to add f(n) to n exactly k times (note that n will change after each operation, so f(n) may change too) and tell him the final value of n.
For example, if Orac gives you n=5 and k=2, at first you should add f(5)=5 to n=5, so your new value of n will be equal to n=10, after that, you should add f(10)=2 to 10, so your new (and the final!) value of n will be equal to 12.
Orac may ask you these queries many times.
Input
The first line of the input is a single integer t\ (1β€ tβ€ 100): the number of times that Orac will ask you.
Each of the next t lines contains two positive integers n,k\ (2β€ nβ€ 10^6, 1β€ kβ€ 10^9), corresponding to a query by Orac.
It is guaranteed that the total sum of n is at most 10^6.
Output
Print t lines, the i-th of them should contain the final value of n in the i-th query by Orac.
Example
Input
3
5 1
8 2
3 4
Output
10
12
12
Note
In the first query, n=5 and k=1. The divisors of 5 are 1 and 5, the smallest one except 1 is 5. Therefore, the only operation adds f(5)=5 to 5, and the result is 10.
In the second query, n=8 and k=2. The divisors of 8 are 1,2,4,8, where the smallest one except 1 is 2, then after one operation 8 turns into 8+(f(8)=2)=10. The divisors of 10 are 1,2,5,10, where the smallest one except 1 is 2, therefore the answer is 10+(f(10)=2)=12.
In the third query, n is changed as follows: 3 β 6 β 8 β 10 β 12. | def mind(n):
for i in range(2,n+1):
if(n%i==0):
return i
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
n+=mind(n)
n+=2*(k-1)
print(n)
| {
"input": [
"3\n5 1\n8 2\n3 4\n"
],
"output": [
"10\n12\n12\n"
]
} |
1,981 | 10 | Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, β¦), max(s_2, s_4, s_6, β¦)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 β€ k β€ n β€ 2 β
10^5) β the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the elements of the array a.
Output
Output a single integer β the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | def check(x,p):
c=0
for i in range(n):
if a[i]<=x or c%2==p:c+=1
if c==k:return True
return False
n,k=map(int,input().split())
a=list(map(int,input().split()))
l,r=min(a),max(a)
ans=r
while l<r:
m=(l+r)//2
if check(m,0) or check(m,1):r=m;ans=m
else:l=m+1
print(ans) | {
"input": [
"4 2\n1 2 3 4\n",
"4 3\n1 2 3 4\n",
"6 4\n5 3 50 2 4 5\n",
"5 3\n5 3 4 2 6\n"
],
"output": [
"1\n",
"2\n",
"3\n",
"2\n"
]
} |
1,982 | 11 | You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i β x (β denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 β€ i < j β€ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x β output the smallest one.
Input
First line contains a single integer n (1 β€ n β€ 3 β
10^5) β the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | import sys;input=sys.stdin.readline
N, = map(int, input().split())
A = list(map(int, input().split()))
def check(l, i):
al,bl=[],[]
a=b=0
ta=tb=0
for j in l:
if (A[j]>>i) & 1:
al.append(j)
ta += 1
b += tb
else:
bl.append(j)
tb += 1
a += ta
return a,b,al, bl
ll = [list(range(N))]
R = 0
X = 0
for i in range(29, -1, -1):
nll = []
ac=bc=0
# print(i, ll)
for l in ll:
a, b, al, bl = check(l, i)
ac += a
bc += b
if al:
nll.append(al)
if bl:
nll.append(bl)
# print(ac, bc)
if ac > bc:
X += 1<<i
R += bc
else:
R += ac
ll = nll
print(R, X)
| {
"input": [
"9\n10 7 9 10 7 5 5 3 5\n",
"3\n8 10 3\n",
"4\n0 1 3 2\n"
],
"output": [
"4 14\n",
"0 8\n",
"1 0\n"
]
} |
1,983 | 9 | Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the enemy's health decreases by a at time t, and then increases by b at time points t + 1, t + 2, ..., t + c due to this ability.
The ability has a cooldown of d seconds, i. e. if Meka-Naruto uses it at time moment t, next time he can use it is the time t + d. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under k spells gets kβ
b amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every d seconds). The enemy is killed if their health points become 0 or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
Input
The first line contains an integer t (1β€ tβ€ 10^5) standing for the number of testcases.
Each test case is described with one line containing four numbers a, b, c and d (1β€ a, b, c, dβ€ 10^6) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
Output
For each testcase in a separate line print -1 if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
Example
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
Note
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets:
* 4 damage (1-st spell cast) at time 0;
* 4 damage (2-nd spell cast) and 3 heal (1-st spell cast) at time 1 (the total of 5 damage to the initial health);
* 4 damage (3-nd spell cast) and 6 heal (1-st and 2-nd spell casts) at time 2 (the total of 3 damage to the initial health);
* and so on.
One can prove that there is no time where the enemy gets the total of 6 damage or more, so the answer is 5. Please note how the health is recalculated: for example, 8-health enemy would not die at time 1, as if we first subtracted 4 damage from his health and then considered him dead, before adding 3 heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type. | import sys
input = sys.stdin.readline
def solve_case():
a, b, c, d = [int(x) for x in input().split()]
if a > b * c:
print(-1)
else:
k = a // (b * d)
print(a * (k + 1) - k * (k + 1) // 2 * b * d)
def main():
for _ in range(int(input())):
solve_case()
main() | {
"input": [
"7\n1 1 1 1\n2 2 2 2\n1 2 3 4\n4 3 2 1\n228 21 11 3\n239 21 11 3\n1000000 1 1000000 1\n"
],
"output": [
"1\n2\n1\n5\n534\n-1\n500000500000\n"
]
} |
1,984 | 7 | Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:
* replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);
* swap any pair of digits in string a.
Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.
Input
The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.
Output
Print on the single line the single number β the minimum number of operations needed to convert string a into string b.
Examples
Input
47
74
Output
1
Input
774
744
Output
1
Input
777
444
Output
3
Note
In the first sample it is enough simply to swap the first and the second digit.
In the second sample we should replace the second digit with its opposite.
In the third number we should replace all three digits with their opposites. | def main():
l = [x == '7' for x, y in zip(input(), input()) if x != y]
x = sum(l)
print(max(x, len(l) - x))
if __name__ == '__main__':
main() | {
"input": [
"774\n744\n",
"47\n74\n",
"777\n444\n"
],
"output": [
"1\n",
"1\n",
"3\n"
]
} |
1,985 | 9 | A pair of positive integers (a,b) is called special if β a/b β = a mod b. Here, β a/b β is the result of the integer division between a and b, while a mod b is its remainder.
You are given two integers x and y. Find the number of special pairs (a,b) such that 1β€ a β€ x and 1 β€ b β€ y.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers x, y (1 β€ x,y β€ 10^9).
Output
For each test case print the answer on a single line.
Example
Input
9
3 4
2 100
4 3
50 3
12 4
69 420
12345 6789
123456 789
12345678 9
Output
1
0
2
3
5
141
53384
160909
36
Note
In the first test case, the only special pair is (3, 2).
In the second test case, there are no special pairs.
In the third test case, there are two special pairs: (3, 2) and (4, 3). | def find():
x, y = map(int, input().split())
s = 0
for j in range(1, int(x**0.5) + 1):
s += max(0, min(y, x//j - 1) - j)
return s
for i in range(int(input())):
print(find()) | {
"input": [
"9\n3 4\n2 100\n4 3\n50 3\n12 4\n69 420\n12345 6789\n123456 789\n12345678 9\n"
],
"output": [
"\n1\n0\n2\n3\n5\n141\n53384\n160909\n36\n"
]
} |
1,986 | 7 | You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input
The first line contains the only integer q (1 β€ q β€ 1013).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer β his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Examples
Input
6
Output
2
Input
30
Output
1
6
Input
1
Output
1
0
Note
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. | import math
def checkprime(x):
for j in range(2,math.ceil(math.sqrt(x))+1):
if(x%j==0):
return (j)
return x
x=int(input())
y=checkprime(x)
if y==x:
print(1,0,sep='\n')
else:
y1=x/y
if checkprime(y1)==y1:
print(2)
else:
print(1,y*checkprime(y1),sep="\n")
| {
"input": [
"30\n",
"1\n",
"6\n"
],
"output": [
"1\n6\n",
"1\n0\n",
"2\n"
]
} |
1,987 | 11 | You are given a rooted tree. Each vertex contains a_i tons of gold, which costs c_i per one ton. Initially, the tree consists only a root numbered 0 with a_0 tons of gold and price c_0 per ton.
There are q queries. Each query has one of two types:
1. Add vertex i (where i is an index of query) as a son to some vertex p_i; vertex i will have a_i tons of gold with c_i per ton. It's guaranteed that c_i > c_{p_i}.
2. For a given vertex v_i consider the simple path from v_i to the root. We need to purchase w_i tons of gold from vertices on this path, spending the minimum amount of money. If there isn't enough gold on the path, we buy all we can.
If we buy x tons of gold in some vertex v the remaining amount of gold in it decreases by x (of course, we can't buy more gold that vertex has at the moment). For each query of the second type, calculate the resulting amount of gold we bought and the amount of money we should spend.
Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program. In standard (if you don't tweak I/O), endl flushes cout in C++ and System.out.println in Java (or println in Kotlin) makes automatic flush as well.
Input
The first line contains three integers q, a_0 and c_0 (1 β€ q β€ 3 β
10^5; 1 β€ a_0, c_0 < 10^6) β the number of queries, the amount of gold in the root and its price.
Next q lines contain descriptions of queries; The i-th query has one of two types:
* "1 p_i a_i c_i" (0 β€ p_i < i; 1 β€ a_i, c_i < 10^6): add vertex i as a son to vertex p_i. The vertex i will have a_i tons of gold with price c_i per one ton. It's guaranteed that p_i exists and c_i > c_{p_i}.
* "2 v_i w_i" (0 β€ v_i < i; 1 β€ w_i < 10^6): buy w_i tons of gold from vertices on path from v_i to 0 spending the minimum amount of money. If there isn't enough gold, we buy as much as we can. It's guaranteed that vertex v_i exist.
It's guaranteed that there is at least one query of the second type.
Output
For each query of the second type, print the resulting amount of gold we bought and the minimum amount of money we should spend.
Example
Input
5 5 2
2 0 2
1 0 3 4
2 2 4
1 0 1 3
2 4 2
Output
2 4
4 10
1 3
Note
Explanation of the sample:
At the first query, the tree consist of root, so we purchase 2 tons of gold and pay 2 β
2 = 4. 3 tons remain in the root.
At the second query, we add vertex 2 as a son of vertex 0. Vertex 2 now has 3 tons of gold with price 4 per one ton.
At the third query, a path from 2 to 0 consists of only vertices 0 and 2 and since c_0 < c_2 we buy 3 remaining tons of gold in vertex 0 and 1 ton in vertex 2. So we bought 3 + 1 = 4 tons and paid 3 β
2 + 1 β
4 = 10. Now, in vertex 0 no gold left and 2 tons of gold remain in vertex 2.
At the fourth query, we add vertex 4 as a son of vertex 0. Vertex 4 now has 1 ton of gold with price 3.
At the fifth query, a path from 4 to 0 consists of only vertices 0 and 4. But since no gold left in vertex 0 and only 1 ton is in vertex 4, we buy 1 ton of gold in vertex 4 and spend 1 β
3 = 3. Now, in vertex 4 no gold left. | import os, sys
input = sys.stdin.buffer.readline
def main():
(Q, A0, C0) = [int(x) for x in input().split()];N = Q + 2;A = [0] * N;C = [0] * N;P = [0] * N;pref = [0] * N
anc = [None for i in range(N)];anc[-1] = [-1] * 20;root = 0;A[root] = A0;C[root] = C0;P[root] = -1;pref[root] = A0;anc[root] = [-1] * 20
def buildJumps(u, parent):
jumps = [0] * 20;jumps[0] = parent
for i in range(1, 20):jumps[i] = anc[jumps[i - 1]][i - 1]
anc[u] = jumps
def getAncestor(u, k):
for i in reversed(range(20)):
if k & (1 << i):u = anc[u][i]
return u
def getLast(u, f):
for i in reversed(range(20)):
if f(anc[u][i]):u = anc[u][i]
return u
for i in range(1, Q + 1):
query = [int(x) for x in input().split()]
if query[0] == 1:_, p, A[i], C[i] = query;P[i] = p;pref[i] = pref[p] + A[i];buildJumps(i, p)
else:
assert query[0] == 2;_, v, want = query;gold = 0;spend = 0
if True:
if A[v] != 0:
hi = getLast(v, lambda node: A[node]);target = want + (pref[hi] - A[hi]);lo = getLast(v, lambda node: pref[node] >= target);path = [lo]
while path[-1] != hi:path.append(P[path[-1]])
for u in reversed(path):take = min(want, A[u]);A[u] -= take;gold += take;spend += C[u] * take;want -= take
else:
while A[v] != 0 and want:u = getLast(v, lambda node: A[node] != 0);take = min(want, A[u]);A[u] -= take;gold += take;spend += C[u] * take;want -= take
os.write(1, b"%d %d\n" % (gold, spend))
if __name__ == "__main__":main() | {
"input": [
"5 5 2\n2 0 2\n1 0 3 4\n2 2 4\n1 0 1 3\n2 4 2\n"
],
"output": [
"\n2 4\n4 10\n1 3\n"
]
} |
1,988 | 10 | Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors β "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | s1=input()
s2=input()
def divisors(s):
n=len(s)
div=set()
for i in range(1,n+1):
if n % i == 0 and all(s[:i] == s[j:j + i] for j in range(i, n, i)):
div.add(s[:i])
return div
a=divisors(s1)
b=divisors(s2)
print(len(a & b))
| {
"input": [
"aaa\naa\n",
"abcdabcd\nabcdabcdabcdabcd\n"
],
"output": [
"1",
"2"
]
} |
1,989 | 11 | To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index i got a person with index fi, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes β there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (xi, yi), which mean that person xi has to call person yi as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?
Input
The first input line contains number n (2 β€ n β€ 105) β amount of BolgenOS community members. The second line contains n space-separated integer numbers fi (1 β€ fi β€ n, i β fi) β index of a person, to whom calls a person with index i.
Output
In the first line output one number β the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any.
Examples
Input
3
3 3 2
Output
1
3 1
Input
7
2 3 1 3 4 4 1
Output
3
2 5
2 6
3 7 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
a = [0] + list(map(int, input().split()))
rev = [[] for _ in range(n + 1)]
indeg = [0] * (n + 1)
for i in range(1, n + 1):
indeg[a[i]] += 1
rev[a[i]].append(i)
_indeg = indeg[:]
for i in range(1, n + 1):
if _indeg[i]:
continue
v = i
while indeg[v] == 0:
indeg[a[v]] -= 1
v = a[v]
visited = [0] * (n + 1)
group = []
group_leaf = []
for i in range(1, n + 1):
if visited[i] or indeg[i] == 0:
continue
visited[i] = 1
leaves = []
stack = [i]
while stack:
v = stack.pop()
if _indeg[v] == 0:
leaves.append(v)
for dest in rev[v]:
if not visited[dest]:
visited[dest] = 1
stack.append(dest)
if not leaves:
leaves.append(i)
group.append(i)
group_leaf.append(leaves)
assert all(visited[1:])
ans = []
m = len(group)
if not (m == 1 and group_leaf[0][0] == group[0]):
for i in range(m):
k = group[(i + 1) % m]
for j in group_leaf[i]:
ans.append(f'{k} {j}')
ans_str = str(len(ans)) + '\n' + '\n'.join(ans)
sys.stdout.buffer.write(ans_str.encode('utf-8'))
| {
"input": [
"3\n3 3 2\n",
"7\n2 3 1 3 4 4 1\n"
],
"output": [
"1\n2 1\n",
"3\n2 6\n6 7\n7 5\n"
]
} |
1,990 | 10 | Mr. Bender has a digital table of size n Γ n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to n, and the columns β numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.
For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1).
In how many seconds will Mr. Bender get happy?
Input
The first line contains four space-separated integers n, x, y, c (1 β€ n, c β€ 109; 1 β€ x, y β€ n; c β€ n2).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
6 4 3 1
Output
0
Input
9 3 8 10
Output
2
Note
Initially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. <image>. | import sys
ii = lambda: sys.stdin.readline().strip()
idata = lambda: [int(x) for x in ii().split()]
sdata = lambda: list(ii())
def solve():
n, x, y, c = idata()
r = n ** 2
l = -1
while l + 1 < r:
middle = (l + r) // 2
ans = 1 + 2 * (middle + 1) * middle
ans -= pow(middle - n + y, 2) if middle - n + y > 0 else 0
ans -= pow(middle + 1 - y, 2) if middle + 1 - y > 0 else 0
ans -= pow(middle - n + x, 2) if middle - n + x > 0 else 0
ans -= pow(middle + 1 - x, 2) if middle + 1 - x > 0 else 0
d = 1 + n - x + y
if middle >= d:
ans += (middle - d + 1) * (middle - d + 2) // 2
d = 2 + 2 * n - y - x
if middle >= d:
ans += (middle - d + 1) * (middle - d + 2) // 2
d = 1 + n - y + x
if middle >= d:
ans += (middle - d + 1) * (middle - d + 2) // 2
d = x + y
if middle >= d:
ans += (middle - d + 1) * (middle - d + 2) // 2
if ans >= c:
r = middle
else:
l = middle
print(r)
return
for t in range(1):
solve() | {
"input": [
"9 3 8 10\n",
"6 4 3 1\n"
],
"output": [
"2\n",
"0\n"
]
} |
1,991 | 10 | You've got a positive integer sequence a1, a2, ..., an. All numbers in the sequence are distinct. Let's fix the set of variables b1, b2, ..., bm. Initially each variable bi (1 β€ i β€ m) contains the value of zero. Consider the following sequence, consisting of n operations.
The first operation is assigning the value of a1 to some variable bx (1 β€ x β€ m). Each of the following n - 1 operations is assigning to some variable by the value that is equal to the sum of values that are stored in the variables bi and bj (1 β€ i, j, y β€ m). At that, the value that is assigned on the t-th operation, must equal at. For each operation numbers y, i, j are chosen anew.
Your task is to find the minimum number of variables m, such that those variables can help you perform the described sequence of operations.
Input
The first line contains integer n (1 β€ n β€ 23). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ak β€ 109).
It is guaranteed that all numbers in the sequence are distinct.
Output
In a single line print a single number β the minimum number of variables m, such that those variables can help you perform the described sequence of operations.
If you cannot perform the sequence of operations at any m, print -1.
Examples
Input
5
1 2 3 6 8
Output
2
Input
3
3 6 5
Output
-1
Input
6
2 4 8 6 10 18
Output
3
Note
In the first sample, you can use two variables b1 and b2 to perform the following sequence of operations.
1. b1 := 1;
2. b2 := b1 + b1;
3. b1 := b1 + b2;
4. b1 := b1 + b1;
5. b1 := b1 + b2. | def Solve(x,B):
if((X,x,B) in Mem):
return Mem[(X,x,B)]
if(len(B)>X):
return False
if(x==len(L)):
return True
if(Form(L[x],B)):
A=list(B)
for e in range(len(B)):
r=A[e]
A[e]=L[x]
if(Solve(x+1,tuple(sorted(A)))):
Mem[(X,x,B)]=True
return True
A[e]=r
A+=[L[x]]
if(Solve(x+1,tuple(sorted(A)))):
Mem[(X,x,B)]=True
return True
Mem[(X,x,B)]=False
return False
def Form(x,B):
for i in range(len(B)):
for j in range(i,len(B)):
if(B[i]+B[j]==x):
return True
return False
n=int(input())
L=list(map(int,input().split()))
done=False
Mem={}
for X in range(1,n+1):
if(Solve(1,(L[0],))):
print(X)
done=True
break
if(not done):
print(-1)
| {
"input": [
"5\n1 2 3 6 8\n",
"3\n3 6 5\n",
"6\n2 4 8 6 10 18\n"
],
"output": [
"2",
"-1",
"3"
]
} |
1,992 | 7 | Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence a1, a1 + d, a1 + 2d, ..., a1 + (n - 1)d, where a1 and d are any numbers.
Geometric progression is a sequence b1, b2 = b1q, ..., bn = bn - 1q, where b1 β 0, q β 0, q β 1.
Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.
Input
The first line contains exactly four integer numbers between 1 and 1000, inclusively.
Output
Print the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.
Print 42 if the given sequence is not an arithmetic or geometric progression.
Examples
Input
836 624 412 200
Output
-12
Input
1 334 667 1000
Output
1333
Note
This problem contains very weak pretests! | def main():
a, b, c, d = [int(i) for i in input().split()]
p1, p2, p3 = b - a, c - b, d - c
q1, q2, q3 = b / a, c / b, d / c
if(p1 == p2 == p3):
print(d + p3)
elif(q1 == q2 == q3 and q1 != 1 and int(d * q3) == d * q3):
print(int(d * q3))
else:
print(42)
main() | {
"input": [
"1 334 667 1000\n",
"836 624 412 200\n"
],
"output": [
"1333",
"-12"
]
} |
1,993 | 8 | Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price β their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
Input
The first line contains two space-separated integers n and m (1 β€ m β€ n β€ 100) β amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 β€ ai β€ 1000) β prices of the TV sets.
Output
Output the only number β the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.
Examples
Input
5 3
-6 0 35 -2 4
Output
8
Input
4 2
7 0 0 -7
Output
7 | def readln(inp=None): return tuple(map(int, (inp or input()).split()))
n, m = readln()
print(-sum(sorted([v if v < 0 else 0 for v in readln()])[:m]))
| {
"input": [
"4 2\n7 0 0 -7\n",
"5 3\n-6 0 35 -2 4\n"
],
"output": [
"7\n",
"8\n"
]
} |
1,994 | 9 | There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.
Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.
The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
Input
The first line contains a single integer β n (1 β€ n β€ 5Β·105). Each of the next n lines contains an integer si β the size of the i-th kangaroo (1 β€ si β€ 105).
Output
Output a single integer β the optimal number of visible kangaroos.
Examples
Input
8
2
5
7
6
9
8
4
2
Output
5
Input
8
9
1
6
2
6
5
8
3
Output
5 | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n=Int()
a=[]
for i in range(n): a.append(Int())
a.sort(reverse=True)
b=a[n//2:]
a=a[0:n//2]
# print(a)
# print(b)
# print()
i=0
j=0
ans=n
while(i<len(a) and j<len(b)):
key=a[i]
while(j<len(b) and key<2*b[j]):
j+=1
if(j!=len(b)):
# print(key,b[j])
ans-=1
j+=1
i+=1
print(ans)
| {
"input": [
"8\n9\n1\n6\n2\n6\n5\n8\n3\n",
"8\n2\n5\n7\n6\n9\n8\n4\n2\n"
],
"output": [
"5\n",
"5\n"
]
} |
1,995 | 7 | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member β Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers β n and k (1 β€ n, k β€ 1000).
Output
In the first line print an integer m β number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 β€ ai, bi β€ n; ai β bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1 | #Problem Set L: Collaborated with Rudrnash Singh
n_k = list(map(int, input().split()))
if n_k[0] >= 1 and n_k[0] <= 1000:
n = n_k[0]
if n_k[1] >= 1 and n_k[1] <= 1000:
k = n_k[1]
def func1(n,k):
for i in range(n):
for j in range(k):
val = (i+j+1)%n
print(i+1, val+1)
if n < (2*k+1):
print("-1")
else:
print(n*k)
func1(n,k)
| {
"input": [
"3 1\n"
],
"output": [
"3\n1 2\n2 3\n3 1\n"
]
} |
1,996 | 11 | There are n employees working in company "X" (let's number them from 1 to n for convenience). Initially the employees didn't have any relationships among each other. On each of m next days one of the following events took place:
* either employee y became the boss of employee x (at that, employee x didn't have a boss before);
* or employee x gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive);
* or comes a request of type "determine whether employee x signs certain documents".
Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.
Input
The first line contains two integers n and m (1 β€ n, m β€ 105) β the number of employees and the number of events.
Each of the next m lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event t (1 β€ t β€ 3).
* If t = 1, then next follow two integers x and y (1 β€ x, y β€ n) β numbers of the company employees. It is guaranteed that employee x doesn't have the boss currently.
* If t = 2, then next follow integer x (1 β€ x β€ n) β the number of the employee who got a document packet.
* If t = 3, then next follow two integers x and i (1 β€ x β€ n; 1 β€ i β€ [number of packets that have already been given]) β the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order.
It is guaranteed that the input has at least one query of the third type.
Output
For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes.
Examples
Input
4 9
1 4 3
2 4
3 3 1
1 2 3
2 2
3 1 2
1 3 1
2 2
3 1 3
Output
YES
NO
YES | n, m = map(int, input().split())
ev = [tuple(map(int, input().split())) for _ in range(m)]
g = [[] for _ in range(n + 1)]
qry = [[] for _ in range(m + 1)]
roots = set(range(1, n + 1))
qcnt = 0
for e in ev:
if e[0] == 1:
g[e[2]].append(e[1])
roots.remove(e[1])
elif e[0] == 3:
qry[e[2]].append((qcnt, e[1]))
qcnt += 1
tin, tout = [0] * (n + 1), [0] * (n + 1)
st = [(u, 0) for u in roots]
time = 0
while st:
u, w = st.pop()
if w:
tout[u] = time
continue
time += 1
tin[u] = time
st.append((u, 1))
for v in g[u]:
st.append((v, 0))
p = list(range(n + 1))
def find(x):
if x != p[x]:
p[x] = find(p[x])
return p[x]
pcnt = 0
ans = [None] * qcnt
for e in ev:
if e[0] == 1:
p[find(e[1])] = find(e[2])
elif e[0] == 2:
pcnt += 1
for qid, x in qry[pcnt]:
ans[qid] = 'YES' if find(e[1]) == find(x) and tin[x] <= tin[e[1]] <= tout[x] else 'NO'
print(*ans, sep='\n') | {
"input": [
"4 9\n1 4 3\n2 4\n3 3 1\n1 2 3\n2 2\n3 1 2\n1 3 1\n2 2\n3 1 3\n"
],
"output": [
"YES\nNO\nYES\n"
]
} |
1,997 | 9 | Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name β The Huff-puffer.
So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with Ξ± liters of petrol (Ξ± β₯ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers.
Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with Ξ± liters of petrol. Otherwise, he doesn't stop at the station and drives on.
For example, if Ξ± = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on.
You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.
One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the Ξ± number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.
Input
The first line contains an integer n (1 β€ n β€ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number Ξ± β₯ 10, to which such a succession of stops corresponds.
Output
Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".
Examples
Input
3
1 2 4
Output
unique
5
Input
2
1 2
Output
not unique
Note
In the second example the answer is not unique. For example, if Ξ± = 10, we'll have such a sequence as 1, 2, 3, and if Ξ± = 14, the sequence will be 1, 2, 4. | #codeforces 48c: the race: math
import math
def readGen(trans):
while 1:
for x in input().split():
yield(trans(x))
readint=readGen(int)
n=next(readint)
a=[0]+[next(readint) for i in range(n)]
p=max((n+1)*a[i]/i-1 for i in range(1,n+1))
q=min((n+1)*(a[i]+1)/i for i in range(1,n+1))
eps=1e-8
u=math.floor(q-eps)
l=math.ceil(p+eps)
#print(p,q,l,u)
if (l<u): print("not unique")
else: print("unique\n%d"%l)
| {
"input": [
"3\n1 2 4\n",
"2\n1 2\n"
],
"output": [
"unique\n5\n",
"not unique\n"
]
} |
1,998 | 7 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s.
Input
The first line contains the s line which is the inputted part. The second line contains an integer n (1 β€ n β€ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only.
Output
If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s.
The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages.
Examples
Input
next
2
nextpermutation
nextelement
Output
nextelement
Input
find
4
find
findfirstof
findit
fand
Output
find
Input
find
4
fondfind
fondfirstof
fondit
fand
Output
find | s = input()
n = int(input())
used = []
for i in range(n):
word = input()
used.append(word)
used = sorted(used)
def main(s, used):
length = len(s)
for used_word in used:
if used_word[0:length] == s:
return used_word
return s
print(main(s, used))
| {
"input": [
"find\n4\nfondfind\nfondfirstof\nfondit\nfand\n",
"next\n2\nnextpermutation\nnextelement\n",
"find\n4\nfind\nfindfirstof\nfindit\nfand\n"
],
"output": [
"find\n",
"nextelement\n",
"find\n"
]
} |
1,999 | 9 | Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.
He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.
A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 β€ i1 < i2 < i3 β€ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.
A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1.
Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
Input
The first line of the input contains two integers, n and k (1 β€ n, k β€ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number.
The second line contains n integers a1, a2, ..., an ( - 109 β€ ai β€ 109) β elements of the sequence.
Output
Output a single number β the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
Examples
Input
5 2
1 1 2 2 4
Output
4
Input
3 1
1 1 1
Output
1
Input
10 3
1 2 6 2 3 6 9 18 3 9
Output
6
Note
In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4. | from collections import Counter
def solve(n, k, arr):
c1 = Counter()
c2 = Counter()
total = 0
for a in reversed(arr):
total += c2[a*k]
c2[a] += c1[a*k]
c1[a] += 1
return total
n, k = map(int, input().split())
arr = list(map(int, input().split()))
print(solve(n, k, arr)) | {
"input": [
"10 3\n1 2 6 2 3 6 9 18 3 9\n",
"5 2\n1 1 2 2 4\n",
"3 1\n1 1 1\n"
],
"output": [
"6\n",
"4\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.