text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
a=input()
print(((len(a)+1)*26)-len(a))
```
Yes
| 91,300 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
d=len(input())
print((d+1)*26-d)
```
Yes
| 91,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
#-------------Program--------------
#----Kuzlyaev-Nikita-Codeforces----
#-------------Training-------------
#----------------------------------
s=str(input())
print(26*len(s+"s")-len(s))
```
Yes
| 91,302 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
s = input()
se = set()
for j in "qwertyuiopasdfghjklzxcvbnm":
for i in range(len(s)+1):
se.add(s[:i]+j+s[i:])
print(len(se))
```
Yes
| 91,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
st = input()
a = [1]*20
a0 = st[0]
j = 0
for i in range(1,len(st)):
if st[i] == a0:
a[j] += 1
else:
a0 = st[i]
j += 1
if a0 != st[len(st)-2]:
j += 1
i = j+1
while i < len(st):
del a[j+1]
i += 1
print(len(a) * 25 + 26)
```
No
| 91,304 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
PRIME_COUNT = 10 ** 6
is_prime = [True] * PRIME_COUNT
primes = []
for i in range(2, 1000):
if is_prime[i]:
for j in range(i * i, PRIME_COUNT, i):
is_prime[j] = False
for i in range(len(is_prime)):
if is_prime[i]:
primes.append(i)
```
No
| 91,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
a=input()
print(26*(len(a)+1)-len(set(a)))
```
No
| 91,306 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?
Please help Haruhi solve this problem.
Input
The first line of input will be a single string s (1 β€ |s| β€ 20). String s consists only of lowercase English letters.
Output
Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.
Examples
Input
a
Output
51
Input
hi
Output
76
Note
In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.
Submitted Solution:
```
'''
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
'''
s=input()
n=len(s)
if(n>1):
a=(26-n)*(n+1)+(n*2)
else:
a=(26-n)*(n+1)+1
print(a)
```
No
| 91,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as <image>.
Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of <image>.
You should compute two statistics: the maximum value of <image> and the number of vertices v with the maximum <image>.
Input
The first line of the input contains one integer n (1 β€ n β€ 300 000) β the number of vertices of the tree.
The second line contains n space-separated integers ci (0 β€ ci β€ 109).
The third line contains a string s consisting of n lowercase English letters β the i-th character of this string is the letter in vertex i.
The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 β€ u, v β€ n) indicating an edge between vertices u and v.
It's guaranteed that the input will describe a tree.
Output
Print two lines.
On the first line, print <image> over all 1 β€ i β€ n.
On the second line, print the number of vertices v for which <image>.
Examples
Input
10
1 2 7 20 20 30 40 50 50 50
cacabbcddd
1 2
6 8
7 2
6 2
5 4
5 9
3 10
2 5
2 3
Output
51
3
Input
6
0 2 4 1 1 1
raaaba
1 2
2 3
2 4
2 5
3 6
Output
6
2
Note
In the first sample, the tree looks like this:
<image>
The sets of strings that can be read from individual vertices are:
<image>
Finally, the values of <image> are:
<image>
In the second sample, the values of <image> are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are <image>; note that <image> can be read down to vertices 3 or 4.
Submitted Solution:
```
class Node:
def __init__(self):
self.l = [None]*30
self.ind = []
def d(i, n, p=-1):
if i in vis: return
if i != 1:
if n.l[ord(st[i-1])-ord('a')]: n = n.l[ord(st[i-1])-ord('a')]
else:
n.l[ord(st[i-1])-ord('a')] = Node()
n.l[ord(st[i-1])-ord('a')].l[p] = n
n = n.l[ord(st[i-1])-ord('a')]
vis[i] = 1
n.ind.append(i)
for j in g[i]:
d(j, n, ord(st[i-1])-ord('a'))
vis2 = {}
def c(n):
if n in vis2: return 0
vis2[n] = 1
cnt = 1
for j in range(27):
if n.l[j]:
cnt += c(n.l[j])
for j in n.ind:
if cnt+num[j-1] in a2:
a2[cnt+num[j-1]][j] = 1
else:
a2[cnt+num[j-1]] = {j: 1}
return cnt
g = []
for i in range(int(3e5+5)):
g.append([])
n = int(input())
num = list(map(int,input().split()))
st = input()
for i in range(n-1):
a,b = map(int,input().split())
g[a].append(b)
g[b].append(a)
root = Node()
vis = {}
d(1, root)
vis = {}
a2 = {}
c(root)
m = -1e9
for i in a2:
m = max(m, i)
print(m)
print(len(a2[m]))
```
No
| 91,308 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as <image>.
Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of <image>.
You should compute two statistics: the maximum value of <image> and the number of vertices v with the maximum <image>.
Input
The first line of the input contains one integer n (1 β€ n β€ 300 000) β the number of vertices of the tree.
The second line contains n space-separated integers ci (0 β€ ci β€ 109).
The third line contains a string s consisting of n lowercase English letters β the i-th character of this string is the letter in vertex i.
The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 β€ u, v β€ n) indicating an edge between vertices u and v.
It's guaranteed that the input will describe a tree.
Output
Print two lines.
On the first line, print <image> over all 1 β€ i β€ n.
On the second line, print the number of vertices v for which <image>.
Examples
Input
10
1 2 7 20 20 30 40 50 50 50
cacabbcddd
1 2
6 8
7 2
6 2
5 4
5 9
3 10
2 5
2 3
Output
51
3
Input
6
0 2 4 1 1 1
raaaba
1 2
2 3
2 4
2 5
3 6
Output
6
2
Note
In the first sample, the tree looks like this:
<image>
The sets of strings that can be read from individual vertices are:
<image>
Finally, the values of <image> are:
<image>
In the second sample, the values of <image> are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are <image>; note that <image> can be read down to vertices 3 or 4.
Submitted Solution:
```
class Node:
def __init__(self):
self.l = [None]*26
self.ind = []
def set(self, i, n):
self.l[i]=n
return self.l[i]
def get(self, i):
return self.l[i]
def d(i, n):
if i in vis: return
if i != 1:
if n.get(ord(st[i-1])-ord('a')): n = n.get(ord(st[i-1])-ord('a'))
else: n = n.set(ord(st[i-1])-ord('a'), Node())
vis[i] = 1
n.ind.append(i)
for j in g[i]:
d(j, n)
def c(n):
cnt = 1
for j in range(26):
if n.get(j):
cnt += c(n.get(j))
for j in n.ind:
if cnt+num[j-1] in a2:
a2[cnt+num[j-1]].append(j)
else:
a2[cnt+num[j-1]] = [j]
return cnt
g = []
for i in range(int(3e5+5)):
g.append([])
n = int(input())
num = list(map(int,input().split()))
st = input()
for i in range(n-1):
a,b = map(int,input().split())
g[a].append(b)
g[b].append(a)
root = Node()
vis = {}
d(1, root)
vis = {}
a2 = {}
c(root)
m = max(i for i in a2)
print(m)
print(len(a2[m]))
```
No
| 91,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of distinct strings which can be read this way as <image>.
Also, there's a number cv assigned to each vertex v. We are interested in vertices with the maximum value of <image>.
You should compute two statistics: the maximum value of <image> and the number of vertices v with the maximum <image>.
Input
The first line of the input contains one integer n (1 β€ n β€ 300 000) β the number of vertices of the tree.
The second line contains n space-separated integers ci (0 β€ ci β€ 109).
The third line contains a string s consisting of n lowercase English letters β the i-th character of this string is the letter in vertex i.
The following n - 1 lines describe the tree T. Each of them contains two space-separated integers u and v (1 β€ u, v β€ n) indicating an edge between vertices u and v.
It's guaranteed that the input will describe a tree.
Output
Print two lines.
On the first line, print <image> over all 1 β€ i β€ n.
On the second line, print the number of vertices v for which <image>.
Examples
Input
10
1 2 7 20 20 30 40 50 50 50
cacabbcddd
1 2
6 8
7 2
6 2
5 4
5 9
3 10
2 5
2 3
Output
51
3
Input
6
0 2 4 1 1 1
raaaba
1 2
2 3
2 4
2 5
3 6
Output
6
2
Note
In the first sample, the tree looks like this:
<image>
The sets of strings that can be read from individual vertices are:
<image>
Finally, the values of <image> are:
<image>
In the second sample, the values of <image> are (5, 4, 2, 1, 1, 1). The distinct strings read in T2 are <image>; note that <image> can be read down to vertices 3 or 4.
Submitted Solution:
```
class Node:
def __init__(self):
self.l = [None]*30
self.ind = []
def d(i, n):
if i in vis: return
if i != 1:
if n.l[ord(st[i-1])-ord('a')]: n = n.l[ord(st[i-1])-ord('a')]
else:
n.l[ord(st[i-1])-ord('a')] = Node()
n = n.l[ord(st[i-1])-ord('a')]
vis[i] = 1
n.ind.append(i)
for j in g[i]:
d(j, n)
def c(n):
cnt = 1
for j in range(27):
if n.l[j]:
cnt += c(n.l[j])
for j in n.ind:
if cnt+num[j-1] in a2:
a2[cnt+num[j-1]][j] = 1
else:
a2[cnt+num[j-1]] = {j: 1}
return cnt
g = []
for i in range(int(3e5+5)):
g.append([])
n = int(input())
num = list(map(int,input().split()))
st = input()
for i in range(n-1):
a,b = map(int,input().split())
g[a].append(b)
g[b].append(a)
root = Node()
vis = {}
d(1, root)
vis = {}
a2 = {}
c(root)
m = -1e9
for i in a2:
m = max(m, i)
print(m)
print(len(a2[m]))
```
No
| 91,310 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
n=int(input())
l=sorted([int(i) for i in input().split()],reverse=True)
l1=[0]*n
l1[0]=l[0]
s=l[0]
for i in range(1,n):
k=min(l[i],l1[i-1]-1)
s+=k
l1[i]=k
if(k==0):
break
print(s)
```
| 91,311 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
n=int(input())
l=[int(x) for x in input().split()]
l.sort()
ans=0
for i in range(n):
val=l[i]
while (val>0) and val in l[:i]:
val-=1
l[i]=val
ans+=val
print(ans)
```
| 91,312 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
"""
B. Making a String
codeforces.com
"""
_, nums = input(), [int(x) for x in input().split(' ')]
nums.sort()
nums.reverse()
result = nums[0]
prev = nums[0]
for n in nums[1:]:
n = prev-1 if n >= prev else n
result += n
prev = n
if n == 0:
break
print (result)
```
| 91,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
n = int(input())
l = list(map(int,input().split()))
l.sort(reverse = 1)
for i in range(1, n):
if l[i] >= l[i-1]:
l[i] = l[i-1]-1
if l[i] < 0: l[i] = 0
print(sum(l))
```
| 91,314 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
def main():
n = int(input())
a = [int(x) for x in input().split()]
print(solver(a))
def solver(L):
L.sort(reverse = True)
total = 0
current = L[0] + 1
for i in range(len(L)):
if L[i] >= current:
current -= 1
if current <= 0:
break
else:
current = L[i]
total += current
return total
#L1 = [2, 5, 5]
#print(solver(L1))
#L1 = [1, 1, 2, 2, 2]
#print(solver(L1))
main()
```
| 91,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
n = int(input())
ai = list(map(int,input().split()))
ai.sort()
ai.reverse()
last_num = ai[0]+1
ans = 0
for num in ai:
if last_num == 0:
break
if num >= last_num:
last_num -= 1
else:
last_num = num
ans += last_num
print(ans)
```
| 91,316 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
N = int(input())
ans = 0
used = set()
for c in sorted([int(x) for x in input().split()], reverse=True):
while c > 0 and c in used:
c -= 1
ans += c
used.add(c)
print(ans)
```
| 91,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Tags: greedy, sortings
Correct Solution:
```
def make_s(lst):
while True:
lst.sort()
for i in range(len(lst) - 1):
if lst[i] == lst[i + 1]:
lst[i] -= 1
break
else:
break
return sum([x for x in lst if x > 0])
n = int(input())
a = [int(i) for i in input().split()]
print(make_s(a))
```
| 91,318 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
n = int(input())
data = list(map(int, input().split()))
answer = 0
for i in range(n):
if data.count(data[i]) == 1:
answer += data[i]
else:
while data[i] > 0:
if data.count(data[i]) == 1:
answer += data[i]
break
else:
data[i] -= 1
print(answer)
```
Yes
| 91,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
n = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = [A[0]]
for i in range(1, n):
if A[i] < ans[-1]:
ans.append(A[i])
else:
ans.append(max(0, ans[-1] - 1))
print(sum(ans))
```
Yes
| 91,320 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
l = sorted(l)[-1::-1]
for i in range(1, n):
if l[i] >= l[i-1]:
l[i] = l[i-1] - 1
if l[i] < 0:
l[i] = 0
print(sum(l))
```
Yes
| 91,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
def main():
n = int(input())
l = list(map(int, input().split()))
l.sort()
for i in range(1, n):
while l.index(l[i]) != i:
l[i] -= 1
answer = 0
for e in l:
if e > 0:
answer += e
print(answer)
if __name__ == "__main__":
main()
```
Yes
| 91,322 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
######### ## ## ## #### ##### ## # ## # ##
# # # # # # # # # # # # # # # # # # #
# # # # ### # # # # # # # # # # # #
# ##### # # # # ### # # # # # # # # #####
# # # # # # # # # # # # # # # # # #
######### # # # # ##### # ##### # ## # ## # #
"""
PPPPPPP RRRRRRR OOOO VV VV EEEEEEEEEE
PPPPPPPP RRRRRRRR OOOOOO VV VV EE
PPPPPPPPP RRRRRRRRR OOOOOOOO VV VV EE
PPPPPPPP RRRRRRRR OOOOOOOO VV VV EEEEEE
PPPPPPP RRRRRRR OOOOOOOO VV VV EEEEEEE
PP RRRR OOOOOOOO VV VV EEEEEE
PP RR RR OOOOOOOO VV VV EE
PP RR RR OOOOOO VV VV EE
PP RR RR OOOO VVVV EEEEEEEEEE
"""
"""
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1
return x
def factorial(x, m):
val = 1
while x>0:
val = (val * x) % m
x -= 1
return val
def fact(x):
val = 1
while x > 0:
val *= x
x -= 1
return val
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
## gcd function
def gcd(a,b):
if b == 0:
return a;
return gcd(b, a % b);
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n:
return 0
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
if hi == None:
hi = len(a);
while lo < hi:
mid = (lo+hi)//2;
if a[mid] < x:
lo = mid+1;
else:
hi = mid;
return lo;
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b;
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
prime[0], prime[1] = False, False
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
res = []
for i in range(2, int(x ** 0.5) + 1):
while x % i == 0:
res.append(i)
x //= i
if x != 1:
res.append(x)
return res
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()));
def float_array():
return list(map(float, input().strip().split()));
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
from itertools import permutations
import math
from bisect import bisect_left
def solve():
n = int(input())
a = sorted(list(map(int,input().split())), reverse = True)
for i in range(1, n):
if a[i] == a[i - 1]:
a[i] = a[i - 1] - 1
print(sum(a))
if __name__ == '__main__':
for _ in range(1):
solve()
# fin_time = datetime.now()
# print("Execution time (for loop): ", (fin_time-init_time))
```
No
| 91,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
l = int(input())
text = input().split()
occ = []
text = list(map(int, text))
for item in text:
if item in occ:
occ.append(item - 1)
if item not in occ:
occ.append(item)
sum = 0
for item in occ:
sum += item
print(sum)
# 1496342017597
```
No
| 91,324 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
n = int(input())
a = sorted(list(map(int, input().split())), reverse=True)
ans = a[0]
b = a[:]
for i in range(1, n):
if a[i] == a[i - 1]:
b[i] = b[i - 1] - 1
ans += b[i]
print(ans)
```
No
| 91,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 β€ n β€ 26) β the number of letters in the alphabet.
The next line contains n integers ai (1 β€ ai β€ 109) β i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer β the maximum length of the string that meets all the requirements.
Examples
Input
3
2 5 5
Output
11
Input
3
1 1 2
Output
3
Note
For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Submitted Solution:
```
import math
def is_prime(n):
if n==1:
return False
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
return False
return True
def inp(n):
ls=list(map(int,input().split()))
return ls
def ans(ls):
flag = [0] * t
for i in range(t):
k = 0
for j in range(t):
if i != j and ls[i] == ls[j] and flag[i] == 0:
flag[j] += 1 + k
k += 1
#print(flag)
for i in range(t):
ls[i] = ls[i] - flag[i]
t=int(input())
ls=inp(t)
while(len(ls)!=len(set(ls))):
ans(ls)
print(sum(ls))
```
No
| 91,326 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.
After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.
Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.
Input
The first line of the input contains two integers n and k (1 β€ n β€ 500 000, 0 β€ k β€ 109) β the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.
The second line contains n integers, the i-th of them is ci (1 β€ ci β€ 109) β initial wealth of the i-th person.
Output
Print a single line containing the difference between richest and poorest peoples wealth.
Examples
Input
4 1
1 1 4 2
Output
2
Input
3 1
2 2 2
Output
0
Note
Lets look at how wealth changes through day in the first sample.
1. [1, 1, 4, 2]
2. [2, 1, 3, 2] or [1, 2, 3, 2]
So the answer is 3 - 1 = 2
In second sample wealth will remain the same for each person.
Tags: binary search, greedy
Correct Solution:
```
import sys
sys.stderr = sys.stdout
def hood(n, k, C):
C.sort()
m, r = divmod(sum(C), n)
m1 = (m + 1) if r else m
c_lo = C[0]
k_lo = k
for i, c in enumerate(C):
if c_lo == m:
break
c_m = min(c, m)
dc = c_m - c_lo
dk = i * dc
if k_lo >= dk:
k_lo -= dk
c_lo = c_m
else:
dc = k_lo // i
c_lo += dc
break
c_hi = C[-1]
k_hi = k
for i, c in enumerate(reversed(C)):
if c_hi == m1:
break
c_m1 = max(c, m1)
dc = c_hi - c_m1
dk = i * dc
if k_hi >= dk:
k_hi -= dk
c_hi = c_m1
else:
dc = k_hi // i
c_hi -= dc
break
return c_hi - c_lo
def main():
n, k = readinti()
C = readintl()
print(hood(n, k, C))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
```
| 91,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.
<image>
Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.
Due to texting app limits, Barney's text may have up to l characters.
Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
Input
The first line of input contains two integers n and l (1 β€ n β€ 200, 1 β€ l β€ 1014) β the number of pickup lines and the maximum length of Barney's text.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line.
The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200.
All strings are not empty.
Output
Print the only integer β the maximum possible value of Nora's happiness level after reading Barney's text.
Examples
Input
3 6
3 2 1
heart
earth
art
Output
6
Input
3 6
3 2 8
heart
earth
art
Output
16
Note
An optimal answer for the first sample case is hearth containing each pickup line exactly once.
An optimal answer for the second sample case is artart.
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
numberofpkl_n = list(invr())
numberofpkl = numberofpkl_n[0]
n = numberofpkl_n[1]
hits = invr()
hits = list(hits)
pickup_lines = list()
for times in range(numberofpkl):
thing = insr()
string = ""
for ch in thing:
string +=ch
pickup_lines.append(string)
# pickup_lines = ['heart', 'earth','art']
# hits = [3 ,2,1]
# print("pickup_lines", pickup_lines)
# len < n
# len(heart) < 6
def fitsInside(line, n):
if len(line) <= n:
return True
else:
return False
# short = list(filter(lambda line: fitsInside(line, n), pickup_lines))
pickline_hit = dict(zip(pickup_lines, hits))
# print("pickline_hit", pickline_hit)
# she is fond of pickup lines
# pickupline -> happy hits
def beginning_of(given):
length = len(given)
result = list()
for indx in range(1, length + 1):
result.append(given[:indx])
return result
def evaluate_hits(given,n):
result = pickline_hit[given]
# print(result, given,1)
# ends with beginning of another pick-up-line(complete another is not counted here)
for pickline in pickup_lines:
if pickline == given:
continue
beginnings = beginning_of(pickline)[:-1]
for string in beginnings:
if string == pickline:
continue
if given.endswith(string):
remaining_character_count = len(pickline) - len(string)
if remaining_character_count + len(given) <= n :
result += pickline_hit[pickline]
pickup_line_modified = given+pickline[len(string):]
# print(pickup_line_modified)
# complete another pick-up-line counted here
for pickline in pickup_lines:
if pickline != given and given.find(pickline) > -1:
result += pickline_hit[pickline]
# print(result, pickline,3)
#multiple of given
if n > len(given):
howmanyfits = int(math.trunc(n / len(given)))
result += (howmanyfits-1)*pickline_hit[given]
# print(result,given,4)
return result
n = 6
criteria = list()
for l in range(1,n+1)[::-1]:
for item in pickup_lines:
criteria.append((evaluate_hits(item,l),l,item) )
print( sorted(criteria,reverse=True)[0][0] )
```
No
| 91,328 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.
<image>
Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.
Due to texting app limits, Barney's text may have up to l characters.
Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
Input
The first line of input contains two integers n and l (1 β€ n β€ 200, 1 β€ l β€ 1014) β the number of pickup lines and the maximum length of Barney's text.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line.
The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200.
All strings are not empty.
Output
Print the only integer β the maximum possible value of Nora's happiness level after reading Barney's text.
Examples
Input
3 6
3 2 1
heart
earth
art
Output
6
Input
3 6
3 2 8
heart
earth
art
Output
16
Note
An optimal answer for the first sample case is hearth containing each pickup line exactly once.
An optimal answer for the second sample case is artart.
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
numberofpkl_n = list(invr())
numberofpkl = numberofpkl_n[0]
n = numberofpkl_n[1]
hits = invr()
hits = list(hits)
pickup_lines = list()
for times in range(numberofpkl):
thing = insr()
string = ""
for ch in thing:
string +=ch
pickup_lines.append(string)
# pickup_lines = ['heart', 'earth','art']
# hits = [3 ,2,1]
# print("pickup_lines", pickup_lines)
# len < n
# len(heart) < 6
def fitsInside(line, n):
if len(line) <= n:
return True
else:
return False
# short = list(filter(lambda line: fitsInside(line, n), pickup_lines))
pickline_hit = dict(zip(pickup_lines, [0 for i in range(len(hits))]))
sorted_pickline_hit = sorted(list(zip(pickup_lines, hits)),reverse=True)
for pkline in list(set(pickup_lines)):
for pk_hit in sorted_pickline_hit:
if pk_hit[0] == pkline:
pickline_hit[pkline] += pk_hit[1]
print(pickline_hit)
# for pl in pickup_lines:
# print("pickline_hit", pickline_hit)
# she is fond of pickup lines
# pickupline -> happy hits
def beginning_of(given):
length = len(given)
result = list()
for indx in range(1, length + 1):
result.append(given[:indx])
return result
def evaluate_hits(given,n):
result = pickline_hit[given]
# print(result, given,1)
# ends with beginning of another pick-up-line(complete another is not counted here)
for pickline in pickup_lines:
if pickline == given:
continue
beginnings = beginning_of(pickline)[:-1]
for string in beginnings:
if string == pickline:
continue
if given.endswith(string):
remaining_character_count = len(pickline) - len(string)
if remaining_character_count + len(given) <= n :
result += pickline_hit[pickline]
pickup_line_modified = given+pickline[len(string):]
# print(pickup_line_modified)
# complete another pick-up-line counted here
for pickline in pickup_lines:
if pickline != given and given.find(pickline) > -1:
result += pickline_hit[pickline]
# print(result, pickline,3)
#multiple of given
if n > len(given):
howmanyfits = int(math.trunc(n / len(given)))
result += (howmanyfits-1)*pickline_hit[given]
# print(result,given,4)
return result
criteria = list()
for l in range(1,n+1)[::-1]:
for item in pickup_lines:
criteria.append((evaluate_hits(item,l),l,item) )
print( sorted(criteria,reverse=True) )
```
No
| 91,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.
<image>
Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.
Due to texting app limits, Barney's text may have up to l characters.
Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
Input
The first line of input contains two integers n and l (1 β€ n β€ 200, 1 β€ l β€ 1014) β the number of pickup lines and the maximum length of Barney's text.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line.
The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200.
All strings are not empty.
Output
Print the only integer β the maximum possible value of Nora's happiness level after reading Barney's text.
Examples
Input
3 6
3 2 1
heart
earth
art
Output
6
Input
3 6
3 2 8
heart
earth
art
Output
16
Note
An optimal answer for the first sample case is hearth containing each pickup line exactly once.
An optimal answer for the second sample case is artart.
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
numberofpkl_n = list(invr())
numberofpkl = numberofpkl_n[0]
n = numberofpkl_n[1]
hits = invr()
hits = list(hits)
pickup_lines = list()
for times in range(numberofpkl):
thing = insr()
string = ""
for ch in thing:
string +=ch
pickup_lines.append(string)
# pickup_lines = ['heart', 'earth','art']
# hits = [3 ,2,1]
# print("pickup_lines", pickup_lines)
# len < n
# len(heart) < 6
def fitsInside(line, n):
if len(line) <= n:
return True
else:
return False
# short = list(filter(lambda line: fitsInside(line, n), pickup_lines))
pickline_hit = dict(zip(pickup_lines, hits))
# print("pickline_hit", pickline_hit)
# she is fond of pickup lines
# pickupline -> happy hits
def beginning_of(given):
length = len(given)
result = list()
for indx in range(1, length + 1):
result.append(given[:indx])
return result
def evaluate_hits(given,n):
result = pickline_hit[given]
# print(result, given,1)
# ends with beginning of another pick-up-line(complete another is not counted here)
for pickline in pickup_lines:
if pickline == given:
continue
beginnings = beginning_of(pickline)[:-1]
for string in beginnings:
if string == pickline:
continue
if given.endswith(string):
remaining_character_count = len(pickline) - len(string)
if remaining_character_count + len(given) <= n :
result += pickline_hit[pickline]
pickup_line_modified = given+pickline[len(string):]
# print(pickup_line_modified)
# complete another pick-up-line counted here
for pickline in pickup_lines:
if pickline != given and given.find(pickline) > -1:
result += pickline_hit[pickline]
# print(result, pickline,3)
#multiple of given
if n > len(given):
howmanyfits = int(math.trunc(n / len(given)))
result += (howmanyfits-1)*pickline_hit[given]
# print(result,given,4)
return result
criteria = list()
for l in range(1,n+1)[::-1]:
for item in pickup_lines:
criteria.append((evaluate_hits(item,l),l,item) )
print( sorted(criteria,reverse=True)[0][0] )
```
No
| 91,330 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.
<image>
Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows n pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees i-th pickup line as a consecutive subsequence of Barney's text message her happiness level increases by ai. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.
Due to texting app limits, Barney's text may have up to l characters.
Barney asked you to help him make Nora as much happy as possible, it's gonna be legen...
Input
The first line of input contains two integers n and l (1 β€ n β€ 200, 1 β€ l β€ 1014) β the number of pickup lines and the maximum length of Barney's text.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 100), meaning that Nora's happiness level increases by ai after every time seeing i-th pickup line.
The next n lines contain the pickup lines. i-th of them contains a single string si consisting of only English lowercase letter. Summary length of all pickup lines does not exceed 200.
All strings are not empty.
Output
Print the only integer β the maximum possible value of Nora's happiness level after reading Barney's text.
Examples
Input
3 6
3 2 1
heart
earth
art
Output
6
Input
3 6
3 2 8
heart
earth
art
Output
16
Note
An optimal answer for the first sample case is hearth containing each pickup line exactly once.
An optimal answer for the second sample case is artart.
Submitted Solution:
```
import math
pickup_lines = ['heart', 'earth','art']
hits = [3 ,2,1]
# print("pickup_lines", pickup_lines)
# len < n
# len(heart) < 6
def fitsInside(line, n):
if len(line) <= n:
return True
else:
return False
# short = list(filter(lambda line: fitsInside(line, n), pickup_lines))
pickline_hit = dict(zip(pickup_lines, hits))
# print("pickline_hit", pickline_hit)
# she is fond of pickup lines
# pickupline -> happy hits
def beginning_of(given):
length = len(given)
result = list()
for indx in range(1, length + 1):
result.append(given[:indx])
return result
def evaluate_hits(given,n):
result = pickline_hit[given]
# print(result, given,1)
# ends with beginning of another pick-up-line(complete another is not counted here)
for pickline in pickup_lines:
if pickline == given:
continue
beginnings = beginning_of(pickline)[:-1]
for string in beginnings:
if string == pickline:
continue
if given.endswith(string):
remaining_character_count = len(pickline) - len(string)
if remaining_character_count + len(given) <= n :
result += pickline_hit[pickline]
pickup_line_modified = given+pickline[len(string):]
# print(pickup_line_modified)
# complete another pick-up-line counted here
for pickline in pickup_lines:
if pickline != given and given.find(pickline) > -1:
result += pickline_hit[pickline]
# print(result, pickline,3)
#multiple of given
if n > len(given):
howmanyfits = int(math.trunc(n / len(given)))
result += (howmanyfits-1)*pickline_hit[given]
# print(result,given,4)
return result
n = 6
criteria = list()
for l in range(1,n+1)[::-1]:
for item in pickup_lines:
criteria.append((evaluate_hits(item,l),l,item) )
print( sorted(criteria,reverse=True)[0][0] )
```
No
| 91,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya plays FreeDiv. In this game he manages a huge state, which has n cities and m two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces.
Unlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than k tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).
Vasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.
Input
The first line contains three integers n, m and k (1 β€ n, k β€ 106, 0 β€ m β€ 106). Each of the next m lines contains two integers. They are the numbers of cities connected by a corresponding road. No road connects city to itself and there is at most one road between each pair of cities.
Output
Print a single number, the minimum number of additional roads.
Examples
Input
3 3 2
1 2
2 3
3 1
Output
0
Input
4 2 2
1 2
3 4
Output
0
Input
4 0 2
Output
1
Note
In the first example only one province exists, so it is not necessary to build any tunnels or roads.
In the second example two provinces exist. It is possible to merge the provinces by building a tunnel between cities 1 and 3.
In the third example at least one additional road is necessary. For example it is possible to build additional road between cities 1 and 2 and build two tunnels between cities 1 and 3, 2 and 4 after that.
Submitted Solution:
```
LmBCxDiGSKuTWIF = map
LmBCxDiGSKuTWIv = int
LmBCxDiGSKuTWIe = input
LmBCxDiGSKuTWIR = range
LmBCxDiGSKuTWIX = print
n, m, k = LmBCxDiGSKuTWIF(LmBCxDiGSKuTWIv, LmBCxDiGSKuTWIe().split())
c = [-1]*n
def LmBCxDiGSKuTWIo(x):
p = x
while c[p] >= 0:
p = c[p]
while c[x] >= 0:
t = c[x]
c[x] = p
x = t
return p
for i in LmBCxDiGSKuTWIR(m):
x, y = LmBCxDiGSKuTWIe().split()
f = LmBCxDiGSKuTWIo(LmBCxDiGSKuTWIv(x)-1)
t = LmBCxDiGSKuTWIo(LmBCxDiGSKuTWIv(y)-1)
if f == t:
continue
if(c[f] & 1):
f, t = t, f
c[t] += c[f]
c[f] = t
l, s, q = 0, 2, 0
for i in LmBCxDiGSKuTWIR(n):
if c[i] >= 0:
continue
j = k if c[i] < -k else-c[i]
if j == 1:
l += 1
else:
s += j-2
q += 1
if l == 1:
LmBCxDiGSKuTWIX(0)
elif k == 1:
LmBCxDiGSKuTWIX(q-2)
elif l <= s:
LmBCxDiGSKuTWIX(0)
else:
LmBCxDiGSKuTWIX((l-s+1)/2)
```
No
| 91,332 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
n=int(input())
print("YES")
while n:
(x,y,a,b)=list(map(int, input().split()))
print(1+x%2+2*(y%2))
n=n-1
```
| 91,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
'''plan
noticed that if both upperle
'''
from sys import stdin, stdout
n = int(stdin.readline().rstrip())
# n = int(input())
coordinates = []
# for i in range(n):
# coordinates.append([int(x) % 2 for x in input().split()])
for i in range(n):
coordinates.append([int(x) % 2 for x in stdin.readline().rstrip().split()])
stdout.write('YES\n')
for coordinate in coordinates:
x1, y1, x2, y2 = coordinate
stdout.write(str(2 * x2 + y2 + 1) + '\n')
```
| 91,334 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
n=int(input())
print("YES")
for i in range(0,n):
a=list(map(int,input().split()))
ans=2*(a[0]&1)+(a[1]&1)+1
print(ans)
```
| 91,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
print('YES')
for _ in range(int(input())):
a,b,c,d = map(int,input().split())
print((2*(a%2))+(b%2)+1)
```
| 91,336 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
'''plan
noticed that if both upperle
'''
from sys import stdin, stdout
from itertools import islice
# n = int(stdin.readline().rstrip())
# n = int(input())
all_lines = stdin.read().split('\n')
stdout.write('YES\n')
for line in islice(all_lines, 1, len(all_lines) - 1):
x1, y1, x2, y2 = (int(x) % 2 for x in line.split())
num = 2 * x2 + y2 + 1
stdout.write(str(num) + '\n')
#print(num)
#stdout.flush()
#exit()
# for i in range(n):
# coordinates.append([int(x) % 2 for x in input().split()])
# for i in range(n):
# coordinates.append([int(x) % 2 for x in stdin.readline().rstrip().split()])
# stdout.write('YES\n')
# for coordinate in coordinates:
# x1, y1, x2, y2 = coordinate
# stdout.write(str(2 * x2 + y2 + 1) + '\n')
```
| 91,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
'''plan
noticed that if both upperle
'''
from sys import stdin, stdout
# n = int(stdin.readline().rstrip())
# n = int(input())
all_lines = stdin.read().split('\n')
stdout.write('YES\n')
for line in all_lines[1:-1]:
x1, y1, x2, y2 = (int(x) % 2 for x in line.split())
num = 2 * x2 + y2 + 1
# stdout.write(str(x2) + ' ' + str(y2) + '\n')
print(str(num) + '\n')
#stdout.flush()
#exit()
# for i in range(n):
# coordinates.append([int(x) % 2 for x in input().split()])
# for i in range(n):
# coordinates.append([int(x) % 2 for x in stdin.readline().rstrip().split()])
# stdout.write('YES\n')
# for coordinate in coordinates:
# x1, y1, x2, y2 = coordinate
# stdout.write(str(2 * x2 + y2 + 1) + '\n')
```
| 91,338 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
n = int(input())
print('YES')
for _ in range(n):
x1,y1,x2,y2 = [int(el) for el in input().split()]
print(x1%2+(y1%2)*2+1)
```
| 91,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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
Tags: constructive algorithms, geometry
Correct Solution:
```
n = int(input())
ans = 'YES\n'
for i in range(n):
x1, y1, x2, y2 = map(int, input().split())
res = (x1 & 1) * 2 + (y1 & 1) + 1
ans += str(res) + '\n'
print(ans)
```
| 91,340 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
from sys import stdin,stdout
n = int(stdin.readline())
a = [0 for i in range(n)]
for i in range(n):
inp = stdin.readline().split()
x = int(inp[0])
y = int(inp[1])
a[i] = 2 * (x % 2) + (y % 2) + 1
stdout.write("YES")
stdout.write('\n')
stdout.write("\n".join(str(i) for i in a))
```
Yes
| 91,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
n = int(input())
rectangles = []
for i in range(n):
a, b, c, d = tuple(map(int,input().split()))
rectangles.append((a,b))
print("YES")
for i in range(n):
a,b = rectangles[i][0], rectangles[i][1]
if a%2 == 0 and b%2 == 0:
print(1)
elif a%2 == 0 and b%2 == 1:
print(2)
elif a%2 == 1 and b%2 == 0:
print(3)
else:
print(4)
```
Yes
| 91,342 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
p = int(input())
print("YES")
for i in range(p):
a, b, c, d = [abs(int(i)) for i in input().split()]
if a % 2 == 0:
print("1" if b % 2 == 0 else "2")
else:
print("3" if b % 2 == 0 else "4")
```
Yes
| 91,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
n=int(input())
print("YES")
while n:
(x,y,a,b)=list(map(int, input().split()))
print(1+x%2+2*(y%2))
n=n-1
# Made By Mostafa_Khaled
```
Yes
| 91,344 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
n = int(input())
arr = [[] for i in range(n)]
ans = [0 for i in range(n)]
for i in range(n):
x, y, xx, yy = map(int, input().split())
arr[i] = ((x * x + y * y) ** 0.5, y, xx, yy, i)
arr.sort()
print("YES")
for i in range(n):
ans[arr[i][4]] = i % 4 + 1
print(*ans, sep='\n')
```
No
| 91,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
n = int(input())
arr = [[] for i in range(n)]
ans = [0 for i in range(n)]
for i in range(n):
x, y, xx, yy = map(int, input().split())
arr[i] = (y, x, yy, xx, i)
arr.sort()
print("YES")
for i in range(n):
ans[arr[i][4]] = i % 4 + 1
print(*ans, sep='\n')
```
No
| 91,346 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
from sys import stdin,stdout
n = int(stdin.readline())
stdout.write("YES")
for i in range(n):
x1, y1, x2, y2 = map(int,stdin.readline().split())
stdout.write(str((x1 % 2) * 2 + (y1 % 2) + 1))
stdout.write('\n')
```
No
| 91,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
for _ in range(int(input())):
a,b,c,d = map(int, input().split())
print(1 + a%2 + 2*(b%2))
```
No
| 91,348 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python3
[n, w] = map(int, input().strip().split())
ais = list(map(int, input().strip().split()))
ni = list(range(n))
ni.sort(key=lambda i: ais[i], reverse=True)
vis = [-((-a) // 2) for a in ais] # ceil
s = sum(vis)
if s > w:
print (-1)
else:
w -= s
for i in ni:
d = ais[i] - vis[i]
d = min(d, w)
vis[i] += d
w -= d
if w == 0:
break
print (' '.join(map(str, vis)))
```
| 91,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
from collections import deque
import math
n,k=map(int,input().split())
arr=list(map(int,input().split()))
q=deque()
v=[False]*n
for i in range(n):
var=int(math.ceil(arr[i]/2))
if k>=var:
q.append(var)
k-=var
else:
print(-1)
exit()
#print(q)
for _ in range(n):
m=0
ind=0
for i in range(n):
if v[i]==True:
continue
else:
if arr[i]>m:
ind=i
m = max(m, arr[i])
v[ind] = True
if k>=(arr[ind]-q[ind]):
k-=arr[ind]-q[ind]
q[ind]=arr[ind]
#print(q)
else:
q[ind]+=k
print(*q)
exit()
print(*q)
```
| 91,350 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
n, w = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a_index = [(x, i) for i, x in enumerate(a)]
a_index.sort(reverse=True)
res = [0] * len(a)
for x, i in a_index:
need = (x+1) // 2
res[i] = need
w -= need
if w < 0:
print(-1)
exit(0)
if w > 0:
for x, i in a_index:
if w == 0:
break
need = min(w, x-res[i])
res[i] += need
w -= need
print(res[0], end="")
for i in range(1, len(res)):
print(" " + str(res[i]), end="")
print()
```
| 91,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
from sys import stdin, stdout
from math import ceil
n, w = map(int, stdin.readline().split())
values = list(map(int, stdin.readline().split()))
fill = [0 for i in range(n)]
for i in range(n):
values[i] = (values[i], i)
values.sort()
label = 1
for i in range(n - 1, -1, -1):
if ceil(values[i][0] / 2) <= w:
fill[i] = ceil(values[i][0] / 2)
w -= ceil(values[i][0] / 2)
else:
label = 0
if not label:
stdout.write(str('-1'))
else:
for i in range(n - 1, -1, -1):
cnt = min(w, values[i][0] - fill[i])
fill[i] += min(w, values[i][0] - fill[i])
w -= cnt
ans = [0 for i in range(n)]
if w:
stdout.write('-1')
else:
for i in range(n):
ans[values[i][1]] = fill[i]
stdout.write(' '.join(list(map(str, ans))))
```
| 91,352 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
desc = input().split()
num = int(desc[0])
w = int(desc[1])
cups = list(map(int, input().split()))
halfsums = 0
resmilk = []
maxel = cups[0]
maxin = 0
maxls = []
for i in range(num):
if cups[i] > maxel:
maxel = cups[i]
maxin = i
if cups[i] % 2 == 0:
thiscup = cups[i]//2
else:
thiscup = (cups[i]//2) + 1
halfsums += thiscup
resmilk.append(thiscup)
if halfsums > w:
print(-1)
else:
while(halfsums != w):
if cups[maxin] - resmilk[maxin] < w - halfsums:
halfsums += cups[maxin] - resmilk[maxin]
resmilk[maxin] = cups[maxin]
maxls.append(maxin)
for i in range(num):
if i not in maxls:
maxin = i
maxel = cups[i]
break
for i in range(num):
if i not in maxls and cups[i] > maxel:
maxin = i
maxel = cups[i]
else:
resmilk[maxin] += w - halfsums
halfsums = w
for e in resmilk:
print(e, end=' ')
```
| 91,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
#Mamma don't raises quitter.................................................
from collections import deque as de
import math
from math import sqrt as sq
from math import floor as fl
from math import ceil as ce
from sys import stdin, stdout
import re
from collections import Counter as cnt
from functools import reduce
from itertools import groupby as gb
#from fractions import Fraction as fr
from bisect import bisect_left as bl, bisect_right as br
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
class My_stack():
def __init__(self):
self.data = []
def my_push(self, x):
return (self.data.append(x))
def my_pop(self):
return (self.data.pop())
def my_peak(self):
return (self.data[-1])
def my_contains(self, x):
return (self.data.count(x))
def my_show_all(self):
return (self.data)
def isEmpty(self):
return len(self.data)==0
arrStack = My_stack()
#decimal to binary
def decimalToBinary(n):
return bin(n).replace("0b", "")
#binary to decimal
def binarytodecimal(n):
return int(n,2)
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def get_prime_factors(number):
prime_factors = []
while number % 2 == 0:
prime_factors.append(2)
number = number / 2
for i in range(3, int(math.sqrt(number)) + 1, 2):
while number % i == 0:
prime_factors.append(int(i))
number = number / i
if number > 2:
prime_factors.append(int(number))
return prime_factors
def get_frequency(list):
dic={}
for ele in list:
if ele in dic:
dic[ele] += 1
else:
dic[ele] = 1
return dic
def Log2(x):
return (math.log10(x) /
math.log10(2));
# Function to get product of digits
def getProduct(n):
product = 1
while (n != 0):
product = product * (n % 10)
n = n // 10
return product
#function to find LCM of two numbers
def lcm(x,y):
lcm = (x*y)//math.gcd(x,y)
return lcm
def isPowerOfTwo(n):
return (math.ceil(Log2(n)) == math.floor(Log2(n)));
#to check whether the given sorted sequnce is forming an AP or not....
def checkisap(list):
d=list[1]-list[0]
for i in range(2,len(list)):
temp=list[i]-list[i-1]
if temp !=d:
return False
return True
#seive of erathanos
def primes_method5(n):
out ={}
sieve = [True] * (n+1)
for p in range(2, n+1):
if (sieve[p]):
out[p]=1
for i in range(p, n+1, p):
sieve[i] = False
return out
#function to get the sum of digits
def getSum(n):
strr = str(n)
list_of_number = list(map(int, strr.strip()))
return sum(list_of_number)
#ceil function gives wrong answer after 10^17 so i have to create my own :)
# because i don't want to doubt on my solution of 900-1000 problem set.
def ceildiv(x,y):
return (x+y-1)//y
def di():return map(int, input().split())
def ii():return int(input())
def li():return list(map(int, input().split()))
def si():return list(map(str, input()))
def indict():
dic = {}
for index, value in enumerate(input().split()):
dic[int(value)] = int(index)+1
return dic
def frqdict():
# by default it is for integer input. :)
dic={}
for index, value in enumerate(input()):
if value not in dic:
dic[value] =1
else:
dic[value] +=1
return dic
#inp = open("input.txt","r")
#out = open("output.txt","w")
#Here we go......................
#practice like your never won
#perform like you never lost
n,w=di()
a=[]
fuls=0
halfs=0
for index,value in enumerate(input().split()):
fuls+=int(value)
halfs+=ce(int(value)/2)
a.append(int(value))
if w < halfs:
print(-1)
else:
if w==halfs:
for i in range(n):
print(ce(a[i]/2), end=" ")
elif w==fuls:
print(*a, sep=" ")
else:
ans=[]
for i in range(n):
ans.append([a[i],ce(a[i]/2),i])
ans.sort(reverse=True)
diff=w-halfs
ch=1
ans2=[]
for i in range(n):
if ch:
halfele = ans[i][1]
fulfele = ans[i][0]
elediff=fulfele-halfele
if diff > elediff :
diff-=elediff
ans[i][1]=fulfele
elif diff ==elediff:
ans[i][1]=fulfele
ch=0
else:
ans[i][1]+=diff
ch=0
ans2.append([ans[i][2], ans[i][1]])
ans2.sort()
for i in range(n):
print(ans2[i][1], end=" ")
```
| 91,354 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
n, w = [int(inp) for inp in input().split()]
cap = [int(a) for a in input().split(" ")]
val = [0] * n
for i in range(n):
cap[i] = (cap[i], i)
cap.sort()
cap.reverse()
for i in range(n):
val[i] = cap[i][0]//2 + int(cap[i][0] % 2 != 0)
w -= val[i]
if w < 0:
print(-1)
exit()
for i in range(n):
v = min(w, cap[i][0] - val[i])
val[i] += v
w -= v
res = [0] * n
for i in range(n):
res[cap[i][1]] = val[i]
for r in res:
print(r, end=" ")
```
| 91,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Tags: constructive algorithms, greedy, sortings
Correct Solution:
```
import sys,math
Tests=1
for _ in range(Tests):
n,w=map(int,sys.stdin.readline().split())
a=list(map(int,sys.stdin.readline().split()))
s=0
for i in range(n):
s+=(a[i]+1)//2
if w<s:
print(-1)
else:
ans=[0]*n
for i in range(n):
ans[i]=(a[i]+1)//2
w-=s
while(w>0):
ind=a.index(max(a))
t=min(w,a[ind]-ans[ind])
ans[ind]+=t
w-=t
a[ind]=0
print(*ans)
```
| 91,356 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
n, w = list(map(int,input().split()))
a = list(map(int,input().split()))
b = [(x + 1) // 2 for x in a]
w -= sum(b)
if w > 0:
a = [(a[i], i) for i in range(n)]
a.sort(reverse=True)
for i in range(n):
x = min(a[i][0] - b[a[i][1]], w)
w -= x
b[a[i][1]] += x
if w == 0:
break
if w >= 0:
print(*b)
else:
print(-1)
```
Yes
| 91,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
import math
n, w = map(int, input().split())
volumes = []
possible = True
teacups = [0] * n
vals = list(map(int, input().split()))
for i in range(n):
poured = math.ceil(vals[i] / 2)
w -= poured
if w < 0:
possible = False
break
volumes.append((vals[i], i))
teacups[i] = poured
if not possible:
print(-1)
else:
svolumes = sorted(volumes, reverse=True)
for j in svolumes:
extra = j[0] - teacups[volumes.index(j)]
if w - extra < 0:
teacups[j[1]] += w
break
w -= extra
teacups[j[1]] += extra
print(' '.join(str(t) for t in teacups))
```
Yes
| 91,358 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
import math
n, w = [int(x) for x in input().split()]
s = input().split()
a = sorted([[int(s[x]), x] for x in range(n)], key=lambda x: x[0], reverse=True)
b = [[math.ceil(x[0]/2), x[1]] for x in a]
sm = sum([x[0] for x in b])
if sm > w:
print(-1)
else:
w -= sm
i = 0
while w:
if b[i][0] < a[i][0]:
b[i][0] += 1
w -= 1
else:
i += 1
for i in [x[0] for x in sorted(b, key=lambda x: x[1])]:
print(i, end=' ')
```
Yes
| 91,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
# Author: Boonnithi Jiaramaneepinit
# Python Interpreter Version: Python 3.5.2
#
# Note: Educational Codeforces Round 21
import math
def fillTea(water, cups):
curW = water
for i in range(len(cups)):
curW -= math.ceil(cups[i]/2)
cups[i] = [cups[i], i, math.ceil(cups[i]/2)]
cups = sorted(cups, key=lambda l:l[0], reverse=True)
if curW < 0:
return ['-1']
# eqLeft = math.floor(curW/len(cups))
# uneqLeft = curW % len(cups)
# print(curW, cups)
# for i in range(len(cups)):
# if i < uneqLeft:
# cups[i][2] += 1
# cups[i][2] = cups[i][2] + eqLeft
curCup = 0
while curW > 0:
curP = min(cups[curCup][0] - cups[curCup][2], curW)
cups[curCup][2] += curP
curW -= curP
curCup += 1
cups = sorted(cups, key=lambda l:l[1], reverse=False)
for i in range(len(cups)):
cups[i] = str(cups[i][2])
# print(curW, cups)
if curW < 0:
return ['-1']
return cups
'''
3 20
22 2 1
'''
if __name__ == '__main__':
[n, w] = [int(x) for x in input().split()]
cups = [int(x) for x in input().split()]
# [n, w] = [3, 20]
# cups = [22, 2, 1]
print(' '.join(fillTea(w, cups)))
```
Yes
| 91,360 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
n, w = map(int, input().split())
a = list(map(int, input().split()))
b = [(ai + 1) // 2 for ai in a]
r = w - sum(b)
if r < 0:
print(-1)
else:
ind = sorted(range(n), key=lambda i: a[i], reverse=True)
for i in ind:
if r <= a[i] - b[i]:
b[i] += r
break
b[i] = a[i]
r -= a[i] - b[i]
print(*b)
```
No
| 91,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
q, w = map(int, input().split())
s = list(map(int, input().split()))
p = list(map(lambda x: ((x + (x % 2)) // 2), s))
lp = sum(p)
o = 0
if lp > w:
print(-1)
else:
k = (w - lp) // len(p)
p = list(map(lambda x: x + k, p))
h = sorted(p, reverse=True)
w -= lp
w %= len(p)
while w > 0:
k = p.index(h[o])
h[o] += 1
p[k] += 1
if p[k] == s[k]:
o += 1
w -= 1
print(*p)
```
No
| 91,362 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
import math
n, w = map(int, input().split())
arr = list(map(int, input().split()))
minNeed = 0
ans = []
for i in range(n):
minNeed += math.ceil(arr[i]/2)
ans.append(math.ceil(arr[i]/2))
if minNeed > w:
print(-1)
else:
ans[arr.index(max(arr))] += (w - minNeed)
print(*ans)
```
No
| 91,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w β€ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least half of its volume
* Every cup will contain integer number of milliliters of tea
* All the tea from the teapot will be poured into cups
* All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
Input
The first line contains two integer numbers n and w (1 β€ n β€ 100, <image>).
The second line contains n numbers a1, a2, ..., an (1 β€ ai β€ 100).
Output
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
Examples
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
Note
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
Submitted Solution:
```
n,totaltea=map(int,input().split())
ar=list(map(int,input().split()))
ans=[0]*n
for i in range(n):ans[i]=(ar[i]+1)//2
if sum(ans)>totaltea:print(-1)
else:
for i in range(n):
ar[i]=[ar[i],i]
ar=sorted(ar)[::-1]
remain=totaltea-sum(ans)
for i in range(n):
if remain==40:break
k=min(remain,ar[i][0]-ans[ar[i][1]])
ans[ar[i][1]]+=k
remain-=k
if remain!=0:print(-1)
else:print(*ans)
```
No
| 91,364 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def pre(n,path,lim):
# lim = n.bit_length()
up = [[-1]*(lim+1) for _ in range(n)]
st,visi,height = [0],[1]+[0]*(n-1),[0]*n
start,finish,time = [0]*n,[0]*n,0
while len(st):
x = st[-1]
y,j = up[x][0],0
while y != -1:
up[x][j] = y
y = up[y][j]
j += 1
while len(path[x]) and visi[path[x][-1]]:
path[x].pop()
if not len(path[x]):
time += 1
finish[x] = time
st.pop()
else:
i = path[x].pop()
st.append(i)
time += 1
visi[i],start[i],up[i][0],height[i] = 1,time,x,height[x]+1
return start,finish,up,height
def is_ancestor(u,v,start,finish):
return start[u] <= start[v] and finish[u] >= finish[v]
def lca(u,v,up,start,finish,lim):
if is_ancestor(u,v,start,finish):
return u
if is_ancestor(v,u,start,finish):
return v
for i in range(lim,-1,-1):
if up[u][i] != -1 and not is_ancestor(up[u][i],v,start,finish):
u = up[u][i]
return up[u][0]
def solve(s,f,t,up,start,finish,lim,height):
a = lca(s,f,up,start,finish,lim)
b = lca(t,f,up,start,finish,lim)
ans = height[f]-max(height[a],height[b])+1
if a == b:
x = lca(s,t,up,start,finish,lim)
ans += height[x]-height[a]
return ans
def main():
n,q = map(int,input().split())
path = [[] for _ in range(n)]
for ind,i in enumerate(map(int,input().split())):
path[ind+1].append(i-1)
path[i-1].append(ind+1)
lim = n.bit_length()
start,finish,up,height = pre(n,path,lim)
for _ in range(q):
a,b,c = map(lambda xx:int(xx)-1,input().split())
print(max(solve(a,b,c,up,start,finish,lim,height),
solve(a,c,b,up,start,finish,lim,height),
solve(b,a,c,up,start,finish,lim,height)))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 91,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def euler_path(n,path):
height = [0]*n+[10**10]
euler,st,visi,he = [],[0],[1]+[0]*(n-1),0
first = [-1]*n
while len(st):
x = st[-1]
euler.append(x)
if first[x] == -1:
first[x] = len(euler)-1
while len(path[x]) and visi[path[x][-1]]:
path[x].pop()
if not len(path[x]):
he -= 1
st.pop()
else:
i = path[x].pop()
he += 1
st.append(i)
height[i],visi[i] = he,1
return height,euler,first
def cons(euler,height):
n = len(euler)
xx = n.bit_length()
dp = [[n]*n for _ in range(xx)]
dp[0] = euler
for i in range(1,xx):
for j in range(n-(1<<i)+1):
a,b = dp[i-1][j],dp[i-1][j+(1<<(i-1))]
dp[i][j] = a if height[a] < height[b] else b
return dp
def lca(l,r,dp,height,first):
l,r = first[l],first[r]
if l > r:
l,r = r,l
xx1 = (r-l+1).bit_length()-1
a,b = dp[xx1][l],dp[xx1][r-(1<<xx1)+1]
return a if height[a] < height[b] else b
def solve(s,f,t,dp,height,first):
a = lca(s,f,dp,height,first)
b = lca(t,f,dp,height,first)
ans = height[f]-max(height[a],height[b])+1
if a == b:
x = lca(s,t,dp,height,first)
ans += height[x]-height[a]
return ans
def main():
n,q = map(int,input().split())
path = [[] for _ in range(n)]
for ind,i in enumerate(map(int,input().split())):
path[ind+1].append(i-1)
path[i-1].append(ind+1)
height,euler,first = euler_path(n,path)
dp = cons(euler,height)
for _ in range(q):
a,b,c = map(lambda xx:int(xx)-1,input().split())
print(max(solve(a,b,c,dp,height,first),
solve(a,c,b,dp,height,first),
solve(b,a,c,dp,height,first)))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 91,366 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(3*10**5)
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
MA=10**5+1
level=20
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]
@bootstrap
def dfs(cur,prev):
depth[cur] = depth[prev] + 1
parent[cur][0] = prev
for i in range(len(tree[cur])):
if (tree[cur][i] != prev):
yield dfs(tree[cur][i], cur)
yield
def precomputeSparseMatrix(n):
for i in range(1,level):
for node in range(1,n+1):
if (parent[node][i-1] != -1):
parent[node][i] =parent[parent[node][i-1]][i-1]
def lca(u,v):
if (depth[v] < depth[u]):
u,v=v,u
diff = depth[v] - depth[u]
for i in range(level):
if ((diff >> i) & 1):
v = parent[v][i]
if (u == v):
return u
i=level-1
while(i>=0):
if (parent[u][i] != parent[v][i]):
u = parent[u][i]
v = parent[v][i]
i+=-1
return parent[u][0]
def add(a,b):
tree[a].append(b)
tree[b].append(a)
def res(s,t,f):
p=lca(t,f)
q=lca(s,f)
if p==q:
r=depth[lca(s,t)]-depth[p]
return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r)
return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1)
n,q=map(int,input().split())
p=list(map(int,input().split()))
for j in range(n-1):
tree[p[j]].append(j+2)
tree[j+2].append(p[j])
dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
a,b,c=map(int,input().split())
print(max(res(a,b,c),res(a,c,b),res(b,c,a)))
```
| 91,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
#!/usr/local/bin/python3
import sys
from collections import defaultdict, deque
n, q = map(int, input().split())
graph = defaultdict(set)
graph_encoded = map(int, input().split())
for n1, n2 in enumerate(graph_encoded, 2):
graph[n1].add(n2)
graph[n2].add(n1)
cache = defaultdict(set)
def shortest_distance(graph, a, b):
frontier = deque([(a, [a])])
seen = set([a])
while frontier:
current_node, path = frontier.popleft()
if (current_node, b) in cache:
return path + cache[(current_node, b)][1:]
if current_node == b:
break
for nn in graph[current_node]:
if nn in seen:
continue
seen.add(nn)
frontier.append((nn, path + [nn]))
return path
for _ in range(q):
a, b, c = map(int, input().split())
if (a == b) and (b == c):
print(1)
continue
ab = shortest_distance(graph, a, b)
for i, x in enumerate(ab):
cache[(x, b)] = ab[i:]
ac = shortest_distance(graph, a, c)
cb = shortest_distance(graph, c, b)
print(max(len(set(ab) & set(cb)), len(set(ac) & set(cb))))
```
No
| 91,368 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
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")
MA=10**5+1
level=18
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]
def dfs(cur,prev):
depth[cur] = depth[prev] + 1
parent[cur][0] = prev
for i in range(len(tree[cur])):
if (tree[cur][i] != prev):
dfs(tree[cur][i], cur)
def precomputeSparseMatrix(n):
for i in range(1,level):
for node in range(1,n+1):
if (parent[node][i-1] != -1):
parent[node][i] =parent[parent[node][i-1]][i-1]
def lca(u,v):
if (depth[v] < depth[u]):
u,v=v,u
diff = depth[v] - depth[u]
for i in range(level):
if ((diff >> i) & 1):
v = parent[v][i]
if (u == v):
return u
i=level-1
while(i>=0):
if (parent[u][i] != parent[v][i]):
u = parent[u][i]
v = parent[v][i]
i+=-1
return parent[u][0]
def add(a,b):
tree[a].append(b)
tree[b].append(a)
def res(s,t,f):
p=lca(t,f)
q=lca(s,f)
if p==q:
r=min(depth[s],depth[t])-depth[p]
return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r)
return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1)
n,q=map(int,input().split())
p=list(map(int,input().split()))
for j in range(n-1):
tree[p[j]].append(j+2)
tree[j+2].append(p[j])
dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
a,b,c=map(int,input().split())
print(max(res(a,b,c),res(a,c,b),res(b,c,a)))
```
No
| 91,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
n, q = map(int, input().split())
p = [[0 for i in range(n)] for j in range(n)]
def Dijkstra_path(s, e):
global n, p
path = [0] * n
d = [1000000] * n
d[s] = 0
u = [False] * n
for i in range(n):
v = -1
for j in range(n):
if v == -1 or (d[j] < d[v] and not u[j]):
v = j
u[v] = True
for to in range(n):
if p[v][to] and d[v] + 1 < d[to]:
d[to] = d[v] + 1
path[to] = v
ans = [0] * n
ans[e] = 1
curr = e
while curr != s:
curr = path[curr]
ans[curr] = 1
return ans
for i, pi in enumerate(input().split()):
p[i + 1][int(pi) - 1] = 1
p[int(pi) - 1][i + 1] = 1
p[i][i] = 1
p[-1][-1] = 1
while q:
a, b, c = map(int, input().split())
a -= 1
b -= 1
c -= 1
max_matches = 0
for x, y, z in [[a, b, c], [b, a, c], [a, c, b], [c, a, b], [b, c, a], [c, b, a]]:
curr_matches = 0
for Misha, Grisha in zip(Dijkstra_path(x, z), Dijkstra_path(y, z)):
if Misha and Grisha:
curr_matches += 1
max_matches = max(max_matches, curr_matches)
print(max_matches)
q -= 1
```
No
| 91,370 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.
The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.
Input
The first line contains two integers n and q (2 β€ n β€ 105, 1 β€ q β€ 105) β the number of stations and the number of days.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi β€ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.
The next q lines contains three integers a, b and c each (1 β€ a, b, c β€ n) β the ids of stations chosen by boys for some day. Note that some of these ids could be same.
Output
Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.
Examples
Input
3 2
1 1
1 2 3
2 3 3
Output
2
3
Input
4 1
1 2 3
1 2 3
Output
2
Note
In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.
In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
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")
MA=10**5+1
level=18
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]
def dfs(cur,prev):
depth[cur] = depth[prev] + 1
parent[cur][0] = prev
for i in range(len(tree[cur])):
if (tree[cur][i] != prev):
dfs(tree[cur][i], cur)
def precomputeSparseMatrix(n):
for i in range(1,level):
for node in range(1,n+1):
if (parent[node][i-1] != -1):
parent[node][i] =parent[parent[node][i-1]][i-1]
def lca(u,v):
if (depth[v] < depth[u]):
u,v=v,u
diff = depth[v] - depth[u]
for i in range(level):
if ((diff >> i) & 1):
v = parent[v][i]
if (u == v):
return u
i=level-1
while(i>=0):
if (parent[u][i] != parent[v][i]):
u = parent[u][i]
v = parent[v][i]
i+=-1
return parent[u][0]
def add(a,b):
tree[a].append(b)
tree[b].append(a)
def res(s,t,f):
k=lca(s,t)
p=lca(f,t)
q=lca(s,f)
if k==s and p==t:
return depth[f]-depth[t]+1
if k==t and q==s:
return depth[f] - depth[s] + 1
if p == t:
return depth[f] - depth[t] + 1
if q==s:
return depth[f] - depth[s] + 1
if k==s:
if q==f and q==s:
return 1
if k==t:
if q == f and p==t:
return 1
if k==s and lca(p,s)==s:
return depth[f]-depth[p]+1
if k==t and lca(q,t)==t:
return depth[f] - depth[q] + 1
if lca(q,k)==k:
return depth[f] - depth[q] + 1
if lca(p,k)==k:
return depth[f] - depth[p] + 1
return depth[f]+depth[k]-2*depth[lca(k,f)]+1
n,q=map(int,input().split())
p=list(map(int,input().split()))
for j in range(n-1):
tree[p[j]].append(j+2)
tree[j+2].append(p[j])
dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
a,b,c=map(int,input().split())
print(max(res(a,b,c),res(a,c,b),res(b,c,a)))
```
No
| 91,371 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: greedy, sortings, two pointers
Correct Solution:
```
N,M,K = map(int,input().split())
INF = 10**6+1
from collections import defaultdict
incoming = defaultdict(list)
outgoing = defaultdict(list)
for _ in range(M):
d,f,t,c = map(int,input().split())
if t == 0:
incoming[d].append((c,f-1))
if f == 0:
outgoing[d].append((c,t-1))
incoming_dates = sorted(incoming.keys())
outgoing_dates = sorted(outgoing.keys(),reverse=True)
Li = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in incoming_dates:
for c,x in incoming[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Li.append((d,total_cost))
Lo = []
mark = [False]*N
cnt = 0
costs = [0]*N
total_cost = 0
for d in outgoing_dates:
for c,x in outgoing[d]:
if mark[x]:
if costs[x] > c:
total_cost += c-costs[x]
costs[x] = c
else:
mark[x] = True
cnt += 1
costs[x] = c
total_cost += c
if cnt == N:
Lo.append((d,total_cost))
Lo.reverse()
if not Li or not Lo:
print(-1)
exit()
# print(Li,Lo)
from bisect import bisect
best = float('inf')
for d,c in Li:
i = bisect(Lo,(d+K+1,0))
if i >= len(Lo):
break
else:
best = min(best,c+Lo[i][1])
if best == float('inf'):
print(-1)
else:
print(best)
```
| 91,372 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: greedy, sortings, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
"""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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""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):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left)/ 2)
# Check if middle element is
# less than or equal to key
if (arr[mid]<=key):
count = mid+1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater( arr,n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,m,k=map(int,input().split())
incom=defaultdict(list)
outgo=defaultdict(list)
for i in range(m):
d,f,t,cost=map(int,input().split())
if t==0:
incom[d].append((f,cost))
else:
outgo[d].append((t,cost))
cost=[9999999999999999999]*n
cou=0
total_cost=0
l=[]
for i in sorted(incom.keys()):
for j in range(len(incom[i])):
if cost[incom[i][j][0]-1]==9999999999999999999:
total_cost+=incom[i][j][1]
cou+=1
else:
total_cost+=min(0,incom[i][j][1]-cost[incom[i][j][0]-1])
cost[incom[i][j][0]-1]=min(cost[incom[i][j][0]-1],incom[i][j][1])
if cou==n:
l.append((i,total_cost))
if max(cost)==9999999999999999999:
print(-1)
sys.exit(0)
cost=[9999999999999999999]*n
cou=0
total_cost=0
l1=[]
for i in sorted(outgo.keys(),reverse=True):
for j in range(len(outgo[i])):
if cost[outgo[i][j][0]-1]==9999999999999999999:
total_cost+=outgo[i][j][1]
cou+=1
else:
total_cost+=min(0,outgo[i][j][1]-cost[outgo[i][j][0]-1])
cost[outgo[i][j][0]-1]=min(cost[outgo[i][j][0]-1],outgo[i][j][1])
if cou==n:
l1.append((i,total_cost))
if max(cost)==9999999999999999999:
print(-1)
sys.exit(0)
l1.reverse()
mint=[0]*len(l1)
mint[-1]=l1[-1][1]
for i in range(len(l1)-2,-1,-1):
mint[i]=min(l1[i][1],mint[i+1])
ans=9999999999999999
t=0
#print(l1,l,mint)
for i in range(len(l)):
d=l[i][0]+k+1
#print(d)
f=0
if t==len(l1):
break
while(d>l1[t][0]):
t+=1
if t==len(l1):
f=1
break
if f==0:
ans=min(ans,l[i][1]+mint[t])
if ans==9999999999999999:
print(-1)
else:
print(ans)
```
| 91,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: greedy, sortings, two pointers
Correct Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(3e11)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
```
| 91,374 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: greedy, sortings, two pointers
Correct Solution:
```
from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
print(-1)
exit(0)
for i in range(m):
pln.append([int(i) for i in input().split()])
pln.sort()
grp=[[pln[0]]];gt=0;
for i in range(1,m):
if pln[i][0]!=pln[i-1][0]:
gt=gt+1
grp.append([])
grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)
from math import inf
pre=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if ti==0:
if mincost[fi]==inf:
ct+=1
if sumcost==inf:
mincost[fi]=min(mincost[fi],ci)
else:
sumcost=sumcost-mincost[fi]
mincost[fi]=min(mincost[fi],ci)
sumcost=sumcost+mincost[fi]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
pre[i]=sumcost
#print(pre)
sa=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
for di,fi,ti,ci in x:
if fi==0:
if mincost[ti]==inf:
ct+=1
if sumcost==inf:
mincost[ti]=min(mincost[ti],ci)
else:
sumcost=sumcost-mincost[ti]
mincost[ti]=min(mincost[ti],ci)
sumcost=sumcost+mincost[ti]
if ct==n and sumcost==inf:
sumcost=sum(mincost[1:])
sa[i]=sumcost
sa.reverse()
#print(sa)
ans=inf
for l,xxi in enumerate(xx):
r=bisect_right(xx,xxi+k)
ansl=pre[l]
ansr= inf if r==len(xx) else sa[r]
ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)
```
| 91,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: greedy, sortings, two pointers
Correct Solution:
```
R=lambda :map(int,input().split())
n,m,k=R()
F,T=[],[]
ans=int(1e12)
for i in range(m):
d,f,t,c=R()
if f:F.append((d,f,c))
else:T.append((-d,t,c))
for p in [F,T]:
cost=[ans]*(n+1)
s=n*ans
q=[]
p.sort()
for d,t,c in p:
#print(p)
if c<cost[t]:
#print(c,cost[t])
s+=c-cost[t]
#print(s)
cost[t]=c
if s<ans:
q.append((s,d))
p.clear()
#print(q)
p+=q
#print(p)
s,t=ans,(0,0)
#print(F,T)
for f in F:
while f:
if f[1]+t[1]+k<0:s=min(s,f[0]+t[0])
elif T:
#print(T)
t=T.pop()
#print(T)
# print(t)
continue
#print(f)
f=0
#print(f)
print(s if s<ans else -1)
# Made By Mostafa_Khaled
```
| 91,376 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T: t = T.pop()
print(s if s < e else -1)
```
No
| 91,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(2e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
```
No
| 91,378 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
f = F.pop()
s = e
for t in T:
while F and t[1] + f[1] + k > 0: f = F.pop()
s = min(s, f[0] + t[0])
print(s if s < e else -1)
```
No
| 91,379 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
g = lambda: map(int, input().split())
n, m, k = g()
F, T = [], []
e = int(1e9)
for i in range(m):
d, f, t, c = g()
if f: F.append((d, f, c))
else: T.append((-d, t, c))
for p in [F, T]:
C = [e] * (n + 1)
s = n * e
q = []
p.sort()
for d, t, c in p:
if C[t] > c:
s += c - C[t]
C[t] = c
if s < e: q.append((s, d))
p.clear()
p += q
s, t = e, (0, 0)
for f in F:
while f:
if t[1] + f[1] + k < 0: s = min(s, f[0] + t[0])
elif T:
t = T.pop()
continue
f = 0
print(s if s < e else -1)
```
No
| 91,380 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems.
Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price.
Ann decided that she wants to buy such non-empty subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems exactly by k. Note that k may be positive, negative or zero.
Unfortunately, Ann is not sure on which segment the sale operates, but she has q assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that).
Currently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by k.
Input
The first line contains two integers n and k (1 β€ n β€ 100 000, - 109 β€ k β€ 109) β the number of books and the needed difference between the number of math problems and the number of economics problems.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ 2), where ti is 1 if the i-th book is on math or 2 if the i-th is on economics.
The third line contains n integers a1, a2, ..., an (0 β€ ai β€ 109), where ai is the number of problems in the i-th book.
The fourth line contains a single integer q (1 β€ q β€ 100 000) β the number of assumptions.
Each of the next q lines contains two integers li and ri (1 β€ li β€ ri β€ n) describing the i-th Ann's assumption.
Output
Print q lines, in the i-th of them print the number of subsegments for the i-th Ann's assumption.
Examples
Input
4 1
1 1 1 2
1 1 1 1
4
1 2
1 3
1 4
3 4
Output
2
3
4
1
Input
4 0
1 2 1 2
0 0 0 0
1
1 4
Output
10
Note
In the first sample Ann can buy subsegments [1;1], [2;2], [3;3], [2;4] if they fall into the sales segment, because the number of math problems is greater by 1 on them that the number of economics problems. So we should count for each assumption the number of these subsegments that are subsegments of the given segment.
Segments [1;1] and [2;2] are subsegments of [1;2].
Segments [1;1], [2;2] and [3;3] are subsegments of [1;3].
Segments [1;1], [2;2], [3;3], [2;4] are subsegments of [1;4].
Segment [3;3] is subsegment of [3;4].
Tags: data structures, flows, hashing
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import ceil
def prod(a, mod=10 ** 9 + 7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
#n = int(input())
n, k = map(int, input().split())
# a, b = map(int, input().split())
# c, d = map(int, input().split())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
# s = input()
for i in range(n):
# math = eco + k
# math - eco = k
if t[i] == 2:
a[i] *= -1
count = [0] * (n + 1)
pre = [0]
for i in a:
pre += [pre[-1] + i]
index = {}
cc = list(set(pre))
for i in range(len(cc)):
index[cc[i]] = i
minusK = [-1]*(n + 1)
plusK = [-1] * (n + 1)
zero = [-1] * (n + 1)
for i in range(n + 1):
if pre[i] - k in index:
minusK[i] = index[pre[i] - k]
if pre[i] + k in index:
plusK[i] = index[pre[i] + k]
zero[i] = index[pre[i]]
BLOCK_SIZE = 320
blocks = [[] for i in range(BLOCK_SIZE)]
q = int(input())
ans = [0]*q
for i in range(q):
l, r = map(int, input().split())
blocks[l // BLOCK_SIZE] += [[l-1, r, i]]
for i in range(len(blocks)):
if not blocks[i]: continue
blocks[i] = sorted(blocks[i], key=lambda x: x[1])
left = right = BLOCK_SIZE * i
res = 0
count[zero[left]] += 1
for l, r, ind in blocks[i]:
while right < r:
right += 1
if minusK[right] != -1:
res += count[minusK[right]]
count[zero[right]] += 1
while left < l:
count[zero[left]] -= 1
if plusK[left] != -1:
res -= count[plusK[left]]
left += 1
while left > l:
left -= 1
if plusK[left] != -1:
res += count[plusK[left]]
count[zero[left]] += 1
ans[ind] = res
while left <= right:
count[zero[left]] -= 1
if plusK[left] != -1:
res -= count[plusK[left]]
left += 1
assert res == 0
for i in ans:
print(i)
```
| 91,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
from random import getrandbits as R
rb=lambda:R(1)
def modu(p,q):
if len(q)==1:
return [0]
p=p[:]
for d in range(len(p)-1,len(q)-2,-1):
#print(d)
a = p.pop()
b = q[-1]
B = [-k*a/b for k in q[:-1]]
#print(B)
for i in range(len(B)):
p[i+1+len(p)-1-(len(q)-1)] += B[i]
while len(p)>1 and abs(p[-1])<1E-6:
p.pop()
return p
def gcd(p,q):
#print(p,q)
if len(q)==1 and abs(q[0])<1E-6:
return p,1
#if len(q)<=1:
# return q,1
else:
p,iters = gcd(q,modu(p,q))
return p,iters+1
#p,iters = gcd([5,3,2],[-10,1])
#print(p,iters)
#q,iters = gcd([2,5,4,1],[3,4,1])
#print(q,iters)
for n in [int(input())]:#range(150,0,-1):
while True:
p = [1]*(n+1)
q = [1]*(n)
for i in range(n):
p[i]=rb()
for i in range(n-1):
q[i]=rb()
Q,iters = gcd(p,q)
if iters<n+1:
continue
#print(Q,iters)
print(len(p)-1)
print(*p)
print(len(q)-1)
print(*q)
break
```
| 91,382 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
a_coeffs = [1, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, -1, 0, 0, 0, 1]
b_coeffs = [1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0]
def rem(a, b):
assert len(a) == len(b) + 1
coeff = a[0] * b[0]
if a[0] == -1:
a = [-c for c in a]
if b[0] == -1:
b = [-c for c in b]
b = b + [0]
assert len(a) == len(b)
r = [c1 - c2 for (c1, c2) in zip(a, b)]
assert r[0] == 0 and r[1] == 0 and r[2] != 0
r = r[2:]
r = [coeff * c for c in r]
return r
def solve(n):
a, b = a_coeffs, b_coeffs
for _ in range(n, 150):
a, b = b, rem(a, b)
if a[0] == -1:
a = [-c for c in a]
if b[0] == -1:
b = [-c for c in b]
return a, b
n = int(input())
a, b = solve(n)
print(len(a) - 1)
print(' '.join(str(c) for c in reversed(a)))
print(len(b) - 1)
print(' '.join(str(c) for c in reversed(b)))
```
| 91,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
"""
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()
```
| 91,384 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
def construct(n):
A = [1]
B = [0]
for i in range(n):
next_A1 = [0 for j in range(len(A)+1)]
next_A2 = [0 for j in range(len(A)+1)]
next_B = [A[j] for j in range(len(A))]
for j in range(len(A)):
next_A1[j+1] = A[j]
next_A2[j+1] = -A[j]
for j in range(len(B)):
next_A1[j] += B[j]
next_A2[j] += B[j]
if max(abs(a) for a in next_A1)<=1:
A = next_A1
else:
assert max(abs(a) for a in next_A2)<=1
A = next_A2
B = next_B
return A,B
N = int(input())
A,B = construct(N)
if A[-1]==-1:
for i in range(len(A)):
A[i] *= -1
if B[-1]==-1:
for i in range(len(B)):
B[i] *= -1
print(len(A)-1)
print(*A)
print(len(B)-1)
print(*B)
```
| 91,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
import sys
n = int(sys.stdin.readline().split()[0])
class Polynomial:
def __init__(self, coef):
first_nonzero = False
index = len(coef) - 1
while not first_nonzero:
if not coef[index] == 0:
first_nonzero = True
else:
if index == 0:
first_nonzero = True
else:
index -= 1
self.degree = index
self.coef = [coef[j] for j in range(index + 1)]
def multiply_by_x(self):
new_coef = [0]
for j in range(self.degree + 1):
new_coef.append(self.coef[j])
return Polynomial(new_coef)
def minus(self):
new_coef = [-self.coef[j] for j in range(self.degree + 1)]
return Polynomial(new_coef)
def add(self, other):
other_coef = other.coef
new_coef = [0 for j in range(max(self.degree, other.degree) + 1)]
m = min(self.degree, other.degree)
M = max(self.degree, other.degree)
if self.degree > other.degree:
bigger_poly = self
else:
bigger_poly = other
for j in range(m + 1):
new_coef[j] = self.coef[j] + other.coef[j]
for j in range(m + 1, M+1):
new_coef[j] = bigger_poly.coef[j]
return Polynomial(new_coef)
def is_legal(self):
result = True
bools = [None for j in range(self.degree + 1)]
bools[self.degree] = self.coef[self.degree] == 1
for j in range(self.degree):
bools[j] = self.coef[j] == 0 or self.coef[j] == 1 or self.coef[j] == -1
for j in range(self.degree + 1):
result = result and bools[j]
return result
def print(self):
output = ""
for j in range(self.degree + 1):
output += str(self.coef[j]) + " "
print(output)
f = []
f.append(Polynomial([1]))
f.append(Polynomial([0, 1]))
for j in range(2, 151):
xf = f[j-1].multiply_by_x()
t_1 = xf.add(f[j - 2])
t_2 = xf.add(f[j - 2].minus())
if t_1.is_legal():
f.append(t_1)
elif t_2.is_legal():
f.append(t_2)
#print(":(")
print(f[n].degree)
f[n].print()
print(f[n-1].degree)
f[n-1].print()
#for j in range(len(f)):
#f[j].print()
```
| 91,386 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
a = [1]
b = []
for _ in range(n):
c = [0]+a[:]
d = a[:]
for i,u in enumerate(b): c[i]+=u
a = [u%2 for u in c]
b = [u%2 for u in d]
print(len(a)-1)
print(*a)
print(len(b)-1)
print(*b)
```
| 91,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
# python3
# utf-8
n = int(input())
A = [1]
B = []
for _ in range(n):
new_A = [0] + A[:]
new_B = A[:]
for i, b in enumerate(B):
new_A[i] += b
A = [a % 2 for a in new_A]
B = [b % 2 for b in new_B]
print(len(A) - 1)
print(*A)
print(len(B) - 1)
print(*B)
```
| 91,388 |
Provide tags and a correct Python 3 solution for this coding contest problem.
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.
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
a, b = [1], [0]
for i in range(n):
new_b = a[:]
a1 = a[:]
a2 = a[:]
a1.append(0)
a2.append(0)
for i in range(-1, -len(b) - 1, -1):
a1[i] += b[i]
for i in range(-1, -len(b) - 1, -1):
a2[i] -= b[i]
if max([abs(kek) for kek in a1]) < 2:
a = a1
elif max([abs(kek) for kek in a2]) < 2:
a = a2
else:
print("oops")
exit(0)
b = new_b
print(len(a) - 1)
print(*(a[::-1]))
print(len(b) - 1)
print(*(b[::-1]))
```
| 91,389 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n = int(input())
def print_poly(a):
print(len(a) - 1)
print(' '.join(map(str, a)))
def shift_add(a, mul, b):
c = [0] * (len(a) + 1)
for i in range(len(a)): c[i + 1] = a[i] * mul
for i in range(len(b)): c[i] += b[i]
return c
a = [0, 1]
b = [1]
for i in range(n - 1):
c = shift_add(a, 1, b)
if max(c) <= 1 and min(c) >= -1:
a, b = c, a
else:
c = shift_add(a, -1, b)
if max(c) <= 1 and min(c) >= -1:
a, b = c, a
else:
print('> <')
if a[-1] == -1:
a = list(map(lambda x: -x, a))
if b[-1] == -1:
b = list(map(lambda x: -x, b))
print_poly(a)
print_poly(b)
```
Yes
| 91,390 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n = int(input())
a = [1]
b = [0]
for i in range(n):
c = a.copy()
a.append(0)
for i in range(len(a) - 1, 0, -1):
a[i] = a[i - 1]
if i < len(b):
a[i] += b[i]
a[i] %= 2
a[0] = b[0]
b = c.copy()
print(len(a) - 1)
for i in a:
print(i, end=' ')
print('')
print(len(b) - 1)
for i in b:
print(i, end=' ')
```
Yes
| 91,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
B = [1, 0] # 1x + 0
R = [1] # 0x + 1
A = list(B)
n = int(input())
for i in range(1, n):
A += [0]
# print('A =', A)
# print('R =', R)
# print('B =', B)
for j in range(-1, -len(R)-1, -1):
A[len(A)+j] += R[len(R)+j]
if A[len(A)+j] == 2:
A[len(A)+j] = 0
R = list(B)
B = list(A)
# print(i, A, R)
print(len(B)-1)
for u in reversed(B):
print(u, end=' ')
print()
print(len(R)-1)
for u in reversed(R):
print(u, end=' ')
print()
```
Yes
| 91,392 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
import sys
#f = open('input', 'r')
f = sys.stdin
n = f.readline()
n = int(n)
t = [[0], [1]]
for j in range(n):
cur = [0] + t[-1]
for i, x in enumerate(t[-2]):
cur[i] += x
if min(cur) < -1 or max(cur) > 1:
cur = [0] + t[-1]
for i, x in enumerate(t[-2]):
cur[i] -= x
t.append(cur)
print(len(t[n+1])-1)
print(' '.join([str(x) for x in t[n+1]]))
print(len(t[n])-1)
print(' '.join([str(x) for x in t[n]]))
```
Yes
| 91,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n = int(input())
print(n)
print(1, '0 ' * n)
print(0)
print(1)
```
No
| 91,394 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n=int(input())
if n%2==0:
ch1="-1"
ch2=" "
for i in range(n):
if i==n-1 or i==n-3:
ch1+="1 "
else:
ch1+="0 "
for i in range(n-1):
if n-i%4==0:
ch2+="1"
else:
ch2+="0"
else:
ch1=""
ch2="-1 "
for i in range(n-1):
if i==n-1 or i==n-3:
ch2+="1 "
else:
ch2+="0 "
for i in range(n):
if n-i%4==0:
ch1+="1 "
else:
ch1+="0 "
print(n)
print(ch1)
print(n-1)
print(ch2)
```
No
| 91,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
#!/usr/bin/env python3
class Polynomial:
def __init__(self, ar):
if isinstance(ar, Polynomial):
ar = ar.ar
self.ar = ar[:]
def add(A, B):
res = []
for x, y in zip_longest(A.ar, B.ar, fillvalue=0):
if abs(x + y) > 1:
return
res.append(x+y)
return Polynomial(res)
def muld(self, d, coeff):
return Polynomial([0]*d + [coeff * x for x in self.ar])
def degree(self):
return len(self.ar)-1
def __repr__(self):
return ' '.join(map(str, self.ar))
# def __repr__(self):
# s = ''
# for d, c in reversed(list(enumerate(self.ar))):
# if d == 0 and c != 0:
# s += '{} 1'.format(('-' if c < 1 else '+'), str(c))
# elif d == 1 and c != 0:
# s += '{} x '.format(('-' if c < 1 else '+'))
# elif c != 0:
# s += '{} x^{} '.format(('-' if c < 1 else '+'), d)
# if s:
# return s[2:].strip() if s[0] == '+' else s.strip()
# else:
# return '0'
def solve():
n = get(int)
def possible(A, B):
A, B = Polynomial(A), Polynomial(B)
muld = n - A.degree()
for d in range(muld+1):
for coeff in [1, -1]:
val = Polynomial.add(A.muld(d, coeff), B)
if val is not None:
# print('{} % {} = {}'.format(val, A, B))
yield val
# @printRecursionTree
def gcd(A, B, k):
if A.degree() > n or B.degree() > n or A.degree() <= B.degree():
return
if k == n:
return A, B
for X in possible(A, B):
val = gcd(X, A, k+1)
if val is not None:
return val
for rem in [[1], [-1]]:
ans = gcd(Polynomial([0, 1]), Polynomial(rem), 1)
if ans is not None:
a, b = ans
if a.ar[-1] == 1 and b.ar[-1] == 1:
return '{}\n{}\n{}\n{}'.format(a.degree(), a, b.degree(), b)
return -1
_testcases = """
9
2
-1 0 1
1
0 1
""".strip()
# ======================= B O I L E R P L A T E ======================= #
# Practicality beats purity
from bisect import bisect_left, bisect_right
from collections import defaultdict
from functools import lru_cache
from itertools import zip_longest
from heapq import heapify, heappop, heappush
from operator import itemgetter, attrgetter
import bisect
import collections
import functools
import heapq
import itertools
import math
import operator
import re
import string
import sys
inf = float('inf')
cache = lru_cache(None)
sys.setrecursionlimit(10000)
def tree():
return collections.defaultdict(tree)
def equal(x, y, epsilon=1e-6):
# https://code.google.com/codejam/kickstart/resources/faq#real-number-behavior
if -epsilon <= x - y <= epsilon:
return True
if -epsilon <= x <= epsilon or -epsilon <= y <= epsilon:
return False
return (-epsilon <= (x - y) / x <= epsilon or -epsilon <= (x - y) / y <= epsilon)
def get(_type): # For easy input
if type(_type) == list:
if len(_type) == 1:
_type = _type[0]
return list(map(_type, input().strip().split()))
else:
return [_type[i](inp) for i, inp in enumerate(input().strip().split())]
else:
return _type(input().strip())
if __name__ == '__main__':
printRecursionTree = timeit = lambda x: x
_p, print = print, lambda *a, **b: None
_p(solve())
```
No
| 91,396 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n = int(input())
if n == 1:
print(1)
print(0, 1)
print(0)
print(1)
elif n == 2:
print(2)
print(-1, 0, 1)
print(1)
print(0, 1)
elif n % 2 == 1:
print(n)
for i in range(n + 1):
print(1, end=' ')
print()
print(n - 1)
for i in range(n - 3):
print(0, end=' ')
print(-1, 0, 1, end=' ')
else:
n-=1
print(n)
for i in range(n + 1):
print(1, end=' ')
print()
print(n - 1)
for i in range(n - 2):
print(0, end=' ')
print(-1, 1, end=' ')
```
No
| 91,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The input contains a single integer a (10 β€ a β€ 999).
Output
Output 0 or 1.
Examples
Input
13
Output
1
Input
927
Output
1
Input
48
Output
0
Tags: math
Correct Solution:
```
# Amirhossein Alimirzaei
# University Of Bojnourd
# Telegram : @HajLorenzo
# Instagram : amirhossein_alimirzaei
# CodeForcesian ;)
print(0 if int(input())%2==0 else 1)
```
| 91,398 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The input contains a single integer a (10 β€ a β€ 999).
Output
Output 0 or 1.
Examples
Input
13
Output
1
Input
927
Output
1
Input
48
Output
0
Tags: math
Correct Solution:
```
n = str(input())
last = n[-1]
int_=int(last)
if int_ % 2==0:
print("0")
else:
print("1")
```
| 91,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.