index
int64 0
5.16k
| difficulty
int64 7
12
| question
stringlengths 126
7.12k
| solution
stringlengths 30
18.6k
| test_cases
dict |
---|---|---|---|---|
4,300 | 11 | Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation p of length n. Scientists found out, that to overcome an obstacle, the robot should make p an identity permutation (make p_i = i for all i).
Unfortunately, scientists can't control the robot. Thus the only way to make p an identity permutation is applying the following operation to p multiple times:
* Select two indices i and j (i β j), such that p_j = i and swap the values of p_i and p_j. It takes robot (j - i)^2 seconds to do this operation.
Positions i and j are selected by the robot (scientists can't control it). He will apply this operation while p isn't an identity permutation. We can show that the robot will make no more than n operations regardless of the choice of i and j on each operation.
Scientists asked you to find out the maximum possible time it will take the robot to finish making p an identity permutation (i. e. worst-case scenario), so they can decide whether they should construct a new lunar rover or just rest and wait. They won't believe you without proof, so you should build an example of p and robot's operations that maximizes the answer.
For a better understanding of the statement, read the sample description.
Input
The first line of input contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
Each of next t lines contains the single integer n (2 β€ n β€ 10^5) β the length of p.
Note, that p is not given to you. You should find the maximum possible time over all permutations of length n.
It is guaranteed, that the total sum of n over all test cases doesn't exceed 10^5.
Output
For each test case in the first line, print how many seconds will the robot spend in the worst case.
In the next line, print the initial value of p that you used to construct an answer.
In the next line, print the number of operations m β€ n that the robot makes in your example.
In the each of next m lines print two integers i and j β indices of positions that the robot will swap on this operation. Note that p_j = i must holds (at the time of operation).
Example
Input
3
2
3
3
Output
1
2 1
1
2 1
5
2 3 1
2
1 3
3 2
5
2 3 1
2
1 3
2 3
Note
For n = 2, p can be either [1, 2] or [2, 1]. In the first case p is already identity, otherwise robot will make it an identity permutation in 1 second regardless of choise i and j on the first operation.
For n = 3, p can be equals [2, 3, 1].
* If robot will select i = 3, j = 2 on the first operation, p will become [2, 1, 3] in one second. Now robot can select only i = 1, j = 2 or i = 2, j = 1. In both cases, p will become identity in one more second (2 seconds in total).
* If robot will select i = 1, j = 3 on the first operation, p will become [1, 3, 2] in four seconds. Regardless of choise of i and j on the second operation, p will become identity in five seconds.
We can show, that for permutation of length 3 robot will always finish all operation in no more than 5 seconds. | def main():
n=int(*input().split())
L=[x for x in range(n+1)];ans=[]
def swp(x,y):
L[x],L[y]=L[y],L[x]
swp(1,n);ans.append((1,n))
for i in range(2,(n+1)//2+1):
swp(i,n);ans.append((i,n))
if not n-i+1==i: swp(n-i+1,1);ans.append((n-i+1,1))
val=sum((i-j)*(i-j) for i,j in ans)
print(val)
for x in range(1,n+1): print(L[x],end=' ')
print("\n%d"%(n-1,))
for x in range(n-2,-1,-1): print(ans[x][0],ans[x][1])
T=int(*input().split())
for ii in range(T):
main() | {
"input": [
"3\n2\n3\n3\n"
],
"output": [
"\n1\n2 1\n1\n2 1\n5\n2 3 1\n2\n1 3\n3 2\n5\n2 3 1\n2\n1 3\n2 3"
]
} |
4,301 | 8 | Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second β from a2 to b2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
Input
The first line of the input file contains integers n and x0 (1 β€ n β€ 100; 0 β€ x0 β€ 1000). The following n lines contain pairs of integers ai, bi (0 β€ ai, bi β€ 1000; ai β bi).
Output
Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.
Examples
Input
3 3
0 7
14 2
4 6
Output
1 | def mp():return map(int,input().split())
def it():return int(input())
n,x=mp()
ans=0
v=[]
p=[]
for _ in range(n):
a,b=sorted(list(mp()))
v.append(a)
p.append(b)
ma=max(v)
mi=min(p)
# print(ma,mi)
if ma>mi:
print(-1)
elif mi>=x>=ma:
print(0)
else:
print(max((x-mi),(ma-x)))
| {
"input": [
"3 3\n0 7\n14 2\n4 6\n"
],
"output": [
"1\n"
]
} |
4,302 | 7 | Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s.
String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".
Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions:
* Insert one letter to any end of the string.
* Delete one letter from any end of the string.
* Change one letter into any other one.
Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u.
Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
Output
Print the only integer β the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
Examples
Input
aaaaa
aaa
Output
0
Input
abcabc
bcd
Output
1
Input
abcdef
klmnopq
Output
7
Note
In the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.
In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.
In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message. | def check(ss):
tmp=0
for i in range(len(u)):
tmp+=ss[i]!=u[i]
return tmp
s = input()
u = input()
s = '#'*2000 + s + '#'*2000
ans=1000000000000
for i in range(len(s)-len(u)):
sub = s[i:i+len(u)]
ans = min(ans , check(sub))
print(ans)
| {
"input": [
"abcdef\nklmnopq\n",
"aaaaa\naaa\n",
"abcabc\nbcd\n"
],
"output": [
"7\n",
"0\n",
"1\n"
]
} |
4,303 | 11 | The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet.
The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, x presents in each. The Beaver will take to the ship exactly a1 + ... + an suitcases.
As the Beaver lands on the i-th planet, he takes ai suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens β each of the bi citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.
The Beaver is going to spend exactly c days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer x so that the planned voyage will take exactly c days?
Input
The first input line contains space-separated integers n and c β the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly.
The next n lines contain pairs of space-separated integers ai, bi (1 β€ i β€ n) β the number of suitcases he can bring to the i-th planet and the number of citizens of the i-th planet, correspondingly.
The input limitations for getting 30 points are:
* 1 β€ n β€ 100
* 1 β€ ai β€ 100
* 1 β€ bi β€ 100
* 1 β€ c β€ 100
The input limitations for getting 100 points are:
* 1 β€ n β€ 104
* 0 β€ ai β€ 109
* 1 β€ bi β€ 109
* 1 β€ c β€ 109
Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations!
Output
Print a single number k β the number of ways to choose x so as to travel for exactly c days. If there are infinitely many possible values of x, print -1.
Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
2 5
1 5
2 4
Output
1
Note
In the first example there is only one suitable value x = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days β he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.
For x = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For x = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long. | I=lambda:map(int,input().split())
n,c=I()
a,b=[],[]
for _ in range(n):x,y=I();a.append(x);b.append(y)
if max(a)==0:print([0,-1][n==c]);exit()
def f(x):
r=0
for i in range(n):
r+=1+a[i]*x//b[i]
if r>c:break
return r
l=-1
r=10**18
while l<r-1:
m=(l+r)//2
if f(m)<c:l=m
else:r=m
L=r
l=-1
r=10**18
while l<r-1:
m=(l+r)//2
if f(m)<=c:l=m
else:r=m
while f(r)>c:r-=1
if r<1:r=1
if L<1:L=1
if f(r)!=c:print(0)
else:print(r-L+1) | {
"input": [
"2 5\n1 5\n2 4\n"
],
"output": [
"1"
]
} |
4,304 | 8 | A renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine.
Let us remind you that a ring is a region located between two concentric circles with radii r and R (r < R). These radii are called internal and external, respectively. Concentric circles are circles with centers located at the same point.
Soon a white canvas, which can be considered as an infinite Cartesian plane, had two perfect rings, painted with solid black paint. As Sasha is very impulsive, the rings could have different radii and sizes, they intersect and overlap with each other in any way. We know only one thing for sure: the centers of the pair of rings are not the same.
When Sasha got tired and fell into a deep sleep, a girl called Ilona came into the room and wanted to cut a circle for the sake of good memories. To make the circle beautiful, she decided to cut along the contour.
We'll consider a contour to be a continuous closed line through which there is transition from one color to another (see notes for clarification). If the contour takes the form of a circle, then the result will be cutting out a circle, which Iona wants.
But the girl's inquisitive mathematical mind does not rest: how many ways are there to cut a circle out of the canvas?
Input
The input contains two lines.
Each line has four space-separated integers xi, yi, ri, Ri, that describe the i-th ring; xi and yi are coordinates of the ring's center, ri and Ri are the internal and external radii of the ring correspondingly ( - 100 β€ xi, yi β€ 100; 1 β€ ri < Ri β€ 100).
It is guaranteed that the centers of the rings do not coinside.
Output
A single integer β the number of ways to cut out a circle from the canvas.
Examples
Input
60 60 45 55
80 80 8 32
Output
1
Input
60 60 45 55
80 60 15 25
Output
4
Input
50 50 35 45
90 50 35 45
Output
0
Note
Figures for test samples are given below. The possible cuts are marked with red dotted line.
<image> <image> <image> | ((x,y,r,R), (u,v,w,W))=[map(int, input().split()) for _ in range(2)]
d = (x-u) ** 2 + (y - v) ** 2
def t(a,b,c):
if c <= a and (a-c)**2 >= d:
return 1
if c >= b and (c-b)**2 >= d:
return 1
if (b+c) ** 2 <= d:
return 1
return 0
print(t(r,R,w) + t(r,R,W) + t(w,W,r) + t(w,W,R))
| {
"input": [
"50 50 35 45\n90 50 35 45\n",
"60 60 45 55\n80 60 15 25\n",
"60 60 45 55\n80 80 8 32\n"
],
"output": [
"0",
"4",
"1"
]
} |
4,305 | 9 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.
Input
The first input line contains two space-separated integers n, m (1 β€ n, m β€ 105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly.
The second line contains n space-separated integers: a1, a2, ..., an (1 β€ ai β€ 107) β the numbers that are multiplied to produce the numerator.
The third line contains m space-separated integers: b1, b2, ..., bm (1 β€ bi β€ 107) β the numbers that are multiplied to produce the denominator.
Output
Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout, mout must satisfy the inequality 1 β€ nout, mout β€ 105, and the actual values in the sets aout, i and bout, i must satisfy the inequality 1 β€ aout, i, bout, i β€ 107.
Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (x > 1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them.
Examples
Input
3 2
100 5 2
50 10
Output
2 3
2 1
1 1 1
Input
4 3
2 5 10 20
100 1 3
Output
1 1
20
3
Note
In the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.
In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | from collections import defaultdict
import bisect
from itertools import accumulate
import os
import sys
import math
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
def factor(n, dic1):
while(n % 2 == 0):
if 2 not in dic1:
dic1[2] = 1
else:
dic1[2] += 1
n = n//2
for i in range(3, int(math.sqrt(n))+1, 2):
while(n % i == 0):
if i not in dic1:
dic1[i] = 1
else:
dic1[i] += 1
n = n//i
if n > 2:
if n not in dic1:
dic1[n] = 1
else:
dic1[n] += 1
def factor1(n, dic2):
while(n % 2 == 0):
if 2 not in dic2:
dic2[2] = 1
else:
dic2[2] += 1
n = n//2
for i in range(3, int(math.sqrt(n))+1, 2):
if n % i == 0:
while(n % i == 0):
if i not in dic2:
dic2[i] = 1
else:
dic2[i] += 1
n = n//i
if n > 2:
if n not in dic2:
dic2[n] = 1
else:
dic2[n] += 1
n, m = map(int, input().split())
dic1 = {}
dic2 = {}
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
for i in range(0, len(a)):
factor(a[i], dic1)
for i in range(0, len(b)):
factor1(b[i], dic2)
ans1 = [1]*n
ans2 = [1]*m
fac1 = []
fac2 = []
for key in dic1:
if key in dic2:
if dic1[key] >= dic2[key]:
dic1[key] -= dic2[key]
dic2[key] = 0
elif dic2[key] > dic1[key]:
dic2[key] -= dic1[key]
dic1[key] = 0
fac11=[]
fac22=[]
for key in dic1:
fac11.append([key,dic1[key]])
for key in dic2:
fac22.append([key,dic2[key]])
fac11.sort(reverse=True)
fac22.sort(reverse=True)
j=0
for i in range(0,len(fac11)):
while(fac11[i][1]>0):
if ans1[j]*fac11[i][0]<=10**7:
ans1[j]=ans1[j]*fac11[i][0]
fac11[i][1]-=1
j=(j+1)%n
j=0
for i in range(0, len(fac22)):
while(fac22[i][1] > 0):
if ans2[j]*fac22[i][0] <= 10**7:
ans2[j] = ans2[j]*fac22[i][0]
fac22[i][1] -= 1
j = (j+1) % m
print(len(ans1),len(ans2))
print(*ans1)
print(*ans2) | {
"input": [
"4 3\n2 5 10 20\n100 1 3\n",
"3 2\n100 5 2\n50 10\n"
],
"output": [
"4 3\n1 1 1 20 \n1 1 3 ",
"3 2\n1 1 2 \n1 1 "
]
} |
4,306 | 7 | Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number n and array a.
loop integer variable i from 1 to nβ-β1
Β Β Β Β loop integer variable j from i to nβ-β1
Β Β Β Β Β Β Β Β if (ajβ>βajβ+β1), then swap the values of elements aj and ajβ+β1
But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of n doesn't exist, print -1.
Input
You've got a single integer n (1 β€ n β€ 50) β the size of the sorted array.
Output
Print n space-separated integers a1, a2, ..., an (1 β€ ai β€ 100) β the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1.
If there are several counter-examples, consisting of n numbers, you are allowed to print any of them.
Examples
Input
1
Output
-1 | def main():
n = int(input())
if n < 3:
print(-1)
else:
print(*list(range(n, 0, -1)))
main()
| {
"input": [
"1\n"
],
"output": [
"-1\n"
]
} |
4,307 | 8 | You've got an n Γ m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.
You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.
A matrix is prime if at least one of the two following conditions fulfills:
* the matrix has a row with prime numbers only;
* the matrix has a column with prime numbers only;
Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.
Input
The first line contains two integers n, m (1 β€ n, m β€ 500) β the number of rows and columns in the matrix, correspondingly.
Each of the following n lines contains m integers β the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105.
The numbers in the lines are separated by single spaces.
Output
Print a single integer β the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.
Examples
Input
3 3
1 2 3
5 6 1
4 4 1
Output
1
Input
2 3
4 8 8
9 2 9
Output
3
Input
2 2
1 3
4 2
Output
0
Note
In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.
In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.
In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | from bisect import bisect_left as bl
n,m=map(int,input().split())
pn,l=[],[]
q=10**5+4
k=[True for i in range(q+2)]
for p in range(2,int(q**.5)+2):
if(k[p]==True):
for i in range(p**2,q+2,p):k[i]=False
for p in range(2,q+1):
if k[p]:pn.append(p)
for i in range(n):
l.append(list(map(int,input().split())))
def f(l,q):
for i in l:
x=0
for j in i:x+=pn[bl(pn,j)]-j
q=min(q,x)
return q
print(f(zip(*l),f(l,q))) | {
"input": [
"3 3\n1 2 3\n5 6 1\n4 4 1\n",
"2 2\n1 3\n4 2\n",
"2 3\n4 8 8\n9 2 9\n"
],
"output": [
"1\n",
"0\n",
"3\n"
]
} |
4,308 | 8 | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number β the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | def solve(s):
c, r = 0, 0
for i in range(5, len(s) + 1):
if s[i - 5:i] == 'heavy':
c += 1
elif s[i - 5:i] == 'metal':
r += c
return r
print(solve(input()))
| {
"input": [
"heavymetalisheavymetal\n",
"trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou\n",
"heavymetalismetal\n"
],
"output": [
"3\n",
"3\n",
"2\n"
]
} |
4,309 | 8 | Xenia the vigorous detective faced n (n β₯ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right.
Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.
But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 β€ li β€ ri β€ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.
You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).
Input
The first line contains four integers n, m, s and f (1 β€ n, m β€ 105; 1 β€ s, f β€ n; s β f; n β₯ 2). Each of the following m lines contains three integers ti, li, ri (1 β€ ti β€ 109, 1 β€ li β€ ri β€ n). It is guaranteed that t1 < t2 < t3 < ... < tm.
Output
Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X".
As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note.
If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.
Examples
Input
3 5 1 3
1 1 2
2 2 3
3 3 3
4 1 1
10 1 3
Output
XXRR | def geto(a, b):
return max(0, min(a[1], b[1]) - max(a[0], b[0])+1)
n,m,s,f = map(int, input().split())
di = {}
for _ in range(m):
t, l, r = map(int, input().split())
di[t] = [l, r]
t = 1
ans = []
while s != f:
if f > s:
inte = [s, s+1]
if t in di and geto(inte, di[t]): ans += ['X']
else:
ans += ['R']
s += 1
else:
inte = [s-1, s]
if t in di and geto(inte, di[t]): ans += ['X']
else:
ans += ['L']
s -= 1
t += 1
print("".join(ans)) | {
"input": [
"3 5 1 3\n1 1 2\n2 2 3\n3 3 3\n4 1 1\n10 1 3\n"
],
"output": [
"XXRR"
]
} |
4,310 | 9 | Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box).
Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.
<image>
Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than xi boxes on the top of i-th box. What is the minimal number of piles she needs to construct?
Input
The first line contains an integer n (1 β€ n β€ 100). The next line contains n integers x1, x2, ..., xn (0 β€ xi β€ 100).
Output
Output a single integer β the minimal possible number of piles.
Examples
Input
3
0 0 10
Output
2
Input
5
0 1 2 3 4
Output
1
Input
4
0 0 0 0
Output
4
Input
9
0 1 0 2 0 1 1 2 10
Output
3
Note
In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2.
<image>
In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom).
<image> | def go():
n = int(input())
a = [int(i) for i in input().split(' ')]
a.sort()
o = 1
for i in range(n):
if(a[i] < i // o):
o += 1
return o
print(go())
| {
"input": [
"3\n0 0 10\n",
"4\n0 0 0 0\n",
"9\n0 1 0 2 0 1 1 2 10\n",
"5\n0 1 2 3 4\n"
],
"output": [
"2\n",
"4\n",
"3\n",
"1\n"
]
} |
4,311 | 12 |
Input
The input contains a single integer a (1 β€ a β€ 64).
Output
Output a single integer.
Examples
Input
2
Output
1
Input
4
Output
2
Input
27
Output
5
Input
42
Output
6 | """
Codeforces April Fools Contest 2014 Problem F
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
res = inputs[:]
inputs[:] = []
while n > len(inputs):
inputs.extend(input().split(" "))
if n > 0:
res = inputs[:n]
inputs[:n] = []
return res
InputHandler = InputHandlerObject()
g = InputHandler.getInput
############################## SOLUTION ##############################
x = int(input())
a = [1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51, 1, 2, 1, 14, 1, 2, 2, 14, 1, 6, 1, 4, 2, 2, 1, 52, 2, 5, 1, 5, 1, 15, 2, 13, 2, 2, 1, 13, 1, 2, 4, 267]
print(a[x-1]) | {
"input": [
"27\n",
"4\n",
"2\n",
"42\n"
],
"output": [
"5",
"2",
"1",
"6"
]
} |
4,312 | 7 | Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The child will follow the algorithm:
* If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great.
* If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).
You are given a multiple-choice questions, can you predict child's choose?
Input
The first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length.
Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_".
Output
Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes).
Examples
Input
A.VFleaKing_is_the_author_of_this_problem
B.Picks_is_the_author_of_this_problem
C.Picking_is_the_author_of_this_problem
D.Ftiasch_is_cute
Output
D
Input
A.ab
B.abcde
C.ab
D.abc
Output
C
Input
A.c
B.cc
C.c
D.c
Output
B
Note
In the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D.
In the second sample, no choice is great, so the child will choose the luckiest choice C.
In the third sample, the choice B (length 2) is twice longer than all other choices', so it is great choice. There is no other great choices so the child will choose B. | def get_len(x) :
return len(x)
a=list(input() for i in range(4))
a.sort(key=get_len)
s=(2*len(a[0])<=len(a[1])+2)
l=(2*len(a[2])<=len(a[3])+2)
print("C" if s^l==0 else (a[0][0] if s else a[3][0]))
| {
"input": [
"A.VFleaKing_is_the_author_of_this_problem\nB.Picks_is_the_author_of_this_problem\nC.Picking_is_the_author_of_this_problem\nD.Ftiasch_is_cute\n",
"A.ab\nB.abcde\nC.ab\nD.abc\n",
"A.c\nB.cc\nC.c\nD.c\n"
],
"output": [
"D",
"C\n",
"B"
]
} |
4,313 | 8 | We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 β€ li β€ ri β€ n) meaning that value <image> should be equal to qi.
Your task is to find any interesting array of n elements or state that such array doesn't exist.
Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β as "and".
Input
The first line contains two integers n, m (1 β€ n β€ 105, 1 β€ m β€ 105) β the number of elements in the array and the number of limits.
Each of the next m lines contains three integers li, ri, qi (1 β€ li β€ ri β€ n, 0 β€ qi < 230) describing the i-th limit.
Output
If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 β€ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them.
If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.
Examples
Input
3 1
1 3 3
Output
YES
3 3 3
Input
3 2
1 3 3
1 3 2
Output
NO | from sys import stdin
input=stdin.readline
def funcand(a,b):
return a&b
class SegmentTree:
def __init__(self, data, default=(1<<31)-1, func=max):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def f(n,q):
a=[0]*(n)
for bit in range(30):
s=[0]*(n+1)
for l,r,nm in q:
if((nm>>bit)&1):
s[l]+=1
s[r]-=1
for i in range(n):
if i>0:
s[i]+=s[i-1] # bich ke bhar raha hai
if s[i]>0:
a[i]|=(1<<bit)
st=SegmentTree(a,func=funcand,default=(1<<31)-1)
for l,r,nm in q:
# print(st.query(l,r))
if st.query(l,r)!=nm:
return "NO"
print("YES")
print(*a)
return ''
q=[]
n,m=map(int,input().strip().split())
for _ in range(m):
l,r,nm=map(int,input().strip().split())
q.append((l-1,r,nm))
print(f(n,q)) | {
"input": [
"3 1\n1 3 3\n",
"3 2\n1 3 3\n1 3 2\n"
],
"output": [
"YES\n3 3 3 ",
"NO\n"
]
} |
4,314 | 8 | Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 β€ i β€ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
Input
The first line contains two space-separated integers n and m (2 β€ n β€ 105, 1 β€ m β€ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.
The following m lines describe the important pairs. The i-th of them (1 β€ i β€ m) contains two space-separated integers ai and bi (1 β€ ai, bi β€ n, ai β bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct.
Output
Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.
Examples
Input
4 5
1 2
1 3
1 4
2 3
2 4
Output
3
Input
4 6
1 2
1 4
2 3
2 4
3 2
3 4
Output
4
Note
For the first sample, one of the optimal ways to construct pipes is shown in the image below:
<image>
For the second sample, one of the optimal ways is shown below:
<image> | def main():
n, m = map(int, input().split())
n += 1
cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)]
def root(x):
if x != cluster[x]:
cluster[x] = x = root(cluster[x])
return x
for _ in range(m):
a, b = map(int, input().split())
ab[a].append(b)
dest[b] += 1
cluster[root(a)] = root(b)
pool = [a for a, f in enumerate(dest) if not f]
for a in pool:
for b in ab[a]:
dest[b] -= 1
if not dest[b]:
pool.append(b)
ab = [True] * n
for a, f in enumerate(dest):
if f:
ab[root(a)] = False
print(n - sum(f and a == c for a, c, f in zip(range(n), cluster, ab)))
if __name__ == '__main__':
from sys import setrecursionlimit
setrecursionlimit(100500)
main()
| {
"input": [
"4 6\n1 2\n1 4\n2 3\n2 4\n3 2\n3 4\n",
"4 5\n1 2\n1 3\n1 4\n2 3\n2 4\n"
],
"output": [
"4\n",
"3\n"
]
} |
4,315 | 7 | There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.
Input
The first line contains an integer n (1 β€ n β€ 106). The second line contains a sequence of integers a1, a2, ..., an (1 β€ ai β€ 3).
Output
Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal.
Examples
Input
9
1 3 2 2 2 1 1 2 3
Output
5
Note
In the example all the numbers equal to 1 and 3 should be replaced by 2. | n = int(input())
def process(A):
d = [0, 0, 0]
for x in A:
d[x-1]+=1
return sum(d)-max(d)
A = [int(x) for x in input().split()]
print(process(A)) | {
"input": [
"9\n1 3 2 2 2 1 1 2 3\n"
],
"output": [
"5\n"
]
} |
4,316 | 9 | Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.
A bar of chocolate can be presented as an n Γ n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following q actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.
After each action, he wants to know how many pieces he ate as a result of this action.
Input
The first line contains integers n (1 β€ n β€ 109) and q (1 β€ q β€ 2Β·105) β the size of the chocolate bar and the number of actions.
Next q lines contain the descriptions of the actions: the i-th of them contains numbers xi and yi (1 β€ xi, yi β€ n, xi + yi = n + 1) β the numbers of the column and row of the chosen cell and the character that represents the direction (L β left, U β up).
Output
Print q lines, the i-th of them should contain the number of eaten pieces as a result of the i-th action.
Examples
Input
6 5
3 4 U
6 1 L
2 5 L
1 6 U
4 3 U
Output
4
3
2
1
2
Input
10 6
2 9 U
10 1 U
1 10 U
8 3 L
10 1 L
6 5 U
Output
9
1
10
6
0
2
Note
Pictures to the sample tests:
<image>
The pieces that were eaten in the same action are painted the same color. The pieces lying on the anti-diagonal contain the numbers of the action as a result of which these pieces were eaten.
In the second sample test the Andrewid tries to start eating chocolate for the second time during his fifth action, starting from the cell at the intersection of the 10-th column and the 1-st row, but this cell is already empty, so he does not eat anything. | import sys
from bisect import bisect
def input():
return sys.stdin.readline().strip()
def solve():
n, q = map(int, input().split())
was = set()
Q = [None]*q
all = [0]*(2*q)
for i in range(q):
x, y, t = input().split()
x, y = int(x), int(y)
Q[i] = (x, y, t)
all[2*i] = x
all[2*i+1] = y
all.sort()
sz = 2*q
V = [0]*(2*sz)
H = [0]*(2*sz)
for x, y, t in Q:
if (x,y) in was:
print(0)
else:
was.add((x,y))
if t == 'L':
TA = H
TB = V
else:
x, y = y, x
TA = V
TB = H
v = bisect(all, y) - 1 + sz
r = 0
while v > 0:
r = max(r, TA[v])
v //= 2
c = x - r
print(c)
r = bisect(all, x) - 1 + sz
l = bisect(all, x - c) + sz
while l <= r:
if l % 2 == 1:
TB[l] = max(TB[l], y)
if r % 2 == 0:
TB[r] = max(TB[r], y)
l = (l+1)//2
r = (r-1)//2
solve()
| {
"input": [
"6 5\n3 4 U\n6 1 L\n2 5 L\n1 6 U\n4 3 U\n",
"10 6\n2 9 U\n10 1 U\n1 10 U\n8 3 L\n10 1 L\n6 5 U\n"
],
"output": [
"4\n3\n2\n1\n2\n",
"9\n1\n10\n6\n0\n2\n"
]
} |
4,317 | 8 | The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.
Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.
The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.
Note that all these questions are independent from each other β the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).
Input
The first line of the input contains a single number n (1 β€ n β€ 105) β the number of houses in the capital of Berland.
The second line contains n space-separated positive integers hi (1 β€ hi β€ 109), where hi equals the number of floors in the i-th house.
Output
Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero.
All houses are numbered from left to right, starting from one.
Examples
Input
5
1 2 3 1 2
Output
3 2 0 2 0
Input
4
3 2 1 4
Output
2 3 4 0 | def f(l):
n = len(l)
rl = [0]*n
rm = l[-1]
for i in range(n-2,-1,-1):
rl[i] = max(rm+1-l[i],0)
if l[i]>rm:
rm = l[i]
return rl
_ = input()
l = list(map(int,input().split()))
print(*f(l)) | {
"input": [
"5\n1 2 3 1 2\n",
"4\n3 2 1 4\n"
],
"output": [
" 3 2 0 2 0 ",
" 2 3 4 0 "
]
} |
4,318 | 7 | Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiadβ'1' for a correctly identified cow and '0' otherwise.
However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.
Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substringβthat is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.
Input
The first line contains the number of questions on the olympiad n (1 β€ n β€ 100 000).
The following line contains a binary string of length n representing Kevin's results on the USAICO.
Output
Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.
Examples
Input
8
10000011
Output
5
Input
2
01
Output
2
Note
In the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.
In the second sample, Kevin can flip the entire string and still have the same score. | def solve(s,n):
ans=1
for i in range(n-1):
if s[i]!=s[i+1]:
ans+=1
return min(ans+2,n)
n=int(input())
s=input()
print(solve(s,n))
| {
"input": [
"2\n01\n",
"8\n10000011\n"
],
"output": [
"2",
"5"
]
} |
4,319 | 10 | Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.
Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.
Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.
As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist.
Input
The first line of the input contains a single integer n (1 β€ n β€ 10100 000).
Output
If there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any.
Examples
Input
4
Output
2
Input
11
Output
10
Input
5
Output
0
Input
33
Output
21
Note
In the first sample 4 = 2 + 2, a = 2 is the only possibility.
In the second sample 11 = 10 + 1, a = 10 β the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.
It's easy to check that there is no suitable a in the third sample.
In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer. | def solve(N):
a, b = 0, len(N)-1
Head, Tail = [], []
while a+1 < b:
A = N[a]
B = N[b]
if A%2 != B%2:
A -= 1
N[a+1] += 10
if A > B:
B += 10
N[b-1] -= 1
if A != B:
return False
if A == 0 and a == 0:
return False
if A < 0 or A > 18:
return False
Head.append(A - A//2)
Tail.append(A//2)
a += 1
b -= 1
if a == b: # one digit
if N[a]%2 != 0:
return False
Head.append(N[a]//2);
elif a < b: # two digits
A = N[a]*10 + N[b]
if A%11 != 0:
return False
Head.append(A//11 - A//22)
Tail.append(A//22)
print(*Head, sep='', end='')
Tail.reverse();
print(*Tail, sep='')
return True
def main():
N = list(map(int, input()))
if solve(N[:]):
return
if N[0] == 1 and len(N) > 1:
N[1] += 10
if solve(N[1:]):
return
print(0)
main() | {
"input": [
"5\n",
"11\n",
"4\n",
"33\n"
],
"output": [
"0\n",
"10\n",
"2\n",
"21"
]
} |
4,320 | 7 | There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.
You know the direction of each particle movement β it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.
Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.
Input
The first line contains the positive integer n (1 β€ n β€ 200 000) β the number of particles.
The second line contains n symbols "L" and "R". If the i-th symbol equals "L", then the i-th particle will move to the left, otherwise the i-th symbol equals "R" and the i-th particle will move to the right.
The third line contains the sequence of pairwise distinct even integers x1, x2, ..., xn (0 β€ xi β€ 109) β the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order.
Output
In the first line print the only integer β the first moment (in microseconds) when two particles are at the same point and there will be an explosion.
Print the only integer -1, if the collision of particles doesn't happen.
Examples
Input
4
RLRL
2 4 6 10
Output
1
Input
3
LLR
40 50 60
Output
-1
Note
In the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3.
In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point. |
def main():
n = int(input())
d = input()
x = list(map(int, input().split()))
t = -1
for i in range(len(x) - 1):
if d[i] == 'R' and d[i+1] == 'L':
time = (x[i] + x[i+1]) // 2 - x[i]
t = min(1e10 if t < 0 else t, time)
print(t)
if __name__ == '__main__':
main() | {
"input": [
"4\nRLRL\n2 4 6 10\n",
"3\nLLR\n40 50 60\n"
],
"output": [
"1",
"-1"
]
} |
4,321 | 9 | There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.
Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.
A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.
On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.
<image>
King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
Input
The first line contains number n, which is the number of knights at the round table (3 β€ n β€ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.
Output
Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".
Examples
Input
3
1 1 1
Output
YES
Input
6
1 0 1 1 1 0
Output
YES
Input
6
1 0 0 1 0 1
Output
NO | def find_divs(n):
divs=[]
for i in range(3,n+1):
if n%i==0:
divs.append(n//i)
return divs
n=int(input())
a=[int(i) for i in input().split()]
divs=find_divs(n)
for div in divs:
for shift in range(0, div):
if(all([i==1 for i in [a[j] for j in range(shift, n, div)]])):
print('YES')
quit()
print('NO') | {
"input": [
"6\n1 0 0 1 0 1\n",
"6\n1 0 1 1 1 0\n",
"3\n1 1 1\n"
],
"output": [
"NO\n",
"YES\n",
"YES\n"
]
} |
4,322 | 10 | One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.
Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length
<image> The picture corresponds to the first example
Input
The first line contains single integer n (1 β€ n β€ 5Β·105) β the number of rectangles.
n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 β€ x1 < x2 β€ 109, - 109 β€ y1 < y2 β€ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.
It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.
Output
Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.
Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 β€ ci β€ 4) β the color of i-th rectangle.
Example
Input
8
0 0 5 3
2 -1 5 0
-3 -4 2 -1
-1 -1 2 0
-3 0 0 5
5 2 10 3
7 -3 10 2
4 -2 7 -1
Output
YES
1
2
2
3
2
2
4
1 |
import sys
def rl(): return sys.stdin.readline()
def ni(): return int(rl())
def nsa(): return rl().split()
def nia(): return [int(x) for x in nsa()]
def nnia(n): return [nia() for _ in range(n)]
n = ni()
rects = nnia(n)
print('YES')
for r in rects:
print((r[0]%2)*2+(r[1]%2)+1)
| {
"input": [
"8\n0 0 5 3\n2 -1 5 0\n-3 -4 2 -1\n-1 -1 2 0\n-3 0 0 5\n5 2 10 3\n7 -3 10 2\n4 -2 7 -1\n"
],
"output": [
"YES\n1\n2\n3\n4\n3\n3\n4\n1\n"
]
} |
4,323 | 7 | Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
<image>
In the above formula, 1 β€ l < r β€ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.
Input
The first line contains single integer n (2 β€ n β€ 105) β the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 β€ ai β€ 109) β the array elements.
Output
Print the only integer β the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array. | def f(a):
c, v, m = 0, 0, 1
for i in range(len(a) - 1):
x = m * abs(a[i] - a[i + 1])
c = max(c + x, x)
v = max(v, c)
m *= -1
return v
n, a = int(input()), list(map(int, input().split()))
print(max(f(a), f(a[1:]))) | {
"input": [
"5\n1 4 2 3 1\n",
"4\n1 5 4 7\n"
],
"output": [
"3\n",
"6\n"
]
} |
4,324 | 9 | After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.
Formally the parking can be represented as a matrix 109 Γ 109. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from 1 to 109 from left to right and the rows by integers from 1 to 109 from top to bottom. By coincidence it turned out, that for every cell (x, y) the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells (i, y) and (x, j), 1 β€ i < x, 1 β€ j < y.
<image> The upper left fragment 5 Γ 5 of the parking
Leha wants to ask the watchman q requests, which can help him to find his car. Every request is represented as five integers x1, y1, x2, y2, k. The watchman have to consider all cells (x, y) of the matrix, such that x1 β€ x β€ x2 and y1 β€ y β€ y2, and if the number of the car in cell (x, y) does not exceed k, increase the answer to the request by the number of the car in cell (x, y). For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo 109 + 7.
However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.
Input
The first line contains one integer q (1 β€ q β€ 104) β the number of Leha's requests.
The next q lines contain five integers x1, y1, x2, y2, k (1 β€ x1 β€ x2 β€ 109, 1 β€ y1 β€ y2 β€ 109, 1 β€ k β€ 2Β·109) β parameters of Leha's requests.
Output
Print exactly q lines β in the first line print the answer to the first request, in the second β the answer to the second request and so on.
Example
Input
4
1 1 1 1 1
3 2 5 4 5
1 1 5 5 10000
1 4 2 5 2
Output
1
13
93
0
Note
Let's analyze all the requests. In each case the requested submatrix is highlighted in blue.
In the first request (k = 1) Leha asks only about the upper left parking cell. In this cell the car's number is 1. Consequentally the answer is 1.
<image>
In the second request (k = 5) suitable numbers are 4, 1, 2, 3, 2, 1. Consequentally the answer is 4 + 1 + 2 + 3 + 2 + 1 = 13.
<image>
In the third request (k = 10000) Leha asks about the upper left frament 5 Γ 5 of the parking. Since k is big enough, the answer is equal to 93.
<image>
In the last request (k = 2) none of the cur's numbers are suitable, so the answer is 0.
<image> | mod = 1000000007
def sum(x,y,k,add) :
if k<add:return 0
up=x+add
if up>k:up=k
add=add+1
return y*(((add+up)*(up-add+1)//2)%mod)%mod
def solve(x,y,k,add=0) :
if x==0 or y==0:return 0
if x>y:x,y=y,x
pw = 1
while (pw<<1)<=y:pw<<=1
if pw<=x:return (sum(pw,pw,k,add)+sum(pw,x+y-pw-pw,k,add+pw)+solve(x-pw,y-pw,k,add))%mod
else:return (sum(pw,x,k,add)+solve(x,y-pw,k,add+pw))%mod
q=int(input())
for i in range(0,q):
x1,y1,x2,y2,k=list(map(int,input().split()))
ans=(solve(x2, y2, k)-solve(x1 - 1, y2, k)-solve(x2, y1 - 1, k)+solve(x1-1,y1-1,k))%mod
if ans<0:ans+=mod
print(ans) | {
"input": [
"4\n1 1 1 1 1\n3 2 5 4 5\n1 1 5 5 10000\n1 4 2 5 2\n"
],
"output": [
"1\n13\n93\n0\n"
]
} |
4,325 | 7 | <image>
Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays β caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.
Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):
<image>
After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.
Slastyona managed to have spinner rotating for exactly n seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.
Input
There are two characters in the first string β the starting and the ending position of a spinner. The position is encoded with one of the following characters: v (ASCII code 118, lowercase v), < (ASCII code 60), ^ (ASCII code 94) or > (ASCII code 62) (see the picture above for reference). Characters are separated by a single space.
In the second strings, a single number n is given (0 β€ n β€ 109) β the duration of the rotation.
It is guaranteed that the ending position of a spinner is a result of a n second spin in any of the directions, assuming the given starting position.
Output
Output cw, if the direction is clockwise, ccw β if counter-clockwise, and undefined otherwise.
Examples
Input
^ >
1
Output
cw
Input
< ^
3
Output
ccw
Input
^ v
6
Output
undefined | def main():
a, b = ("v<^>".index(c) for c in input()[::2])
n = int(input())
print(("cw", "ccw")[not (n - a + b) % 4] if n % 2 else "undefined")
if __name__ == '__main__':
main()
| {
"input": [
"^ v\n6\n",
"^ >\n1\n",
"< ^\n3\n"
],
"output": [
"undefined\n",
"undefined\n",
"undefined\n"
]
} |
4,326 | 10 | Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.
You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.
Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.
Input
The first line of input contains three integers n, m and k (1 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ k β€ 106).
The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 β€ di β€ 106, 0 β€ fi β€ n, 0 β€ ti β€ n, 1 β€ ci β€ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.
Output
Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.
If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).
Examples
Input
2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500
Output
24500
Input
2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000
Output
-1
Note
The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.
In the second sample it is impossible to send jury member from city 2 back home from Metropolis. | def main():
n, m, k = map(int, input().split())
ff, tt = [], []
for _ in range(m):
d, f, t, c = map(int, input().split())
if f:
ff.append((d, f, c))
else:
tt.append((-d, t, c))
for ft in ff, tt:
cnt, costs = n, [1000001] * (n + 1)
ft.sort(reverse=True)
while ft:
day, city, cost = ft.pop()
oldcost = costs[city]
if oldcost > cost:
costs[city] = cost
if oldcost == 1000001:
cnt -= 1
if not cnt:
break
else:
print(-1)
return
total = sum(costs) - 1000001
l = [(day, total)]
while ft:
day, city, cost = ft.pop()
oldcost = costs[city]
if oldcost > cost:
total -= oldcost - cost
costs[city] = cost
if l[-1][0] == day:
l[-1] = (day, total)
else:
l.append((day, total))
if ft is ff:
ff = l
else:
tt = l
l, k = [], -k
d, c = tt.pop()
try:
for day, cost in ff:
while d + day >= k:
d, c = tt.pop()
if d + day < k:
l.append(c + cost)
except IndexError:
pass
print(min(l, default=-1))
if __name__ == '__main__':
main()
| {
"input": [
"2 4 5\n1 2 0 5000\n2 1 0 4500\n2 1 0 3000\n8 0 1 6000\n",
"2 6 5\n1 1 0 5000\n3 2 0 5500\n2 2 0 6000\n15 0 2 9000\n9 0 1 7000\n8 0 2 6500\n"
],
"output": [
"-1",
"24500\n"
]
} |
4,327 | 8 | n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
Input
The first line contains two integers: n and k (2 β€ n β€ 500, 2 β€ k β€ 1012) β the number of people and the number of wins.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.
Output
Output a single integer β power of the winner.
Examples
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
Note
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner. | def main():
n,k = map(int,input().split())
l = list(map(int,input().split()))
res = 0
count = 0
if n < k:
res = max(l)
else:
while count != k:
if l[0] > l[1]:
count +=1
l = swap(l,1)
else:
count = 1
l = swap(l,0)
res = l[0]
print(res)
def swap(l, i):
tmp = l[i]
l.pop(i)
l.append(tmp)
return l
main() | {
"input": [
"2 10000000000\n2 1\n",
"6 2\n6 5 3 1 2 4\n",
"2 2\n1 2\n",
"4 2\n3 1 2 4\n"
],
"output": [
"2",
"6",
"2",
"3"
]
} |
4,328 | 10 | Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way:
<image>
This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder of division of polynomial <image> by polynomial <image>, it is also denoted as <image>.
Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials <image>. If the polynomial <image> is zero, the result is <image>, otherwise the result is the value the algorithm returns for pair <image>. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question.
You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair <image> to pair <image>.
Input
You are given a single integer n (1 β€ n β€ 150) β the number of steps of the algorithm you need to reach.
Output
Print two polynomials in the following format.
In the first line print a single integer m (0 β€ m β€ n) β the degree of the polynomial.
In the second line print m + 1 integers between - 1 and 1 β the coefficients of the polynomial, from constant to leading.
The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials.
If there is no answer for the given n, print -1.
If there are multiple answer, print any of them.
Examples
Input
1
Output
1
0 1
0
1
Input
2
Output
2
-1 0 1
1
0 1
Note
In the second example you can print polynomials x2 - 1 and x. The sequence of transitions is
(x2 - 1, x) β (x, - 1) β ( - 1, 0).
There are two steps in it. | """
NTC here
"""
import sys
inp= sys.stdin.readline
input = lambda : inp().strip()
flush= sys.stdout.flush
# import threading
# sys.setrecursionlimit(10**6)
# threading.stack_size(2**25)
def iin(): return int(input())
def lin(): return list(map(int, input().split()))
# range = xrange
# input = raw_input
def main():
n = iin()
ans = [0]*(n+1)
ans[0]=1
ans1 = [0]*(n+1)
sol = 0
# print(ans, ans1)
for i in range(n):
su = ans1[:]
for j in range(n):
su[j+1]+=ans[j]
if su[j+1]>1:su[j+1]=0
# print(1, su, ans)
ans, ans1= su, ans
# print(ans, ans1, mx)
if sol:
print(-1)
else:
m1, m2=0, 0
for i in range(n+1):
if abs(ans[i]):
m1 = i+1
if abs(ans1[i]):
m2 = i+1
print(m1-1)
print( *ans[:m1])
print( m2-1)
print( *ans1[:m2])
main()
# threading.Thread(target=main).start()
| {
"input": [
"2\n",
"1\n"
],
"output": [
"2\n1 0 1 \n1\n0 1 \n",
"1\n0 1 \n0\n1 \n"
]
} |
4,329 | 7 | Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
Input
The first line of the input contains one integer n (1 β€ n β€ 100) β the length of the sequence. The second line contains the sequence consisting of n characters U and R.
Output
Print the minimum possible length of the sequence of moves after all replacements are done.
Examples
Input
5
RUURU
Output
3
Input
17
UUURRRRRUUURURUUU
Output
13
Note
In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13). | import sys
import re
def main():
n, s = sys.stdin.read().strip().split()
return int(n) - len(re.findall('UR|RU', s))
print(main())
| {
"input": [
"17\nUUURRRRRUUURURUUU\n",
"5\nRUURU\n"
],
"output": [
"13\n",
"3\n"
]
} |
4,330 | 10 | This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 β€ i β€ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.
As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.
You can ask questions of form Β«which number was received by student i?Β», and the goal is to determine whether the desired pair exists in no more than 60 questions.
Input
At the beginning the even integer n (2 β€ n β€ 100 000) is given β the total number of students.
You are allowed to ask no more than 60 questions.
Output
To ask the question about the student i (1 β€ i β€ n), you should print Β«? iΒ». Then from standard output you can read the number ai received by student i ( - 109 β€ ai β€ 109).
When you find the desired pair, you should print Β«! iΒ», where i is any student who belongs to the pair (1 β€ i β€ n). If you determined that such pair doesn't exist, you should output Β«! -1Β». In both cases you should immediately terminate the program.
The query that contains your answer is not counted towards the limit of 60 queries.
Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.
Hacking
Use the following format for hacking:
In the first line, print one even integer n (2 β€ n β€ 100 000) β the total number of students.
In the second line print n integers ai ( - 109 β€ ai β€ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1.
The hacked solution will not have direct access to the sequence ai.
Examples
Input
8
<span class="tex-span"></span>
2
<span class="tex-span"></span>
2
Output
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 8
<span class="tex-span"></span>
! 4
Input
6
<span class="tex-span"></span>
1
<span class="tex-span"></span>
2
<span class="tex-span"></span>
3
<span class="tex-span"></span>
2
<span class="tex-span"></span>
1
<span class="tex-span"></span>
0
Output
<span class="tex-span"></span>
? 1
<span class="tex-span"></span>
? 2
<span class="tex-span"></span>
? 3
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 5
<span class="tex-span"></span>
? 6
<span class="tex-span"></span>
! -1
Note
Input-output in statements illustrates example interaction.
In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2
In the second sample the selection sequence is 1, 2, 3, 2, 1, 0. | USE_STDIO = True
import sys
if not USE_STDIO:
try: import mypc
except: pass
def get_two(x, n):
print('?', x)
sys.stdout.flush()
a = int(input())
x += n // 2
if x > n:
x -= n
print('?', x)
sys.stdout.flush()
b = int(input())
return a, b
def answer(x):
print('!', x)
sys.stdout.flush()
def main():
n, = map(int, input().split(' '))
if n % 4 != 0:
answer(-1)
return
x, y = get_two(1, n)
if x == y:
answer(1)
return
l, r = 2, n // 2
for _ in range(30):
mid = (l + r) // 2
xn, yn = get_two(mid, n)
if xn == yn:
answer(mid)
return
if (yn - xn) * (y - x) > 0:
l = mid + 1
else:
r = mid - 1
answer(-1)
if __name__ == '__main__':
main()
| {
"input": [
"8\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n2\n",
"6\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n3 \n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n0"
],
"output": [
"? 1\n? 5\n! 1\n",
"! -1\n"
]
} |
4,331 | 11 | You are given two huge binary integer numbers a and b of lengths n and m respectively. You will repeat the following process: if b > 0, then add to the answer the value a~ \&~ b and divide b by 2 rounding down (i.e. remove the last digit of b), and repeat the process again, otherwise stop the process.
The value a~ \&~ b means bitwise AND of a and b. Your task is to calculate the answer modulo 998244353.
Note that you should add the value a~ \&~ b to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if a = 1010_2~ (10_{10}) and b = 1000_2~ (8_{10}), then the value a~ \&~ b will be equal to 8, not to 1000.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the length of a and the length of b correspondingly.
The second line of the input contains one huge integer a. It is guaranteed that this number consists of exactly n zeroes and ones and the first digit is always 1.
The third line of the input contains one huge integer b. It is guaranteed that this number consists of exactly m zeroes and ones and the first digit is always 1.
Output
Print the answer to this problem in decimal notation modulo 998244353.
Examples
Input
4 4
1010
1101
Output
12
Input
4 5
1001
10101
Output
11
Note
The algorithm for the first example:
1. add to the answer 1010_2~ \&~ 1101_2 = 1000_2 = 8_{10} and set b := 110;
2. add to the answer 1010_2~ \&~ 110_2 = 10_2 = 2_{10} and set b := 11;
3. add to the answer 1010_2~ \&~ 11_2 = 10_2 = 2_{10} and set b := 1;
4. add to the answer 1010_2~ \&~ 1_2 = 0_2 = 0_{10} and set b := 0.
So the answer is 8 + 2 + 2 + 0 = 12.
The algorithm for the second example:
1. add to the answer 1001_2~ \&~ 10101_2 = 1_2 = 1_{10} and set b := 1010;
2. add to the answer 1001_2~ \&~ 1010_2 = 1000_2 = 8_{10} and set b := 101;
3. add to the answer 1001_2~ \&~ 101_2 = 1_2 = 1_{10} and set b := 10;
4. add to the answer 1001_2~ \&~ 10_2 = 0_2 = 0_{10} and set b := 1;
5. add to the answer 1001_2~ \&~ 1_2 = 1_2 = 1_{10} and set b := 0.
So the answer is 1 + 8 + 1 + 0 + 1 = 11. | def get_input_list():
return list(map(int, input().split()))
n, m = get_input_list()
a = input()
b = input()
l = 0
q = 1
v = 0
i = n-1
j = m-1
r = 0
mod = 998244353
while j >= 0:
if i>=0 and a[i] == '1':
v = (v+q)%mod
if b[j] == '1':
r = (r+v)%mod
i -= 1
q = (q << 1)%mod
j -= 1
print(r)
| {
"input": [
"4 4\n1010\n1101\n",
"4 5\n1001\n10101\n"
],
"output": [
"12\n",
"11\n"
]
} |
4,332 | 9 | 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 nice.
A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is t, then for each i, j such that t_i = t_j should be satisfied |i-j|~ mod~ 3 = 0. The value |x| means absolute value of x, the operation x~ mod~ y means remainder of x when divided by y.
For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".
Among all ways to recolor the initial garland to make it nice 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 nice garland from the given one.
In the second line of the output print one string t of length n β a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.
Examples
Input
3
BRB
Output
1
GRB
Input
7
RGBGRBB
Output
3
RGBRGBR | input()
data = input()
patterns = ('RGB', 'RBG', 'GRB', 'GBR', 'BRG', 'BGR')
def dist(s, p):
return sum((1 for i, c in enumerate(s) if p[i % 3] != c))
ds = [(dist(data, p), p) for p in patterns]
n, p = min(ds)
print(n)
print((p * (len(data) // 3 + 3))[:len(data)])
| {
"input": [
"7\nRGBGRBB\n",
"3\nBRB\n"
],
"output": [
"3\nRGBRGBR\n",
"0\nBRB\n"
]
} |
4,333 | 7 | The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.
Future students will be asked just a single question. They are given a sequence of integer numbers a_1, a_2, ..., a_n, each number is from 1 to 3 and a_i β a_{i + 1} for each valid i. The i-th number represents a type of the i-th figure:
1. circle;
2. isosceles triangle with the length of height equal to the length of base;
3. square.
The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:
* (i + 1)-th figure is inscribed into the i-th one;
* each triangle base is parallel to OX;
* the triangle is oriented in such a way that the vertex opposite to its base is at the top;
* each square sides are parallel to the axes;
* for each i from 2 to n figure i has the maximum possible length of side for triangle and square and maximum radius for circle.
Note that the construction is unique for some fixed position and size of just the first figure.
The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?
So can you pass the math test and enroll into Berland State University?
Input
The first line contains a single integer n (2 β€ n β€ 100) β the number of figures.
The second line contains n integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 3, a_i β a_{i + 1}) β types of the figures.
Output
The first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise.
If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.
Examples
Input
3
2 1 3
Output
Finite
7
Input
3
1 2 3
Output
Infinite
Note
Here are the glorious pictures for the examples. Note that the triangle is not equilateral but just isosceles with the length of height equal to the length of base. Thus it fits into a square in a unique way.
The distinct points where figures touch are marked red.
In the second example the triangle and the square touch each other for the whole segment, it contains infinite number of points.
<image> | n = input()
a = [int(x) for x in input().split()]
# circle, triangle, square
def solve():
res = 0
for i in range(1, len(a)):
if (a[i-1], a[i]) in [(3,2), (2,3)]:
print('Infinite')
return
if (a[i-1],a[i]) in [(1,3), (3,1)]:
res += 4
else:
res += 3
if a[i] == 2 and i > 1 and a[i-1] == 1 and a[i-2] == 3:
res -= 1
print('Finite')
print(res)
solve()
| {
"input": [
"3\n2 1 3\n",
"3\n1 2 3\n"
],
"output": [
"Finite\n7",
"Infinite"
]
} |
4,334 | 10 | Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!
When building the graph, he needs four conditions to be satisfied:
* It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops.
* The number of vertices must be exactly n β a number he selected. This number is not necessarily prime.
* The total number of edges must be prime.
* The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime.
Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4.
<image>
Note that the graph can be disconnected.
Please help Bob to find any such graph!
Input
The input consists of a single integer n (3 β€ n β€ 1 000) β the number of vertices.
Output
If there is no graph satisfying the conditions, print a single line containing the integer -1.
Otherwise, first print a line containing a prime number m (2 β€ m β€ (n(n-1))/(2)) β the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 β€ u_i, v_i β€ n) β meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops.
If there are multiple solutions, you may print any of them.
Note that the graph can be disconnected.
Examples
Input
4
Output
5
1 2
1 3
2 3
2 4
3 4
Input
8
Output
13
1 2
1 3
2 3
1 4
2 4
1 5
2 5
1 6
2 6
1 7
1 8
5 8
7 8
Note
The first example was described in the statement.
In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied.
<image> | n = int(input())
def pr(x):
for i in range(2, x):
if x % i == 0:
return False
return True
e = []
for i in range(n):
e += [[i, (i+1) % n]]
x = n
u = 0
v = n // 2
while not pr(x):
e += [[u, v]]
x += 1
u += 1
v += 1
print(x)
for g in e:
print(g[0]+1, g[1]+1) | {
"input": [
"4\n",
"8\n"
],
"output": [
"5\n1 2\n2 3\n3 4\n4 1\n1 3\n",
"11\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 1\n1 5\n2 6\n3 7\n"
]
} |
4,335 | 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 β€ 2000) β the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1 β€ k β€ n β€ 2000) β 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 2000 (β n β€ 2000).
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". | def rgb(n, k, s):
t, result = 'RGB', list()
for i in range(n - k + 1):
for j in range(3):
count = 0
for z in range(k):
if s[i + z] != t[(z + j) % 3]:
count += 1
result.append(count)
return min(result)
q = int(input())
lst = list()
for y in range(q):
N, K = [int(w) for w in input().split()]
v = input()
lst.append(rgb(N, K, v))
for elem in lst:
print(elem)
| {
"input": [
"3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR\n"
],
"output": [
"1\n0\n3\n"
]
} |
4,336 | 11 | You are given two strings s and t both of length 2 and both consisting only of characters 'a', 'b' and 'c'.
Possible examples of strings s and t: "ab", "ca", "bb".
You have to find a string res consisting of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and t should not occur in res as substrings.
A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc".
If there are multiple answers, you can print any of them.
Input
The first line of the input contains one integer n (1 β€ n β€ 10^5) β the number of characters 'a', 'b' and 'c' in the resulting string.
The second line of the input contains one string s of length 2 consisting of characters 'a', 'b' and 'c'.
The third line of the input contains one string t of length 2 consisting of characters 'a', 'b' and 'c'.
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 res on the second line. res should consist of 3n characters, n characters should be 'a', n characters should be 'b' and n characters should be 'c' and s and t should not occur in res as substrings.
If there are multiple answers, you can print any of them.
Examples
Input
2
ab
bc
Output
YES
acbbac
Input
3
aa
bc
Output
YES
cacbacbab
Input
1
cb
ac
Output
YES
abc | from itertools import permutations
def good(s, t, r):
for i in range(len(s) - 1):
pa = s[i:i + 2]
if pa == t or pa == r:
return False
return True
n = int(input())
s = input()
t = input()
l = []
for p in permutations('abc'):
l.append(p[0]*n + p[1]*n + p[2]*n)
l.append((p[0] + p[1] + p[2]) * n)
print('YES')
for x in l:
if(good(x, s, t)):
print(x)
exit() | {
"input": [
"3\naa\nbc\n",
"1\ncb\nac\n",
"2\nab\nbc\n"
],
"output": [
"YES\nacbacbacb",
"YES\nabc",
"YES\nacbacb"
]
} |
4,337 | 7 | Another Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced β their sum is equal to 0.
Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.
There are two conditions though:
* For each participant i, their modified rating change b_i must be integer, and as close to (a_i)/(2) as possible. It means that either b_i = β (a_i)/(2) β or b_i = β (a_i)/(2) β. In particular, if a_i is even, b_i = (a_i)/(2). Here β x β denotes rounding down to the largest integer not greater than x, and β x β denotes rounding up to the smallest integer not smaller than x.
* The modified rating changes must be perfectly balanced β their sum must be equal to 0.
Can you help with that?
Input
The first line contains a single integer n (2 β€ n β€ 13 845), denoting the number of participants.
Each of the next n lines contains a single integer a_i (-336 β€ a_i β€ 1164), denoting the rating change of the i-th participant.
The sum of all a_i is equal to 0.
Output
Output n integers b_i, each denoting the modified rating change of the i-th participant in order of input.
For any i, it must be true that either b_i = β (a_i)/(2) β or b_i = β (a_i)/(2) β. The sum of all b_i must be equal to 0.
If there are multiple solutions, print any. We can show that a solution exists for any valid input.
Examples
Input
3
10
-5
-5
Output
5
-2
-3
Input
7
-7
-29
0
3
24
-29
38
Output
-3
-15
0
2
12
-15
19
Note
In the first example, b_1 = 5, b_2 = -3 and b_3 = -2 is another correct solution.
In the second example there are 6 possible solutions, one of them is shown in the example output. |
def read():
return (input() )
n = int (read() )
sign = 1
for i in range(n ) :
x = int(read())
if x%2 == 0 :
print(int(x/2 ) )
else :
sign = sign*(-1)
k = (x+sign)/2
print(int(k ))
| {
"input": [
"3\n10\n-5\n-5\n",
"7\n-7\n-29\n0\n3\n24\n-29\n38\n"
],
"output": [
"5\n-2\n-3\n",
"-4\n-14\n0\n1\n12\n-14\n19\n"
]
} |
4,338 | 11 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.
Given an undirected labeled tree consisting of n vertices, find a set of segments such that:
1. both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n should appear as an endpoint of exactly one segment;
2. all segments are non-degenerate;
3. for each pair (i, j) such that i β j, i β [1, n] and j β [1, n], the vertices i and j are connected with an edge if and only if the segments i and j intersect, but neither segment i is fully contained in segment j, nor segment j is fully contained in segment i.
Can you solve this problem too?
Input
The first line contains one integer n (1 β€ n β€ 5 β
10^5) β the number of vertices in the tree.
Then n - 1 lines follow, each containing two integers x_i and y_i (1 β€ x_i, y_i β€ n, x_i β y_i) denoting the endpoints of the i-th edge.
It is guaranteed that the given graph is a tree.
Output
Print n pairs of integers, the i-th pair should contain two integers l_i and r_i (1 β€ l_i < r_i β€ 2n) β the endpoints of the i-th segment. All 2n integers you print should be unique.
It is guaranteed that the answer always exists.
Examples
Input
6
1 2
1 3
3 4
3 5
2 6
Output
9 12
7 10
3 11
1 5
2 4
6 8
Input
1
Output
1 2 | def main():
import sys
input = sys.stdin.buffer.readline
N = int(input())
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
st = [1]
seen = [0] * (N+1)
seen[1] = 1
LL = [0] * (2 * N + 3)
LL[-1] = 1
LL[1] = 0
LL_rev = [0] * (2 * N + 3)
LL_rev[1] = -1
LL_rev[-1] = 0
st_append = st.append
while st:
v = st.pop()
for u in adj[v]:
if not seen[u]:
seen[u] = 1
st_append(u)
v_next = LL[v]
v_prev = LL_rev[v]
LL[v] = u
LL[u] = v_next
LL_rev[v_next] = u
LL_rev[u] = v
u_ = -u
LL_rev[v] = u_
#LL_rev[u_] = v_prev
LL[v_prev] = u_
LL[u_] = v
s = -1
ans1 = [0] * (N + 1)
ans2 = [0] * (N + 1)
for i in range(1, 2 * N + 1):
if s < 0:
ans1[-s] = i
else:
ans2[s] = i
s = LL[s]
ans = '\n'.join([' '.join(map(str, [ans1[i], ans2[i]])) for i in range(1, N + 1)])
sys.stdout.write(ans)
if __name__ == '__main__':
main()
| {
"input": [
"6\n1 2\n1 3\n3 4\n3 5\n2 6\n",
"1\n"
],
"output": [
"1 4\n3 6\n2 10\n9 11\n8 12\n5 7\n",
"1 2\n"
]
} |
4,339 | 8 | Guy-Manuel and Thomas are going to build a polygon spaceship.
You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation:
<image>
Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored:
<image>
The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are [similar](https://tinyurl.com/vp5m7vl).
Input
The first line of input will contain a single integer n (3 β€ n β€ 10^5) β the number of points.
The i-th of the next n lines contains two integers x_i, y_i (|x_i|, |y_i| β€ 10^9), denoting the coordinates of the i-th vertex.
It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.
Output
Output "YES" in a separate line, if P and T are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).
Examples
Input
4
1 0
4 1
3 4
0 3
Output
YES
Input
3
100 86
50 0
150 0
Output
nO
Input
8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
Output
YES
Note
The following image shows the first sample: both P and T are squares. The second sample was shown in the statements.
<image> |
def main():
N = int(input())
if N % 2:
print("NO")
return
pts = [complex(*map(int, input().strip().split())) for _ in range(N)]
for i in range(N // 2):
if pts[i] + pts[i + N // 2] != pts[0] + pts[N // 2]:
print("NO")
return
print("YES")
main()
| {
"input": [
"3\n100 86\n50 0\n150 0\n",
"4\n1 0\n4 1\n3 4\n0 3\n",
"8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3\n"
],
"output": [
"NO\n",
"YES\n",
"YES\n"
]
} |
4,340 | 11 | Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
t = int(input())
ans = array('i', [0]) * t
mod = 10**9 + 7
for i in range(t):
n, p = map(int, input().split())
a = sorted(map(int, input().split()), reverse=True)
if p == 1:
ans[i] = n & 1
continue
v, prev = 0, a[0]
for x in a:
if v > 0:
for _ in range(prev, x, -1):
v *= p
if v > n:
v = -1
break
prev = x
if v == 0:
ans[i] = (ans[i] + pow(p, x, mod)) % mod
v += 1
else:
ans[i] = (ans[i] - pow(p, x, mod)) % mod
v -= 1
sys.stdout.buffer.write('\n'.join(map(str, ans)).encode('utf-8'))
| {
"input": [
"4\n5 2\n2 3 4 4 3\n3 1\n2 10 1000\n4 5\n0 1 1 100\n1 8\n89\n"
],
"output": [
"4\n1\n146981438\n747093407\n"
]
} |
4,341 | 7 | Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, β¦, p_k (k β₯ 1; 1 β€ p_i β€ n; p_i β p_j if i β j) of A such that A_{p_1} = A_{p_2} = β¦ = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, β¦, p_k to letter y. More formally: for each i (1 β€ i β€ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 10) β the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 β€ n β€ 10^5) β the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b β \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} β b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc β \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c β t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} β ts\color{blue}{r}). | def dfs(u):V[u]=0;return sum(dfs(v)for v in g[u]if V[v])+1
I=input
for _ in[0]*int(I()):
I();V=[1]*117;g=[[]for _ in V];f=0
for x,y in zip(map(ord,I()),map(ord,I())):f|=x>y;g[x]+=y,;g[y]+=x,
print((sum(dfs(i)-1for i in range(117)if V[i]),-1)[f]) | {
"input": [
"5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda\n"
],
"output": [
"2\n-1\n3\n2\n-1\n"
]
} |
4,342 | 7 | A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
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 two integers n and k (2 β€ k β€ n β€ 3 β
10^5, k is even) β the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s| = n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3 β
10^5.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
Input
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
Output
YES
YES
NO
YES
YES
NO
NO
YES
NO
Note
For the first test case, the string is already a 4-balanced bitstring.
For the second test case, the string can be transformed into 101.
For the fourth test case, the string can be transformed into 0110.
For the fifth test case, the string can be transformed into 1100110. | from collections import Counter
def func(s,k):
r = [None]*k
for i in range(len(s)):
if s[i]!="?":
if r[i%k]==None:
r[i%k] = s[i]
elif r[i%k]!=s[i]:
return False
c = Counter(r)
return abs(c['0']-c['1'])<=c[None]
for _ in range(int(input())):
n,k = map(int,input().split())
s = input()
print("YES" if func(s,k) else "NO") | {
"input": [
"9\n6 4\n100110\n3 2\n1?1\n3 2\n1?0\n4 4\n????\n7 4\n1?0??1?\n10 10\n11??11??11\n4 2\n1??1\n4 4\n?0?0\n6 2\n????00\n"
],
"output": [
"YES\nYES\nNO\nYES\nYES\nNO\nNO\nYES\nNO\n"
]
} |
4,343 | 10 | You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4β
LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
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.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 5000) β lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters β string A.
The third line contains a string consisting of m lowercase Latin letters β string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 β
|abb|) - |abb| - |abab| = 4 β
3 - 3 - 4 = 5. | def lcs(s1,s2):
dp=[[0 for _ in range(m+1)]for _ in range(n+1)]
ans=0
for i in range(1,n+1):
for j in range(1,m+1):
if s1[i-1]==s2[j-1]:
dp[i][j]=2+dp[i-1][j-1]
else:
dp[i][j]=max(-1+dp[i-1][j],dp[i][j-1]-1,0)
ans=max(ans,dp[i][j])
return ans
n,m=map(int,input().split())
s1=input()
s2=input()
print(lcs(s1, s2))
| {
"input": [
"7 7\nuiibwws\nqhtkxcn\n",
"4 5\nabba\nbabab\n",
"8 10\nbbbbabab\nbbbabaaaaa\n"
],
"output": [
"0\n",
"5\n",
"12\n"
]
} |
4,344 | 10 | During their New Year holidays, Alice and Bob play the following game using an array a of n integers:
* Players take turns, Alice moves first.
* Each turn a player chooses any element and removes it from the array.
* If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change.
* Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change.
If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared.
For example, if n = 4 and a = [5, 2, 7, 3], then the game could go as follows (there are other options):
* On the first move, Alice chooses 2 and get two points. Her score is now 2. The array a is now [5, 7, 3].
* On the second move, Bob chooses 5 and get five points. His score is now 5. The array a is now [7, 3].
* On the third move, Alice chooses 7 and get no points. Her score is now 2. The array a is now [3].
* On the last move, Bob chooses 3 and get three points. His score is now 8. The array a is empty now.
* Since Bob has more points at the end of the game, he is the winner.
You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array.
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case contains an integer n (1 β€ n β€ 2 β
10^5) β the number of elements in the array a.
The next line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the array a used to play the game.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output on a separate line:
* "Alice" if Alice wins with the optimal play;
* "Bob" if Bob wins with the optimal play;
* "Tie", if a tie is declared during the optimal play.
Example
Input
4
4
5 2 7 3
3
3 2 1
4
2 2 2 2
2
7 8
Output
Bob
Tie
Alice
Alice | import sys
# sys.stdin = open('input.txt','r')
input = sys.stdin.readline
def greater(a, b):
return a > b
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
ans = 0
for i in range(n):
if i % 2 == 0:
if a[i] % 2 == 0:
ans += a[i]
else:
if a[i] % 2 == 1:
ans -= a[i]
if ans == 0:
print("Tie")
elif ans > 0:
print("Alice")
else:
print("Bob")
| {
"input": [
"4\n4\n5 2 7 3\n3\n3 2 1\n4\n2 2 2 2\n2\n7 8\n"
],
"output": [
"\nBob\nTie\nAlice\nAlice\n"
]
} |
4,345 | 11 | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: <https://codeforces.com/blog/entry/45307>.
There is a city in which Dixit lives. In the city, there are n houses. There is exactly one directed road between every pair of houses. For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the i-th house is k_i.
Two houses A and B are bi-reachable if A is reachable from B and B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B.
Dixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of |k_A - k_B|, where k_i is the number of roads leading to the house i. If more than one optimal pair exists, any of them is suitable.
Since Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist?
In the problem input, you are not given the direction of each road. You are given β for each house β only the number of incoming roads to that house (k_i).
You are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is no upper limit on the number of queries. But, you cannot ask more queries after the judge answers "Yes" to any of your queries. Also, you cannot ask the same query twice.
Once you have exhausted all your queries (or the judge responds "Yes" to any of your queries), your program must output its guess for the two houses and quit.
See the Interaction section below for more details.
Input
The first line contains a single integer n (3 β€ n β€ 500) denoting the number of houses in the city. The next line contains n space-separated integers k_1, k_2, ..., k_n (0 β€ k_i β€ n - 1), the i-th of them represents the number of incoming roads to the i-th house.
Interaction
To ask a query, print "? A B" (1 β€ A,B β€ N, Aβ B). The judge will respond "Yes" if house B is reachable from house A, or "No" otherwise.
To output the final answer, print "! A B", where A and B are bi-reachable with the maximum possible value of |k_A - k_B|. If there does not exist such pair of houses A and B, output "! 0 0".
After outputting the final answer, your program must terminate immediately, otherwise you will receive Wrong Answer verdict.
You cannot ask the same query twice. There is no upper limit to the number of queries you ask, but, you cannot ask more queries after the judge answers "Yes" to any of your queries. Your program must now output the final answer ("! A B" or "! 0 0") and terminate.
If you ask a query in incorrect format or repeat a previous query, you will get Wrong Answer verdict.
After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get the Idleness limit exceeded error. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Examples
Input
3
1 1 1
Yes
Output
? 1 2
! 1 2
Input
4
1 2 0 3
No
No
No
No
No
No
Output
? 2 1
? 1 3
? 4 1
? 2 3
? 4 2
? 4 3
! 0 0
Note
In the first sample input, we are given a city of three houses with one incoming road each. The user program asks one query: "? 1 2": asking whether we can reach from house 1 to house 2. The judge responds with "Yes". The user program now concludes that this is sufficient information to determine the correct answer. So, it outputs "! 1 2" and quits.
In the second sample input, the user program queries for six different pairs of houses, and finally answers "! 0 0" as it is convinced that no two houses as desired in the question exist in this city. | import sys
def guess(i, j):
print(f"? {i} {j}")
sys.stdout.flush()
return input()
def answer(i, j):
print(f"! {i} {j}")
sys.stdout.flush()
def solve(n, k):
pairs = []
for i in range(len(k)):
for j in range(i+1, len(k)):
pairs.append((abs(k[i] - k[j]), i, j))
for d, i, j in reversed(sorted(pairs)):
a, b = i, j
if k[i] < k[j]:
a, b = b, a
r = guess(a+1, b+1)
if r == "Yes":
answer(a+1, b+1)
return
answer(0, 0)
n = int(input())
k = [int(v) for v in input().split()]
solve(n, k) | {
"input": [
"4\n1 2 0 3\nNo\nNo\nNo\nNo\nNo\nNo",
"3\n1 1 1\nYes"
],
"output": [
"\n? 2 1\n? 1 3\n? 4 1\n? 2 3\n? 4 2\n? 4 3\n! 0 0",
"\n? 1 2\n! 1 2"
]
} |
4,346 | 10 | You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i.
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 β€ 2 β
10^5).
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n) β array a.
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_j - a_i = j - i.
Example
Input
4
6
3 5 1 4 6 6
3
1 2 3
4
1 3 3 4
6
1 6 3 4 5 6
Output
1
3
3
10 | from sys import stdin
def get_ints(): return list(map(int, stdin.readline().strip().split()))
for _ in range(int(input())):
ans = 0
n = int(input())
ar = get_ints()
freq = [0]*(n+1)*2
ans=0
for i in range(n):
ar[i] -= i
ans+=freq[ar[i]+n+1]
freq[ar[i]+n+1]+=1
print(ans) | {
"input": [
"4\n6\n3 5 1 4 6 6\n3\n1 2 3\n4\n1 3 3 4\n6\n1 6 3 4 5 6\n"
],
"output": [
"\n1\n3\n3\n10\n"
]
} |
4,347 | 8 | By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.
In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.
Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).
Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.
To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:
* "Success" if the activation was successful.
* "Already on", if the i-th collider was already activated before the request.
* "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.
The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:
* "Success", if the deactivation was successful.
* "Already off", if the i-th collider was already deactivated before the request.
You don't need to print quotes in the output of the responses to the requests.
Input
The first line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the number of colliders and the number of requests, correspondingly.
Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β activate the i-th collider, or "- i" (without the quotes) β deactivate the i-th collider (1 β€ i β€ n).
Output
Print m lines β the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.
Examples
Input
10 10
+ 6
+ 10
+ 5
- 10
- 5
- 6
+ 10
+ 3
+ 6
+ 3
Output
Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on
Note
Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". | import random, math, sys
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right
from collections import Counter
input = sys.stdin.readline
# Function to call the actual solution
def solution(li, n, m):
s = [[] for i in range(n)]
for j in range(2, n, 2):
s[j] = [2]
for i in range(3, n, 2):
if s[i]:
continue
for j in range(i, n, i):
s[j].append(i)
p, d, r = {}, set(), [''] * m
for j in range(len(li)):
t = li[j][0]
i = int(li[j][1])
if t[0] == '+':
if i in d:
r[j] = 'Already on'
continue
for q in s[i]:
if q in p:
r[j] = 'Conflict with ' + str(p[q])
break
else:
r[j] = 'Success'
d.add(i)
for q in s[i]: p[q] = i
else:
if i in d:
r[j] = 'Success'
for q in s[i]: p.pop(q)
d.remove(i)
else:
r[j] = 'Already off'
return r
# Function to take input
def input_test():
# for _ in range(int(input())):
# n = int(input())
n, m = map(int, input().strip().split(" "))
quer = []
for i in range(m):
qu = list(map(str, input().strip().split(" ")))
quer.append(qu)
# a, b, c = map(int, input().strip().split(" "))
# li = list(map(int, input().strip().split(" ")))
out = solution(quer, n+1, m)
for i in out:
print(i)
# Function to test my code
def test():
pass
# seive()
input_test()
# test() | {
"input": [
"10 10\n+ 6\n+ 10\n+ 5\n- 10\n- 5\n- 6\n+ 10\n+ 3\n+ 6\n+ 3\n"
],
"output": [
"Success\nConflict with 6\nSuccess\nAlready off\nSuccess\nSuccess\nSuccess\nSuccess\nConflict with 10\nAlready on\n"
]
} |
4,348 | 8 | You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0.
Write the program which finds the number of points in the intersection of two given sets.
Input
The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive.
Output
Print the number of points in the intersection or -1 if there are infinite number of points.
Examples
Input
1 1 0
2 2 0
Output
-1
Input
1 1 0
2 -2 0
Output
1 | a,b,c=map(int,input().split())
d,e,f=map(int,input().split())
def F(i,j,k):
return not i and not j and k
print(1 if d*b-a*e else 0 if F(a,b,c) or F(d,e,f) or c*e-b*f or a*f-c*d else -1)
| {
"input": [
"1 1 0\n2 2 0\n",
"1 1 0\n2 -2 0\n"
],
"output": [
"-1",
"1"
]
} |
4,349 | 8 | Emuskald is an avid horticulturist and owns the world's longest greenhouse β it is effectively infinite in length.
Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.
Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.
Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.
Input
The first line of input contains two space-separated integers n and m (1 β€ n, m β€ 5000, n β₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 β€ si β€ m), and one real number xi (0 β€ xi β€ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point.
It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 β€ i < n).
Output
Output a single integer β the minimum number of plants to be replanted.
Examples
Input
3 2
2 1
1 2.0
1 3.100
Output
1
Input
3 3
1 5.0
2 5.5
3 6.0
Output
0
Input
6 3
1 14.284235
2 17.921382
1 20.328172
3 20.842331
1 25.790145
1 27.204125
Output
2
Note
In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.
In the second test case, the species are already in the correct order, so no replanting is needed. | def f(arr):
arr=[None]+arr
dp=[0]*(len(arr))
for i in range(1,len(arr)):
j=int(arr[i])
for k in range(int(j),0,-1):
dp[j]=max(dp[j],1+dp[k])
return len(arr)-max(dp)-1
a,b=map(int,input().strip().split())
lst=[]
for i in range(a):
x,y=map(float,input().strip().split())
lst.append(x)
print(f(lst)) | {
"input": [
"3 2\n2 1\n1 2.0\n1 3.100\n",
"3 3\n1 5.0\n2 5.5\n3 6.0\n",
"6 3\n1 14.284235\n2 17.921382\n1 20.328172\n3 20.842331\n1 25.790145\n1 27.204125\n"
],
"output": [
"1\n",
"0\n",
"2\n"
]
} |
4,350 | 11 | By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:
You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:
1. For given numbers xi and vi assign value vi to element axi.
2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β₯ 2: fi = fi - 1 + fi - 2.
3. For a group of three numbers li ri di you should increase value ax by di for all x (li β€ x β€ ri).
Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2Β·105) β the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 β€ ai β€ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 β€ ti β€ 3) β the operation type:
* if ti = 1, then next follow two integers xi vi (1 β€ xi β€ n, 0 β€ vi β€ 105);
* if ti = 2, then next follow two integers li ri (1 β€ li β€ ri β€ n);
* if ti = 3, then next follow three integers li ri di (1 β€ li β€ ri β€ n, 0 β€ di β€ 105).
The input limits for scoring 30 points are (subproblem E1):
* It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.
The input limits for scoring 70 points are (subproblems E1+E2):
* It is guaranteed that there will be queries of the 1-st and 2-nd type only.
The input limits for scoring 100 points are (subproblems E1+E2+E3):
* No extra limitations.
Output
For each query print the calculated sum modulo 1000000000 (109).
Examples
Input
5 5
1 3 1 2 4
2 1 4
2 1 5
2 2 4
1 3 10
2 1 5
Output
12
32
8
50
Input
5 4
1 3 1 2 4
3 1 4 1
2 2 4
1 2 10
2 1 5
Output
12
45 | mod = 10**9
FibArray = [1,1]
def fibonacci(n):
if n<=len(FibArray):
return FibArray[n-1]
else:
temp_fib = fibonacci(n-1)+fibonacci(n-2)
FibArray.append(temp_fib)
return temp_fib
n, m = map(int, input().split())
a = list(map(int, input().split()))
for _ in range(m):
query = list(map(int, input().split()))
if query[0]==1:
a[query[1]-1] = query[2]
elif query[0]==3:
d = query[3]
for i in range(query[1]-1, query[2]):
a[i]+=d
else:
l, r = query[1], query[2]
s = 0
for x in range(r-l+1):
# print(fibonacci(x+1), a[l+x-1])
s+=((fibonacci(x+1)*a[l+x-1]))
print(s%mod)
| {
"input": [
"5 4\n1 3 1 2 4\n3 1 4 1\n2 2 4\n1 2 10\n2 1 5\n",
"5 5\n1 3 1 2 4\n2 1 4\n2 1 5\n2 2 4\n1 3 10\n2 1 5\n"
],
"output": [
" 12\n 45\n",
" 12\n 32\n 8\n 50\n"
]
} |
4,351 | 8 | Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 β€ n β€ 500) β amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 β€ Wi β€ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1 | def code(c):
return ord(c) - ord('a')
def main():
a = input()
b = input()
m = int(input())
n = 26
d = [[10 ** 9 for i in range(n)] for j in range(n)]
for i in range(n):
d[i][i] = 0
for i in range(m):
s, t, w = input().split()
w = int(w)
s = code(s)
t = code(t)
d[s][t] = min(d[s][t], w)
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
if len(a) != len(b):
print(-1)
else:
ans = 0
res = []
for i in range(len(a)):
x = code(a[i])
y = code(b[i])
min_c = 'a'
min_cost = 10 ** 9
for j in range(n):
cur = d[x][j] + d[y][j]
if cur < min_cost:
min_cost = cur
min_c = chr(j + ord('a'))
res.append(min_c)
ans += min_cost
if ans >= 10 ** 9:
print(-1)
else:
print(ans)
for j in res:
print(j, end='')
print()
main() | {
"input": [
"uayd\nuxxd\n3\na x 8\nx y 13\nd c 3\n",
"abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0\n",
"a\nb\n3\na b 2\na b 3\nb a 5\n"
],
"output": [
"21\nuxyd\n",
"-1\n",
"2\nb\n"
]
} |
4,352 | 8 | Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | def halyava(lst, t):
count = 1
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if sorted(lst)[j] - sorted(lst)[i] <= t:
count = max(j - i + 1, count)
return count
n = int(input())
b = [int(x) for x in input().split()]
T = int(input())
print(halyava(b, T))
| {
"input": [
"6\n4 1 7 8 3 8\n1\n"
],
"output": [
"3\n"
]
} |
4,353 | 7 | There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 β€ a, b β€ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2 | a,b=map(int,input().split())
def get(a):
return list([i,j] for i in range(1,a) for j in range(1,a) if i*i+j*j==a*a)
A=get(a)
B=get(b)
for [a,b] in A:
for [c,d] in B:
if a*c==b*d and b!=d:
print("YES\n0 0\n%d %d\n%d %d" %(-a,b,c,d))
exit(0)
print("NO") | {
"input": [
"5 5\n",
"5 10\n",
"1 1\n"
],
"output": [
"YES\n0 0\n3 4\n-4 3\n",
"YES\n0 0\n3 4\n-8 6\n",
"NO\n"
]
} |
4,354 | 10 | Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 β€ n β€ 105; 1 β€ k β€ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second | from sys import stdin, setrecursionlimit
setrecursionlimit(200000)
n,k = [int(x) for x in stdin.readline().split()]
tree = {}
for x in range(n):
s = stdin.readline().strip()
cur = tree
for x in s:
if not x in cur:
cur[x] = {}
cur = cur[x]
def forced(tree):
if not tree:
return (False,True)
else:
win = False
lose = False
for x in tree:
a,b = forced(tree[x])
if not a:
win = True
if not b:
lose = True
return (win,lose)
a,b = forced(tree)
if a == 0:
print('Second')
elif a == 1 and b == 1:
print('First')
else:
if k%2 == 0:
print('Second')
else:
print('First')
| {
"input": [
"2 3\na\nb\n",
"3 1\na\nb\nc\n",
"1 2\nab\n"
],
"output": [
"First\n",
"First\n",
"Second\n"
]
} |
4,355 | 8 | As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2).
The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time.
Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.
Input
The first line contains two space-separated positive integers n and k (1 β€ n β€ 100, 1 β€ k β€ 1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 β€ ai β€ 104) β the towers' initial heights.
Output
In the first line print two space-separated non-negative integers s and m (m β€ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that.
In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β j). Note that in the process of performing operations the heights of some towers can become equal to zero.
If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.
Examples
Input
3 2
5 8 5
Output
0 2
2 1
2 3
Input
3 4
2 2 4
Output
1 1
3 2
Input
5 3
8 3 2 6 3
Output
3 3
1 3
1 2
1 3
Note
In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | import itertools
import math
def main():
n, k = map(int, input().split())
a = list(map(int, input().split()))
res = []
for i in range(k):
if max(a) - min(a) <= 1:
break
t = (a.index(max(a)), a.index(min(a)))
res.append(t)
a[t[0]] -= 1
a[t[1]] += 1
print(max(a) - min(a), len(res))
for t in res:
print(t[0] + 1, t[1] + 1)
if __name__ == "__main__":
main()
| {
"input": [
"3 2\n5 8 5\n",
"3 4\n2 2 4\n",
"5 3\n8 3 2 6 3\n"
],
"output": [
"0 2\n2 1\n2 3\n",
"1 1\n3 1\n",
"3 3\n1 3\n1 2\n1 3\n"
]
} |
4,356 | 8 | Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 β€ q β€ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
Output
In the first line output the integer n β the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Examples
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123 | def s():
n = int(input())
m = dict()
r = []
for _ in range(n):
a = input().split(' ')
i = len(r)
if a[0] not in m:
r.append(a)
m[a[0]] = i
else:
i = m[a[0]]
del m[a[0]]
r[i][1] = a[1]
m[r[i][1]] = i
print(len(r))
print(*[' '.join(i) for i in r], sep='\n')
s() | {
"input": [
"5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov\n"
],
"output": [
"3\nMisha MikeMirzayanov\nVasya VasyaPetrov123\nPetya Ivanov\n"
]
} |
4,357 | 9 | Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.
Input
The first line contains two integers w, m (2 β€ w β€ 109, 1 β€ m β€ 109) β the number defining the masses of the weights and the mass of the item.
Output
Print word 'YES' if the item can be weighted and 'NO' if it cannot.
Examples
Input
3 7
Output
YES
Input
100 99
Output
YES
Input
100 50
Output
NO
Note
Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1.
Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.
Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. | def main():
w, m = map(int, input().split())
while m > 1:
c = m % w
if c not in {0, 1, w - 1}:
return print('NO')
m //= w
if c == w - 1:
m += 1
print('YES')
main() | {
"input": [
"3 7\n",
"100 50\n",
"100 99\n"
],
"output": [
"YES\n",
"NO\n",
"YES\n"
]
} |
4,358 | 9 | There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | from math import floor
def main():
a, b = map(int, input().split())
if (b > a):
print(-1)
return
y = (a + b) / 2
k = y // b
print(y / k)
main() | {
"input": [
"1 3\n",
"4 1\n",
"3 1\n"
],
"output": [
"-1\n",
"1.2500000000\n",
"1.0000000000\n"
]
} |
4,359 | 8 | You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the sizes of arrays a and b.
The second line contains n integers β the elements of array a ( - 109 β€ ai β€ 109).
The third line contains m integers β the elements of array b ( - 109 β€ bj β€ 109).
Output
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
Examples
Input
5 4
1 3 5 7 9
6 4 2 8
Output
3 2 1 4
Input
5 5
1 2 1 2 5
3 1 4 1 5
Output
4 2 4 2 5 | import bisect
cin = lambda:map(int,input().split())
def solve():
n, m = cin()
a = cin()
b = cin()
a = sorted(a)
li = [bisect.bisect_right(a, i) for i in b]
print(' '.join(map(str, li)))
solve() | {
"input": [
"5 5\n1 2 1 2 5\n3 1 4 1 5\n",
"5 4\n1 3 5 7 9\n6 4 2 8\n"
],
"output": [
"4 2 4 2 5 ",
"3 2 1 4 "
]
} |
4,360 | 11 | Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.
You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.
Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.
Input
The first line contains integer n (2 β€ n β€ 5Β·105) β the number of vertices in the tree.
Each of the next n - 1 lines contains two integers xi, yi (1 β€ xi, yi β€ n) β the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree.
Output
Print the only integer t β the minimal time required for all ants to be in the root of the tree.
Examples
Input
12
1 2
1 3
1 4
2 5
2 6
3 7
3 8
3 9
8 10
8 11
8 12
Output
6
Input
2
2 1
Output
1 | import sys
def main():
n = int(sys.stdin.buffer.readline().decode('utf-8'))
adj = [[] for _ in range(n)]
deg = [0]*n
for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
adj[u-1].append(v-1)
adj[v-1].append(u-1)
deg[u-1] += 1
deg[v-1] += 1
ans = 0
for x in adj[0]:
depth = []
stack = [(x, 0, 1)]
while stack:
v, par, d = stack.pop()
if deg[v] == 1:
depth.append(d)
else:
for dest in adj[v]:
if dest != par:
stack.append((dest, v, d+1))
depth.sort()
for i in range(1, len(depth)):
depth[i] = max(depth[i], depth[i-1]+1)
ans = max(ans, depth[-1])
print(ans)
if __name__ == '__main__':
main() | {
"input": [
"2\n2 1\n",
"12\n1 2\n1 3\n1 4\n2 5\n2 6\n3 7\n3 8\n3 9\n8 10\n8 11\n8 12\n"
],
"output": [
"1",
"6"
]
} |
4,361 | 7 | There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | def main():
n, a, b = map(int, input().split())
if n > a * b:
print(-1)
return
res = [[0] * b for _ in range(a)]
for i in range(n):
y, x = divmod(i, b)
res[y][b - x - 1 if y & 1 else x] = i + 1
for row in res:
print(' '.join(map(str, row)))
if __name__ == '__main__':
main()
| {
"input": [
"10 2 2\n",
"8 4 3\n",
"3 2 2\n"
],
"output": [
"-1\n",
"1 2 3 \n4 5 6 \n7 8 0 \n0 0 0 \n",
"1 2 \n0 3 \n"
]
} |
4,362 | 7 | It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.
We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each.
For both Adil and Bera the process looks as follows:
1. Choose to stop or to continue to collect bottles.
2. If the choice was to continue then choose some bottle and walk towards it.
3. Pick this bottle and walk to the recycling bin.
4. Go to step 1.
Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.
They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.
Input
First line of the input contains six integers ax, ay, bx, by, tx and ty (0 β€ ax, ay, bx, by, tx, ty β€ 109) β initial positions of Adil, Bera and recycling bin respectively.
The second line contains a single integer n (1 β€ n β€ 100 000) β the number of bottles on the ground.
Then follow n lines, each of them contains two integers xi and yi (0 β€ xi, yi β€ 109) β position of the i-th bottle.
It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct.
Output
Print one real number β the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if <image>.
Examples
Input
3 1 1 2 0 0
3
1 1
2 1
2 3
Output
11.084259940083
Input
5 0 4 2 2 0
5
5 2
3 0
5 5
3 5
3 3
Output
33.121375178000
Note
Consider the first sample.
Adil will use the following path: <image>.
Bera will use the following path: <image>.
Adil's path will be <image> units long, while Bera's path will be <image> units long. | def dis(x1, y1, x2, y2):
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
ax, ay, bx, by, tx, ty = map(int, input().split())
n = int(input())
a, b, s = [], [], 0
for i in range(n):
x, y = map(int, input().split())
dist = dis(tx, ty, x, y)
a.append((dis(ax, ay, x, y) - dist, i))
b.append((dis(bx, by, x, y) - dist, i))
s += dist * 2
a.sort()
b.sort()
if n > 1 and a[0][1] == b[0][1]:
res = min(a[0][0], b[0][0], a[0][0]+b[1][0], a[1][0]+b[0][0])
else:
res = min(a[0][0], b[0][0])
if (n > 1) :
res = min(a[0][0]+b[0][0], res)
print(res + s)
| {
"input": [
"3 1 1 2 0 0\n3\n1 1\n2 1\n2 3\n",
"5 0 4 2 2 0\n5\n5 2\n3 0\n5 5\n3 5\n3 3\n"
],
"output": [
"11.084259940083063\n",
"33.121375178\n"
]
} |
4,363 | 7 | Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special.
Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].
Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible.
You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.
The mex of a set S is a minimum possible non-negative integer that is not in S.
Input
The first line contains two integers n and m (1 β€ n, m β€ 105).
The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 β€ li β€ ri β€ n), that describe the subarray a[li], a[li + 1], ..., a[ri].
Output
In the first line print single integer β the maximum possible minimum mex.
In the second line print n integers β the array a. All the elements in a should be between 0 and 109.
It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109.
If there are multiple solutions, print any of them.
Examples
Input
5 3
1 3
2 5
4 5
Output
2
1 0 2 1 0
Input
4 2
1 4
2 4
Output
3
5 2 0 1
Note
The first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2. | def main():
n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(m)]
z = min(y - x + 1 for x, y in a)
print (z)
print( ' '.join([str(i % z) for i in range(n)]))
main()
| {
"input": [
"4 2\n1 4\n2 4\n",
"5 3\n1 3\n2 5\n4 5\n"
],
"output": [
"3\n0 1 2 0 \n",
"2\n0 1 0 1 0 \n"
]
} |
4,364 | 7 | Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
* Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
<image>
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. 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 polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string si β the name of the i-th polyhedron in Anton's collection. The string can look like this:
* "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.
* "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.
* "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.
* "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.
* "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
Output
Output one number β the total number of faces in all the polyhedrons in Anton's collection.
Examples
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
Note
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces. | def solve():
n=int(input())
c=0
d={"Tetrahedron":4,"Cube":6,"Octahedron":8,"Dodecahedron":12,"Icosahedron":20}
for _ in range(n):
s=input()
c+=d[s]
print(c)
solve()
| {
"input": [
"3\nDodecahedron\nOctahedron\nOctahedron\n",
"4\nIcosahedron\nCube\nTetrahedron\nDodecahedron\n"
],
"output": [
"28\n",
"42\n"
]
} |
4,365 | 7 | Is it rated?
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.
It's known that if at least one participant's rating has changed, then the round was rated for sure.
It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.
In this problem, you should not make any other assumptions about the rating system.
Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.
Input
The first line contains a single integer n (2 β€ n β€ 1000) β the number of round participants.
Each of the next n lines contains two integers ai and bi (1 β€ ai, bi β€ 4126) β the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.
Output
If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".
Examples
Input
6
3060 3060
2194 2194
2876 2903
2624 2624
3007 2991
2884 2884
Output
rated
Input
4
1500 1500
1300 1300
1200 1200
1400 1400
Output
unrated
Input
5
3123 3123
2777 2777
2246 2246
2246 2246
1699 1699
Output
maybe
Note
In the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.
In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.
In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not. | def rate():
a=[]
noTests=int(input())
for i in range(noTests):
ai,bi=map(int,input().strip().split())
if ai!=bi:
return "rated"
a.append(ai)
if a==sorted(a,reverse=True):
return "maybe"
return "unrated"
print(rate())
| {
"input": [
"5\n3123 3123\n2777 2777\n2246 2246\n2246 2246\n1699 1699\n",
"4\n1500 1500\n1300 1300\n1200 1200\n1400 1400\n",
"6\n3060 3060\n2194 2194\n2876 2903\n2624 2624\n3007 2991\n2884 2884\n"
],
"output": [
"maybe\n",
"unrated\n",
"rated\n"
]
} |
4,366 | 8 | There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.
You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order.
You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.
Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.
Input
The first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout.
The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout.
The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.
Output
Print the text if the same keys were pressed in the second layout.
Examples
Input
qwertyuiopasdfghjklzxcvbnm
veamhjsgqocnrbfxdtwkylupzi
TwccpQZAvb2017
Output
HelloVKCup2017
Input
mnbvcxzlkjhgfdsapoiuytrewq
asdfghjklqwertyuiopzxcvbnm
7abaCABAABAcaba7
Output
7uduGUDUUDUgudu7 | def main():
a, b, c = (input() for _ in "abc")
print(c.translate(str.maketrans(a + a.upper(), b + b.upper())))
if __name__ == '__main__':
main()
| {
"input": [
"qwertyuiopasdfghjklzxcvbnm\nveamhjsgqocnrbfxdtwkylupzi\nTwccpQZAvb2017\n",
"mnbvcxzlkjhgfdsapoiuytrewq\nasdfghjklqwertyuiopzxcvbnm\n7abaCABAABAcaba7\n"
],
"output": [
"HelloVKCup2017\n",
"7uduGUDUUDUgudu7\n"
]
} |
4,367 | 10 | Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.
For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:
1. He looks through all the coins from left to right;
2. If he sees that the i-th coin is still in circulation, and (i + 1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (i + 1)-th.
Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.
Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.
The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.
Input
The first line contains single integer n (1 β€ n β€ 300 000) β number of coins that Sasha puts behind Dima.
Second line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right.
Output
Print n + 1 numbers a0, a1, ..., an, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on.
Examples
Input
4
1 3 4 2
Output
1 2 3 2 1
Input
8
6 8 3 4 7 2 1 5
Output
1 2 2 3 4 3 4 5 1
Note
Let's denote as O coin out of circulation, and as X β coin is circulation.
At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.
After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.
XOOO β OOOX
After replacement of the third coin, Dima's actions look this way:
XOXO β OXOX β OOXX
After replacement of the fourth coin, Dima's actions look this way:
XOXX β OXXX
Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n=int(input())
a=list(map(int,input().split()))
r=[1]
c=1
b=[0]*n
for i in range (n):
b[a[i]-1]=1
temp=c
for j in range (n-temp,-1,-1):
if b[j]==1:
c+=1
else:
break
r.append(i+2-c+1)
print(*r) | {
"input": [
"4\n1 3 4 2\n",
"8\n6 8 3 4 7 2 1 5\n"
],
"output": [
"1 2 3 2 1\n",
"1 2 2 3 4 3 4 5 1\n"
]
} |
4,368 | 10 | Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square.
Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.
Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path β a continuous curve, going through the shop, and having the cinema and the house as its ends.
The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2.
Find the maximum distance that Alan and Bob will cover together, discussing the film.
Input
The first line contains two integers: t1, t2 (0 β€ t1, t2 β€ 100). The second line contains the cinema's coordinates, the third one β the house's, and the last line β the shop's.
All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.
Output
In the only line output one number β the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.
Examples
Input
0 2
0 0
4 0
-3 0
Output
1.0000000000
Input
0 0
0 0
2 0
1 0
Output
2.0000000000 | def a():
t1, t2 = map(int, input().split())
cinema = complex(*map(int, input().split()))
house = complex(*map(int, input().split()))
shop = complex(*map(int, input().split()))
cinema_to_house = abs(house - cinema)
cinema_to_shop = abs(shop - cinema)
shop_to_house = abs(house - shop)
alice_max = cinema_to_shop + shop_to_house + t1
bob_max = cinema_to_house + t2
def check(d):
c1, c2, c3 = (cinema, d), (house, bob_max - d), (shop, alice_max - d - shop_to_house)
for i in range(3):
status = intersect(c1, c2)
if status == 0:
return False
if status == 1:
return intersect(c1 if c1[1] < c2[1] else c2, c3)
for intersection in status:
if abs(intersection - c3[0]) - 1e-10 <= c3[1]:
return True
c1, c2, c3 = c2, c3, c1
if cinema_to_shop + shop_to_house <= bob_max:
print(min(alice_max, bob_max))
else:
lower, upper = 0, min(alice_max, bob_max)
while upper - lower > 1e-10:
mid = (lower + upper) * 0.5
if check(mid):
lower = mid
else:
upper = mid
print(lower)
def intersect(a, b):
dif = b[0] - a[0]
dist = abs(dif)
if dist > a[1] + b[1] + 1e-10:
return 0
if dist <= abs(a[1] - b[1]) - 1e-10:
return 1
k = (dist * dist + a[1] * a[1] - b[1] * b[1]) / (2 * dist)
u = dif * k / dist
v = dif * 1j / dist * (a[1] * a[1] - k * k) ** 0.5
return [a[0] + u + v, a[0] + u - v]
a()
| {
"input": [
"0 0\n0 0\n2 0\n1 0\n",
"0 2\n0 0\n4 0\n-3 0\n"
],
"output": [
"2.0000000000\n",
"1.0000000000\n"
]
} |
4,369 | 9 | Imp is watching a documentary about cave painting.
<image>
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.
Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all <image>, 1 β€ i β€ k, are distinct, i. e. there is no such pair (i, j) that:
* 1 β€ i < j β€ k,
* <image>, where <image> is the remainder of division x by y.
Input
The only line contains two integers n, k (1 β€ n, k β€ 1018).
Output
Print "Yes", if all the remainders are distinct, and "No" otherwise.
You can print each letter in arbitrary case (lower or upper).
Examples
Input
4 4
Output
No
Input
5 3
Output
Yes
Note
In the first sample remainders modulo 1 and 4 coincide. | def main():
n, k = map(int, input().split())
for i in range(1, k + 1):
if (n % i != (i - 1)):
print("No")
return
print("Yes")
main() | {
"input": [
"4 4\n",
"5 3\n"
],
"output": [
"No\n",
"Yes\n"
]
} |
4,370 | 10 | Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!
Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles β one bottle of each kind. We know that the volume of milk in each bottle equals w.
When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem β and what is actually the way to do it?
Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!
Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.
Input
The only input data file contains three integers n, w and m (1 β€ n β€ 50, 100 β€ w β€ 1000, 2 β€ m β€ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company.
Output
Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO".
If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 β€ b β€ n). All numbers b on each line should be different.
If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.
Examples
Input
2 500 3
Output
YES
1 333.333333
2 333.333333
2 166.666667 1 166.666667
Input
4 100 5
Output
YES
3 20.000000 4 60.000000
1 80.000000
4 40.000000 2 40.000000
3 80.000000
2 60.000000 1 20.000000
Input
4 100 7
Output
NO
Input
5 500 2
Output
YES
4 250.000000 5 500.000000 2 500.000000
3 500.000000 1 500.000000 4 250.000000 | import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, w, m = map(int, input().split())
w = float(w)
eps = 1e-9
req = n * w / m
cup = [req] * m
ans = [[] for _ in range(m)]
j = 0
for i in range(n):
milk = w
cnt = 0
while j < m and milk > eps:
x = min(milk, cup[j])
milk -= x
cup[j] -= x
ans[j].append(f'{i+1} {x:.8f}')
cnt += 1
if cup[j] < eps:
j += 1
if cnt > 2:
print('NO')
exit()
print('YES')
print('\n'.join(' '.join(line) for line in ans))
| {
"input": [
"5 500 2\n",
"4 100 7\n",
"2 500 3\n",
"4 100 5\n"
],
"output": [
"YES\n1 500.000000 2 500.000000 3 250.000000 \n3 250.000000 4 500.000000 5 500.000000 \n",
"NO\n",
"YES\n1 333.333333 \n1 166.666667 2 166.666667 \n2 333.333333 \n",
"YES\n1 80.000000 \n1 20.000000 2 60.000000 \n2 40.000000 3 40.000000 \n3 60.000000 4 20.000000 \n4 80.000000 \n"
]
} |
4,371 | 8 | You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.
Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".
You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by 1. For example, if you delete the character in the position 2 from the string "exxxii", then the resulting string is "exxii".
Input
The first line contains integer n (3 β€ n β€ 100) β the length of the file name.
The second line contains a string of length n consisting of lowercase Latin letters only β the file name.
Output
Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.
Examples
Input
6
xxxiii
Output
1
Input
5
xxoxx
Output
0
Input
10
xxxxxxxxxx
Output
8
Note
In the first example Polycarp tried to send a file with name contains number 33, written in Roman numerals. But he can not just send the file, because it name contains three letters "x" in a row. To send the file he needs to remove any one of this letters. | import re
def main():
n = int(input())
print(n - len(re.sub('xxx+', 'xx', input())))
if __name__ == '__main__':
main()
| {
"input": [
"10\nxxxxxxxxxx\n",
"5\nxxoxx\n",
"6\nxxxiii\n"
],
"output": [
"8\n",
"0\n",
"1\n"
]
} |
4,372 | 7 | There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.
Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside.
They want to divide the balloons among themselves. In addition, there are several conditions to hold:
* Do not rip the packets (both Grigory and Andrew should get unbroken packets);
* Distribute all packets (every packet should be given to someone);
* Give both Grigory and Andrew at least one packet;
* To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets.
Help them to divide the balloons or determine that it's impossible under these conditions.
Input
The first line of input contains a single integer n (1 β€ n β€ 10) β the number of packets with balloons.
The second line contains n integers: a_1, a_2, β¦, a_n (1 β€ a_i β€ 1000) β the number of balloons inside the corresponding packet.
Output
If it's impossible to divide the balloons satisfying the conditions above, print -1.
Otherwise, print an integer k β the number of packets to give to Grigory followed by k distinct integers from 1 to n β the indices of those. The order of packets doesn't matter.
If there are multiple ways to divide balloons, output any of them.
Examples
Input
3
1 2 1
Output
2
1 2
Input
2
5 5
Output
-1
Input
1
10
Output
-1
Note
In the first test Grigory gets 3 balloons in total while Andrey gets 1.
In the second test there's only one way to divide the packets which leads to equal numbers of balloons.
In the third test one of the boys won't get a packet at all. | def scanf(t=int):
return list(map(t, input().split()))
n, = scanf()
m = scanf()
if n == 1 or n == 2 and m[0] == m[1]:
print(-1)
quit()
i = min(range(n), key=lambda x: m[x])
print(1)
print(i + 1) | {
"input": [
"2\n5 5\n",
"1\n10\n",
"3\n1 2 1\n"
],
"output": [
"-1\n",
"-1\n",
"1\n1\n"
]
} |
4,373 | 9 | Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, β¦, a_{i_k} where 1β€ i_1 < i_2 < β¦ < i_kβ€ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < β¦ < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > β¦ > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 β€ n β€ 10^5) β the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | import math
def listsum(l):
a = []
for i in l:
a = a+i
return a
n = int(input())
m = math.ceil(math.sqrt(n))
a = [" ".join([str(m-i+x*m) for x in range(int((n-m+i)/m)+1)]) for i in range(m)]
print(" ".join(a)) | {
"input": [
"2\n",
"4\n"
],
"output": [
"2 1\n",
"3 4 1 2 \n"
]
} |
4,374 | 10 | You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 β€ n β€ 10^5, 1 β€ s β€ 10^9) β the number of vertices in the tree and the sum of edge weights.
Each of the following nβ1 lines contains two space-separated integer numbers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} β€ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | def main():
n, s = map(int, input().split())
g = [0 for _ in range(n)]
for _ in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a] += 1
g[b] += 1
m = 0
for x in g:
if x == 1:
m += 1
print(2 * s / m)
main()
| {
"input": [
"4 3\n1 2\n1 3\n1 4\n",
"6 1\n2 1\n2 3\n2 5\n5 4\n5 6\n",
"5 5\n1 2\n2 3\n3 4\n3 5\n"
],
"output": [
"2.0\n",
"0.5\n",
"3.3333333333333335\n"
]
} |
4,375 | 8 | Given a string s of length n and integer k (1 β€ k β€ n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s:
* x non-intersecting (non-overlapping) substrings of length k,
* all characters of these x substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings).
A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers i and j (1 β€ i β€ j β€ n), denoted as s[i ... j] = "s_{i}s_{i+1} ... s_{j}".
For example, if k = 2, then:
* the string "aabb" has level 1 (you can select substring "aa"),
* the strings "zzzz" and "zzbzz" has level 2 (you can select two non-intersecting substrings "zz" in each of them),
* the strings "abed" and "aca" have level 0 (you can't find at least one substring of the length k=2 containing the only distinct character).
Zuhair gave you the integer k and the string s of length n. You need to find x, the level of the string s.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the length of the string and the value of k.
The second line contains the string s of length n consisting only of lowercase Latin letters.
Output
Print a single integer x β the level of the string.
Examples
Input
8 2
aaacaabb
Output
2
Input
2 1
ab
Output
1
Input
4 2
abab
Output
0
Note
In the first example, we can select 2 non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is 2.
In the second example, we can select either substring "a" or "b" to get the answer 1. | def check(s,i,k):
for j in range(i+1,i+k):
if s[j]!=s[i]:
return j
return None
n,k=map(int,input().split())
s=input()
i=0
l=[0]*26
while i<n-k+1:
if check(s,i,k)==None:
l[ord(s[i])-97]+=1
i+=k
else:
i=check(s,i,k)
if len(l)!=0:
print(max(l))
else:
print(0)
| {
"input": [
"4 2\nabab\n",
"8 2\naaacaabb\n",
"2 1\nab\n"
],
"output": [
"0\n",
"2\n",
"1\n"
]
} |
4,376 | 11 | You have a set of items, each having some integer weight not greater than 8. You denote that a subset of items is good if total weight of items in the subset does not exceed W.
You want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set when calculating the answer.
Input
The first line contains one integer W (0 β€ W β€ 10^{18}) β the maximum total weight of a good subset.
The second line denotes the set of items you have. It contains 8 integers cnt_1, cnt_2, ..., cnt_8 (0 β€ cnt_i β€ 10^{16}), where cnt_i is the number of items having weight i in the set.
Output
Print one integer β the maximum possible weight of a good subset of items.
Examples
Input
10
1 2 3 4 5 6 7 8
Output
10
Input
0
0 0 0 0 0 0 0 0
Output
0
Input
3
0 4 1 0 0 9 8 3
Output
3 | import os
import sys
from functools import lru_cache, reduce
from io import BytesIO
sys.setrecursionlimit(30000)
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
print = lambda x: os.write(1, str(x).encode())
def main():
init_w = int(input())
cnt = [int(i) for i in input().split()]
dp_cnt = [min(cnt_i, 16) for i, cnt_i in enumerate(cnt)]
greedy_cnt = [cnt_i - dp_cnt_i for cnt_i, dp_cnt_i in zip(cnt, dp_cnt)]
i, w = 8, init_w
while (i > 0) and (w > 0):
w -= i * greedy_cnt[i - 1]
if w < 0:
w %= i
for j in range(2):
w += i if min(greedy_cnt[i - 1], dp_cnt[i - 1]) > j + 1 else 0
i -= 1
weights = reduce(list.__add__, (dp_cnt_i * [i + 1] for i, dp_cnt_i in enumerate(dp_cnt)))
@lru_cache(maxsize=None)
def solve(i, val):
if val == 0:
return True
if i == 0:
return False
return solve(i - 1, val) or solve(i - 1, val - weights[i - 1])
for val in range(min(w, sum(weights)), -1, -1):
if solve(len(weights), val):
print(init_w - w + val)
break
if __name__ == '__main__':
main()
| {
"input": [
"3\n0 4 1 0 0 9 8 3\n",
"10\n1 2 3 4 5 6 7 8\n",
"0\n0 0 0 0 0 0 0 0\n"
],
"output": [
"3",
"10",
"0"
]
} |
4,377 | 7 | It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.
Serval will go to the bus station at time t, and there are n bus routes which stop at this station. For the i-th bus route, the first bus arrives at time s_i minutes, and each bus of this route comes d_i minutes later than the previous one.
As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
Input
The first line contains two space-separated integers n and t (1β€ nβ€ 100, 1β€ tβ€ 10^5) β the number of bus routes and the time Serval goes to the station.
Each of the next n lines contains two space-separated integers s_i and d_i (1β€ s_i,d_iβ€ 10^5) β the time when the first bus of this route arrives and the interval between two buses of this route.
Output
Print one number β what bus route Serval will use. If there are several possible answers, you can print any of them.
Examples
Input
2 2
6 4
9 5
Output
1
Input
5 5
3 3
2 5
5 6
4 9
6 1
Output
3
Input
3 7
2 2
2 3
2 4
Output
1
Note
In the first example, the first bus of the first route arrives at time 6, and the first bus of the second route arrives at time 9, so the first route is the answer.
In the second example, a bus of the third route arrives at time 5, so it is the answer.
In the third example, buses of the first route come at times 2, 4, 6, 8, and so fourth, buses of the second route come at times 2, 5, 8, and so fourth and buses of the third route come at times 2, 6, 10, and so on, so 1 and 2 are both acceptable answers while 3 is not. | def tmax(m, t):
if m[0] >= t:
return m[0]
else:
return t + (m[1] - ((t - m[0]) % m[1])) % m[1]
n, t = map(int, input().split())
print(min([(tmax(list(map(int, input().split())), t), i + 1) for i in range(n)])[1])
| {
"input": [
"3 7\n2 2\n2 3\n2 4\n",
"2 2\n6 4\n9 5\n",
"5 5\n3 3\n2 5\n5 6\n4 9\n6 1\n"
],
"output": [
"1",
"1",
"3"
]
} |
4,378 | 10 | You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | import os
import sys
from bisect import bisect_right
from fractions import Fraction
def main():
n=int(input())
a=list(map(int , input().split()))
arr=a[::-1]
lt=[1]*n
rt=[1]*n
for i in range(n-1):
if a[i]<a[i+1]:
lt[i+1]=lt[i]+1
for i in range(n-1):
if (arr[i]>arr[i+1]):
rt[-i-2]+=rt[-i-1]
ans =max(lt)
for i in range(n-2):
if a[i]<a[i+2]:
ans = max(ans , lt[i]+rt[i+2])
print(ans)
if __name__ == "__main__":
main() | {
"input": [
"7\n6 5 4 3 2 4 3\n",
"5\n1 2 5 3 4\n",
"2\n1 2\n"
],
"output": [
"2",
"4",
"2"
]
} |
4,379 | 11 | You are given a permutation p_1, p_2, ... , p_n (an array where each integer from 1 to n appears exactly once). The weight of the i-th element of this permutation is a_i.
At first, you separate your permutation into two non-empty sets β prefix and suffix. More formally, the first set contains elements p_1, p_2, ... , p_k, the second β p_{k+1}, p_{k+2}, ... , p_n, where 1 β€ k < n.
After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay a_i dollars to move the element p_i.
Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.
For example, if p = [3, 1, 2] and a = [7, 1, 4], then the optimal strategy is: separate p into two parts [3, 1] and [2] and then move the 2-element into first set (it costs 4). And if p = [3, 5, 1, 6, 2, 4], a = [9, 1, 9, 9, 1, 9], then the optimal strategy is: separate p into two parts [3, 5, 1] and [6, 2, 4], and then move the 2-element into first set (it costs 1), and 5-element into second set (it also costs 1).
Calculate the minimum number of dollars you have to spend.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the length of permutation.
The second line contains n integers p_1, p_2, ... , p_n (1 β€ p_i β€ n). It's guaranteed that this sequence contains each element from 1 to n exactly once.
The third line contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ 10^9).
Output
Print one integer β the minimum number of dollars you have to spend.
Examples
Input
3
3 1 2
7 1 4
Output
4
Input
4
2 4 1 3
5 9 8 3
Output
3
Input
6
3 5 1 6 2 4
9 1 9 9 1 9
Output
2 | import sys
from itertools import accumulate
input = sys.stdin.readline
n=int(input())
P=tuple(map(int,input().split()))
A=tuple(map(int,input().split()))
seg_el=1<<((n+1).bit_length())
SEGMIN=[0]*(2*seg_el)
SEGADD=[0]*(2*seg_el)
for i in range(n):
SEGMIN[P[i]+seg_el]=A[i]
SEGMIN=list(accumulate(SEGMIN))
for i in range(seg_el-1,0,-1):
SEGMIN[i]=min(SEGMIN[i*2],SEGMIN[(i*2)+1])
def adds(l,r,x):
L=l+seg_el
R=r+seg_el
while L<R:
if L & 1:
SEGADD[L]+=x
L+=1
if R & 1:
R-=1
SEGADD[R]+=x
L>>=1
R>>=1
L=(l+seg_el)>>1
R=(r+seg_el-1)>>1
while L!=R:
if L>R:
SEGMIN[L]=min(SEGMIN[L*2]+SEGADD[L*2],SEGMIN[1+(L*2)]+SEGADD[1+(L*2)])
L>>=1
else:
SEGMIN[R]=min(SEGMIN[R*2]+SEGADD[R*2],SEGMIN[1+(R*2)]+SEGADD[1+(R*2)])
R>>=1
while L!=0:
SEGMIN[L]=min(SEGMIN[L*2]+SEGADD[L*2],SEGMIN[1+(L*2)]+SEGADD[1+(L*2)])
L>>=1
S=tuple(accumulate(A))
ANS=1<<31
for i in range(n-1):
adds(P[i],n+1,-A[i]*2)
ANS=min(ANS,SEGMIN[1]+S[i])
print(ANS)
| {
"input": [
"6\n3 5 1 6 2 4\n9 1 9 9 1 9\n",
"4\n2 4 1 3\n5 9 8 3\n",
"3\n3 1 2\n7 1 4\n"
],
"output": [
"2\n",
"3\n",
"4\n"
]
} |
4,380 | 11 | Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of p players playing in p different positions. She also recognizes the importance of audience support, so she wants to select k people as part of the audience.
There are n people in Byteland. Alice needs to select exactly p players, one for each position, and exactly k members of the audience from this pool of n people. Her ultimate goal is to maximize the total strength of the club.
The i-th of the n persons has an integer a_{i} associated with him β the strength he adds to the club if he is selected as a member of the audience.
For each person i and for each position j, Alice knows s_{i, j} β the strength added by the i-th person to the club if he is selected to play in the j-th position.
Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.
Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.
Input
The first line contains 3 integers n,p,k (2 β€ n β€ 10^{5}, 1 β€ p β€ 7, 1 β€ k, p+k β€ n).
The second line contains n integers a_{1},a_{2},β¦,a_{n}. (1 β€ a_{i} β€ 10^{9}).
The i-th of the next n lines contains p integers s_{i, 1}, s_{i, 2}, ..., s_{i, p}. (1 β€ s_{i,j} β€ 10^{9})
Output
Print a single integer {res} β the maximum possible strength of the club.
Examples
Input
4 1 2
1 16 10 3
18
19
13
15
Output
44
Input
6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
Output
377
Input
3 2 1
500 498 564
100002 3
422332 2
232323 1
Output
422899
Note
In the first sample, we can select person 1 to play in the 1-st position and persons 2 and 3 as audience members. Then the total strength of the club will be equal to a_{2}+a_{3}+s_{1,1}. | import io
import os
# PSA:
# The key optimization that made this pass was to avoid python big ints by using floats (which have integral precision <= 2^52)
# None of the other optimizations really mattered in comparison.
# Credit for this trick goes to pajenegod: https://codeforces.com/blog/entry/77309?#comment-622486
popcount = []
for mask in range(1 << 7):
popcount.append(bin(mask).count("1"))
maskToPos = []
for mask in range(1 << 7):
maskToPos.append([i for i in range(7) if mask & (1 << i)])
inf = float("inf")
def solve(N, P, K, audienceScore, playerScore):
scores = sorted(zip(audienceScore, playerScore), reverse=True)
scoresA = [0.0 for i in range(N)]
scoresP = [0.0 for i in range(7 * N)]
for i, (a, ps) in enumerate(scores):
scoresA[i] = float(a)
for j, p in enumerate(ps):
scoresP[7 * i + j] = float(p)
f = [-inf for mask in range(1 << P)]
nextF = [-inf for mask in range(1 << P)]
f[0] = scoresA[0]
for pos in range(P):
f[1 << pos] = scoresP[pos]
for n in range(1, N):
for mask in range(1 << P):
best = f[mask]
if n - popcount[mask] < K:
best += scoresA[n]
for pos in maskToPos[mask]:
best = max(best, scoresP[7 * n + pos] + f[mask - (1 << pos)])
nextF[mask] = best
f, nextF = nextF, f
return int(max(f))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, P, K = list(map(int, input().split()))
audienceScore = [int(x) for x in input().split()]
playerScore = [[int(x) for x in input().split()] for i in range(N)]
ans = solve(N, P, K, audienceScore, playerScore)
print(ans)
| {
"input": [
"4 1 2\n1 16 10 3\n18\n19\n13\n15\n",
"3 2 1\n500 498 564\n100002 3\n422332 2\n232323 1\n",
"6 2 3\n78 93 9 17 13 78\n80 97\n30 52\n26 17\n56 68\n60 36\n84 55\n"
],
"output": [
"44",
"422899",
"377"
]
} |
4,381 | 7 | You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{x-1} for j = 1, 2, β¦, k. Note that you are allowed to not select any indices at all.
You have to make a nondecreasing as fast as possible. Find the smallest number T such that you can make the array nondecreasing after at most T seconds.
Array a is nondecreasing if and only if a_{1} β€ a_{2} β€ β¦ β€ a_{n}.
You have to answer t independent test cases.
Input
The first line contains a single integer t (1 β€ t β€ 10^{4}) β the number of test cases.
The first line of each test case contains single integer n (1 β€ n β€ 10^{5}) β the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.
The second line of each test case contains n integers a_{1}, a_{2}, β¦, a_{n} (-10^{9} β€ a_{i} β€ 10^{9}).
Output
For each test case, print the minimum number of seconds in which you can make a nondecreasing.
Example
Input
3
4
1 7 6 5
5
1 2 3 4 5
2
0 -4
Output
2
0
3
Note
In the first test case, if you select indices 3, 4 at the 1-st second and 4 at the 2-nd second, then a will become [1, 7, 7, 8]. There are some other possible ways to make a nondecreasing in 2 seconds, but you can't do it faster.
In the second test case, a is already nondecreasing, so answer is 0.
In the third test case, if you do nothing at first 2 seconds and select index 2 at the 3-rd second, a will become [0, 0]. | def susanoo(x):
ret=0
while x:
ret+=1
x//=2
return ret
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(1,n):
if a[i]<a[i-1]:
d=a[i-1]-a[i]
ans=max(ans,susanoo(d))
a[i]=a[i-1]
print(ans) | {
"input": [
"3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n"
],
"output": [
"2\n0\n3\n"
]
} |
4,382 | 7 | You are given a permutation p_1, p_2, ..., p_n. Recall that sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
Find three indices i, j and k such that:
* 1 β€ i < j < k β€ n;
* p_i < p_j and p_j > p_k.
Or say that there are no such indices.
Input
The first line contains a single integer T (1 β€ T β€ 200) β the number of test cases.
Next 2T lines contain test cases β two lines per test case. The first line of each test case contains the single integer n (3 β€ n β€ 1000) β the length of the permutation p.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n; p_i β p_j if i β j) β the permutation p.
Output
For each test case:
* if there are such indices i, j and k, print YES (case insensitive) and the indices themselves;
* if there are no such indices, print NO (case insensitive).
If there are multiple valid triples of indices, print any of them.
Example
Input
3
4
2 1 4 3
6
4 6 1 2 5 3
5
5 3 1 2 4
Output
YES
2 3 4
YES
3 5 6
NO | def solve(n,a):
for i in range(n-2):
if a[i]<a[i+1]>a[i+2]:return i+1,i+2,i+3
return -1
for _ in range(int(input())):
n=int(input());a=list(map(int,input().split()));s=solve(n,a)
if s==-1:print('NO')
else:print('YES');print(*s) | {
"input": [
"3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 3 1 2 4\n"
],
"output": [
"YES\n2 3 4\nYES\n1 2 3\nNO\n"
]
} |
4,383 | 7 | A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example:
* 10010 and 01111 are similar (they have the same character in position 4);
* 10010 and 11111 are similar;
* 111 and 111 are similar;
* 0110 and 1001 are not similar.
You are given an integer n and a binary string s consisting of 2n-1 characters. Let's denote s[l..r] as the contiguous substring of s starting with l-th character and ending with r-th character (in other words, s[l..r] = s_l s_{l + 1} s_{l + 2} ... s_r).
You have to construct a binary string w of length n which is similar to all of the following strings: s[1..n], s[2..n+1], s[3..n+2], ..., s[n..2n-1].
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 50).
The second line of each test case contains the binary string s of length 2n - 1. Each character s_i is either 0 or 1.
Output
For each test case, print the corresponding binary string w of length n. If there are multiple such strings β print any of them. It can be shown that at least one string w meeting the constraints always exists.
Example
Input
4
1
1
3
00000
4
1110000
2
101
Output
1
000
1010
00
Note
The explanation of the sample case (equal characters in equal positions are bold):
The first test case:
* 1 is similar to s[1..1] = 1.
The second test case:
* 000 is similar to s[1..3] = 000;
* 000 is similar to s[2..4] = 000;
* 000 is similar to s[3..5] = 000.
The third test case:
* 1010 is similar to s[1..4] = 1110;
* 1010 is similar to s[2..5] = 1100;
* 1010 is similar to s[3..6] = 1000;
* 1010 is similar to s[4..7] = 0000.
The fourth test case:
* 00 is similar to s[1..2] = 10;
* 00 is similar to s[2..3] = 01. |
def main():
for _ in range(int(input())):
n = int(input())
s = input()
print(s[::2])
main()
| {
"input": [
"4\n1\n1\n3\n00000\n4\n1110000\n2\n101\n"
],
"output": [
"1\n000\n1100\n11\n"
]
} |
4,384 | 8 | You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p). | def res(n):
nu=s=1
for i in range(n):
nu=(nu*(2*n-i))%m
s=(s*(i+1))%m
return((nu*pow(s,m-2,m))%m)
m=998244353
n=int(input())
fg=sorted(list(map(int,input().split())))
f=abs((sum(fg[:n])-sum(fg[n:])))
print((f*res(n))%m)
#print(f) | {
"input": [
"1\n1 4\n",
"3\n2 2 2 2 2 2\n",
"5\n13 8 35 94 9284 34 54 69 123 846\n",
"2\n2 1 2 1\n"
],
"output": [
"6\n",
"0\n",
"2588544\n",
"12\n"
]
} |
4,385 | 9 | You want to build a fence that will consist of n equal sections. All sections have a width equal to 1 and height equal to k. You will place all sections in one line side by side.
Unfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the i-th section is equal to h_i.
You should follow several rules to build the fence:
1. the consecutive sections should have a common side of length at least 1;
2. the first and the last sections should stand on the corresponding ground levels;
3. the sections between may be either on the ground level or higher, but not higher than k - 1 from the ground level h_i (the height should be an integer);
<image> One of possible fences (blue color) for the first test case
Is it possible to build a fence that meets all rules?
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains two integers n and k (2 β€ n β€ 2 β
10^5; 2 β€ k β€ 10^8) β the number of sections in the fence and the height of each section.
The second line of each test case contains n integers h_1, h_2, ..., h_n (0 β€ h_i β€ 10^8), where h_i is the ground level beneath the i-th section.
It's guaranteed that the sum of n over test cases doesn't exceed 2 β
10^5.
Output
For each test case print YES if it's possible to build the fence that meets all rules. Otherwise, print NO.
You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).
Example
Input
3
6 3
0 0 2 5 1 1
2 3
0 2
3 2
3 0 2
Output
YES
YES
NO
Note
In the first test case, one of the possible fences is shown in the picture.
In the second test case, according to the second rule, you should build both sections on the corresponding ground levels, and since k = 3, h_1 = 0, and h_2 = 2 the first rule is also fulfilled.
In the third test case, according to the second rule, you should build the first section on height 3 and the third section on height 2. According to the first rule, the second section should be on the height of at least 2 (to have a common side with the first section), but according to the third rule, the second section can be built on the height of at most h_2 + k - 1 = 1. | def sv():
N, K = map(int, input().split())
H = list(map(int, input().split()))
a, b = 0, 10000000000
for n, h in enumerate(H):
a = max(a, h)
b = min(b, h+K-1 if n > 0 and n < N-1 else h)
if a>b: return False
a -= K-1
b += K-1
return True
TC = int(input())
for tc in range(TC):
print('YES' if sv() else 'NO')
| {
"input": [
"3\n6 3\n0 0 2 5 1 1\n2 3\n0 2\n3 2\n3 0 2\n"
],
"output": [
"\nYES\nYES\nNO\n"
]
} |
4,386 | 11 | You are given a directed graph consisting of n vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.
You should process m queries with it. Each query is one of three types:
* "+ u v c" β add arc from u to v with label c. It's guaranteed that there is no arc (u, v) in the graph at this moment;
* "- u v" β erase arc from u to v. It's guaranteed that the graph contains arc (u, v) at this moment;
* "? k" β find the sequence of k vertices v_1, v_2, ..., v_k such that there exist both routes v_1 β v_2 β ... β v_k and v_k β v_{k - 1} β ... β v_1 and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times.
Input
The first line contains two integers n and m (2 β€ n β€ 2 β
10^5; 1 β€ m β€ 2 β
10^5) β the number of vertices in the graph and the number of queries.
The next m lines contain queries β one per line. Each query is one of three types:
* "+ u v c" (1 β€ u, v β€ n; u β v; c is a lowercase Latin letter);
* "- u v" (1 β€ u, v β€ n; u β v);
* "? k" (2 β€ k β€ 10^5).
It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type.
Output
For each query of the third type, print YES if there exist the sequence v_1, v_2, ..., v_k described above, or NO otherwise.
Example
Input
3 11
+ 1 2 a
+ 2 3 b
+ 3 2 a
+ 2 1 b
? 3
? 2
- 2 1
- 3 2
+ 2 1 c
+ 3 2 d
? 5
Output
YES
NO
YES
Note
In the first query of the third type k = 3, we can, for example, choose a sequence [1, 2, 3], since 1 \xrightarrow{a} 2 \xrightarrow{b} 3 and 3 \xrightarrow{a} 2 \xrightarrow{b} 1.
In the second query of the third type k = 2, and we can't find sequence p_1, p_2 such that arcs (p_1, p_2) and (p_2, p_1) have the same characters.
In the third query of the third type, we can, for example, choose a sequence [1, 2, 3, 2, 1], where 1 \xrightarrow{a} 2 \xrightarrow{b} 3 \xrightarrow{d} 2 \xrightarrow{c} 1. | def solve():
n, m = map(int, input().split());e = dict();same = 0;diff = 0;res = []
for i in range(m):
a = input().split();c = a[0]
if c == '+':
u = int(a[1]);v = int(a[2]);c = a[3];z = e.get((v,u),None)
if z == c: same += 1
elif z is not None: diff += 1
e[(u,v)] = c
elif c == '-':
u = int(a[1]);v = int(a[2]);c = e[(u,v)];del e[(u,v)];z = e.get((v,u),None)
if z == c: same -= 1
elif z is not None: diff -= 1
else:
c = int(a[1])
if c % 2 == 1: res.append('YES' if diff + same > 0 else 'NO')
else: res.append('YES' if same > 0 else 'NO')
print('\n'.join(res))
solve() | {
"input": [
"3 11\n+ 1 2 a\n+ 2 3 b\n+ 3 2 a\n+ 2 1 b\n? 3\n? 2\n- 2 1\n- 3 2\n+ 2 1 c\n+ 3 2 d\n? 5\n"
],
"output": [
"\nYES\nNO\nYES\n"
]
} |
4,387 | 10 | You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size nΓ m. The set of vertices is \{(i, j)|1β€ iβ€ n, 1β€ jβ€ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2β€ n, mβ€ 500, 1β€ kβ€ 20).
The j-th number (1β€ j β€ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1β€ jβ€ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) β (1,1) β (1,2) β (2,2) β (2,1), the boredness is 4 + 1 + 2 + 3 = 10. | def roll(i,j):
ways = []
if j:
ways.append(2*hor[i][j-1] + grid[i][j-1])
if m-1-j:
ways.append(2*hor[i][j] + grid[i][j+1])
if i:
ways.append(2*ver[i-1][j] + grid[i-1][j])
if n-1-i:
ways.append(2*ver[i][j] + grid[i+1][j])
return min(ways)
n , m , k = map(int, input().split())
hor = [list(map(int, input().split())) for _ in range(n)]
ver = [list(map(int, input().split())) for _ in range(n-1)]
grid = [[0]*m for _ in range(n)]
if k%2:
for _ in range(n):
print(" ".join(["-1"]*m))
else:
for _ in range(k//2):
new_grid = [[roll(i,j) for j in range(m)] for i in range(n)]
grid = new_grid[:]
for i in range(n):
print(" ".join(map(str,grid[i]))) | {
"input": [
"3 3 10\n1 1\n1 1\n1 1\n1 1 1\n1 1 1\n",
"2 2 4\n1\n3\n4 2\n",
"2 2 3\n1\n2\n3 4\n"
],
"output": [
"\n10 10 10\n10 10 10\n10 10 10\n",
"\n4 4\n10 6\n",
"\n-1 -1\n-1 -1\n"
]
} |
4,388 | 8 | Polycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: <image> (for i β₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and <image> denotes the operation of taking the remainder of division.
For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, ....
Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2.
Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β₯ k: ri = ri + t.
Input
The single line of the input contains four integers a, b, m and r0 (1 β€ m β€ 105, 0 β€ a, b β€ 1000, 0 β€ r0 < m), separated by single spaces.
Output
Print a single integer β the period of the sequence.
Examples
Input
2 6 12 11
Output
2
Input
2 3 5 1
Output
4
Input
3 6 81 9
Output
1
Note
The first sample is described above.
In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ...
In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ... | def main():
a, b, m, r = map(int, input().split())
l, s = [], set()
while r not in s:
s.add(r)
l.append(r)
r = (r * a + b) % m
print(len(l) - l.index(r))
if __name__ == '__main__':
main()
| {
"input": [
"2 6 12 11\n",
"3 6 81 9\n",
"2 3 5 1\n"
],
"output": [
"2\n",
"1\n",
"4\n"
]
} |
4,389 | 9 | The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.
In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.
The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca".
Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.
Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.
Output
Print a single number β length of the sought dynasty's name in letters.
If Vasya's list is wrong and no dynasty can be found there, print a single number 0.
Examples
Input
3
abc
ca
cba
Output
6
Input
4
vvp
vvp
dam
vvp
Output
0
Input
3
ab
c
def
Output
1
Note
In the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings).
In the second sample there aren't acceptable dynasties.
The only dynasty in the third sample consists of one king, his name is "c". | import sys
import math
from heapq import *;
input = sys.stdin.readline
from functools import cmp_to_key;
def pi():
return(int(input()))
def pl():
return(int(input(), 16))
def ti():
return(list(map(int,input().split())))
def ts():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
mod = 1000000007;
f = [];
def fact(n,m):
global f;
f = [1 for i in range(n+1)];
f[0] = 1;
for i in range(1,n+1):
f[i] = (f[i-1]*i)%m;
def fast_mod_exp(a,b,m):
res = 1;
while b > 0:
if b & 1:
res = (res*a)%m;
a = (a*a)%m;
b = b >> 1;
return res;
def inverseMod(n,m):
return fast_mod_exp(n,m-2,m);
def ncr(n,r,m):
if n < 0 or r < 0 or r > n: return 0;
if r == 0: return 1;
return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m;
def main():
C();
def C():
n = pi();
x = [];
dp = [[0 for j in range(26)] for i in range(26)];
ans = 0;
for i in range(n):
x.append(input()[:-1]);
l = ord(x[i][0]) - ord('a');
r = ord(x[i][len(x[i])-1]) - ord('a');
for j in range(26):
if dp[j][l] != 0:
dp[j][r] = max(dp[j][r], dp[j][l]+len(x[i]));
dp[l][r] = max(dp[l][r], len(x[i]));
for i in range(26):
ans = max(ans, dp[i][i]);
print(ans);
main(); | {
"input": [
"3\nabc\nca\ncba\n",
"4\nvvp\nvvp\ndam\nvvp\n",
"3\nab\nc\ndef\n"
],
"output": [
"6\n",
"0\n",
"1\n"
]
} |
4,390 | 9 | A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least k people must work in the store.
Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly n consecutive days, then rest for exactly m days, then work for n more days and rest for m more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day x, then he should work on days [x, x + 1, ..., x + n - 1], [x + m + n, x + m + n + 1, ..., x + m + 2n - 1], and so on. Day x can be chosen arbitrarily by Vitaly.
There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day β otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.
Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least k working employees, and one of the working employees should have the key to the store.
Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.
Input
The first line contains three integers n, m and k (1 β€ m β€ n β€ 1000, n β 1, 1 β€ k β€ 1000).
Output
In the first line print a single integer z β the minimum required number of employees.
In the second line print z positive integers, separated by spaces: the i-th integer ai (1 β€ ai β€ 104) should represent the number of the day, on which Vitaly should hire the i-th employee.
If there are multiple answers, print any of them.
Examples
Input
4 3 2
Output
4
1 1 4 5
Input
3 3 1
Output
3
1 3 5 | def readInts(): return map(int, input().split())
def solve():
line0 = []
try: line0 = readInts()
except EOFError: return False
n, m, k = line0
cnt = [0] * 10000
ans = []
keyPos = 1
head = 1
while head <= n+m or keyPos <= n+m:
head = min ( head, keyPos )
keyPos = max ( keyPos, head+n-1 )
ans.append ( head )
for i in range(head, head+n):
cnt[i] += 1
while cnt[head] >= k:
head += 1
print ( len(ans) )
print ( " ".join(map(str,ans)) )
return True
while solve(): pass
| {
"input": [
"4 3 2\n",
"3 3 1\n"
],
"output": [
"4\n1 1 4 5\n",
"3\n1 3 5\n"
]
} |
4,391 | 9 | In 2N - 1 boxes there are apples and oranges. Your task is to choose N boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges.
Input
The first input line contains one number T β amount of tests. The description of each test starts with a natural number N β amount of boxes. Each of the following 2N - 1 lines contains numbers ai and oi β amount of apples and oranges in the i-th box (0 β€ ai, oi β€ 109). The sum of N in all the tests in the input doesn't exceed 105. All the input numbers are integer.
Output
For each test output two lines. In the first line output YES, if it's possible to choose N boxes, or NO otherwise. If the answer is positive output in the second line N numbers β indexes of the chosen boxes. Boxes are numbered from 1 in the input order. Otherwise leave the second line empty. Separate the numbers with one space.
Examples
Input
2
2
10 15
5 7
20 18
1
0 0
Output
YES
1 3
YES
1 | import os,io
from sys import stdout
import collections
# import random
import math
from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import Counter
# from decimal import Decimal
# import heapq
# from functools import lru_cache
# import sys
# sys.setrecursionlimit(10**6)
# from functools import lru_cache
# @lru_cache(maxsize=None)
def primes(n):
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return [2] + [i for i in range(3,n,2) if sieve[i]]
def binomial_coefficient(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def powerOfK(k, max):
if k == 1:
return [1]
if k == -1:
return [-1, 1]
result = []
n = 1
while n <= max:
result.append(n)
n *= k
return result
def prefixSum(arr):
for i in range(1, len(arr)):
arr[i] = arr[i] + arr[i-1]
return arr
def divisors(n):
i = 1
result = []
while i*i <= n:
if n%i == 0:
if n/i == i:
result.append(i)
else:
result.append(i)
result.append(n/i)
i+=1
return result
def kadane(a,size):
max_so_far = 0
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
# @lru_cache(maxsize=None)
def digitsSum(n):
if n == 0:
return 0
r = 0
while n > 0:
r += n % 10
n //= 10
return r
def print_grid(grid):
for line in grid:
print("".join(line))
# INPUTS --------------------------
# s = input().decode('utf-8').strip()
# n = int(input())
# l = list(map(int, input().split()))
# t = int(input())
# for _ in range(t):
# for _ in range(t):
t = int(input())
for _ in range(t):
n = int(input())
boxes = []
i = 0
for _ in range(2*n-1):
boxes.append(list(map(int, input().split()))+[i+1])
i+=1
boxes = sorted(boxes, key=itemgetter(1))
even = boxes[::2]
odd = boxes[1::2] + [boxes[-1]]
apples = sum([e[0] for e in boxes])
halfapple = apples // 2
if apples % 2 == 1:
halfapple += 1
aeven = sum([e[0] for e in even])
aodd = sum([e[0] for e in odd])
if aeven >= halfapple:
print('YES')
res = []
for e in even:
res.append(e[2])
print(" ".join([str(e) for e in sorted(res)]))
elif aodd >= halfapple:
print('YES')
res = []
for e in odd:
res.append(e[2])
print(" ".join([str(e) for e in sorted(res)]))
else:
print('NO')
| {
"input": [
"2\n2\n10 15\n5 7\n20 18\n1\n0 0\n"
],
"output": [
"YES\n1 3 \nYES\n1 \n"
]
} |
4,392 | 7 | There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.
Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times.
Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction c, if Liss is standing on a stone whose colors is c, Liss will move one stone forward, else she will not move.
You are given a string t. The number of instructions is equal to the length of t, and the i-th character of t represents the i-th instruction.
Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence.
Input
The input contains two lines. The first line contains the string s (1 β€ |s| β€ 50). The second line contains the string t (1 β€ |t| β€ 50). The characters of each string will be one of "R", "G", or "B". It is guaranteed that Liss don't move out of the sequence.
Output
Print the final 1-based position of Liss in a single line.
Examples
Input
RGB
RRR
Output
2
Input
RRRBGBRBBB
BBBRR
Output
3
Input
BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB
BBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB
Output
15 | s=input()
t=input()
def fn(s,t):
pos=0
for i in t:
if i==s[pos]:pos+=1
return (pos+1)
print(fn(s,t)) | {
"input": [
"RRRBGBRBBB\nBBBRR\n",
"RGB\nRRR\n",
"BRRBGBRGRBGRGRRGGBGBGBRGBRGRGGGRBRRRBRBBBGRRRGGBBB\nBBRBGGRGRGBBBRBGRBRBBBBRBRRRBGBBGBBRRBBGGRBRRBRGRB\n"
],
"output": [
"3",
"2",
"15"
]
} |
4,393 | 7 | Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l β€ r).
He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].
The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj β€ x β€ rj.
Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.
Input
The first line contains two integers n and k (1 β€ n, k β€ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 β€ li β€ ri β€ 105), separated by a space.
It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 β€ i < j β€ n) the following inequality holds, min(ri, rj) < max(li, lj).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
2 3
1 2
3 4
Output
2
Input
3 7
1 2
3 3
4 7
Output
0 | def main():
n, k = map(int, input().split())
res = 0
for _ in range(n):
a, b = map(int, input().split())
res -= b - a + 1
print(res % k)
if __name__ == '__main__':
main()
| {
"input": [
"2 3\n1 2\n3 4\n",
"3 7\n1 2\n3 3\n4 7\n"
],
"output": [
"2\n",
"0\n"
]
} |
4,394 | 7 | During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4. | from sys import stdin,stdout
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
def fn(a):
print('a',a)
n=len(a)
pos1=[0]
for i in range(1,n):
pos1+=[pos1[-1]+a[i]*i]
print('pos1',pos1)
neg=[]
for i in range(n):
neg+=[i*(n-i-1)*a[i]]
print('neg',neg)
d=[]
for i in range(1,n+1):
sm=0
for j in range(1,i):
sm+=a[j-1]*(j-1)-(n-i)*a[i-1]
d+=[sm]
print('d',d);
print('================================')
p=-1
for i in range(1,n):
if pos1[i-1]-neg[i]<k:
p=i
break
if p==-1:return
a.pop(p)
fn(a)
for _ in range(1):#nmbr()):
n,k=lst()
a=lst()
# fn(a)
# exit(0)
pos = [0]
for i in range(1, n):
pos += [pos[-1] + a[i] * i]
removed=0
positive_term=0
for i in range(1,n):
negative_term=(i-removed)*a[i]*(n-i-1)
# print(positive_term,positive_term-negative_term)
if (positive_term-negative_term)<k:
removed+=1
stdout.write(str(i+1)+'\n')
else:positive_term += (i - removed) * a[i]
| {
"input": [
"5 0\n5 3 4 1 2\n",
"10 -10\n5 5 1 7 5 1 2 4 9 2\n"
],
"output": [
"2\n3\n4\n",
"2\n4\n5\n7\n8\n9\n"
]
} |
4,395 | 9 | Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum.
The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1.
Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.
Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal β by "and".
Input
The first line contains integer n (1 β€ n β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ a1 < a2 < ... < an β€ 109).
Output
In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk β the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.
Examples
Input
5
1 2 3 4 5
Output
2
4 5
Input
3
1 2 4
Output
1
4 | import functools
n = int(input())
nums = list(map(int, input().split()))
bits = ["{0:b}".format(num) for num in nums]
def possible(v):
possible_vals = [
nums[x]
for x in range(n)
if len(bits[x]) > v and bits[x][len(bits[x])-v-1] == '1'
]
if len(possible_vals) == 0:
return False, []
res = functools.reduce((lambda x, y: x&y), possible_vals, pow(2, v+1)-1)
return bool(res & ((1 << (v+1))-1) == (1 << v)), possible_vals
for x in range(30, -1, -1):
p, vals = possible(x)
if p:
print(len(vals))
print(' '.join(list(map(str, vals))))
break | {
"input": [
"5\n1 2 3 4 5\n",
"3\n1 2 4\n"
],
"output": [
"2\n4 5 ",
"1\n4 "
]
} |
4,396 | 10 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 β€ l β€ r β€ n), such that the following conditions hold:
1. there is integer j (l β€ j β€ r), such that all integers al, al + 1, ..., ar are divisible by aj;
2. value r - l takes the maximum value among all pairs for which condition 1 is true;
Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.
Input
The first line contains integer n (1 β€ n β€ 3Β·105).
The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 106).
Output
Print two integers in the first line β the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.
Examples
Input
5
4 6 9 3 6
Output
1 3
2
Input
5
1 3 5 7 9
Output
1 4
1
Input
5
2 3 5 7 11
Output
5 0
1 2 3 4 5
Note
In the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.
In the second sample all numbers are divisible by number 1.
In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | import math
# import collections
# from itertools import permutations
# from itertools import combinations
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
'''def is_prime(n):
j=2
while j*j<=n:
if n%j==0:
return 0
j+=1
return 1'''
'''def gcd(x, y):
while(y):
x, y = y, x % y
return x'''
'''fact=[]
def factors(n) :
i = 1
while i <= math.sqrt(n):
if (n % i == 0) :
if (n / i == i) :
fact.append(i)
else :
fact.append(i)
fact.append(n//i)
i = i + 1'''
def prob():
n = int(input())
n+=1
# s=input()
l=[1]
l+=[int(x) for x in input().split()]
l+=[1]
# a,b = list(map(int , input().split()))
p = [True]*n
s=0
q = [i for i in range(1,n)]
for i in range(1,n):
if p[i]:
a=i
b=i
d=l[i]
if d==1:
s,q = n-2 , [1]
break
while l[a-1] % d == 0:
a-=1
while l[b+1] % d == 0:
b+=1
p[b]=False
d = b-a
if d>s:
s,q = d,[a]
elif d==s and s!=0:
q.append(a)
print(len(q) , s)
print(*q)
t=1
# t=int(input())
for _ in range(0,t):
prob() | {
"input": [
"5\n1 3 5 7 9\n",
"5\n2 3 5 7 11\n",
"5\n4 6 9 3 6\n"
],
"output": [
"1 4\n1 ",
"5 0\n1 2 3 4 5 ",
"1 3\n2 "
]
} |
4,397 | 9 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills:
a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.
For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.
Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).
Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of cards. The next line contains the sequence of integers β the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108.
Output
If Arthur can write infinitely many distinct integers on the card, print on a single line -1.
Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples).
Examples
Input
3
4 1 7
Output
2
-2 10
Input
1
10
Output
-1
Input
4
1 3 5 9
Output
1
7
Input
4
4 3 4 5
Output
0
Input
2
2 4
Output
3
0 3 6 | def main():
n = int(input())
l = sorted(map(int, input().split()))
if n == 1:
print(-1)
return
elif n == 2:
a, b = l
res = {a * 2 - b, b * 2 - a}
if not (a + b) & 1:
res.add((a + b) // 2)
else:
q = min(l[1] - l[0], l[-1] - l[-2])
a, res = l[0] - q, ()
for b in l:
if q != b - a:
if res or q * 2 != b - a:
res = ()
break
else:
res = (b - q,)
a = b
else:
if not res:
res = {l[0] - q, b + q}
print(len(res))
if res:
print(*sorted(res))
if __name__ == '__main__':
main()
| {
"input": [
"4\n4 3 4 5\n",
"4\n1 3 5 9\n",
"3\n4 1 7\n",
"1\n10\n",
"2\n2 4\n"
],
"output": [
"0\n",
"1\n7\n",
"2\n-2 10\n",
"-1\n",
"3\n0 3 6\n"
]
} |
4,398 | 9 | Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 β€ n β€ 105). Each of the next n - 1 lines contains two integers ui and vi (1 β€ ui, vi β€ n; ui β vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | N = int(1e5+3)
n = int(input())
adj = list([] for i in range(N))
for _ in range(n-1):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
a = [0] + list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
def dfs(u, p, c_lvl, p_lvl, d):
stk = [(u, p, c_lvl, p_lvl)]
while stk:
(u, p, c_lvl, p_lvl) = stk.pop()
if c_lvl != d[u]:
c_lvl = 1 - c_lvl
res.append(str(u))
for v in adj[u]:
if v != p:
stk += [(v, u, p_lvl, c_lvl)]
d = [i ^ j for (i, j) in zip(a, b)]
res = []
dfs(1, 0, 0, 0, d)
print(len(res))
print('\n'.join(res))
| {
"input": [
"10\n2 1\n3 1\n4 2\n5 1\n6 2\n7 5\n8 6\n9 8\n10 5\n1 0 1 1 0 1 0 1 0 1\n1 0 1 0 0 1 1 1 0 1\n"
],
"output": [
"2\n4\n7\n"
]
} |
4,399 | 10 | Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 β€ l β€ r β€ n and gcd(al, al + 1, ..., ar) = xi.
<image> is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi.
Input
The first line of the input contains integer n, (1 β€ n β€ 105), denoting the length of the sequence. The next line contains n space separated integers a1, ..., an, (1 β€ ai β€ 109).
The third line of the input contains integer q, (1 β€ q β€ 3 Γ 105), denoting the number of queries. Then follows q lines, each contain an integer xi, (1 β€ xi β€ 109).
Output
For each query print the result in a separate line.
Examples
Input
3
2 6 3
5
1
2
3
4
6
Output
1
2
2
0
1
Input
7
10 20 3 15 1000 60 16
10
1
2
3
4
5
6
10
20
60
1000
Output
14
0
2
2
2
0
2
2
1
1 | from sys import stdin
n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
q = int(stdin.readline())
def gcd(a,b):
while a != 0:
a,b = b%a, a
return b
totals = {}
new = {}
for x in a[::-1]:
old = new
new = {}
for y in old:
g = gcd(x,y)
if g in new:
new[g] += old[y]
else:
new[g] = old[y]
if x in new:
new[x] += 1
else:
new[x] = 1
for y in new:
if y in totals:
totals[y] += new[y]
else:
totals[y] = new[y]
for x in range(q):
c = int(stdin.readline())
if c in totals:
print(totals[c])
else:
print(0)
| {
"input": [
"7\n10 20 3 15 1000 60 16\n10\n1\n2\n3\n4\n5\n6\n10\n20\n60\n1000\n",
"3\n2 6 3\n5\n1\n2\n3\n4\n6\n"
],
"output": [
" 14\n 0\n 2\n 2\n 2\n 0\n 2\n 2\n 1\n 1\n",
" 1\n 2\n 2\n 0\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.