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.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
a, b, s = input(), input(), input()
i = 0
p = [-1] + [0] * len(s)
for j in range(1, len(s)):
while i + 1 and s[i] != s[j]: i = p[i]
i += 1
p[j + 1] = i
f = lambda a, b: a if len(a) > len(b) else b
g = lambda: [[''] * len(s) for i in range(len(b) + 1)]
u, v = g(), g()
for x in a:
for i, y in enumerate(b):
v[i] = [f(x, y) for x, y in zip(u[i], v[i - 1])]
if x == y:
for k, n in enumerate(u[i - 1]):
while k > -1 and x != s[k]: k = p[k]
k += 1
if k < len(s): v[i][k] = f(v[i][k], n + x)
u, v = v, g()
t = max(u[-2], key=lambda q: len(q))
print(t if t else 0)
```
Yes
| 15,400 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
a, b, v = input(), input(), input()
t = [[-1] * len(b) for x in range(len(a))]
def g(i, j):
if i < 0 or j < 0: return ''
if t[i][j] == -1:
s = g(i - 1, j - 1)
if a[i] == b[j]: s += a[i]
t[i][j] = max(s, g(i - 1, j), g(i, j - 1), key=lambda q: len(q) - q.count(v))
return t[i][j]
s = g(len(a) - 1, len(b) - 1)
while v in s: s = min(s.replace(v, v[:-1]), s.replace(v, v[1:]), key=lambda q: q.count(v))
print(s if s else 0)
```
Yes
| 15,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
s1, s2, virus = [input().strip() for _ in range(3)]
n, m, v = len(s1), len(s2), len(virus)
# preprocessing (inneficient, but |virus| is small)
next_suffix = [v - 1 for i in range(v - 1)] + [v]
for i in range(v - 1):
j = v - 1 - i - 1
while j > 0:
if virus[i + 1:i + 1 + j] == virus[-j:]:
next_suffix[i] = v - j - 1
break
j -= 1
def memoize(function):
memo = dict()
def memoized(*args):
if args in memo:
return memo[args]
ans = function(*args)
memo[args] = ans
return ans
return memoized
@memoize
def lcs(i, j, k):
if k < 0:
return (float("-inf"), "")
if i < 0 or j < 0:
return (0, "")
if s1[i] == s2[j]:
if s1[i] != virus[k]:
newk = k
while newk < v and virus[newk] != s1[i]:
newk = next_suffix[newk]
r = lcs(i - 1, j - 1, newk - 1)
return (r[0] + 1, r[1] + s1[i])
else:
r1 = lcs(i - 1, j - 1, k - 1)
r1 = (r1[0] + 1, r1[1] + s1[i])
r2 = lcs(i - 1, j - 1, k)
return max(r1, r2, key=lambda x: x[0])
return max(lcs(i, j - 1, k), lcs(i - 1, j, k), key=lambda x: x[0])
ans = lcs(n - 1, m - 1, v - 1)
if ans[0] > 0:
print(ans[1])
else:
print(0)
```
Yes
| 15,402 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
def backtrk(arr, l1, l2, lcs, s1, s2):
while l1 > 0 and l2 > 0:
if s2[l1-1] == s1[l2-1]:
lcs.append(s2[l1-1])
l1 -= 1
l2 -= 1
elif arr[l1-1][l2] > arr[l1][l2-1]:
l1 -= 1
else:
l2 -= 1
s1 = list(input())
s2 = list(input())
virus = list(input())
arr, lcs= [], []
arr.append([0 for i in range(len(s1)+1)])
for i in range(1, len(s2)+1):
p = [0]*(len(s1)+1)
for j in range(1, len(s1)+1):
if(s2[i-1] == s1[j-1]):
p[j] = 1 + arr[i-1][j-1]
else:
p[j] = max(arr[i-1][j], p[j-1])
arr.append(p)
#print(arr[len(s2)][len(s1)])
if arr[len(s2)][len(s1)]:
backtrk(arr, len(s2), len(s1), lcs, s1, s2)
lcs.reverse()
if len(virus) <= len(lcs):
for i in range(len(lcs)):
count = 0
if lcs[i] == virus[0]:
for j in range(0, len(virus)):
if(i+j) < len(lcs) and (lcs[i+j] == virus[j]):
count += 1
else:
break
if(count == len(virus)):
lcs[i] = '0'
flag = True
for i in range(len(lcs)):
if lcs[i] != '0':
print(lcs[i], end='')
flag = False
if flag:
print("0")
```
No
| 15,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
def LCS(x, y):
m = len(x)-1
n = len(y)-1
b = [0]*(m+1)
c = [0]*(m+1)
for i in range(m+1):
c[i] = [0]*(n+1)
b[i] = [0]*(n+1)
for i in range(1, m+1):
for j in range(1, n+1):
if x[i] == y[j]:
c[i][j] = c[i-1][j-1] + 1
b[i][j] = 1
elif c[i-1][j] >= c[i][j-1]:
c[i][j] = c[i-1][j]
b[i][j] = 2
else:
c[i][j] = c[i][j-1]
b[i][j] = 3
return c, b
def print_LCS(b, x, i, j):
global z
if i == 0 or j == 0:
return
if b[i][j] == 1:
print_LCS(b, x, i-1, j-1)
z = z + x[i]
elif b[i][j] == 2:
print_LCS(b, x, i-1, j)
else:
print_LCS(b, x, i, j-1)
s1 = input()
s2 = input()
v = input()
c, b = LCS('1'+s1, '1'+s2)
ans = ''
for i in range(1, len(s1)+1):
for j in range(1, len(s2)+1):
z=''; print_LCS(b, '1'+s1, i, j)
z = z.replace(v, '')
if len(z) > len(ans):
ans = z
if len(ans) > 0:
print(ans)
else:
print(0)
```
No
| 15,404 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
# Why do we fall ? So we can learn to pick ourselves up.
def lcs(s1,s2):
m = len(s1)
n = len(s2)
gar = [[0]*(n+1) for i in range(0,m+1)]
for i in range(0,m+1):
for j in range(0,n+1):
if i == 0 or j == 0:
gar[i][j] = 0
elif s1[i-1] == s2[j-1]:
gar[i][j] = gar[i-1][j-1] + 1
else:
gar[i][j] = max(gar[i-1][j],gar[i][j-1])
ss = ""
i,j = m,n
while i > 0 and j > 0:
if s1[i-1] == s2[j-1]:
ss += s1[i-1]
i -= 1
j -= 1
elif gar[i-1][j] > gar[i][j-1]:
i -= 1
else:
j -= 1
return ss[::-1]
s1 = input()
s2 = input()
virus = input()
ss = lcs(s1,s2)
ind = ss.find(virus)
if ind != -1:
ss = ss[:ind] + ss[ind+len(virus):]
print([ss,0][len(ss) == 0])
"""
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
"""
```
No
| 15,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.
Input
The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
Output
Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
Examples
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
Output
0
Submitted Solution:
```
a, b, s = input(), input(), input()
i = 0
p = [-1] + [0] * len(s)
for j in range(1, len(s)):
while i + 1 and s[i] != s[j]: i = p[i]
i += 1
p[j + 1] = i
d = [[] for i in b] + [[]]
u, v = d[:], d[:]
for x in a:
for i, y in enumerate(b):
r = u[i] + v[i - 1]
if x == y:
for n, k in u[i - 1]:
while k > -1 and x != s[k]: k = p[k]
if k < len(s): r.append((n + x, k + 1))
r.append((x, s[0] == x))
if not r: continue
r.sort(key=lambda q: len(q[0]))
n, k = r.pop()
while r:
q = r.pop()
if len(q[0]) < len(n):
v[i].append((n, k))
n = q[0]
k = min(k, q[1])
v[i].append((n, k))
u, v = v, d[:]
print(max(u[-2], key=lambda q: len(q[0])) if u[-2] else 0)
```
No
| 15,406 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 — the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s.
Output
If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.
Examples
Input
8
00111000
Output
YES
Input
7
1001011
Output
NO
Input
7
1010100
Output
YES
Submitted Solution:
```
inpt = open('input.txt', 'r')
outpt = open('output.txt', 'w')
n = int(inpt.readline())
s = inpt.readline()
check = []
for i in range(len(s)):
if s[i] == '1':
check.append(i)
flag = 0
for j in range(1, len(check)-1):
if check[j] - check[j-1] == check[j+1] - check[j]:
flag = 0
else:
flag = 1
outpt.write('YES' if flag ==0 else 'NO')
outpt.close()
# 10
# 0011111011
```
No
| 15,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 — the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s.
Output
If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.
Examples
Input
8
00111000
Output
YES
Input
7
1001011
Output
NO
Input
7
1010100
Output
YES
Submitted Solution:
```
from collections import Counter
I = open('input.txt', 'r')
O = open('output.txt', 'w')
input = lambda: I.readline()[:-1]
print = lambda x: O.write(str(x) + '\n')
n = int(input())
s = input().strip('0').split('1')
cnt = Counter(len(x) for x in s)
print('YES' if len(cnt.items()) <= 1 else 'NO')
```
No
| 15,408 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 — the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s.
Output
If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.
Examples
Input
8
00111000
Output
YES
Input
7
1001011
Output
NO
Input
7
1010100
Output
YES
Submitted Solution:
```
Inp = open('input.txt')
out = open('output.txt', 'w')
n = Inp.readline().rstrip()
n = int(n)
s = Inp.readline().rstrip()
s = list(s)
pas = 0
res = []
f = 0
for i in range(len(s)):
if s[i] == '1':
f = 1
if i == 0:
res.append(1)
else:
res.append(pas)
pas = 0
elif s[i] == '0' and f != 0:
pas += 1
if len(set(res)) == 1:
out.write('YES')
exit()
out.write('NO')
```
No
| 15,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 — the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s.
Output
If Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.
Examples
Input
8
00111000
Output
YES
Input
7
1001011
Output
NO
Input
7
1010100
Output
YES
Submitted Solution:
```
import sys
f = open("input.txt")
o = open("output.txt", "w")
n_bits = int(f.readline())
bits = [x for x in f.readline().strip()]
if bits[-1] == "1":
o.write("NO")
sys.exit(0)
cur_str = ""
values = []
for bit in bits:
if bit == "1":
cur_str += "1"
else:
if cur_str != "":
values.append(cur_str)
cur_str = ""
lengths = [len(x) for x in values]
for i in range(1, len(lengths)):
if lengths[i] != lengths[i-1]:
o.write("NO")
sys.exit(0)
o.write("YES")
```
No
| 15,410 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
# Made By Mostafa_Khaled
bot = True
n, k = map(int, input().split())
if k == 0 and n == 1:
print(1)
elif n // 2 > k or n == 1:
print(-1)
else:
x = (k - n // 2 + 1)
print(x, x * 2, *range(x * 2 + 1, x * 2 + 1 + n - 2))
# Made By Mostafa_Khaled
```
| 15,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
#!/usr/bin/env python3
from sys import stdin
MAXNUM = int(2e6)
primes = list()
isprime = [True for i in range(MAXNUM+1)]
def getPrimes():
for i in range(2, MAXNUM+1):
if isprime[i]:
primes.append(i)
j = i*i
while j < MAXNUM+1:
isprime[j] = False
j += i
def solve(tc):
n, k = map(int, stdin.readline().split())
pairs = n//2
if pairs==0:
if k==0:
print(' '.join(map(lambda x: str(x), list(range(1,n+1)))))
else:
print(-1)
return
if pairs > k:
print(-1)
return
getPrimes()
remain = k - (pairs - 1)
ans = list()
ans.extend([remain, remain*2])
p = 0
while len(ans) < n:
if primes[p] != remain and primes[p] != remain*2:
ans.append(primes[p])
p += 1
print(' '.join(map(lambda x: str(x), ans)))
tc = 1
solve(tc)
```
| 15,412 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
import sys
[n,k] = map(int, sys.stdin.readline().split())
def solve():
# global n
# nx = n
# n = 2 * (n//2)
if n == 1 and k == 0:
print(1)
return
if n == 1 and k > 0:
print(-1)
return
if n//2 > k:
print(-1)
return
rest = k - n//2
# if rest > 0:
print(rest+1, end=" ")
print(2*rest+2, end=" ")
for i in range(2*rest+3, n + 2*rest+3-2):
print(i, end=" ")
# else:
# for i in range(1, n+1):
# print(i, end=" ")
print()
solve()
```
| 15,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
n, k = map(int, input().split())
if n % 2:
pairs = (n-1)//2
else:
pairs = n//2
if pairs > k or (not pairs and k > 0):
print(-1)
else:
if pairs < k:
answer = [k-pairs+1, (k-pairs+1)*2]
answer += [i for i in range(answer[1]+1, answer[1]+n-1)]
else:
answer = [i for i in range(1, n+1)]
print(' '.join(map(str, answer)))
```
| 15,414 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
n, k = map(int, input().split())
if n // 2 > k:
print(-1)
elif n == 1 and k != 0:
print(-1)
elif n == 1 and k == 0:
print(1)
else:
a = n // 2 - 1
for i in range(1, a + 1):
print(2 * i - 1, 2 * i, end=' ')
print((k - a) * 3 + 4 * a - (4 * a) % (k - a), 4 * a - (4 * a) % (k - a) + (k - a) * 4, end=' ')
if n % 2:
print(998244353)
```
| 15,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
n,k=map(int,input().split())
if n==1:
if k==0:
print(1)
else:
print(-1)
elif k<n//2:
print(-1)
else:
z=k-((n-2)//2)
print(z,z*2,end=' ')
for i in range(2,n):
print(2*z+i,end=' ')
```
| 15,416 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
# 414A
from sys import stdin
__author__ = 'artyom'
n, k = list(map(int, stdin.readline().strip().split()))
if n == 1:
if k == 0:
print(1)
else:
print(-1)
exit()
pairs = n // 2
if k < pairs:
print(-1)
exit()
x, y = 1, 2
if k > pairs:
x = k - pairs + 1
y = x * 2
print(x, end=' ')
print(y, end=' ')
if n > 2:
for i in range(y + 1, y + n - 2):
print(i, end=' ')
print(y + n - 2)
```
| 15,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Tags: constructive algorithms, number theory
Correct Solution:
```
import time,math as mt,bisect,sys
from sys import stdin,stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IO(): # to take string input
return stdin.readline()
def IP(): # to take tuple as input
return map(int,stdin.readline().split())
def L(): # to take list as input
return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
if a==0:
return b
elif b==0:
return a
if a>b:
return gcd(a%b,b)
else:
return gcd(a,b%a)
def readTree(): # to read tree
v=int(input())
adj=[set() for i in range(v+1)]
for i in range(v-1):
u1,u2=In()
adj[u1].add(u2)
adj[u2].add(u1)
return adj,v
def bfs(adj,v): # a schema of bfs
visited=[False]*(v+1)
q=deque()
while q:
pass
def sieve():
li=[True]*1000001
li[0],li[1]=False,False
for i in range(2,len(li),1):
if li[i]==True:
for j in range(i*i,len(li),i):
li[j]=False
prime=[]
for i in range(1000001):
if li[i]==True:
prime.append(i)
return prime
def setBit(n):
count=0
while n!=0:
n=n&(n-1)
count+=1
return count
mx=10**7
spf=[mx]*(mx+1)
def SPF():
spf[1]=1
for i in range(2,mx+1):
if spf[i]==mx:
spf[i]=i
for j in range(i*i,mx+1,i):
if i<spf[j]:
spf[j]=i
return
#####################################################################################
mod=10**9+7
def solve():
n,k=IP()
if n==1:
if k==0:
P(1)
return
P(-1)
return
if k==0:
P(-1)
return
y=k-(n-2)//2
li=[]
if (n-2)//2<k:
li.append(y)
li.append(y*2)
for i in range(y*2+1,y*2+n-1):
li.append(i)
print(*li)
return
P(-1)
return
solve()
#######
#
#
####### # # # #### # # #
# # # # # # # # # # #
# #### # # #### #### # #
###### # # #### # # # # #
```
| 15,418 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
import sys
from math import log2,floor,ceil,sqrt,gcd
import bisect
# from collections import deque
sys.setrecursionlimit(10**5)
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 1000000007
n,k= Ri()
odd = False
if n%2 == 1:
n-=1
odd = True
if n//2 > k or (n == 0 and k != 0):
print(-1)
elif n == 0 and k == 0:
print(1)
else:
k = k-n//2+1
print(k,end=" ")
print(2*k,end=" ")
maxx = 2*k+1
for i in range(n//2-1):
print(maxx,end = " ")
maxx+=1
print(maxx,end= " ")
maxx+=1
if odd:
print(maxx,end = " ")
```
Yes
| 15,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
from math import log, ceil
from collections import defaultdict
n,k = [int(x) for x in input().split()]
l = [i for i in range(1,n+1)]
d = k - n//2 + 1
if (n//2>k):
print(-1)
elif n==1:
if k==0:
print(1)
else:
print(-1)
else:
d = k-n//2+1
l[0] = d
l[1] = 2*d
for i in range(2,n):
l[i] = l[i-1]+1
print(*l)
```
Yes
| 15,420 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
n,k=value()
if(k==0 and n==1):
print(1)
exit()
if(k<n//2 or n==1):
print(-1)
exit()
ans=[]
#print(ans)
pairs=n//2
k-=(pairs-1)
ans.append(k)
ans.append(k*2)
k=2*k+1
for i in range(pairs-1):
ans.append(k)
ans.append(k+1)
k+=2
if(n%2==1):
ans.append(ans[-1]+1)
print(*ans)
```
Yes
| 15,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
n,k = map(int,input().split())
if n==1 :
print(1 if k==0 else -1)
else:
pr = (n-2)//2
k -= pr
if k<1 :
print(-1)
else:
res = []
res += [k,2*k]
res += list(range(2*k+1,2*k+1+2*pr))
if n%2:
res += [2*k+1+2*pr]
print(*res)
# C:\Users\Usuario\HOME2\Programacion\ACM
```
Yes
| 15,422 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
#from sys import stdin
#input=stdin.readline
#a = sorted([(n, i) for i, n in enumerate(map(int, input().split()))])
# from collections import Counter
# import sys
#s="abcdefghijklmnopqrstuvwxyz"
#n=int(input())
#n,k=map(int,input().split())
#arr=list(map(int,input().split()))
#arr=list(map(int,input().split()))
n,k=map(int,input().split())
var=k-n//2+1
if k<n//2:
print(-1)
exit()
if n==1:
print(-1)
exit()
g=1
for i in range(n):
if i==0:
print(var,end=" ")
elif i==1:
print(2*var,end=" ")
else:
print(2*var+g,end=" ")
g+=1
```
No
| 15,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
from math import *
from bisect import *
from collections import Counter,defaultdict
from sys import stdin, stdout
input = stdin.readline
I =lambda:int(input())
SI =lambda:input()
M =lambda:map(int,input().split())
LI=lambda:list(map(int,input().split()))
n,k=M()
a=[]
b=n//2
if b>k or b==0:
print(-1)
else:
c=k-(b-1)
a+=[c,c+c]
d=2*c+1
for i in range(d,(d+n)-2):
a+=[i]
print(*a)
```
No
| 15,424 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
n , m = map(int,input().split())
ans=[]
c=0
if m<n//2:
print(-1)
exit()
elif n==1 and m!=0:
print(-1)
exit()
elif n==1 and m==0:
print(0)
exit()
m-=(n//2-1)
ans.append((1)*m)
ans.append((2)*m)
k=ans[-1]
for i in range(1,n-2,2):
ans.append(k+i)
ans.append(k+i+1)
if n%2!=0:
ans.append(10**9)
print(*ans)
```
No
| 15,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.
Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way.
Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
Input
The first line of input contains two space-separated integers n, k (1 ≤ n ≤ 105; 0 ≤ k ≤ 108).
Output
If such sequence doesn't exist output -1 otherwise output n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Examples
Input
5 2
Output
1 2 3 4 5
Input
5 3
Output
2 4 3 7 1
Input
7 2
Output
-1
Note
gcd(x, y) is greatest common divisor of x and y.
Submitted Solution:
```
n,k=(int(i) for i in input().split())
k1=(n-2)//2
x=k-((n-2)//2)
l=[x,2*x]
if(k>=n//2):
for i in range(n-2):
l.append(2*x+1+i)
print(*l)
else:
print(-1)
```
No
| 15,426 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
multiplos_de_onze = [0, 1, 11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111, 1111111111, 11111111111,
111111111111, 1111111111111, 11111111111111, 111111111111111, 1111111111111111,
11111111111111111]
def procura_onze(n, i): # i = 16 pois será as posições do vetor decrementadas
divisao = int(n / multiplos_de_onze[i])
resto = n % multiplos_de_onze[i]
if resto == 0:
return divisao*i
else:
return divisao*i + min(i + procura_onze(multiplos_de_onze[i] - resto, i - 1), procura_onze(resto, i - 1))
def divide():
n = int(input())
m = procura_onze(n, 16)
print(m)
divide()
```
| 15,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {n: 0}
m = len(str(n)) + 1
u = int('1' * (m+1))
for i in range(m, 0, -1):
d, e, u = {}, d, u // 10
for v, c in e.items():
lim = v // u
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
```
| 15,428 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
one = []
for i in range(17):
one.append(0)
def code():
i = 1
j = 0
k = 0
one[0] = 0
for i in range(1, 17):
one[i] = one[i-1]*10+1
n = int(input())
print(df(n, 16))
def df(n, i):
k = int(n/one[i])
n %= one[i]
if n == 0:
return k*i
else:
return k*i+min(i+df(one[i]-n, i-1), df(n, i-1))
code()
```
| 15,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
import math
acc = []
n = int(input())
def OneNum (num, One):
onetrans = num // acc[One]
num = num % acc[One]
if num == 0:
return onetrans*One
else:
return onetrans*One + min(OneNum(num, One-1), One + OneNum(acc[One] - num, One - 1))
acc.append(0)
for i in range(1,17):
acc.append (acc[i-1]*10 + 1)
print (OneNum(n,16))
```
| 15,430 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {n: 0}
u = 10 ** (len(str(n)) + 2) // 9
for i in range(len(str(n)) + 1, 0, -1):
d, e = {}, d
u //= 10
for v, c in e.items():
lim = v//u
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
```
| 15,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
class OneArithmetic():
def __init__(self, n):
self.n = n
self.m = [0]*17
v = 0
for i in range(1,17):
v = 10*v+1
self.m[i] = v
def dfs(self, v, d):
v = abs(v)
if d == 1:
return v
elif v == 0:
return 0
else:
k = int(v/self.m[d])
ans = min( self.dfs( v - k * self.m[d] , d - 1 ) + k * d , self.dfs( ( k + 1 ) * self.m[d] - v , d - 1 ) + ( k + 1 ) * d )
return ans
def min_digits(self):
v = self.dfs(self.n,16)
return v
n = int(input())
print(OneArithmetic(n).min_digits())
```
| 15,432 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {n: 0}
u = 10 ** (len(str(n)) + 2) // 9
for i in range(len(str(n)) + 1, 0, -1):
d, e = {}, d
u //= 10
for v, c in e.items():
lim = v//u
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
# Made By Mostafa_Khaled
```
| 15,433 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Tags: brute force, dfs and similar, divide and conquer
Correct Solution:
```
n = int(input())
d = {}
def count(x):
if x == 0:
return 0
elif x in d:
return d[x]
x_s = str(x)
low = int("1"*len(x_s)) if int("1"*len(x_s)) <= x else int("1"*(len(x_s)-1))
high = int("1"*len(x_s)) if int("1"*len(x_s)) >= x else int("1"*(len(x_s)+1))
l_val, h_val = -1, -1
if abs(x - low) < x:
l_val = len(str(low)) + count(abs(x - low))
if abs(x - high) < x:
h_val = len(str(high)) + count(abs(x - high))
ret = min(l_val, h_val) if min(l_val, h_val) >= 0 else max(l_val, h_val)
d[x] = ret
return ret
print(count(n))
```
| 15,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
multiplos_de_onze = [0, 1, 11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111, 1111111111, 11111111111,
111111111111, 1111111111111, 11111111111111, 111111111111111, 1111111111111111,
11111111111111111]
# Entrada maxima, n maior que 1 e n menor que 10 elevado a 15
def procura_onze(n, i): # i = 16 - pois será a ultima posição do vetor
divisao = int(n / multiplos_de_onze[i])
resto = n % multiplos_de_onze[i]
if resto == 0:
return divisao*i
else:
return divisao*i + min(i + procura_onze(multiplos_de_onze[i] - resto, i - 1), procura_onze(resto, i - 1))
def divide():
n = int(input())
m = procura_onze(n, 16)
print(m)
divide()
```
Yes
| 15,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
"""
Codeforces Testing Round 10 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0:
return inputs
if mode == 1:
return inputs.split()
if mode == 2:
return [int(x) for x in inputs.split()]
def write(s="\n"):
if isinstance(s, list): s = " ".join(s)
s = str(s)
print(s, end="")
################################################### SOLUTION
def g(n):
return (10**n-1)//9
def solve(n):
if n <= 6: return n
if 7 <= n <= 11: return 13-n
l = 1
while g(l) < n: l += 1
l -= 1
gl = g(l)
a = n
res1 = 0
res1 += (a // gl) * l
a %= gl
res1 += solve(a)
b = g(l+1) - n
res2 = l+1
res2 += (b // gl) * l
b %= gl
res2 += solve(b)
return min(res1, res2)
n, = read()
print(solve(n))
```
Yes
| 15,436 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
ans=1000000000000
mul = []
def dfs(now, num, opt):
if num == 0:
global ans
ans = min(ans, opt)
return
if now == -1:
return
i=-10
while i * mul[now] <= num:
i+=1
dfs(now-1, num-(i-1)*mul[now], opt+abs(i-1)*(now+1))
dfs(now-1, num-i*mul[now], opt+abs(i)*(now+1))
def main():
mul.append(int(1))
num = int(input())
for i in range(1,18,1):
mul.append(mul[i-1]*10)
for i in range(1,18,1):
mul[i] += mul[i-1]
i = 1
while mul[i] <= num:
i+=1
n=i
dfs(n, num, 0)
print(ans)
main()
```
Yes
| 15,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
import math
def find(n,i):
ans = 0
k = n // ones[i]
n = n % ones[i]
ans = ans + k * i
if n == 0:
return ans
return ans + min(find(n, i-1), i + find(ones[i] - n, i-1))
n = int(input())
ones = [0]
for i in range(1,17):
one = 10 * ones[i-1] + 1
ones.append(one)
print(find(n,16))
```
Yes
| 15,438 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
num=int(input())
kolvoed=0
while num:
sk='1'
while int(sk)<=num:
sk=sk+'1'
if num==6:
kolvoed+=6
num-=6
elif (int(sk)-num)>(num-int(sk[:-1])):
num=num-int(sk[:-1])
kolvoed+=len(sk)-1
else:
num=int(sk)-num
kolvoed+=len(sk)
print(kolvoed)
```
No
| 15,439 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
s = str(input())
ans = 0
while int(s)!=0:
l = len(s)
tmp = "1"*len(s) #xâu 1
so1 = int(s)
so2 = int(tmp)
#print("so1 =",so1)
#print("so2 =",so2)
#print("l =",l)
if so1 > so2*int(s[0]):
ans += int(s[0])*l
so1 = so1-so2*int(s[0])
s = str(so1)
#print("1",ans)
#print (s)
elif so1 < so2*int(s[0]):
ans+=l*int(s[0])
so1=so2*int(s[0])-so1
s = str(so1)
#print (s)
#print("2",ans)
else:
ans+=l*int(s[0])
s = str(so1-so2*int(s[0]))
#print("3",ans)
print(ans)
```
No
| 15,440 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
from sys import stdin, setrecursionlimit, stdout
#setrecursionlimit(1000000) #use "python" instead of "pypy" to avoid MLE
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heapreplace, heappushpop
from bisect import bisect_right, bisect_left
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())
mod=1000000007
res=['NO', 'YES']
#######################################################################################
########################### M Y F U N C T I O N S ###########################
#######################################################################################
def ones(n):
global cnt
x=0
while True:
p=x*10+1
if abs(n-x)>abs(n-p):
x=p
cnt+=1
else:
return x
#######################################################################################
########################### M A I N P R O G R A M ###########################
#######################################################################################
test=1
test_case=1
while test<=test_case:
test+=1
x=ii()
cnt=0
while x:
x=abs(x-ones(x))
print(cnt)
```
No
| 15,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Output
Print expected minimal number of digits 1.
Examples
Input
121
Output
6
Submitted Solution:
```
n = int(input())
d = {n: 0}
u = 10 ** (len(str(n)) + 2) // 9
for i in range(len(str(n)) + 1, 0, -1):
print(d)
d, e = {}, d
u //= 10
for v, c in e.items():
lim = v//u
print(lim)
for x in range(-1 - lim, 1 - lim):
t = v + x * u
d[t] = min(c + i * abs(x), d.get(t, 999))
print(d[0])
```
No
| 15,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
def print(x):
sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = readInts()
adj: list = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = readInts()
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(0, n):
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
```
| 15,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int, input().split())
M = 10**9+7
a = list(map(int, input().split()))
g = [[] for _ in range(n)]
for _ in range(n-1):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
vis = [0]*n
def dfs(i, prev, j):
s = 1
for v in g[i]:
if 0 < a[v] - a[j] <= d or a[v] == a[j] and v > j:
if v != prev:
s += s * dfs(v, i, j) % M
return s
print(sum(dfs(i, -1, i) for i in range(n))%M)
```
| 15,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
tyt_yge_bili[nomer] = True
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if not ((a[j-1] < a[nach-1]) or (a[j-1] > a[nach-1] + d)) and not ((a[j-1] == a[nach-1]) and (j < nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez = (rez + f[z]) % MOD
print(rez)
```
| 15,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
f = lambda: map(int, input().split())
m = 1000000007
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
p[u - 1].append(v - 1)
p[v - 1].append(u - 1)
def g(u, x, y):
s = 1
for v in p[u]:
if 0 < t[v] - t[y] <= d or t[v] == t[y] and v > y:
if v != x: s += s * g(v, u, y) % m
return s
print(sum(g(y, -1, y) for y in range(n)) % m)
```
| 15,446 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
def dfs(nomer,mas,tyt_yge_bili,f,nach):
f[nomer] = 1;
tyt_yge_bili[nomer] = True
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if ((a[j-1] >= a[nach-1]) and (a[j-1] <= a[nach-1] + d)) and ((a[j-1] != a[nach-1]) or (j >= nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez = (rez + f[z]) % MOD
print(rez)
```
| 15,447 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
def print(x):
sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = [0] + readInts()
adj: list = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = readInts()
adj[u].append(v)
adj[v].append(u)
vis = [False for _ in range(n + 1)]
f = [0 for _ in range(n + 1)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(1, n + 1):
vis = [False for _ in range(n + 1)]
f = [0 for _ in range(n + 1)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
```
| 15,448 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
tyt_yge_bili[nomer] = True
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if ((a[j-1] >= a[nach-1]) and (a[j-1] <= a[nach-1] + d)) and ((a[j-1] != a[nach-1]) or (j >= nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez = (rez + f[z]) % MOD
print(rez)
```
| 15,449 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
# def print(x):
# sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = readInts()
adj: list = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = readInts()
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(0, n):
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
```
| 15,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
f = lambda: map(int, input().split())
m = 1000000007
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
u -= 1
v -= 1
p[u].append(v)
p[v].append(u)
def g(u, x, a, b, q):
k = 1
for v in p[u]:
if a < t[v] <= b or t[v] == a and v > q:
if v != x: k += k * g(v, u, a, b, q) % m
return k
s = 0
for q in range(n):
a = t[q]
b = a + d
s += g(q, -1, a, b, q)
print(s % m)
```
Yes
| 15,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
mod=10**9+7
d,n=map(int,input().split())
a=[0]+list(map(int,input().split()))
tree=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=map(int,input().split())
tree[u].append(v)
tree[v].append(u)
def dfs(u,root):
visited[u]=True
f[u]=1
for i in tree[u]:
if visited[i]==False:
if a[i]<a[root] or a[i]>a[root]+d:continue
if a[i]==a[root] and i<root: continue
dfs(i,root)
f[u]=(f[u]*(f[i]+1))%(mod)
ans=0
for i in range(1,n+1):
visited = [False] * (n+1)
f = [0] * (n+1)
dfs(i,i)
ans=(ans+f[i])%mod
print(ans)
```
Yes
| 15,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
if nomer not in tyt_yge_bili:
tyt_yge_bili.append(nomer)
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if j not in tyt_yge_bili:
if not ((a[j-1] < a[nach-1]) or (a[j-1] > a[nach-1] + d)) and not ((a[j-1] == a[nach-1]) and (j < nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = [0 for _ in range(n+1)]
tyt_yge_bili = []
dfs(z,mas,tyt_yge_bili,f , z)
rez += f[z]
print(rez)
```
No
| 15,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
from bisect import bisect
print( bisect([1,3,7],4))
```
No
| 15,454 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
f = lambda: map(int, input().split())
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
u -= 1
v -= 1
p[u].append(v)
p[v].append(u)
def g(u, x, a, b, q):
k = 1
for v in p[u]:
if a < t[v] <= b or t[v] == a and v > q:
if v != x: k *= g(v, u, a, b, q)
return k + 1
s = 0
for q in range(n):
a = t[q]
b = a + d
s += g(q, -1, a, b, q)
print(s - n)
```
No
| 15,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
tyt_yge_bili[nomer] = True
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if not ((a[j-1] < a[nach-1]) or (a[j-1] > a[nach-1] + d)) and not ((a[j-1] == a[nach-1]) and (j < nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez += f[z] % MOD
print(rez)
```
No
| 15,456 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Tags: geometry
Correct Solution:
```
def O3():
n = int(input())
maxh = maxw = -10 ** 6
minh = minw = 10**6
for _ in range(n):
x, y = [int(x) for x in input().split()]
h, w = x + y, x-y
maxh= max(maxh, h)
minh = min(minh, h)
maxw = max(maxw, w)
minw = min(minw, w)
print(maxh-minh + maxw - minw + 4)
if __name__ == '__main__':
O3()
```
| 15,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Tags: geometry
Correct Solution:
```
n = int(input())
# Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
x1 = y1 = -(10**7)
x2 = y2 = 10**7
for i in range(1, n+1):
mylist = list(map(int, input().split()))
x1 = max(x1, mylist[0]+mylist[1])
y1 = max(y1, mylist[0]-mylist[1])
x2 = min(x2, mylist[0]+mylist[1])
y2 = min(y2, mylist[0]-mylist[1])
# plus 1 for diagonal case (on point +1) => 4 points => +4
total = x1 + y1 - x2 - y2 + 4
print(total)
```
| 15,458 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Tags: geometry
Correct Solution:
```
import math
n = int(input())
l = []
for i in range(n):
l.append(tuple(list(map(int, input().split(" ")))))
l = list(set(l))
n = len(l)
pmin = 0
for i in range(1, n):
if(l[i][1] < l[pmin][1] or (l[i][1] == l[pmin][1] and l[i][0] < l[pmin][0])):
pmin = i
l[pmin], l[0] = l[0], l[pmin]
def orientation(p0, p1, p2):
x = (p1[1] - p0[1]) * (p2[0] - p1[0]) - (p1[0] - p0[0]) * (p2[1] - p1[1])
if(x < 0):
return -1
if(x > 0):
return 1
return 0
l = [(p[0] - l[0][0], p[1] - l[0][1]) for p in l[1:]]
l.sort(key = lambda p: (-p[0]/p[1] if(p[1] != 0) else -10e14, p[0] ** 2 + p[1] ** 2))
l = [(0, 0)] + l
t = [l[0]]
i = 1
n = len(l)
while(1):
while(i < n - 1 and orientation(l[0], l[i], l[i + 1]) == 0):
i += 1
if(i >= n - 1):
break
t.append(l[i])
i += 1
t.append(l[-1])
if(len(t) == 1):
print(4)
elif(len(t) == 2):
print(max(abs(t[1][1] - t[0][1]), abs(t[1][0] - t[0][0])) * 2 + 4)
else:
stack = [t[0], t[1], t[2]]
for i in range(3, len(t)):
while(orientation(stack[-2], stack[-1], t[i]) == 1):
stack.pop()
stack.append(t[i])
n = len(stack)
s = 4
for i in range(n - 1):
s += max(abs(stack[i + 1][1] - stack[i][1]), abs(stack[i + 1][0] - stack[i][0]))
s += max(abs(stack[0][1] - stack[n - 1][1]), abs(stack[0][0] - stack[n - 1][0]))
print(s)
```
| 15,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Tags: geometry
Correct Solution:
```
n = int(input())
x, y = map(int, input().split())
max_x = min_x = x
max_y = min_y = y
sum_pp = x + y
sum_pn = x - y
sum_np = -x + y
sum_nn = -x - y
for i in range(1, n):
x, y = map(int, input().split())
max_x = max(max_x, x)
min_x = min(min_x, x)
max_y = max(max_y, y)
min_y = min(min_y, y)
if x + y > sum_pp:
sum_pp = x + y
if x - y > sum_pn:
sum_pn = x - y
if -x + y > sum_np:
sum_np = -x + y
if -x - y > sum_nn:
sum_nn = -x - y
box = 2 * (max_x - min_x + max_y - min_y)
box -= max_x + max_y - sum_pp
box -= max_x - min_y - sum_pn
box -= -min_x + max_y - sum_np
box -= -min_x - min_y - sum_nn
box += 4
print(box)
```
| 15,460 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Tags: geometry
Correct Solution:
```
n=int(input())
mh=sh=-10**7
ml=sl=10**7
for i in range(n):
a,b=map(int,input().split())
m,s=a+b,a-b
mh=max(mh,m)
ml=min(ml,m)
sh=max(sh,s)
sl=min(sl,s)
print(mh-ml+sh-sl+4)
```
| 15,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Submitted Solution:
```
a=int(input())
x=[]
y=[]
for i in range (a):
b=input().split()
x.append(b[0])
y.append(b[1])
xm=x[0]
ym=y[0]
for i in x:
if int(i)>=int(xm):
xm=int(i)
else:
continue
for i in y:
if int(i)>=int(ym):
ym=int(i)
else:
continue
print(2*(xm+ym))
```
No
| 15,462 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Submitted Solution:
```
import math
n = int(input())
l = []
for i in range(n):
l.append(tuple(list(map(int, input().split(" ")))))
l = list(set(l))
n = len(l)
pmin = 0
for i in range(1, n):
if(l[i][1] < l[pmin][1] or (l[i][1] == l[pmin][1] and l[i][0] < l[pmin][0])):
pmin = i
l[pmin], l[0] = l[0], l[pmin]
def orientation(p0, p1, p2):
x = (p1[1] - p0[1]) * (p2[0] - p1[0]) - (p1[0] - p0[0]) * (p2[1] - p1[1])
if(x < 0):
return -1
if(x > 0):
return 1
return 0
l = [(p[0] - l[0][0], p[1] - l[0][1]) for p in l[1:]]
def custom1(p):
if(p[0] < 0):
return abs(p[0]/p[1])
if(p[0] > 0):
return -abs(p[1]/p[0])
return 0
def custom2(p):
return p[0] ** 2 + p[1] ** 2
l.sort(key = lambda p: (custom1(p), custom2(p)))
l = [(0, 0)] + l
t = [l[0]]
i = 1
n = len(l)
while(1):
while(i < n - 1 and orientation(l[0], l[i], l[i + 1]) == 0):
i += 1
if(i >= n - 1):
break
t.append(l[i])
i += 1
t.append(l[-1])
if(len(t) == 1):
print(4)
elif(len(t) == 2):
print(max(abs(t[1][1] - t[0][1]), abs(t[1][0] - t[0][0])) * 2 + 4)
else:
stack = [t[0], t[1], t[2]]
for i in range(3, len(t)):
while(orientation(stack[-2], stack[-1], t[i]) == 1):
stack.pop()
stack.append(t[i])
n = len(stack)
s = 4
for i in range(n - 1):
s += max(abs(stack[i + 1][1] - stack[i][1]), abs(stack[i + 1][0] - stack[i][0]))
s += max(abs(stack[0][1] - stack[n - 1][1]), abs(stack[0][0] - stack[n - 1][0]))
print(s)
```
No
| 15,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Submitted Solution:
```
a=int(input())
x=[]
y=[]
for i in range (a):
b=input().split()
x.append(b[0])
y.append(b[1])
xm=x[0]
ym=y[0]
for i in x:
if int(i)>=int(x[0]):
xm=int(i)
else:
continue
for i in y:
if int(i)>=int(y[0]):
ym=int(i)
else:
continue
print(2*(xm+ym))
```
No
| 15,464 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.
The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to <image>. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
Input
The first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.
Output
Print the single number — the minimum number of moves in the sought path.
Examples
Input
4
1 1
5 1
5 3
1 3
Output
16
Note
Picture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
<image>
Submitted Solution:
```
import functools
n = int(input())
l = []
for i in range(n):
l.append(tuple(list(map(int, input().split(" ")))))
l = list(set(l))
n = len(l)
pmin = 0
for i in range(1, n):
if(l[i][1] < l[pmin][1] or (l[i][1] == l[pmin][1] and l[i][0] < l[pmin][0])):
pmin = i
l[pmin], l[0] = l[0], l[pmin]
def orientation(p0, p1, p2):
x = (p1[1] - p0[1]) * (p2[0] - p1[0]) - (p1[0] - p0[0]) * (p2[1] - p1[1])
if(x < 0):
return -1
if(x > 0):
return 1
return 0
def construct(p0):
def compare(p1, p2):
ox = orientation(p0, p1, p2)
if(ox == 0):
d1 = (p1[0] - p0[0]) ** 2 + (p1[1] - p0[1]) ** 2
d2 = (p2[0] - p0[0]) ** 2 + (p2[1] - p0[1]) ** 2
if(d1 < d2):
return -1
return 1
return ox
return compare
l[1:] = sorted(l[1:], key = functools.cmp_to_key(construct(l[0])))
t = [l[0]]
i = 1
n = len(l)
while(1):
while(i < n - 1 and orientation(l[0], l[i], l[i + 1]) == 0):
i += 1
t.append(l[i])
i += 1
if(i >= n - 1):
break
t.append(l[-1])
if(len(t) == 1):
print(4)
elif(len(t) == 2):
print(max(abs(t[1][1] - t[0][1]), abs(t[1][0] - t[0][0])) * 2 + 4)
else:
stack = [t[0], t[1], t[2]]
for i in range(3, len(t)):
while(orientation(stack[-2], stack[-1], t[i]) == 1):
stack.pop()
stack.append(t[i])
n = len(stack)
s = 4
for i in range(n - 1):
s += max(abs(t[i + 1][1] - t[i][1]), abs(t[i + 1][0] - t[i][0]))
s += max(abs(t[0][1] - t[n - 1][1]), abs(t[0][0] - t[n - 1][0]))
print(s)
```
No
| 15,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, ai < ai + 1 for all i from 1 to n - 1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number n, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop n. During the day, the bus runs non-stop on this route.
The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.
One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.
For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: <image>, then the request about this segment of the path will have form: 3, 4, 5, 5, 6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1, 2, 2, 3, 3, 4, 5, 5, 6.
You will have to repeat the Berland programmers achievement and implement this function.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of stops.
The second line contains n integers (1 ≤ ai ≤ 109) — the distance from the i-th stop to the central square. The numbers in the second line go in the increasing order.
The third line contains integer m (1 ≤ m ≤ 4·105) — the number of stops the bus visited on some segment of the path.
The fourth line contains m integers (1 ≤ bi ≤ n) — the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus.
It is guaranteed that the query corresponds to some segment of the path.
Output
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print - 1.
Examples
Input
6
2 3 5 7 11 13
5
3 4 5 5 6
Output
10
Input
6
2 3 5 7 11 13
9
1 2 2 3 3 4 5 5 6
Output
16
Input
3
10 200 300
4
1 2 2 3
Output
-1
Input
3
1 2 3
4
1 2 2 3
Output
3
Note
The first test from the statement demonstrates the first example shown in the statement of the problem.
The second test from the statement demonstrates the second example shown in the statement of the problem.
In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely.
In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely.
Tags: constructive algorithms, greedy, hashing, implementation
Correct Solution:
```
r = lambda: list(map(int, input().split()))
ri = lambda: int(input())
n, a, m, b = ri(), r(), ri(), r()
c = [0] * n
for e in b: c[e - 1] += 1
c[0] *= 2; c[-1] *= 2
d = 0
df= 0
r = max(e // 2 for e in c)
c = [e - r * 2 for e in c]
if any(c):
for i in range(n - 1):
de = a[i+1] - a[i]
d += min(c[i], c[i+1]) * de
df += de
print(d + r * 2 * df)
else:
de = a[1] - a[0]
for i in range(1, n - 1):
if a[i + 1] - a[i] != de: print(-1); break
else: print(r * de * 2 * (n - 1) - de)
```
| 15,466 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, ai < ai + 1 for all i from 1 to n - 1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number n, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop n. During the day, the bus runs non-stop on this route.
The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.
One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.
For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: <image>, then the request about this segment of the path will have form: 3, 4, 5, 5, 6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1, 2, 2, 3, 3, 4, 5, 5, 6.
You will have to repeat the Berland programmers achievement and implement this function.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of stops.
The second line contains n integers (1 ≤ ai ≤ 109) — the distance from the i-th stop to the central square. The numbers in the second line go in the increasing order.
The third line contains integer m (1 ≤ m ≤ 4·105) — the number of stops the bus visited on some segment of the path.
The fourth line contains m integers (1 ≤ bi ≤ n) — the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus.
It is guaranteed that the query corresponds to some segment of the path.
Output
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print - 1.
Examples
Input
6
2 3 5 7 11 13
5
3 4 5 5 6
Output
10
Input
6
2 3 5 7 11 13
9
1 2 2 3 3 4 5 5 6
Output
16
Input
3
10 200 300
4
1 2 2 3
Output
-1
Input
3
1 2 3
4
1 2 2 3
Output
3
Note
The first test from the statement demonstrates the first example shown in the statement of the problem.
The second test from the statement demonstrates the second example shown in the statement of the problem.
In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely.
In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely.
Tags: constructive algorithms, greedy, hashing, implementation
Correct Solution:
```
n=int(input())
c=[0]*n
a=[int(x) for x in input().split()]
m=int(input())
b=[int(x)-1 for x in input().split()]
for e in b:
c[e]+=1
c[0]*=2
c[-1]*=2
d=0
df=0
r=max([e//2 for e in c])
c=[e-r*2 for e in c]
if not any(c):
de=a[1]-a[0]
for i in range(1,n-1):
if a[i+1]-a[i]!=de:
print(-1)
break
else:
print(r*de*2*(n-1)-de)
else:
for i in range(n-1):
de=a[i+1]-a[i]
d+=min(c[i],c[i+1])*de
df+=de
print(d+r*2*df)
```
| 15,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, ai < ai + 1 for all i from 1 to n - 1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number n, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop n. During the day, the bus runs non-stop on this route.
The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.
One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.
For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: <image>, then the request about this segment of the path will have form: 3, 4, 5, 5, 6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1, 2, 2, 3, 3, 4, 5, 5, 6.
You will have to repeat the Berland programmers achievement and implement this function.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of stops.
The second line contains n integers (1 ≤ ai ≤ 109) — the distance from the i-th stop to the central square. The numbers in the second line go in the increasing order.
The third line contains integer m (1 ≤ m ≤ 4·105) — the number of stops the bus visited on some segment of the path.
The fourth line contains m integers (1 ≤ bi ≤ n) — the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus.
It is guaranteed that the query corresponds to some segment of the path.
Output
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print - 1.
Examples
Input
6
2 3 5 7 11 13
5
3 4 5 5 6
Output
10
Input
6
2 3 5 7 11 13
9
1 2 2 3 3 4 5 5 6
Output
16
Input
3
10 200 300
4
1 2 2 3
Output
-1
Input
3
1 2 3
4
1 2 2 3
Output
3
Note
The first test from the statement demonstrates the first example shown in the statement of the problem.
The second test from the statement demonstrates the second example shown in the statement of the problem.
In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely.
In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely.
Submitted Solution:
```
n=int(input())
c=[0]*n
a=[int(x) for x in input().split()]
m=int(input())
b=[int(x)-1 for x in input().split()]
for e in b:
c[e]+=1
c[0]*=2
c[-1]*=2
d=0
df=0
r=max([e//2 for e in c])
c=[e-r*2 for e in c]
if not any(c):
de=a[1]-a[0]
for i in range(1,n-1):
if a[i+1]-a[i]!=de:
print(-1)
break
else:
print(r*de*2*(n-1)+de*(2*(n-1)-1))
else:
for i in range(n-1):
de=a[i+1]-a[i]
d+=min(c[i],c[i+1])*de
df+=de
print(d+r*2*df)
```
No
| 15,468 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, ai < ai + 1 for all i from 1 to n - 1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number n, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop n. During the day, the bus runs non-stop on this route.
The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.
One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.
For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: <image>, then the request about this segment of the path will have form: 3, 4, 5, 5, 6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1, 2, 2, 3, 3, 4, 5, 5, 6.
You will have to repeat the Berland programmers achievement and implement this function.
Input
The first line contains integer n (2 ≤ n ≤ 2·105) — the number of stops.
The second line contains n integers (1 ≤ ai ≤ 109) — the distance from the i-th stop to the central square. The numbers in the second line go in the increasing order.
The third line contains integer m (1 ≤ m ≤ 4·105) — the number of stops the bus visited on some segment of the path.
The fourth line contains m integers (1 ≤ bi ≤ n) — the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus.
It is guaranteed that the query corresponds to some segment of the path.
Output
In the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print - 1.
Examples
Input
6
2 3 5 7 11 13
5
3 4 5 5 6
Output
10
Input
6
2 3 5 7 11 13
9
1 2 2 3 3 4 5 5 6
Output
16
Input
3
10 200 300
4
1 2 2 3
Output
-1
Input
3
1 2 3
4
1 2 2 3
Output
3
Note
The first test from the statement demonstrates the first example shown in the statement of the problem.
The second test from the statement demonstrates the second example shown in the statement of the problem.
In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely.
In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely.
Submitted Solution:
```
n=int(input())
c=[0]*n
a=[int(x) for x in input().split()]
m=int(input())
b=[int(x)-1 for x in input().split()]
for e in b:
c[e]+=1
c[0]*=2
c[-1]*=2
d=0
df=0
r=max([e//2 for e in c])
c=[e-r*2 for e in c]
if not any(c):
df=a[1]-a[0]
for i in range(1,n-1):
if a[i+1]-a[i]!=df:
print(-1)
break
else:
print(df*2*(n-1)-1)
else:
for i in range(n-1):
de=a[i+1]-a[i]
d+=min(c[i],c[i+1])*de
df+=de
print(d+r*2*df)
```
No
| 15,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.
The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.
You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≤ ai ≤ 108, 1 ≤ li ≤ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates.
It is guaranteed that all the ai's are distinct.
Output
Print a single integer — the maximum total length of the illuminated part of the path.
Examples
Input
3
1 1
2 2
3 3
Output
5
Input
4
1 2
3 3
4 3
6 2
Output
9
Submitted Solution:
```
no = int(input())
details = []
for _ in range(no):
v = input().split()
v[0] = int(v[0])
v[1] = int(v[1])
details.append(v)
details.sort()
ans = 0
for i in range(no):
if i==0 or i==(no-1):
ans+=details[i][1]
else:
if details[i-1][0]<details[i+1][0]:
ans+=details[i-1][0]
else:
ans+=details[i+1][0]
print(ans)
```
No
| 15,470 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.
The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.
You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≤ ai ≤ 108, 1 ≤ li ≤ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates.
It is guaranteed that all the ai's are distinct.
Output
Print a single integer — the maximum total length of the illuminated part of the path.
Examples
Input
3
1 1
2 2
3 3
Output
5
Input
4
1 2
3 3
4 3
6 2
Output
9
Submitted Solution:
```
import random
n = int(input())
al = []
for i in range (n):
ii = [int(c) for c in input().split()]
al.append(ii)
random.seed()
ch = [-1, 1]
def rc():
intervals = []
for i in range(n):
nc = random.choice(ch)
ni = [al[i][0], al[i][0] + nc * al[i][1]]
ni.sort()
while intervals and ni[0] <= intervals[-1][1]:
ni[0] = min(ni[0], intervals[-1][0])
ni[1] = max(ni[1], intervals[-1][1])
del intervals[-1]
intervals.append(ni)
ml = 0
for ii in intervals:
l = ii[1] - ii[0]
if l > ml:
ml = l
return ml
gl = 0
for i in range(n**2):
ll = rc()
if ll > gl:
gl = ll
print(gl)
```
No
| 15,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.
The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.
You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≤ ai ≤ 108, 1 ≤ li ≤ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates.
It is guaranteed that all the ai's are distinct.
Output
Print a single integer — the maximum total length of the illuminated part of the path.
Examples
Input
3
1 1
2 2
3 3
Output
5
Input
4
1 2
3 3
4 3
6 2
Output
9
Submitted Solution:
```
no = int(input())
details = []
for _ in range(no):
v = input().split()
v[0] = int(v[0])
v[1] = int(v[1])
details.append(v)
details.sort()
ans = 0
for i in range(no):
if i==0 or i==(no-1):
ans+=details[i][1]
else:
if details[i-1][0]<details[i+1][0]:
ans+=details[i-1][1]
else:
ans+=details[i+1][1]
print(ans)
```
No
| 15,472 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.
The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.
You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≤ ai ≤ 108, 1 ≤ li ≤ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates.
It is guaranteed that all the ai's are distinct.
Output
Print a single integer — the maximum total length of the illuminated part of the path.
Examples
Input
3
1 1
2 2
3 3
Output
5
Input
4
1 2
3 3
4 3
6 2
Output
9
Submitted Solution:
```
import random
n = int(input())
al = []
for i in range (n):
ii = [int(c) for c in input().split()]
al.append(ii)
random.seed()
ch = [-1, 1]
def rc():
intervals = []
for i in range(n):
nc = random.choice(ch)
ni = [al[i][0], al[i][0] + nc * al[i][1]]
ni.sort()
while intervals and ni[0] <= intervals[-1][1]:
ni[0] = min(ni[0], intervals[-1][0])
ni[1] = max(ni[1], intervals[-1][1])
del intervals[-1]
intervals.append(ni)
ml = 0
for ii in intervals:
l = ii[1] - ii[0]
if l > ml:
ml = l
return ml
gl = 0
for i in range(n**2 + 10000):
ll = rc()
if ll > gl:
gl = ll
print(gl)
```
No
| 15,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
from math import gcd
def help():
ans = []
a,b = map(int,input().split(" "))
if(gcd(a,b)>1):
print("Impossible")
return
while a!=1 or b!=1:
if(a==1):
ans.append(str(b-1)+"B")
break
elif(b==1):
ans.append(str(a-1)+"A")
break
elif(a>b):
ans.append(str(a//b)+"A")
a = a%b
elif(b>a):
ans.append(str(b//a)+"B")
b = b%a
print(*ans[::],sep="")
help()
```
| 15,474 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
def gcd(m, n):
if m < n:
m, n = n, m
r = m % n
while r:
m, n = n, r
r = m % n
return n
def search(x, y):
global ans
while True:
if x == 1:
ans = ans + ("" if y == 1 else str(y - 1) + 'B')
return
if y == 1:
ans = ans + ("" if x == 1 else str(x - 1) + 'A')
return
if x < y:
ans = ans + str(y // x) + 'B'
x, y = x, y % x
else:
ans = ans + str(x // y) + 'A'
x, y = x % y, y
a, b = [ int(i) for i in input().split() ]
if gcd(a, b) != 1:
print("Impossible")
else:
ans = ""
search(a, b)
print(ans)
```
| 15,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
from operator import gt, lt
x, y = (int(w) for w in input().split())
if x>y:
ch = 'AB'
op1, op2 = lt, gt
ax, ay, bx, by = 1, 0, 0, 1
else:
ch = 'BA'
op1, op2 = gt, lt
ax, ay, bx, by = 0, 1, 1, 0
ans = []
while(ax+ay+bx+by < x+y):
n=0
for sh in range(59,-1,-1):
t = n + (1<<sh)
if op1(y * (bx + t*ax), x * (by + t*ay)): n = t
if not n:
print('Impossible')
exit(0)
ans.append(n)
ax, bx = bx + n*ax, ax # Increment and swap
ay, by = by + n*ay, ay # Increment and swap
op1, op2 = op2, op1
for i,a in enumerate(ans): print('%d%s' % (a, ch[i&1]), end='')
print()
```
| 15,476 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
def gcd(a,b):
if b==0:
return a
else:
return gcd(b, a%b)
def solve(x, y, a, b):
ans=""
while not x==1 or not y==1:
if x < y:
x,y,a,b=y,x,b,a
ans+=str((x-1)//y)+a
x = x - (x-1)//y * y
print (ans)
x,y=map(int, input().split())
if gcd(x,y)>1:
print ("Impossible")
else:
solve(x,y, "A", "B")
```
| 15,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
a = input().split()
target = (int(a[0]), int(a[1]))
x=(1, 0)
y=(0, 1)
toadd="A"
ans = ""
def less(a, b):
return a[0]*b[1]<b[0]*a[1]
while True:
z = (x[0]+y[0], x[1]+y[1])
if z[0] > target[0] or z[1] > target[1]:
print("Impossible")
exit()
if z==target:
print(ans)
exit()
if less(z, target): # z replaces y
low = 1
high = int(1e18)
while (high > low):
guess = (low+high+1)//2
if less((x[0]*guess+y[0], x[1]*guess+y[1]), target):
low = guess
else:
high = guess - 1
ans += str(low)
ans += "A"
y = (y[0] + low * x[0], y[1] + low * x[1])
elif less(target, z):
low = 1
high = int(1e18)
while (high > low):
guess = (low+high+1)//2
if less(target,(x[0]+guess*y[0], x[1]+guess*y[1])):
low = guess
else:
high = guess - 1
ans += str(low)
ans += "B"
x = (x[0] + low * y[0], x[1] + low * y[1])
else:
print("Impossible")
exit()
```
| 15,478 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
def gcd(m, n):
if m < n:
m, n = n, m
r = m % n
while r:
m, n = n, r
r = m % n
return n
def search(x, y):
while True:
if x == 1:
ans.extend( [] if y == 1 else (str(y - 1) + 'B') )
return
if y == 1:
ans.extend( [] if x == 1 else (str(x - 1) + 'A') )
return
if x < y:
ans.append(str(y // x) + 'B')
x, y = x, y % x
else:
ans.append(str(x // y) + 'A')
x, y = x % y, y
a, b = [ int(i) for i in input().split() ]
if gcd(a, b) != 1:
print("Impossible")
else:
ans = []
search(a, b)
i, length = 0, len(ans)
print(''.join(ans))
```
| 15,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
def gcd(x, y):
if y == 0:
return x
return gcd(y, x % y)
x, y = map(int, input().split())
if gcd(x, y) != 1:
print('Impossible')
exit()
a = []
while y != 1:
a += [x // y]
x %= y
x, y = y, x
a += [x-1]
s = 'A'
for x in a:
if x > 0:
print(x, end=s)
s = 'AB'.replace(s, '')
```
| 15,480 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Tags: number theory
Correct Solution:
```
import fractions
def solve(x, y):
if fractions.gcd(x, y) > 1: return 'Impossible'
turn = x > y
if not turn: x, y = y, x
ans = []
while x != 0 and y != 0:
ans.append((x//y, 'A' if turn else 'B'))
x, y = y, x%y
turn = not turn
ans[-1] = (ans[-1][0]-1, ans[-1][1])
return ''.join(str(n) + l for n, l in ans)
x, y = [int(x) for x in input().split()]
print(solve(x, y))
```
| 15,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
def gcd(x , y):
if(x > y):x , y = y , x
if(x == 0):return y
return gcd(y % x , x)
A , B = map(int , input().split())
def solve(X , Y):
if(X > Y):
if(Y == 1):
print(str(X - 1) + "A" , end = "")
return;
else:
print(str(X // Y) + "A" , end = "")
solve(X % Y , Y)
else:
if(X == 1):
print(str(Y - 1) + "B" , end = "")
return;
else:
print(str(Y // X) + "B" , end = "")
solve(X , Y % X)
if(gcd(A , B) == 1):
solve(A , B)
else:
print("Impossible")
```
Yes
| 15,482 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
def solve(a, b):
r = []
while a and b and a+b > 2:
q = min((a//b + b//a), max(a, b)-1)
r.append(str(q))
if a > b:
r.append('A')
a -= b*q
else:
r.append('B')
b -= a*q
if a != 1 or b != 1:
return 'Impossible'
return ''.join(r)
def main():
a, b = map(int, input().split())
print(solve(a, b))
main()
```
Yes
| 15,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
x, y = (int(w) for w in input().split())
ax, ay = 1, 0
bx, by = 0, 1
anext = (x>y)
ch = 'AB' if x>y else 'BA'
ans = []
while(ax+ay+bx+by < x+y):
if(anext):
n=0
for sh in range(59,-1,-1):
t = n + (1<<sh)
#print('Aiming for', x/y)
if y * (bx + t*ax) < x * (by + t*ay):
n = t
#print('Include', sh)
if not n:
print('Impossible')
exit(0)
ans.append(n)
bx = bx + n*ax
by = by + n*ay
else:
n=0
for sh in range(59,-1,-1):
t = n + (1<<sh)
#print('Beaming for', x/y)
#print(y, ' * (', ax, ' + ', t, '*', bx, ') > ', x, ' * (', ay, ' * ', t, '*', by, ')')
if y * (ax + t*bx) > x * (ay + t*by):
#print(y * (ax + t*bx), '>', x * (ay * t*by))
n = t
#print('Include', sh)
if not n:
print('Impossible')
exit(0)
ans.append(n)
ax = ax + n*bx
ay = ay + n*by
anext = not anext
for i,a in enumerate(ans):
print('%d%s' % (a, ch[i&1]), end='')
print()
```
Yes
| 15,484 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class fraction:
n, m = 0, 0
def __init__(self, n, m):
d = int(gcd(n, m))
self.n = int(n//d)
self.m = int(m//d)
def add(self, tmp):
return fraction(self.n * tmp.m, self.m * tmp.n)
def compareTo(self ,tmp):
a = self.n * tmp.m
b = self.m * tmp.n
if a > b:
return 1
elif a < b:
return -1
return 0
def sternBrocotAdd(self, tmp):
return fraction(self.n + tmp.n, self.m + tmp.m);
def run(left, right, result):
a = left.n
b = left.m
p = right.n
q = right.m
n = result.n
m = result.m
mid = left.sternBrocotAdd(right)
if mid.compareTo(result) == 0:
return
ch = 'Z'
x = 0
if mid.compareTo(result) <= 0:
x = int((b * n - a * m) // (p * m - q * n))
left = fraction(a + p * x, b + q * x)
ch = 'A'
if left.compareTo(result) == 0:
x -= 1
else:
x = int((p * m - q * n) // (b * n - a * m))
right = fraction(a * x + p, b * x + q)
ch = 'B'
if right.compareTo(result) == 0:
x -= 1
s = str.format("%d%c"%(x, ch))
print(s, end="")
if left.compareTo(result) == 0 or right.compareTo(result) == 0:
return
run(left, right, result)
p, q = map(int, input().split())
d = gcd(p, q)
if d == 1:
result = fraction(p, q)
right = fraction(1, 0)
left = fraction(0, 1)
run(left, right, result)
else:
print('Impossible')
```
Yes
| 15,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class fraction:
n, m = 0, 0
def __init__(self, n, m):
d = gcd(n, m)
self.n = n/d
self.m = m/d
def add(self, tmp):
return fraction(self.n * tmp.m, self.m * tmp.n)
def compareTo(self ,tmp):
a = self.n * tmp.m
b = self.m * tmp.n
if a > b:
return 1
elif a < b:
return -1
return 0
def sternBrocotAdd(self, tmp):
return fraction(self.n + tmp.n, self.m + tmp.m);
def run(left, right, result):
a = left.n
b = left.m
p = right.n
q = right.m
n = result.n
m = result.m
if left.compareTo(result) == 0:
return;
if right.compareTo(result) == 0:
return;
mid = left.sternBrocotAdd(right)
ch = 'Z'
if mid.compareTo(result) <= 0:
x = int((b * n - a * m) / (p * m - q * n))
left = fraction(a + p * x, b + q * x)
if left.compareTo(result) == 0:
x -= 1
ch = 'A'
else:
x = int((p * m - q * n) / (b * n - a * m))
right = fraction(a * x + p, b * x + q)
if right.compareTo(result) == 0:
x -= 1
ch = 'B'
s = str.format("%d%c"%(x, ch))
print(s, end="")
if left.compareTo(result) == 0 or right.compareTo(result) == 0:
return
run(left, right, result)
p, q = map(int, input().split())
d = gcd(p, q)
if d == 1:
result = fraction(p, q)
right = fraction(1, 0)
left = fraction(0, 1)
run(left, right, result)
else:
print('Impossible')
```
No
| 15,486 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
a, b = input().split()
a = int(a)
b = int(b)
strin=""
countA=0
countB=0
while a + b !=2:
if a < b:
countA = countA*(-1)
countB = countB + 1
b= b-a
elif a>b:
countB = countB*(-1)
countA = countA + 1
a= a-b
elif a==b and a!=1:
strin = "Impossible"
break
if (a==b and a!=1 and strin=="Impossible"):
break
if countB<0:
strin=strin+str(-countB)+'B'
# print(-countB,"B")
countB=0
elif countA <0:
strin=strin+str(-countA)+'A'
# print(-countA,"A")
countA=0
if (a==b and a==1):
countA = countA*(-1)
countB = countB*(-1)
if countB<0:
strin=strin+str(-countB)+'B'
# print(-countB,"B")
countB=0
elif countA <0:
strin=strin+str(-countA)+'B'
# print(-countA,"A")
countA=0
strin.replace(' ', '')
print(strin)
```
No
| 15,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class fraction:
n, m = 0, 0
def __init__(self, n, m):
d = gcd(n, m)
self.n = n/d
self.m = m/d
def add(self, tmp):
return fraction(self.n * tmp.m, self.m * tmp.n)
def compareTo(self ,tmp):
a = self.n * tmp.m
b = self.m * tmp.n
if a > b:
return 1
elif a < b:
return -1
return 0
def sternBrocotAdd(self, tmp):
return fraction(self.n + tmp.n, self.m + tmp.m);
def run(left, right, result):
a = left.n
b = left.m
p = right.n
q = right.m
n = result.n
m = result.m
if left.compareTo(result) == 0:
return;
if right.compareTo(result) == 0:
return;
mid = left.sternBrocotAdd(right)
ch = 'Z'
if mid.compareTo(result) <= 0:
x = int((b * n - a * m) / (p * m - q * n))
left = fraction(a + p * x, b + q * x)
if left.compareTo(result) == 0:
x -= 1
ch = 'A'
else:
x = int((p * m - q * n) / (b * n - a * m))
right = fraction(a * x + p, b * x + q)
if right.compareTo(result) == 0:
x -= 1
ch = 'B'
s = str.format("%d%c"%(x, ch))
print(s, end="")
if left.compareTo(result) == 0 or right.compareTo(result) == 0:
return
run(left, right, result)
p, q = map(int, input().split())
print("%d %d"%(p, q))
result = fraction(p, q)
right = fraction(1, 0)
left = fraction(0, 1)
run(left, right, result)
```
No
| 15,488 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.
You know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.
Input
The first line of the input contains two integers, x, y (1 ≤ x, y ≤ 1018, xy > 1) — the number of oranges and apples that were initially in the bag.
Output
Print any sequence of cards that would meet the problem conditions as a compressed string of characters 'A' and 'B. That means that you need to replace the segments of identical consecutive characters by the number of repetitions of the characters and the actual character. For example, string AAABAABBB should be replaced by string 3A1B2A3B, but cannot be replaced by 2A1A1B2A3B or by 3AB2A3B. See the samples for clarifications of the output format. The string that you print should consist of at most 106 characters. It is guaranteed that if the answer exists, its compressed representation exists, consisting of at most 106 characters. If there are several possible answers, you are allowed to print any of them.
If the sequence of cards that meet the problem statement does not not exist, print a single word Impossible.
Examples
Input
1 4
Output
3B
Input
2 2
Output
Impossible
Input
3 2
Output
1A1B
Note
In the first sample, if the row contained three cards with letter 'B', then Bob should give one apple to Alice three times. So, in the end of the game Alice has one orange and three apples, and Bob has one apple, in total it is one orange and four apples.
In second sample, there is no answer since one card is not enough for game to finish, and two cards will produce at least three apples or three oranges.
In the third sample, cards contain letters 'AB', so after removing the first card Bob has one orange and one apple, and after removal of second card Alice has two oranges and one apple. So, in total it is three oranges and two apples.
Submitted Solution:
```
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class fraction:
n, m = 0, 0
def __init__(self, n, m):
d = gcd(n, m)
self.n = n/d
self.m = m/d
def add(self, tmp):
return fraction(self.n * tmp.m, self.m * tmp.n)
def compareTo(self ,tmp):
a = self.n * tmp.m
b = self.m * tmp.n
if a > b:
return 1
elif a < b:
return -1
return 0
def sternBrocotAdd(self, tmp):
return fraction(self.n + tmp.n, self.m + tmp.m);
def run(left, right, result):
a = left.n
b = left.m
p = right.n
q = right.m
n = result.n
m = result.m
mid = left.sternBrocotAdd(right)
if mid.compareTo(result) == 0:
return
ch = 'Z'
x = 0
if mid.compareTo(result) <= 0:
x = int((b * n - a * m) / (p * m - q * n))
left = fraction(a + p * x, b + q * x)
ch = 'A'
if left.compareTo(result) == 0:
x -= 1
else:
x = int((p * m - q * n) / (b * n - a * m))
right = fraction(a * x + p, b * x + q)
ch = 'B'
if right.compareTo(result) == 0:
x -= 1
s = str.format("%d%c"%(x, ch))
print(s, end="")
if left.compareTo(result) == 0 or right.compareTo(result) == 0:
return
run(left, right, result)
p, q = map(int, input().split())
d = gcd(p, q)
if d == 1:
result = fraction(p, q)
right = fraction(1, 0)
left = fraction(0, 1)
run(left, right, result)
else:
print('Impossible')
```
No
| 15,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end.
Tags: hashing, strings
Correct Solution:
```
from time import time
opposite = {
'N': 'S',
'S': 'N',
'E': 'W',
'W': 'E'
}
otr = str.maketrans(opposite)
bits = {
'N': 0,
'S': 1,
'E': 2,
'W': 3,
}
Q = 4294967291
def combine(h, v, q):
return (h<<2 | v) % q
def combinel(h, v, q, s):
return (v*s + h) % q
def flip(s):
return ''.join(reversed(s.translate(otr)))
def solvable(p1, p2):
h1 = 0
h2 = 0
s = 1
for i in reversed(range(len(p1))):
n1 = bits[p1[i]]
n2 = bits[opposite[p2[i]]]
h1 = combine(h1, n1, Q)
h2 = combinel(h2, n2, Q, s)
if h1 == h2 and p1[i:] == flip(p2[i:]):
return False
s = (s<<2) % Q
return True
if __name__ == '__main__':
n = int(input())
p1 = input()
p2 = input()
print('YES' if solvable(p1, p2) else 'NO')
# Made By Mostafa_Khaled
```
| 15,490 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end.
Submitted Solution:
```
import heapq
opposite = {
'N': 'S',
'S': 'N',
'E': 'W',
'W': 'E'
}
def move(m, i, p):
if i < len(p) and m == p[i]:
return i+1
elif i > 0 and opposite[m] == p[i-1]:
return i-1
else:
return i
def solvable(p1, p2):
n = len(p1)
pq = [(n, (0, 0))]
seen = {(0, 0)}
while pq:
_, (i, j) = heapq.heappop(pq)
print(p1[:i]+"|"+p1[i:])
print(p2[:j]+"|"+p2[j:])
print()
if i == j == n:
return True
for m in 'NEWS':
i_ = move(m, i, p1)
j_ = move(m, j, p2)
ij_ = i_, j_
if ij_ not in seen:
seen.add(ij_)
heapq.heappush(pq, (n-min(i_, j_), ij_))
return False
if __name__ == '__main__':
n = int(input())
p1 = input()
p2 = input()
print('YES' if solvable(p1, p2) else 'NO')
```
No
| 15,491 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end.
Submitted Solution:
```
from time import time
opposite = {
'N': 'S',
'S': 'N',
'E': 'W',
'W': 'E'
}
otr = str.maketrans(opposite)
bits = {
'N': 0,
'S': 1,
'E': 2,
'W': 3,
}
Q = 4294967291
def combine(h, v, q):
return (h<<2 | v) % q
def combinel(h, v, q, s):
return (v*s + h) % q
def flip(s):
return ''.join(reversed(s.translate(otr)))
def solvable(p1, p2):
h1 = 0
h2 = 0
s = 0
for i in reversed(range(len(p1))):
n1 = bits[p1[i]]
n2 = bits[opposite[p2[i]]]
h1 = combine(h1, n1, Q)
h2 = combinel(h2, n2, Q, s)
if h1 == h2 and p1[i:] == flip(p2[i:]):
return False
s = (s<<2) % Q
return True
if __name__ == '__main__':
n = int(input())
p1 = input()
p2 = input()
print('YES' if solvable(p1, p2) else 'NO')
```
No
| 15,492 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
n = int(input())
m = [0] * 366
f = [0] * 366
res = 0
for i in range(n):
x, l, r = [i for i in input().split()]
l = int(l)
r = int(r)
if x == 'M':
for j in range(l-1, r):
m[j] += 1
else:
for j in range(l-1, r):
f[j] += 1
for i in range(366):
res = max(res, min(m[i], f[i]))
print(res * 2)
```
| 15,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/629/B
n = int(input())
a_g = list([0] * 367 for _ in range(2))
a_b = [0] * 367
for _ in range(n):
g, s, e = input().split()
for i in range(int(s), int(e) + 1):
a_g[1 if g == "F" else 0][i] += 1
m = 0
for i in range(1, 367):
m = max(m, 2 * min(a_g[0][i], a_g[1][i]))
print(m)
```
| 15,494 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
readInts=lambda: list(map(int, input().split()))
n = int(input())
num = [[0,0] for i in range(370)]
for i in range(n):
s,u,v = (input().split())
u=int(u)
v=int(v)
c=int(s=='F')
num[u][c]+=1
num[v+1][c]-=1
x=0;y=0
ret=0
for i in range(367):
x+=num[i][0]
y+=num[i][1]
ret=max(ret,min(x,y))
ret*=2
print(ret)
```
| 15,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
n = int(input())
m1 = {}
m2 = {}
for x in range(367):
m1[x] = 0
for y in range(367):
m2[y] = 0
for friend in range(n):
g, a, b = input().split()
for bruh in range(int(a), int(b)+1):
if g == "M":
m1[bruh] += 1
elif g == "F":
m2[bruh] += 1
attendees = []
for day in range(367):
attendees.append(min(m1[day], m2[day]))
print(max(attendees)*2)
```
| 15,496 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
n=int(input())
ab=[list(input().split()) for i in range(n)]
man,woman=0,0
day=[]
for i in range(1,367):
for x in range(len(ab)):
if int(ab[x][1])<=i<=int(ab[x][2]):
if ab[x][0]=='M':
man+=1
else:
woman+=1
day.append(2*min(man,woman))
man=0
woman=0
print(max(day))
```
| 15,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
n = int(input())
f = [0]*366
m = [0]*366
for i in range(n):
a,b,c = input().split()
if a=='F':
for j in range(int(b)-1,int(c)):f[j]+=1
if a=='M':
for j in range(int(b)-1,int(c)):m[j]+=1
ans = 0
for i in range(366):
t = min(m[i],f[i])
ans = max(ans,t)
print(ans*2)
```
| 15,498 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.
Output
Print the maximum number of people that may come to Famil Door's party.
Examples
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
Note
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Tags: brute force
Correct Solution:
```
n = int(input())
male,female = [0]*370,[0]*370
for _ in range(n):
g,l,r = input().split()
if g =='M':
for i in range(int(l),int(r)+1):
male[i]+=1
else:
for i in range(int(l),int(r)+1):
female[i]+=1
ans = 0
for i in range(1,367):
tans = 2*min(male[i],female[i])
if tans>ans:
ans = tans
print(ans)
```
| 15,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.